Completed
Branch models-cleanup/main (f1e009)
by
unknown
62:32 queued 53:11
created
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +19 added lines, -17 removed lines patch added patch discarded remove patch
@@ -916,7 +916,7 @@  discard block
 block discarded – undo
916 916
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
917 917
      * foreign key to the WP_User table)
918 918
      *
919
-     * @return string|boolean string on success, boolean false when there is no
919
+     * @return string|false string on success, boolean false when there is no
920 920
      * foreign key to the WP_User table
921 921
      * @throws ReflectionException
922 922
      */
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
      *
1047 1047
      * @param array  $query_params
1048 1048
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1049
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1049
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1050 1050
      *                                  fields on the model, and the models we joined to in the query. However, you can
1051 1051
      *                                  override this and set the select to "*", or a specific column name, like
1052 1052
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
      * found in the database matching the given query conditions.
1214 1214
      *
1215 1215
      * @param mixed $current_field_value    Value used for the reference point.
1216
-     * @param null  $field_to_order_by      What field is used for the
1216
+     * @param string  $field_to_order_by      What field is used for the
1217 1217
      *                                      reference point.
1218 1218
      * @param int   $limit                  How many to return.
1219 1219
      * @param array $query_params           Extra conditions on the query.
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
      * as found in the database matching the given query conditions.
1249 1249
      *
1250 1250
      * @param mixed $current_field_value    Value used for the reference point.
1251
-     * @param null  $field_to_order_by      What field is used for the
1251
+     * @param string  $field_to_order_by      What field is used for the
1252 1252
      *                                      reference point.
1253 1253
      * @param int   $limit                  How many to return.
1254 1254
      * @param array $query_params           Extra conditions on the query.
@@ -1283,7 +1283,7 @@  discard block
 block discarded – undo
1283 1283
      * database matching the given query conditions.
1284 1284
      *
1285 1285
      * @param mixed $current_field_value    Value used for the reference point.
1286
-     * @param null  $field_to_order_by      What field is used for the
1286
+     * @param string  $field_to_order_by      What field is used for the
1287 1287
      *                                      reference point.
1288 1288
      * @param array $query_params           Extra conditions on the query.
1289 1289
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1318,7 +1318,7 @@  discard block
 block discarded – undo
1318 1318
      * the database matching the given query conditions.
1319 1319
      *
1320 1320
      * @param mixed $current_field_value    Value used for the reference point.
1321
-     * @param null  $field_to_order_by      What field is used for the
1321
+     * @param string  $field_to_order_by      What field is used for the
1322 1322
      *                                      reference point.
1323 1323
      * @param array $query_params           Extra conditions on the query.
1324 1324
      * @param null  $columns_to_select      If left null, then an EE_Base_Class
@@ -1470,7 +1470,7 @@  discard block
 block discarded – undo
1470 1470
      *
1471 1471
      * @param string $field_name The name of the field the formats are being retrieved for.
1472 1472
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1473
-     * @return array formats in an array with the date format first, and the time format last.
1473
+     * @return string[] formats in an array with the date format first, and the time format last.
1474 1474
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1475 1475
      * @since 4.6.x
1476 1476
      */
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1552 1552
      *                                format is
1553 1553
      *                                'U', this is ignored.
1554
-     * @return DateTime
1554
+     * @return string
1555 1555
      * @throws EE_Error
1556 1556
      */
1557 1557
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2476,7 +2476,7 @@  discard block
 block discarded – undo
2476 2476
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2477 2477
      * EEM_Base::$_db_verification_level
2478 2478
      *
2479
-     * @param $wpdb_method
2479
+     * @param string $wpdb_method
2480 2480
      * @param $arguments_to_provide
2481 2481
      * @return string
2482 2482
      * @throws EE_Error
@@ -2595,6 +2595,7 @@  discard block
 block discarded – undo
2595 2595
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2596 2596
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2597 2597
      *                             because these will be inserted in any new rows created as well.
2598
+     * @param EE_Base_Class $id_or_obj
2598 2599
      * @return boolean of success
2599 2600
      * @throws EE_Error
2600 2601
      */
@@ -2606,7 +2607,7 @@  discard block
 block discarded – undo
2606 2607
 
2607 2608
 
2608 2609
     /**
2609
-     * @param mixed  $id_or_obj
2610
+     * @param EE_Base_Class  $id_or_obj
2610 2611
      * @param string $relationName
2611 2612
      * @param array  $where_query_params
2612 2613
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2647,7 +2648,7 @@  discard block
 block discarded – undo
2647 2648
      * However, if the model objects can't be deleted because of blocking related model objects, then
2648 2649
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2649 2650
      *
2650
-     * @param EE_Base_Class|int|string $id_or_obj
2651
+     * @param EE_Base_Class $id_or_obj
2651 2652
      * @param string                   $model_name
2652 2653
      * @param array                    $query_params
2653 2654
      * @return int how many deleted
@@ -2668,7 +2669,7 @@  discard block
 block discarded – undo
2668 2669
      * the model objects can't be hard deleted because of blocking related model objects,
2669 2670
      * just does a soft-delete on them instead.
2670 2671
      *
2671
-     * @param EE_Base_Class|int|string $id_or_obj
2672
+     * @param EE_Base_Class $id_or_obj
2672 2673
      * @param string                   $model_name
2673 2674
      * @param array                    $query_params
2674 2675
      * @return int how many deleted
@@ -2726,6 +2727,7 @@  discard block
 block discarded – undo
2726 2727
      * @param string $model_name   like 'Event', or 'Registration'
2727 2728
      * @param array  $query_params
2728 2729
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2730
+     * @param EE_Base_Class $id_or_obj
2729 2731
      * @return float
2730 2732
      * @throws EE_Error
2731 2733
      * @throws ReflectionException
@@ -3759,7 +3761,7 @@  discard block
 block discarded – undo
3759 3761
      * We should use default where conditions on related models when they requested to use default where conditions
3760 3762
      * on all models, or specifically just on other related models
3761 3763
      *
3762
-     * @param      $default_where_conditions_value
3764
+     * @param      string $default_where_conditions_value
3763 3765
      * @param bool $for_this_model false means this is for OTHER related models
3764 3766
      * @return bool
3765 3767
      */
@@ -3799,7 +3801,7 @@  discard block
 block discarded – undo
3799 3801
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3800 3802
      * on this model or others
3801 3803
      *
3802
-     * @param      $default_where_conditions_value
3804
+     * @param      string $default_where_conditions_value
3803 3805
      * @param bool $for_this_model false means this is for OTHER related models
3804 3806
      * @return bool
3805 3807
      */
@@ -4988,7 +4990,7 @@  discard block
 block discarded – undo
4988 4990
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4989 4991
      * Eg, on EE_Answer that would be ANS_ID field object
4990 4992
      *
4991
-     * @param $field_obj
4993
+     * @param EE_Model_Field_Base $field_obj
4992 4994
      * @return boolean
4993 4995
      */
4994 4996
     public function is_primary_key_field($field_obj)
@@ -5798,7 +5800,7 @@  discard block
 block discarded – undo
5798 5800
     /**
5799 5801
      * Read comments for assume_values_already_prepared_by_model_object()
5800 5802
      *
5801
-     * @return int
5803
+     * @return boolean
5802 5804
      */
5803 5805
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5804 5806
     {
@@ -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   +6547 added lines, -6547 removed lines patch added patch discarded remove patch
@@ -37,6553 +37,6553 @@
 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 null $timezone
565
-     * @throws EE_Error
566
-     */
567
-    protected function __construct($timezone = null)
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 blogid 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 ($this->_cap_restriction_generators !== false) {
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 there are cap restriction generators, use them to make the default cap restrictions
689
-        if ($this->_cap_restriction_generators !== false) {
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 = null)
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
-        // we might have a timezone set, let set_timezone decide what to do with it
764
-        static::$_instance->set_timezone($timezone);
765
-        // Espresso_model object
766
-        return static::$_instance;
767
-    }
768
-
769
-
770
-    /**
771
-     * resets the model and returns it
772
-     *
773
-     * @param null | string $timezone
774
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
775
-     * all its properties reset; if it wasn't instantiated, returns null)
776
-     * @throws EE_Error
777
-     * @throws ReflectionException
778
-     * @throws InvalidArgumentException
779
-     * @throws InvalidDataTypeException
780
-     * @throws InvalidInterfaceException
781
-     */
782
-    public static function reset($timezone = null)
783
-    {
784
-        if (static::$_instance instanceof EEM_Base) {
785
-            // let's try to NOT swap out the current instance for a new one
786
-            // because if someone has a reference to it, we can't remove their reference
787
-            // so it's best to keep using the same reference, but change the original object
788
-            // reset all its properties to their original values as defined in the class
789
-            $r                 = new ReflectionClass(get_class(static::$_instance));
790
-            $static_properties = $r->getStaticProperties();
791
-            foreach ($r->getDefaultProperties() as $property => $value) {
792
-                // don't set instance to null like it was originally,
793
-                // but it's static anyways, and we're ignoring static properties (for now at least)
794
-                if (! isset($static_properties[ $property ])) {
795
-                    static::$_instance->{$property} = $value;
796
-                }
797
-            }
798
-            // and then directly call its constructor again, like we would if we were creating a new one
799
-            static::$_instance->__construct(
800
-                $timezone,
801
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
802
-            );
803
-            return self::instance();
804
-        }
805
-        return null;
806
-    }
807
-
808
-
809
-    /**
810
-     * @return LoaderInterface
811
-     * @throws InvalidArgumentException
812
-     * @throws InvalidDataTypeException
813
-     * @throws InvalidInterfaceException
814
-     */
815
-    private static function getLoader()
816
-    {
817
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
818
-            EEM_Base::$loader = LoaderFactory::getLoader();
819
-        }
820
-        return EEM_Base::$loader;
821
-    }
822
-
823
-
824
-    /**
825
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
826
-     *
827
-     * @param boolean $translated return localized strings or JUST the array.
828
-     * @return array
829
-     * @throws EE_Error
830
-     * @throws InvalidArgumentException
831
-     * @throws InvalidDataTypeException
832
-     * @throws InvalidInterfaceException
833
-     * @throws ReflectionException
834
-     */
835
-    public function status_array($translated = false)
836
-    {
837
-        if (! array_key_exists('Status', $this->_model_relations)) {
838
-            return [];
839
-        }
840
-        $model_name   = $this->get_this_model_name();
841
-        $status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
842
-        $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
843
-        $status_array = [];
844
-        foreach ($stati as $status) {
845
-            $status_array[ $status->ID() ] = $status->get('STS_code');
846
-        }
847
-        return $translated
848
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
849
-            : $status_array;
850
-    }
851
-
852
-
853
-    /**
854
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
855
-     *
856
-     * @param array $query_params             see github link below for more info
857
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
858
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
859
-     *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
860
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
861
-     *                                        EEM_Transaction::instance()->get_all( array( array(
862
-     *                                        'OR'=>array(
863
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
864
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
865
-     *                                        )
866
-     *                                        ),
867
-     *                                        'limit'=>10,
868
-     *                                        'group_by'=>'TXN_ID'
869
-     *                                        ));
870
-     *                                        get all the answers to the question titled "shirt size" for event with id
871
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
872
-     *                                        'Question.QST_display_text'=>'shirt size',
873
-     *                                        'Registration.Event.EVT_ID'=>12
874
-     *                                        ),
875
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
876
-     *                                        ));
877
-     * @throws EE_Error
878
-     * @throws ReflectionException
879
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
880
-     *                                        or if you have the development copy of EE you can view this at the path:
881
-     *                                        /docs/G--Model-System/model-query-params.md
882
-     */
883
-    public function get_all($query_params = [])
884
-    {
885
-        if (
886
-            isset($query_params['limit'])
887
-            && ! isset($query_params['group_by'])
888
-        ) {
889
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
890
-        }
891
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params));
892
-    }
893
-
894
-
895
-    /**
896
-     * Modifies the query parameters so we only get back model objects
897
-     * that "belong" to the current user
898
-     *
899
-     * @param array $query_params see github link below for more info
900
-     * @return array
901
-     * @throws ReflectionException
902
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
903
-     */
904
-    public function alter_query_params_to_only_include_mine($query_params = [])
905
-    {
906
-        $wp_user_field_name = $this->wp_user_field_name();
907
-        if ($wp_user_field_name) {
908
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
909
-        }
910
-        return $query_params;
911
-    }
912
-
913
-
914
-    /**
915
-     * Returns the name of the field's name that points to the WP_User table
916
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
917
-     * foreign key to the WP_User table)
918
-     *
919
-     * @return string|boolean string on success, boolean false when there is no
920
-     * foreign key to the WP_User table
921
-     * @throws ReflectionException
922
-     */
923
-    public function wp_user_field_name()
924
-    {
925
-        try {
926
-            if (! empty($this->_model_chain_to_wp_user)) {
927
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
928
-                $last_model_name              = end($models_to_follow_to_wp_users);
929
-                $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
930
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
931
-            } else {
932
-                $model_with_fk_to_wp_users = $this;
933
-                $model_chain_to_wp_user    = '';
934
-            }
935
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
936
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
937
-        } catch (EE_Error $e) {
938
-            return false;
939
-        }
940
-    }
941
-
942
-
943
-    /**
944
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
945
-     * (or transiently-related model) has a foreign key to the wp_users table;
946
-     * useful for finding if model objects of this type are 'owned' by the current user.
947
-     * This is an empty string when the foreign key is on this model and when it isn't,
948
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
949
-     * (or transiently-related model)
950
-     *
951
-     * @return string
952
-     */
953
-    public function model_chain_to_wp_user()
954
-    {
955
-        return $this->_model_chain_to_wp_user;
956
-    }
957
-
958
-
959
-    /**
960
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
961
-     * like how registrations don't have a foreign key to wp_users, but the
962
-     * events they are for are), or is unrelated to wp users.
963
-     * generally available
964
-     *
965
-     * @return boolean
966
-     */
967
-    public function is_owned()
968
-    {
969
-        if ($this->model_chain_to_wp_user()) {
970
-            return true;
971
-        }
972
-        try {
973
-            $this->get_foreign_key_to('WP_User');
974
-            return true;
975
-        } catch (EE_Error $e) {
976
-            return false;
977
-        }
978
-    }
979
-
980
-
981
-    /**
982
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
983
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
984
-     * the model)
985
-     *
986
-     * @param array  $query_params
987
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
-     *                                  fields on the model, and the models we joined to in the query. However, you can
990
-     *                                  override this and set the select to "*", or a specific column name, like
991
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
-     *                                  the aliases used to refer to this selection, and values are to be
994
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
-     * @throws EE_Error
998
-     * @throws InvalidArgumentException
999
-     * @throws ReflectionException
1000
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1001
-     */
1002
-    protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1003
-    {
1004
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1005
-        $model_query_info         = $this->_create_model_query_info_carrier($query_params);
1006
-        $select_expressions       = $columns_to_select === null
1007
-            ? $this->_construct_default_select_sql($model_query_info)
1008
-            : '';
1009
-        if ($this->_custom_selections instanceof CustomSelects) {
1010
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1011
-            $select_expressions .= $select_expressions
1012
-                ? ', ' . $custom_expressions
1013
-                : $custom_expressions;
1014
-        }
1015
-
1016
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1017
-        return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1023
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1024
-     * method of including extra select information.
1025
-     *
1026
-     * @param array             $query_params
1027
-     * @param null|array|string $columns_to_select
1028
-     * @return null|CustomSelects
1029
-     * @throws InvalidArgumentException
1030
-     */
1031
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1032
-    {
1033
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1034
-            return null;
1035
-        }
1036
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1037
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1038
-        return new CustomSelects($selects);
1039
-    }
1040
-
1041
-
1042
-    /**
1043
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1044
-     * but you can use the model query params to more easily
1045
-     * take care of joins, field preparation etc.
1046
-     *
1047
-     * @param array  $query_params
1048
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1049
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1050
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1051
-     *                                  override this and set the select to "*", or a specific column name, like
1052
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1053
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1054
-     *                                  the aliases used to refer to this selection, and values are to be
1055
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1056
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1057
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1058
-     * @throws EE_Error
1059
-     * @throws ReflectionException
1060
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1061
-     */
1062
-    public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1063
-    {
1064
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1065
-    }
1066
-
1067
-
1068
-    /**
1069
-     * For creating a custom select statement
1070
-     *
1071
-     * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1072
-     *                                        or an array where keys are aliases, and values are arrays where 0=>the
1073
-     *                                        selection SQL, and 1=>is the datatype
1074
-     * @return string
1075
-     * @throws EE_Error
1076
-     */
1077
-    private function _construct_select_from_input($columns_to_select)
1078
-    {
1079
-        if (is_array($columns_to_select)) {
1080
-            $select_sql_array = [];
1081
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083
-                    throw new EE_Error(
1084
-                        sprintf(
1085
-                            esc_html__(
1086
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1087
-                                'event_espresso'
1088
-                            ),
1089
-                            $selection_and_datatype,
1090
-                            $alias
1091
-                        )
1092
-                    );
1093
-                }
1094
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1095
-                    throw new EE_Error(
1096
-                        sprintf(
1097
-                            esc_html__(
1098
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1099
-                                'event_espresso'
1100
-                            ),
1101
-                            $selection_and_datatype[1],
1102
-                            $selection_and_datatype[0],
1103
-                            $alias,
1104
-                            implode(', ', $this->_valid_wpdb_data_types)
1105
-                        )
1106
-                    );
1107
-                }
1108
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1109
-            }
1110
-            $columns_to_select_string = implode(', ', $select_sql_array);
1111
-        } else {
1112
-            $columns_to_select_string = $columns_to_select;
1113
-        }
1114
-        return $columns_to_select_string;
1115
-    }
1116
-
1117
-
1118
-    /**
1119
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1120
-     *
1121
-     * @return string
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function primary_key_name()
1125
-    {
1126
-        return $this->get_primary_key_field()->get_name();
1127
-    }
1128
-
1129
-
1130
-    /**
1131
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1132
-     * If there is no primary key on this model, $id is treated as primary key string
1133
-     *
1134
-     * @param mixed $id int or string, depending on the type of the model's primary key
1135
-     * @return EE_Base_Class
1136
-     * @throws EE_Error
1137
-     * @throws ReflectionException
1138
-     */
1139
-    public function get_one_by_ID($id)
1140
-    {
1141
-        if ($this->get_from_entity_map($id)) {
1142
-            return $this->get_from_entity_map($id);
1143
-        }
1144
-        return $this->get_one(
1145
-            $this->alter_query_params_to_restrict_by_ID(
1146
-                $id,
1147
-                ['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1148
-            )
1149
-        );
1150
-    }
1151
-
1152
-
1153
-    /**
1154
-     * Alters query parameters to only get items with this ID are returned.
1155
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1156
-     * or could just be a simple primary key ID
1157
-     *
1158
-     * @param int   $id
1159
-     * @param array $query_params see github link below for more info
1160
-     * @return array of normal query params,
1161
-     * @throws EE_Error
1162
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1163
-     */
1164
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1165
-    {
1166
-        if (! isset($query_params[0])) {
1167
-            $query_params[0] = [];
1168
-        }
1169
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1170
-        if ($conditions_from_id === null) {
1171
-            $query_params[0][ $this->primary_key_name() ] = $id;
1172
-        } else {
1173
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1174
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1175
-        }
1176
-        return $query_params;
1177
-    }
1178
-
1179
-
1180
-    /**
1181
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1182
-     * array. If no item is found, null is returned.
1183
-     *
1184
-     * @param array $query_params like EEM_Base's $query_params variable.
1185
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1186
-     * @throws EE_Error
1187
-     * @throws ReflectionException
1188
-     */
1189
-    public function get_one($query_params = [])
1190
-    {
1191
-        if (! is_array($query_params)) {
1192
-            EE_Error::doing_it_wrong(
1193
-                'EEM_Base::get_one',
1194
-                sprintf(
1195
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1196
-                    gettype($query_params)
1197
-                ),
1198
-                '4.6.0'
1199
-            );
1200
-            $query_params = [];
1201
-        }
1202
-        $query_params['limit'] = 1;
1203
-        $items                 = $this->get_all($query_params);
1204
-        if (empty($items)) {
1205
-            return null;
1206
-        }
1207
-        return array_shift($items);
1208
-    }
1209
-
1210
-
1211
-    /**
1212
-     * Returns the next x number of items in sequence from the given value as
1213
-     * found in the database matching the given query conditions.
1214
-     *
1215
-     * @param mixed $current_field_value    Value used for the reference point.
1216
-     * @param null  $field_to_order_by      What field is used for the
1217
-     *                                      reference point.
1218
-     * @param int   $limit                  How many to return.
1219
-     * @param array $query_params           Extra conditions on the query.
1220
-     * @param null  $columns_to_select      If left null, then an array of
1221
-     *                                      EE_Base_Class objects is returned,
1222
-     *                                      otherwise you can indicate just the
1223
-     *                                      columns you want returned.
1224
-     * @return EE_Base_Class[]|array
1225
-     * @throws EE_Error
1226
-     * @throws ReflectionException
1227
-     */
1228
-    public function next_x(
1229
-        $current_field_value,
1230
-        $field_to_order_by = null,
1231
-        $limit = 1,
1232
-        $query_params = [],
1233
-        $columns_to_select = null
1234
-    ) {
1235
-        return $this->_get_consecutive(
1236
-            $current_field_value,
1237
-            '>',
1238
-            $field_to_order_by,
1239
-            $limit,
1240
-            $query_params,
1241
-            $columns_to_select
1242
-        );
1243
-    }
1244
-
1245
-
1246
-    /**
1247
-     * Returns the previous x number of items in sequence from the given value
1248
-     * as found in the database matching the given query conditions.
1249
-     *
1250
-     * @param mixed $current_field_value    Value used for the reference point.
1251
-     * @param null  $field_to_order_by      What field is used for the
1252
-     *                                      reference point.
1253
-     * @param int   $limit                  How many to return.
1254
-     * @param array $query_params           Extra conditions on the query.
1255
-     * @param null  $columns_to_select      If left null, then an array of
1256
-     *                                      EE_Base_Class objects is returned,
1257
-     *                                      otherwise you can indicate just the
1258
-     *                                      columns you want returned.
1259
-     * @return EE_Base_Class[]|array
1260
-     * @throws EE_Error
1261
-     * @throws ReflectionException
1262
-     */
1263
-    public function previous_x(
1264
-        $current_field_value,
1265
-        $field_to_order_by = null,
1266
-        $limit = 1,
1267
-        $query_params = [],
1268
-        $columns_to_select = null
1269
-    ) {
1270
-        return $this->_get_consecutive(
1271
-            $current_field_value,
1272
-            '<',
1273
-            $field_to_order_by,
1274
-            $limit,
1275
-            $query_params,
1276
-            $columns_to_select
1277
-        );
1278
-    }
1279
-
1280
-
1281
-    /**
1282
-     * Returns the next item in sequence from the given value as found in the
1283
-     * database matching the given query conditions.
1284
-     *
1285
-     * @param mixed $current_field_value    Value used for the reference point.
1286
-     * @param null  $field_to_order_by      What field is used for the
1287
-     *                                      reference point.
1288
-     * @param array $query_params           Extra conditions on the query.
1289
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1290
-     *                                      object is returned, otherwise you
1291
-     *                                      can indicate just the columns you
1292
-     *                                      want and a single array indexed by
1293
-     *                                      the columns will be returned.
1294
-     * @return EE_Base_Class|null|array()
1295
-     * @throws EE_Error
1296
-     * @throws ReflectionException
1297
-     */
1298
-    public function next(
1299
-        $current_field_value,
1300
-        $field_to_order_by = null,
1301
-        $query_params = [],
1302
-        $columns_to_select = null
1303
-    ) {
1304
-        $results = $this->_get_consecutive(
1305
-            $current_field_value,
1306
-            '>',
1307
-            $field_to_order_by,
1308
-            1,
1309
-            $query_params,
1310
-            $columns_to_select
1311
-        );
1312
-        return empty($results) ? null : reset($results);
1313
-    }
1314
-
1315
-
1316
-    /**
1317
-     * Returns the previous item in sequence from the given value as found in
1318
-     * the database matching the given query conditions.
1319
-     *
1320
-     * @param mixed $current_field_value    Value used for the reference point.
1321
-     * @param null  $field_to_order_by      What field is used for the
1322
-     *                                      reference point.
1323
-     * @param array $query_params           Extra conditions on the query.
1324
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1325
-     *                                      object is returned, otherwise you
1326
-     *                                      can indicate just the columns you
1327
-     *                                      want and a single array indexed by
1328
-     *                                      the columns will be returned.
1329
-     * @return EE_Base_Class|null|array()
1330
-     * @throws EE_Error
1331
-     * @throws ReflectionException
1332
-     */
1333
-    public function previous(
1334
-        $current_field_value,
1335
-        $field_to_order_by = null,
1336
-        $query_params = [],
1337
-        $columns_to_select = null
1338
-    ) {
1339
-        $results = $this->_get_consecutive(
1340
-            $current_field_value,
1341
-            '<',
1342
-            $field_to_order_by,
1343
-            1,
1344
-            $query_params,
1345
-            $columns_to_select
1346
-        );
1347
-        return empty($results) ? null : reset($results);
1348
-    }
1349
-
1350
-
1351
-    /**
1352
-     * Returns the a consecutive number of items in sequence from the given
1353
-     * value as found in the database matching the given query conditions.
1354
-     *
1355
-     * @param mixed  $current_field_value   Value used for the reference point.
1356
-     * @param string $operand               What operand is used for the sequence.
1357
-     * @param string $field_to_order_by     What field is used for the reference point.
1358
-     * @param int    $limit                 How many to return.
1359
-     * @param array  $query_params          Extra conditions on the query.
1360
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1361
-     *                                      otherwise you can indicate just the columns you want returned.
1362
-     * @return EE_Base_Class[]|array
1363
-     * @throws EE_Error
1364
-     * @throws ReflectionException
1365
-     */
1366
-    protected function _get_consecutive(
1367
-        $current_field_value,
1368
-        $operand = '>',
1369
-        $field_to_order_by = null,
1370
-        $limit = 1,
1371
-        $query_params = [],
1372
-        $columns_to_select = null
1373
-    ) {
1374
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1375
-        if (empty($field_to_order_by)) {
1376
-            if ($this->has_primary_key_field()) {
1377
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1378
-            } else {
1379
-                if (WP_DEBUG) {
1380
-                    throw new EE_Error(
1381
-                        esc_html__(
1382
-                            '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).',
1383
-                            'event_espresso'
1384
-                        )
1385
-                    );
1386
-                }
1387
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1388
-                return [];
1389
-            }
1390
-        }
1391
-        if (! is_array($query_params)) {
1392
-            EE_Error::doing_it_wrong(
1393
-                'EEM_Base::_get_consecutive',
1394
-                sprintf(
1395
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1396
-                    gettype($query_params)
1397
-                ),
1398
-                '4.6.0'
1399
-            );
1400
-            $query_params = [];
1401
-        }
1402
-        // let's add the where query param for consecutive look up.
1403
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1404
-        $query_params['limit']                 = $limit;
1405
-        // set direction
1406
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1407
-        $query_params['order_by'] = $operand === '>'
1408
-            ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1409
-            : [$field_to_order_by => 'DESC'] + $incoming_orderby;
1410
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1411
-        if (empty($columns_to_select)) {
1412
-            return $this->get_all($query_params);
1413
-        }
1414
-        // getting just the fields
1415
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1416
-    }
1417
-
1418
-
1419
-    /**
1420
-     * This sets the _timezone property after model object has been instantiated.
1421
-     *
1422
-     * @param string|null $timezone valid PHP DateTimeZone timezone string
1423
-     */
1424
-    public function set_timezone($timezone)
1425
-    {
1426
-        // don't set the timezone if the incoming value is the same
1427
-        if (! empty($timezone) && $timezone === $this->_timezone) {
1428
-            return;
1429
-        }
1430
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
1431
-        // note we need to loop through relations and set the timezone on those objects as well.
1432
-        foreach ($this->_model_relations as $relation) {
1433
-            $relation->set_timezone($this->_timezone);
1434
-        }
1435
-        // and finally we do the same for any datetime fields
1436
-        foreach ($this->_fields as $field) {
1437
-            if ($field instanceof EE_Datetime_Field) {
1438
-                $field->set_timezone($this->_timezone);
1439
-            }
1440
-        }
1441
-    }
1442
-
1443
-
1444
-    /**
1445
-     * This just returns whatever is set for the current timezone.
1446
-     *
1447
-     * @access public
1448
-     * @return string
1449
-     */
1450
-    public function get_timezone()
1451
-    {
1452
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1453
-        if (empty($this->_timezone)) {
1454
-            foreach ($this->_fields as $field) {
1455
-                if ($field instanceof EE_Datetime_Field) {
1456
-                    $this->set_timezone($field->get_timezone());
1457
-                    break;
1458
-                }
1459
-            }
1460
-        }
1461
-        // if timezone STILL empty then return the default timezone for the site.
1462
-        if (empty($this->_timezone)) {
1463
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1464
-        }
1465
-        return $this->_timezone;
1466
-    }
1467
-
1468
-
1469
-    /**
1470
-     * This returns the date formats set for the given field name and also ensures that
1471
-     * $this->_timezone property is set correctly.
1472
-     *
1473
-     * @param string $field_name The name of the field the formats are being retrieved for.
1474
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1475
-     * @return array formats in an array with the date format first, and the time format last.
1476
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1477
-     * @since 4.6.x
1478
-     */
1479
-    public function get_formats_for($field_name, $pretty = false)
1480
-    {
1481
-        $field_settings = $this->field_settings_for($field_name);
1482
-        // if not a valid EE_Datetime_Field then throw error
1483
-        if (! $field_settings instanceof EE_Datetime_Field) {
1484
-            throw new EE_Error(
1485
-                sprintf(
1486
-                    esc_html__(
1487
-                        '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.',
1488
-                        'event_espresso'
1489
-                    ),
1490
-                    $field_name
1491
-                )
1492
-            );
1493
-        }
1494
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1495
-        // the field.
1496
-        $this->_timezone = $field_settings->get_timezone();
1497
-        return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1498
-    }
1499
-
1500
-
1501
-    /**
1502
-     * This returns the current time in a format setup for a query on this model.
1503
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1504
-     * it will return:
1505
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1506
-     *  NOW
1507
-     *  - or a unix timestamp (equivalent to time())
1508
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1509
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1510
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1511
-     *
1512
-     * @param string $field_name       The field the current time is needed for.
1513
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1514
-     *                                 formatted string matching the set format for the field in the set timezone will
1515
-     *                                 be returned.
1516
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1517
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1518
-     *                                 exception is triggered.
1519
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1520
-     * @throws Exception
1521
-     * @since 4.6.x
1522
-     */
1523
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1524
-    {
1525
-        $formats  = $this->get_formats_for($field_name);
1526
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1527
-        if ($timestamp) {
1528
-            return $DateTime->format('U');
1529
-        }
1530
-        // not returning timestamp, so return formatted string in timezone.
1531
-        switch ($what) {
1532
-            case 'time':
1533
-                return $DateTime->format($formats[1]);
1534
-            case 'date':
1535
-                return $DateTime->format($formats[0]);
1536
-            default:
1537
-                return $DateTime->format(implode(' ', $formats));
1538
-        }
1539
-    }
1540
-
1541
-
1542
-    /**
1543
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1544
-     * for the model are.  Returns a DateTime object.
1545
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1546
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1547
-     * ignored.
1548
-     *
1549
-     * @param string $field_name      The field being setup.
1550
-     * @param string $timestring      The date time string being used.
1551
-     * @param string $incoming_format The format for the time string.
1552
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1553
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1554
-     *                                format is
1555
-     *                                'U', this is ignored.
1556
-     * @return DateTime
1557
-     * @throws EE_Error
1558
-     */
1559
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1560
-    {
1561
-        // just using this to ensure the timezone is set correctly internally
1562
-        $this->get_formats_for($field_name);
1563
-        // load EEH_DTT_Helper
1564
-        $set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1565
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1566
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1567
-        return DbSafeDateTime::createFromDateTime($incomingDateTime);
1568
-    }
1569
-
1570
-
1571
-    /**
1572
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1573
-     *
1574
-     * @return EE_Table_Base[]
1575
-     */
1576
-    public function get_tables()
1577
-    {
1578
-        return $this->_tables;
1579
-    }
1580
-
1581
-
1582
-    /**
1583
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1584
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1585
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1586
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1587
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1588
-     * model object with EVT_ID = 1
1589
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1590
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1591
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1592
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1593
-     * are not specified)
1594
-     *
1595
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1596
-     *                                         columns!), values are strings, integers, floats, and maybe arrays if
1597
-     *                                         they
1598
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1599
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1600
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1601
-     *                                         ID=34, we'd use this method as follows:
1602
-     *                                         EEM_Transaction::instance()->update(
1603
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1604
-     *                                         array(array('TXN_ID'=>34)));
1605
-     * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1606
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1607
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1608
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1609
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1610
-     *                                         TRUE, it is assumed that you've already called
1611
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1612
-     *                                         malicious javascript. However, if
1613
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1614
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1615
-     *                                         and every other field, before insertion. We provide this parameter
1616
-     *                                         because model objects perform their prepare_for_set function on all
1617
-     *                                         their values, and so don't need to be called again (and in many cases,
1618
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1619
-     *                                         prepare_for_set method...)
1620
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1621
-     *                                         in this model's entity map according to $fields_n_values that match
1622
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1623
-     *                                         by setting this to FALSE, but be aware that model objects being used
1624
-     *                                         could get out-of-sync with the database
1625
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1626
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1627
-     *                                         bad)
1628
-     * @throws EE_Error
1629
-     * @throws ReflectionException
1630
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1631
-     */
1632
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1633
-    {
1634
-        if (! is_array($query_params)) {
1635
-            EE_Error::doing_it_wrong(
1636
-                'EEM_Base::update',
1637
-                sprintf(
1638
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1639
-                    gettype($query_params)
1640
-                ),
1641
-                '4.6.0'
1642
-            );
1643
-            $query_params = [];
1644
-        }
1645
-        /**
1646
-         * Action called before a model update call has been made.
1647
-         *
1648
-         * @param EEM_Base $model
1649
-         * @param array    $fields_n_values the updated fields and their new values
1650
-         * @param array    $query_params
1651
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1652
-         */
1653
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1654
-        /**
1655
-         * Filters the fields about to be updated given the query parameters. You can provide the
1656
-         * $query_params to $this->get_all() to find exactly which records will be updated
1657
-         *
1658
-         * @param array    $fields_n_values fields and their new values
1659
-         * @param EEM_Base $model           the model being queried
1660
-         * @param array    $query_params
1661
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1662
-         */
1663
-        $fields_n_values = (array)apply_filters(
1664
-            'FHEE__EEM_Base__update__fields_n_values',
1665
-            $fields_n_values,
1666
-            $this,
1667
-            $query_params
1668
-        );
1669
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1670
-        // to do that, for each table, verify that it's PK isn't null.
1671
-        $tables = $this->get_tables();
1672
-        // 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
1673
-        // NOTE: we should make this code more efficient by NOT querying twice
1674
-        // before the real update, but that needs to first go through ALPHA testing
1675
-        // as it's dangerous. says Mike August 8 2014
1676
-        // we want to make sure the default_where strategy is ignored
1677
-        $this->_ignore_where_strategy = true;
1678
-        $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1679
-        foreach ($wpdb_select_results as $wpdb_result) {
1680
-            // type cast stdClass as array
1681
-            $wpdb_result = (array)$wpdb_result;
1682
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1683
-            if ($this->has_primary_key_field()) {
1684
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1685
-            } else {
1686
-                // 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)
1687
-                $main_table_pk_value = null;
1688
-            }
1689
-            // 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
1690
-            // 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
1691
-            if (count($tables) > 1) {
1692
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1693
-                // in that table, and so we'll want to insert one
1694
-                foreach ($tables as $table_obj) {
1695
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1696
-                    // if there is no private key for this table on the results, it means there's no entry
1697
-                    // in this table, right? so insert a row in the current table, using any fields available
1698
-                    if (
1699
-                    ! (array_key_exists($this_table_pk_column, $wpdb_result)
1700
-                       && $wpdb_result[ $this_table_pk_column ])
1701
-                    ) {
1702
-                        $success = $this->_insert_into_specific_table(
1703
-                            $table_obj,
1704
-                            $fields_n_values,
1705
-                            $main_table_pk_value
1706
-                        );
1707
-                        // if we died here, report the error
1708
-                        if (! $success) {
1709
-                            return false;
1710
-                        }
1711
-                    }
1712
-                }
1713
-            }
1714
-            //              //and now check that if we have cached any models by that ID on the model, that
1715
-            //              //they also get updated properly
1716
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1717
-            //              if( $model_object ){
1718
-            //                  foreach( $fields_n_values as $field => $value ){
1719
-            //                      $model_object->set($field, $value);
1720
-            // let's make sure default_where strategy is followed now
1721
-            $this->_ignore_where_strategy = false;
1722
-        }
1723
-        // if we want to keep model objects in sync, AND
1724
-        // if this wasn't called from a model object (to update itself)
1725
-        // then we want to make sure we keep all the existing
1726
-        // model objects in sync with the db
1727
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1728
-            if ($this->has_primary_key_field()) {
1729
-                $model_objs_affected_ids = $this->get_col($query_params);
1730
-            } else {
1731
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1732
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1733
-                $model_objs_affected_ids     = [];
1734
-                foreach ($models_affected_key_columns as $row) {
1735
-                    $combined_index_key                             = $this->get_index_primary_key_string($row);
1736
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1737
-                }
1738
-            }
1739
-            if (! $model_objs_affected_ids) {
1740
-                // wait wait wait- if nothing was affected let's stop here
1741
-                return 0;
1742
-            }
1743
-            foreach ($model_objs_affected_ids as $id) {
1744
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1745
-                if ($model_obj_in_entity_map) {
1746
-                    foreach ($fields_n_values as $field => $new_value) {
1747
-                        $model_obj_in_entity_map->set($field, $new_value);
1748
-                    }
1749
-                }
1750
-            }
1751
-            // if there is a primary key on this model, we can now do a slight optimization
1752
-            if ($this->has_primary_key_field()) {
1753
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1754
-                $query_params = [
1755
-                    [$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1756
-                    'limit'                    => count($model_objs_affected_ids),
1757
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1758
-                ];
1759
-            }
1760
-        }
1761
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1762
-        $SQL              = "UPDATE "
1763
-                            . $model_query_info->get_full_join_sql()
1764
-                            . " SET "
1765
-                            . $this->_construct_update_sql($fields_n_values)
1766
-                            . $model_query_info->get_where_sql(
1767
-            );// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1768
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1769
-        /**
1770
-         * Action called after a model update call has been made.
1771
-         *
1772
-         * @param EEM_Base $model
1773
-         * @param array    $fields_n_values the updated fields and their new values
1774
-         * @param array    $query_params
1775
-         * @param int      $rows_affected
1776
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1777
-         */
1778
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1779
-        return $rows_affected;// how many supposedly got updated
1780
-    }
1781
-
1782
-
1783
-    /**
1784
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1785
-     * are teh values of the field specified (or by default the primary key field)
1786
-     * that matched the query params. Note that you should pass the name of the
1787
-     * model FIELD, not the database table's column name.
1788
-     *
1789
-     * @param array  $query_params
1790
-     * @param string $field_to_select
1791
-     * @return array just like $wpdb->get_col()
1792
-     * @throws EE_Error
1793
-     * @throws ReflectionException
1794
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1795
-     */
1796
-    public function get_col($query_params = [], $field_to_select = null)
1797
-    {
1798
-        if ($field_to_select) {
1799
-            $field = $this->field_settings_for($field_to_select);
1800
-        } elseif ($this->has_primary_key_field()) {
1801
-            $field = $this->get_primary_key_field();
1802
-        } else {
1803
-            $field_settings = $this->field_settings();
1804
-            // no primary key, just grab the first column
1805
-            $field = reset($field_settings);
1806
-        }
1807
-        $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1808
-        $select_expressions = $field->get_qualified_column();
1809
-        $SQL                =
1810
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1811
-        return $this->_do_wpdb_query('get_col', [$SQL]);
1812
-    }
1813
-
1814
-
1815
-    /**
1816
-     * Returns a single column value for a single row from the database
1817
-     *
1818
-     * @param array  $query_params
1819
-     * @param string $field_to_select
1820
-     * @return string
1821
-     * @throws EE_Error
1822
-     * @throws ReflectionException
1823
-     * @see EEM_Base::get_col()
1824
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1825
-     */
1826
-    public function get_var($query_params = [], $field_to_select = null)
1827
-    {
1828
-        $query_params['limit'] = 1;
1829
-        $col                   = $this->get_col($query_params, $field_to_select);
1830
-        if (! empty($col)) {
1831
-            return reset($col);
1832
-        }
1833
-        return null;
1834
-    }
1835
-
1836
-
1837
-    /**
1838
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1839
-     * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1840
-     * injection, but currently no further filtering is done
1841
-     *
1842
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1843
-     *                               be updated to in the DB
1844
-     * @return string of SQL
1845
-     * @throws EE_Error
1846
-     * @global      $wpdb
1847
-     */
1848
-    public function _construct_update_sql($fields_n_values)
1849
-    {
1850
-        global $wpdb;
1851
-        $cols_n_values = [];
1852
-        foreach ($fields_n_values as $field_name => $value) {
1853
-            $field_obj = $this->field_settings_for($field_name);
1854
-            // if the value is NULL, we want to assign the value to that.
1855
-            // wpdb->prepare doesn't really handle that properly
1856
-            $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1857
-            $value_sql       = $prepared_value === null ? 'NULL'
1858
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1859
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1860
-        }
1861
-        return implode(",", $cols_n_values);
1862
-    }
1863
-
1864
-
1865
-    /**
1866
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1867
-     * Performs a HARD delete, meaning the database row should always be removed,
1868
-     * not just have a flag field on it switched
1869
-     * Wrapper for EEM_Base::delete_permanently()
1870
-     *
1871
-     * @param mixed   $id
1872
-     * @param boolean $allow_blocking
1873
-     * @return int the number of rows deleted
1874
-     * @throws EE_Error
1875
-     * @throws ReflectionException
1876
-     */
1877
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1878
-    {
1879
-        return $this->delete_permanently(
1880
-            [
1881
-                [$this->get_primary_key_field()->get_name() => $id],
1882
-                'limit' => 1,
1883
-            ],
1884
-            $allow_blocking
1885
-        );
1886
-    }
1887
-
1888
-
1889
-    /**
1890
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1891
-     * Wrapper for EEM_Base::delete()
1892
-     *
1893
-     * @param mixed   $id
1894
-     * @param boolean $allow_blocking
1895
-     * @return int the number of rows deleted
1896
-     * @throws EE_Error
1897
-     * @throws ReflectionException
1898
-     */
1899
-    public function delete_by_ID($id, $allow_blocking = true)
1900
-    {
1901
-        return $this->delete(
1902
-            [
1903
-                [$this->get_primary_key_field()->get_name() => $id],
1904
-                'limit' => 1,
1905
-            ],
1906
-            $allow_blocking
1907
-        );
1908
-    }
1909
-
1910
-
1911
-    /**
1912
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1913
-     * meaning if the model has a field that indicates its been "trashed" or
1914
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1915
-     *
1916
-     * @param array   $query_params
1917
-     * @param boolean $allow_blocking
1918
-     * @return int how many rows got deleted
1919
-     * @throws EE_Error
1920
-     * @throws ReflectionException
1921
-     * @see EEM_Base::delete_permanently
1922
-     */
1923
-    public function delete($query_params, $allow_blocking = true)
1924
-    {
1925
-        return $this->delete_permanently($query_params, $allow_blocking);
1926
-    }
1927
-
1928
-
1929
-    /**
1930
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1931
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1932
-     * as archived, not actually deleted
1933
-     *
1934
-     * @param array   $query_params
1935
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1936
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1937
-     *                                deletes regardless of other objects which may depend on it. Its generally
1938
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1939
-     *                                DB
1940
-     * @return int how many rows got deleted
1941
-     * @throws EE_Error
1942
-     * @throws ReflectionException
1943
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1944
-     */
1945
-    public function delete_permanently($query_params, $allow_blocking = true)
1946
-    {
1947
-        /**
1948
-         * Action called just before performing a real deletion query. You can use the
1949
-         * model and its $query_params to find exactly which items will be deleted
1950
-         *
1951
-         * @param EEM_Base $model
1952
-         * @param array    $query_params
1953
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1954
-         *                                 to block (prevent) this deletion
1955
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1956
-         */
1957
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1958
-        // some MySQL databases may be running safe mode, which may restrict
1959
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1960
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1961
-        // to delete them
1962
-        $items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1963
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1964
-        $deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1965
-            $columns_and_ids_for_deleting
1966
-        );
1967
-        /**
1968
-         * Allows client code to act on the items being deleted before the query is actually executed.
1969
-         *
1970
-         * @param EEM_Base $this                            The model instance being acted on.
1971
-         * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1972
-         * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1973
-         * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1974
-         *                                                  derived from the incoming query parameters.
1975
-         * @see details on the structure of this array in the phpdocs
1976
-         *                                                  for the `_get_ids_for_delete_method`
1977
-         *
1978
-         */
1979
-        do_action(
1980
-            'AHEE__EEM_Base__delete__before_query',
1981
-            $this,
1982
-            $query_params,
1983
-            $allow_blocking,
1984
-            $columns_and_ids_for_deleting
1985
-        );
1986
-        if ($deletion_where_query_part) {
1987
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1988
-            $table_aliases    = array_keys($this->_tables);
1989
-            $SQL              = "DELETE "
1990
-                                . implode(", ", $table_aliases)
1991
-                                . " FROM "
1992
-                                . $model_query_info->get_full_join_sql()
1993
-                                . " WHERE "
1994
-                                . $deletion_where_query_part;
1995
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1996
-        } else {
1997
-            $rows_deleted = 0;
1998
-        }
1999
-
2000
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2001
-        // there was no error with the delete query.
2002
-        if (
2003
-            $this->has_primary_key_field()
2004
-            && $rows_deleted !== false
2005
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2006
-        ) {
2007
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2008
-            foreach ($ids_for_removal as $id) {
2009
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2010
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2011
-                }
2012
-            }
2013
-
2014
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2015
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2016
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2017
-            // (although it is possible).
2018
-            // Note this can be skipped by using the provided filter and returning false.
2019
-            if (
2020
-            apply_filters(
2021
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2022
-                ! $this instanceof EEM_Extra_Meta,
2023
-                $this
2024
-            )
2025
-            ) {
2026
-                EEM_Extra_Meta::instance()->delete_permanently(
2027
-                    [
2028
-                        0 => [
2029
-                            'EXM_type' => $this->get_this_model_name(),
2030
-                            'OBJ_ID'   => [
2031
-                                'IN',
2032
-                                $ids_for_removal,
2033
-                            ],
2034
-                        ],
2035
-                    ]
2036
-                );
2037
-            }
2038
-        }
2039
-
2040
-        /**
2041
-         * Action called just after performing a real deletion query. Although at this point the
2042
-         * items should have been deleted
2043
-         *
2044
-         * @param EEM_Base $model
2045
-         * @param array    $query_params
2046
-         * @param int      $rows_deleted
2047
-         * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2048
-         */
2049
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
-        return $rows_deleted;// how many supposedly got deleted
2051
-    }
2052
-
2053
-
2054
-    /**
2055
-     * Checks all the relations that throw error messages when there are blocking related objects
2056
-     * for related model objects. If there are any related model objects on those relations,
2057
-     * adds an EE_Error, and return true
2058
-     *
2059
-     * @param EE_Base_Class|int $this_model_obj_or_id
2060
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2061
-     *                                                 should be ignored when determining whether there are related
2062
-     *                                                 model objects which block this model object's deletion. Useful
2063
-     *                                                 if you know A is related to B and are considering deleting A,
2064
-     *                                                 but want to see if A has any other objects blocking its deletion
2065
-     *                                                 before removing the relation between A and B
2066
-     * @return boolean
2067
-     * @throws EE_Error
2068
-     * @throws ReflectionException
2069
-     */
2070
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2071
-    {
2072
-        // first, if $ignore_this_model_obj was supplied, get its model
2073
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2074
-            $ignored_model = $ignore_this_model_obj->get_model();
2075
-        } else {
2076
-            $ignored_model = null;
2077
-        }
2078
-        // now check all the relations of $this_model_obj_or_id and see if there
2079
-        // are any related model objects blocking it?
2080
-        $is_blocked = false;
2081
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2082
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2083
-                // if $ignore_this_model_obj was supplied, then for the query
2084
-                // on that model needs to be told to ignore $ignore_this_model_obj
2085
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2086
-                    $related_model_objects = $relation_obj->get_all_related(
2087
-                        $this_model_obj_or_id,
2088
-                        [
2089
-                            [
2090
-                                $ignored_model->get_primary_key_field()->get_name() => [
2091
-                                    '!=',
2092
-                                    $ignore_this_model_obj->ID(),
2093
-                                ],
2094
-                            ],
2095
-                        ]
2096
-                    );
2097
-                } else {
2098
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2099
-                }
2100
-                if ($related_model_objects) {
2101
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2102
-                    $is_blocked = true;
2103
-                }
2104
-            }
2105
-        }
2106
-        return $is_blocked;
2107
-    }
2108
-
2109
-
2110
-    /**
2111
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2112
-     *
2113
-     * @param array $row_results_for_deleting
2114
-     * @param bool  $allow_blocking
2115
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2116
-     *                              model DOES have a primary_key_field, then the array will be a simple single
2117
-     *                              dimension array where the key is the fully qualified primary key column and the
2118
-     *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2119
-     *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2120
-     *                              be a two dimensional array where each element is a group of columns and values that
2121
-     *                              get deleted. Example: array(
2122
-     *                              0 => array(
2123
-     *                              'Term_Relationship.object_id' => 1
2124
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2125
-     *                              ),
2126
-     *                              1 => array(
2127
-     *                              'Term_Relationship.object_id' => 1
2128
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2129
-     *                              )
2130
-     *                              )
2131
-     * @throws EE_Error
2132
-     * @throws ReflectionException
2133
-     */
2134
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2135
-    {
2136
-        $ids_to_delete_indexed_by_column = [];
2137
-        if ($this->has_primary_key_field()) {
2138
-            $primary_table                   = $this->_get_main_table();
2139
-            $ids_to_delete_indexed_by_column = $query = [];
2140
-            foreach ($row_results_for_deleting as $item_to_delete) {
2141
-                // before we mark this item for deletion,
2142
-                // make sure there's no related entities blocking its deletion (if we're checking)
2143
-                if (
2144
-                    $allow_blocking
2145
-                    && $this->delete_is_blocked_by_related_models(
2146
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2147
-                    )
2148
-                ) {
2149
-                    continue;
2150
-                }
2151
-                // primary table deletes
2152
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2153
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2155
-                }
2156
-            }
2157
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2158
-            $fields = $this->get_combined_primary_key_fields();
2159
-            foreach ($row_results_for_deleting as $item_to_delete) {
2160
-                $ids_to_delete_indexed_by_column_for_row = [];
2161
-                foreach ($fields as $cpk_field) {
2162
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2163
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2164
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2165
-                    }
2166
-                }
2167
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2168
-            }
2169
-        } else {
2170
-            // so there's no primary key and no combined key...
2171
-            // sorry, can't help you
2172
-            throw new EE_Error(
2173
-                sprintf(
2174
-                    esc_html__(
2175
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2176
-                        "event_espresso"
2177
-                    ),
2178
-                    get_class($this)
2179
-                )
2180
-            );
2181
-        }
2182
-        return $ids_to_delete_indexed_by_column;
2183
-    }
2184
-
2185
-
2186
-    /**
2187
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2188
-     * the corresponding query_part for the query performing the delete.
2189
-     *
2190
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2191
-     * @return string
2192
-     * @throws EE_Error
2193
-     */
2194
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2195
-    {
2196
-        $query_part = '';
2197
-        if (empty($ids_to_delete_indexed_by_column)) {
2198
-            return $query_part;
2199
-        } elseif ($this->has_primary_key_field()) {
2200
-            $query = [];
2201
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2202
-                // make sure we have unique $ids
2203
-                $ids     = array_unique($ids);
2204
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2205
-            }
2206
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2207
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2208
-            $ways_to_identify_a_row = [];
2209
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2210
-                $values_for_each_combined_primary_key_for_a_row = [];
2211
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2212
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2213
-                }
2214
-                $ways_to_identify_a_row[] = '('
2215
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2216
-                                            . ')';
2217
-            }
2218
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2219
-        }
2220
-        return $query_part;
2221
-    }
2222
-
2223
-
2224
-    /**
2225
-     * Gets the model field by the fully qualified name
2226
-     *
2227
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2228
-     * @return EE_Model_Field_Base
2229
-     * @throws EE_Error
2230
-     */
2231
-    public function get_field_by_column($qualified_column_name)
2232
-    {
2233
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2234
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2235
-                return $field_obj;
2236
-            }
2237
-        }
2238
-        throw new EE_Error(
2239
-            sprintf(
2240
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2241
-                $this->get_this_model_name(),
2242
-                $qualified_column_name
2243
-            )
2244
-        );
2245
-    }
2246
-
2247
-
2248
-    /**
2249
-     * Count all the rows that match criteria the model query params.
2250
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2251
-     * column
2252
-     *
2253
-     * @param array  $query_params
2254
-     * @param string $field_to_count field on model to count by (not column name)
2255
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2256
-     *                               that by the setting $distinct to TRUE;
2257
-     * @return int
2258
-     * @throws EE_Error
2259
-     * @throws ReflectionException
2260
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2261
-     */
2262
-    public function count($query_params = [], $field_to_count = null, $distinct = false)
2263
-    {
2264
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
-        if ($field_to_count) {
2266
-            $field_obj       = $this->field_settings_for($field_to_count);
2267
-            $column_to_count = $field_obj->get_qualified_column();
2268
-        } elseif ($this->has_primary_key_field()) {
2269
-            $pk_field_obj    = $this->get_primary_key_field();
2270
-            $column_to_count = $pk_field_obj->get_qualified_column();
2271
-        } else {
2272
-            // there's no primary key
2273
-            // if we're counting distinct items, and there's no primary key,
2274
-            // we need to list out the columns for distinction;
2275
-            // otherwise we can just use star
2276
-            if ($distinct) {
2277
-                $columns_to_use = [];
2278
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2279
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2280
-                }
2281
-                $column_to_count = implode(',', $columns_to_use);
2282
-            } else {
2283
-                $column_to_count = '*';
2284
-            }
2285
-        }
2286
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2287
-        $SQL             =
2288
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2290
-    }
2291
-
2292
-
2293
-    /**
2294
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2295
-     *
2296
-     * @param array  $query_params
2297
-     * @param string $field_to_sum name of field (array key in $_fields array)
2298
-     * @return float
2299
-     * @throws EE_Error
2300
-     * @throws ReflectionException
2301
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2302
-     */
2303
-    public function sum($query_params, $field_to_sum = null)
2304
-    {
2305
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
-        if ($field_to_sum) {
2307
-            $field_obj = $this->field_settings_for($field_to_sum);
2308
-        } else {
2309
-            $field_obj = $this->get_primary_key_field();
2310
-        }
2311
-        $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL             =
2313
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
-        $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315
-        $data_type       = $field_obj->get_wpdb_data_type();
2316
-        if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2318
-        }
2319
-        // must be %f
2320
-        return (float)$return_value;
2321
-    }
2322
-
2323
-
2324
-    /**
2325
-     * Just calls the specified method on $wpdb with the given arguments
2326
-     * Consolidates a little extra error handling code
2327
-     *
2328
-     * @param string $wpdb_method
2329
-     * @param array  $arguments_to_provide
2330
-     * @return mixed
2331
-     * @throws EE_Error
2332
-     * @global wpdb  $wpdb
2333
-     */
2334
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
-    {
2336
-        // if we're in maintenance mode level 2, DON'T run any queries
2337
-        // because level 2 indicates the database needs updating and
2338
-        // is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
-            throw new EE_Error(
2341
-                sprintf(
2342
-                    esc_html__(
2343
-                        "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.",
2344
-                        "event_espresso"
2345
-                    )
2346
-                )
2347
-            );
2348
-        }
2349
-        global $wpdb;
2350
-        if (! method_exists($wpdb, $wpdb_method)) {
2351
-            throw new EE_Error(
2352
-                sprintf(
2353
-                    esc_html__(
2354
-                        'There is no method named "%s" on Wordpress\' $wpdb object',
2355
-                        'event_espresso'
2356
-                    ),
2357
-                    $wpdb_method
2358
-                )
2359
-            );
2360
-        }
2361
-        $old_show_errors_value = $wpdb->show_errors;
2362
-        if (WP_DEBUG) {
2363
-            $wpdb->show_errors(false);
2364
-        }
2365
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2366
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2367
-        if (WP_DEBUG) {
2368
-            $wpdb->show_errors($old_show_errors_value);
2369
-            if (! empty($wpdb->last_error)) {
2370
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371
-            }
2372
-            if ($result === false) {
2373
-                throw new EE_Error(
2374
-                    sprintf(
2375
-                        esc_html__(
2376
-                            'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2377
-                            'event_espresso'
2378
-                        ),
2379
-                        $wpdb_method,
2380
-                        var_export($arguments_to_provide, true)
2381
-                    )
2382
-                );
2383
-            }
2384
-        } elseif ($result === false) {
2385
-            EE_Error::add_error(
2386
-                sprintf(
2387
-                    esc_html__(
2388
-                        '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"',
2389
-                        'event_espresso'
2390
-                    ),
2391
-                    $wpdb_method,
2392
-                    var_export($arguments_to_provide, true),
2393
-                    $wpdb->last_error
2394
-                ),
2395
-                __FILE__,
2396
-                __FUNCTION__,
2397
-                __LINE__
2398
-            );
2399
-        }
2400
-        return $result;
2401
-    }
2402
-
2403
-
2404
-    /**
2405
-     * Attempts to run the indicated WPDB method with the provided arguments,
2406
-     * and if there's an error tries to verify the DB is correct. Uses
2407
-     * the static property EEM_Base::$_db_verification_level to determine whether
2408
-     * we should try to fix the EE core db, the addons, or just give up
2409
-     *
2410
-     * @param string $wpdb_method
2411
-     * @param array  $arguments_to_provide
2412
-     * @return mixed
2413
-     * @throws EE_Error
2414
-     */
2415
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2416
-    {
2417
-        global $wpdb;
2418
-        $wpdb->last_error = null;
2419
-        $result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2420
-        // was there an error running the query? but we don't care on new activations
2421
-        // (we're going to setup the DB anyway on new activations)
2422
-        if (
2423
-            ($result === false || ! empty($wpdb->last_error))
2424
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2425
-        ) {
2426
-            switch (EEM_Base::$_db_verification_level) {
2427
-                case EEM_Base::db_verified_none:
2428
-                    // let's double-check core's DB
2429
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2430
-                    break;
2431
-                case EEM_Base::db_verified_core:
2432
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2433
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2434
-                    break;
2435
-                case EEM_Base::db_verified_addons:
2436
-                    // ummmm... you in trouble
2437
-                    return $result;
2438
-            }
2439
-            if (! empty($error_message)) {
2440
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441
-                trigger_error($error_message);
2442
-            }
2443
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2444
-        }
2445
-        return $result;
2446
-    }
2447
-
2448
-
2449
-    /**
2450
-     * Verifies the EE core database is up-to-date and records that we've done it on
2451
-     * EEM_Base::$_db_verification_level
2452
-     *
2453
-     * @param string $wpdb_method
2454
-     * @param array  $arguments_to_provide
2455
-     * @return string
2456
-     * @throws EE_Error
2457
-     */
2458
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2459
-    {
2460
-        global $wpdb;
2461
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2462
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2463
-        $error_message                    = sprintf(
2464
-            esc_html__(
2465
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2466
-                'event_espresso'
2467
-            ),
2468
-            $wpdb->last_error,
2469
-            $wpdb_method,
2470
-            wp_json_encode($arguments_to_provide)
2471
-        );
2472
-        EE_System::instance()->initialize_db_if_no_migrations_required();
2473
-        return $error_message;
2474
-    }
2475
-
2476
-
2477
-    /**
2478
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2479
-     * EEM_Base::$_db_verification_level
2480
-     *
2481
-     * @param $wpdb_method
2482
-     * @param $arguments_to_provide
2483
-     * @return string
2484
-     * @throws EE_Error
2485
-     */
2486
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2487
-    {
2488
-        global $wpdb;
2489
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2490
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2491
-        $error_message                    = sprintf(
2492
-            esc_html__(
2493
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2494
-                'event_espresso'
2495
-            ),
2496
-            $wpdb->last_error,
2497
-            $wpdb_method,
2498
-            wp_json_encode($arguments_to_provide)
2499
-        );
2500
-        EE_System::instance()->initialize_addons();
2501
-        return $error_message;
2502
-    }
2503
-
2504
-
2505
-    /**
2506
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2507
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2508
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2509
-     * ..."
2510
-     *
2511
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2512
-     * @return string
2513
-     */
2514
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515
-    {
2516
-        return " FROM " . $model_query_info->get_full_join_sql() .
2517
-               $model_query_info->get_where_sql() .
2518
-               $model_query_info->get_group_by_sql() .
2519
-               $model_query_info->get_having_sql() .
2520
-               $model_query_info->get_order_by_sql() .
2521
-               $model_query_info->get_limit_sql();
2522
-    }
2523
-
2524
-
2525
-    /**
2526
-     * Set to easily debug the next X queries ran from this model.
2527
-     *
2528
-     * @param int $count
2529
-     */
2530
-    public function show_next_x_db_queries($count = 1)
2531
-    {
2532
-        $this->_show_next_x_db_queries = $count;
2533
-    }
2534
-
2535
-
2536
-    /**
2537
-     * @param $sql_query
2538
-     */
2539
-    public function show_db_query_if_previously_requested($sql_query)
2540
-    {
2541
-        if ($this->_show_next_x_db_queries > 0) {
2542
-            echo $sql_query;
2543
-            $this->_show_next_x_db_queries--;
2544
-        }
2545
-    }
2546
-
2547
-
2548
-    /**
2549
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2550
-     * There are the 3 cases:
2551
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2552
-     * $otherModelObject has no ID, it is first saved.
2553
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2554
-     * has no ID, it is first saved.
2555
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2556
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2557
-     * join table
2558
-     *
2559
-     * @param EE_Base_Class                     /int $thisModelObject
2560
-     * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2561
-     * @param string $relationName                     , key in EEM_Base::_relations
2562
-     *                                                 an attendee to a group, you also want to specify which role they
2563
-     *                                                 will have in that group. So you would use this parameter to
2564
-     *                                                 specify array('role-column-name'=>'role-id')
2565
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2566
-     *                                                 to for relation to methods that allow you to further specify
2567
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2568
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2569
-     *                                                 because these will be inserted in any new rows created as well.
2570
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2571
-     * @throws EE_Error
2572
-     */
2573
-    public function add_relationship_to(
2574
-        $id_or_obj,
2575
-        $other_model_id_or_obj,
2576
-        $relationName,
2577
-        $extra_join_model_fields_n_values = []
2578
-    ) {
2579
-        $relation_obj = $this->related_settings_for($relationName);
2580
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2581
-    }
2582
-
2583
-
2584
-    /**
2585
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2586
-     * There are the 3 cases:
2587
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2588
-     * error
2589
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2590
-     * an error
2591
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2592
-     *
2593
-     * @param EE_Base_Class /int $id_or_obj
2594
-     * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2595
-     * @param string $relationName key in EEM_Base::_relations
2596
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2597
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599
-     *                             because these will be inserted in any new rows created as well.
2600
-     * @return boolean of success
2601
-     * @throws EE_Error
2602
-     */
2603
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2604
-    {
2605
-        $relation_obj = $this->related_settings_for($relationName);
2606
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2607
-    }
2608
-
2609
-
2610
-    /**
2611
-     * @param mixed  $id_or_obj
2612
-     * @param string $relationName
2613
-     * @param array  $where_query_params
2614
-     * @param EE_Base_Class[] objects to which relations were removed
2615
-     * @return EE_Base_Class[]
2616
-     * @throws EE_Error
2617
-     */
2618
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2619
-    {
2620
-        $relation_obj = $this->related_settings_for($relationName);
2621
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2622
-    }
2623
-
2624
-
2625
-    /**
2626
-     * Gets all the related items of the specified $model_name, using $query_params.
2627
-     * Note: by default, we remove the "default query params"
2628
-     * because we want to get even deleted items etc.
2629
-     *
2630
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2631
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2632
-     * @param array  $query_params see github link below for more info
2633
-     * @return EE_Base_Class[]
2634
-     * @throws EE_Error
2635
-     * @throws ReflectionException
2636
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
-     */
2638
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2639
-    {
2640
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2641
-        $relation_settings = $this->related_settings_for($model_name);
2642
-        return $relation_settings->get_all_related($model_obj, $query_params);
2643
-    }
2644
-
2645
-
2646
-    /**
2647
-     * Deletes all the model objects across the relation indicated by $model_name
2648
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2649
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2650
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651
-     *
2652
-     * @param EE_Base_Class|int|string $id_or_obj
2653
-     * @param string                   $model_name
2654
-     * @param array                    $query_params
2655
-     * @return int how many deleted
2656
-     * @throws EE_Error
2657
-     * @throws ReflectionException
2658
-     */
2659
-    public function delete_related($id_or_obj, $model_name, $query_params = [])
2660
-    {
2661
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2662
-        $relation_settings = $this->related_settings_for($model_name);
2663
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2664
-    }
2665
-
2666
-
2667
-    /**
2668
-     * Hard deletes all the model objects across the relation indicated by $model_name
2669
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2670
-     * the model objects can't be hard deleted because of blocking related model objects,
2671
-     * just does a soft-delete on them instead.
2672
-     *
2673
-     * @param EE_Base_Class|int|string $id_or_obj
2674
-     * @param string                   $model_name
2675
-     * @param array                    $query_params
2676
-     * @return int how many deleted
2677
-     * @throws EE_Error
2678
-     * @throws ReflectionException
2679
-     */
2680
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2681
-    {
2682
-        $model_obj         = $this->ensure_is_obj($id_or_obj);
2683
-        $relation_settings = $this->related_settings_for($model_name);
2684
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2685
-    }
2686
-
2687
-
2688
-    /**
2689
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2690
-     * unless otherwise specified in the $query_params
2691
-     *
2692
-     * @param int             /EE_Base_Class $id_or_obj
2693
-     * @param string $model_name     like 'Event', or 'Registration'
2694
-     * @param array  $query_params
2695
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2696
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2697
-     *                               that by the setting $distinct to TRUE;
2698
-     * @return int
2699
-     * @throws EE_Error
2700
-     * @throws ReflectionException
2701
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2702
-     */
2703
-    public function count_related(
2704
-        $id_or_obj,
2705
-        $model_name,
2706
-        $query_params = [],
2707
-        $field_to_count = null,
2708
-        $distinct = false
2709
-    ) {
2710
-        $related_model = $this->get_related_model_obj($model_name);
2711
-        // we're just going to use the query params on the related model's normal get_all query,
2712
-        // except add a condition to say to match the current mod
2713
-        if (! isset($query_params['default_where_conditions'])) {
2714
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715
-        }
2716
-        $this_model_name                                                 = $this->get_this_model_name();
2717
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2719
-        return $related_model->count($query_params, $field_to_count, $distinct);
2720
-    }
2721
-
2722
-
2723
-    /**
2724
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2725
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2726
-     *
2727
-     * @param int           /EE_Base_Class $id_or_obj
2728
-     * @param string $model_name   like 'Event', or 'Registration'
2729
-     * @param array  $query_params
2730
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2731
-     * @return float
2732
-     * @throws EE_Error
2733
-     * @throws ReflectionException
2734
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
-     */
2736
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737
-    {
2738
-        $related_model = $this->get_related_model_obj($model_name);
2739
-        if (! is_array($query_params)) {
2740
-            EE_Error::doing_it_wrong(
2741
-                'EEM_Base::sum_related',
2742
-                sprintf(
2743
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2744
-                    gettype($query_params)
2745
-                ),
2746
-                '4.6.0'
2747
-            );
2748
-            $query_params = [];
2749
-        }
2750
-        // we're just going to use the query params on the related model's normal get_all query,
2751
-        // except add a condition to say to match the current mod
2752
-        if (! isset($query_params['default_where_conditions'])) {
2753
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754
-        }
2755
-        $this_model_name                                                 = $this->get_this_model_name();
2756
-        $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2758
-        return $related_model->sum($query_params, $field_to_sum);
2759
-    }
2760
-
2761
-
2762
-    /**
2763
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2764
-     * $modelObject
2765
-     *
2766
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2767
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2768
-     * @param array               $query_params     see github link below for more info
2769
-     * @return EE_Base_Class
2770
-     * @throws EE_Error
2771
-     * @throws ReflectionException
2772
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2773
-     */
2774
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2775
-    {
2776
-        $query_params['limit'] = 1;
2777
-        $results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2778
-        if ($results) {
2779
-            return array_shift($results);
2780
-        }
2781
-        return null;
2782
-    }
2783
-
2784
-
2785
-    /**
2786
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2787
-     *
2788
-     * @return string
2789
-     */
2790
-    public function get_this_model_name()
2791
-    {
2792
-        return str_replace("EEM_", "", get_class($this));
2793
-    }
2794
-
2795
-
2796
-    /**
2797
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2798
-     *
2799
-     * @return EE_Any_Foreign_Model_Name_Field
2800
-     * @throws EE_Error
2801
-     */
2802
-    public function get_field_containing_related_model_name()
2803
-    {
2804
-        foreach ($this->field_settings(true) as $field) {
2805
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2806
-                $field_with_model_name = $field;
2807
-            }
2808
-        }
2809
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2810
-            throw new EE_Error(
2811
-                sprintf(
2812
-                    esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2813
-                    $this->get_this_model_name()
2814
-                )
2815
-            );
2816
-        }
2817
-        return $field_with_model_name;
2818
-    }
2819
-
2820
-
2821
-    /**
2822
-     * Inserts a new entry into the database, for each table.
2823
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2824
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2825
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2826
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2827
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2828
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2829
-     *
2830
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2831
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2832
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2833
-     *                              of EEM_Base)
2834
-     * @return int|string new primary key on main table that got inserted
2835
-     * @throws EE_Error
2836
-     * @throws ReflectionException
2837
-     */
2838
-    public function insert($field_n_values)
2839
-    {
2840
-        /**
2841
-         * Filters the fields and their values before inserting an item using the models
2842
-         *
2843
-         * @param array    $fields_n_values keys are the fields and values are their new values
2844
-         * @param EEM_Base $model           the model used
2845
-         */
2846
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2848
-            $main_table = $this->_get_main_table();
2849
-            $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2850
-            if ($new_id !== false) {
2851
-                foreach ($this->_get_other_tables() as $other_table) {
2852
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2853
-                }
2854
-            }
2855
-            /**
2856
-             * Done just after attempting to insert a new model object
2857
-             *
2858
-             * @param EEM_Base $model           used
2859
-             * @param array    $fields_n_values fields and their values
2860
-             * @param int|string the              ID of the newly-inserted model object
2861
-             */
2862
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2863
-            return $new_id;
2864
-        }
2865
-        return false;
2866
-    }
2867
-
2868
-
2869
-    /**
2870
-     * Checks that the result would satisfy the unique indexes on this model
2871
-     *
2872
-     * @param array  $field_n_values
2873
-     * @param string $action
2874
-     * @return boolean
2875
-     * @throws EE_Error
2876
-     * @throws ReflectionException
2877
-     */
2878
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2879
-    {
2880
-        foreach ($this->unique_indexes() as $index_name => $index) {
2881
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2882
-            if ($this->exists([$uniqueness_where_params])) {
2883
-                EE_Error::add_error(
2884
-                    sprintf(
2885
-                        esc_html__(
2886
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2887
-                            "event_espresso"
2888
-                        ),
2889
-                        $action,
2890
-                        $this->_get_class_name(),
2891
-                        $index_name,
2892
-                        implode(",", $index->field_names()),
2893
-                        http_build_query($uniqueness_where_params)
2894
-                    ),
2895
-                    __FILE__,
2896
-                    __FUNCTION__,
2897
-                    __LINE__
2898
-                );
2899
-                return false;
2900
-            }
2901
-        }
2902
-        return true;
2903
-    }
2904
-
2905
-
2906
-    /**
2907
-     * Checks the database for an item that conflicts (ie, if this item were
2908
-     * saved to the DB would break some uniqueness requirement, like a primary key
2909
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2910
-     * can be either an EE_Base_Class or an array of fields n values
2911
-     *
2912
-     * @param EE_Base_Class|array $obj_or_fields_array
2913
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2914
-     *                                                 when looking for conflicts
2915
-     *                                                 (ie, if false, we ignore the model object's primary key
2916
-     *                                                 when finding "conflicts". If true, it's also considered).
2917
-     *                                                 Only works for INT primary key,
2918
-     *                                                 STRING primary keys cannot be ignored
2919
-     * @return EE_Base_Class|array
2920
-     * @throws EE_Error
2921
-     * @throws ReflectionException
2922
-     */
2923
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2924
-    {
2925
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2926
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2927
-        } elseif (is_array($obj_or_fields_array)) {
2928
-            $fields_n_values = $obj_or_fields_array;
2929
-        } else {
2930
-            throw new EE_Error(
2931
-                sprintf(
2932
-                    esc_html__(
2933
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2934
-                        "event_espresso"
2935
-                    ),
2936
-                    get_class($this),
2937
-                    $obj_or_fields_array
2938
-                )
2939
-            );
2940
-        }
2941
-        $query_params = [];
2942
-        if (
2943
-            $this->has_primary_key_field()
2944
-            && ($include_primary_key
2945
-                || $this->get_primary_key_field()
2946
-                   instanceof
2947
-                   EE_Primary_Key_String_Field)
2948
-            && isset($fields_n_values[ $this->primary_key_name() ])
2949
-        ) {
2950
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2951
-        }
2952
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953
-            $uniqueness_where_params                              =
2954
-                array_intersect_key($fields_n_values, $unique_index->fields());
2955
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2956
-        }
2957
-        // if there is nothing to base this search on, then we shouldn't find anything
2958
-        if (empty($query_params)) {
2959
-            return [];
2960
-        }
2961
-        return $this->get_one($query_params);
2962
-    }
2963
-
2964
-
2965
-    /**
2966
-     * Like count, but is optimized and returns a boolean instead of an int
2967
-     *
2968
-     * @param array $query_params
2969
-     * @return boolean
2970
-     * @throws EE_Error
2971
-     * @throws ReflectionException
2972
-     */
2973
-    public function exists($query_params)
2974
-    {
2975
-        $query_params['limit'] = 1;
2976
-        return $this->count($query_params) > 0;
2977
-    }
2978
-
2979
-
2980
-    /**
2981
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2982
-     *
2983
-     * @param int|string $id
2984
-     * @return boolean
2985
-     * @throws EE_Error
2986
-     * @throws ReflectionException
2987
-     */
2988
-    public function exists_by_ID($id)
2989
-    {
2990
-        return $this->exists(
2991
-            [
2992
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2993
-                [
2994
-                    $this->primary_key_name() => $id,
2995
-                ],
2996
-            ]
2997
-        );
2998
-    }
2999
-
3000
-
3001
-    /**
3002
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3003
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3004
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3005
-     * on the main table)
3006
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
3007
-     * cases where we want to call it directly rather than via insert().
3008
-     *
3009
-     * @access   protected
3010
-     * @param EE_Table_Base $table
3011
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3012
-     *                                       float
3013
-     * @param int           $new_id          for now we assume only int keys
3014
-     * @return int ID of new row inserted, or FALSE on failure
3015
-     * @throws EE_Error
3016
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3017
-     */
3018
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3019
-    {
3020
-        global $wpdb;
3021
-        $insertion_col_n_values = [];
3022
-        $format_for_insertion   = [];
3023
-        $fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3024
-        foreach ($fields_on_table as $field_name => $field_obj) {
3025
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3026
-            if ($field_obj->is_auto_increment()) {
3027
-                continue;
3028
-            }
3029
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
3031
-            if ($prepared_value !== null) {
3032
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3033
-                $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034
-            }
3035
-        }
3036
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3037
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
3038
-            // so add the fk to the main table as a column
3039
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3040
-            $format_for_insertion[]                              =
3041
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3042
-        }
3043
-        // insert the new entry
3044
-        $result = $this->_do_wpdb_query(
3045
-            'insert',
3046
-            [$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3047
-        );
3048
-        if ($result === false) {
3049
-            return false;
3050
-        }
3051
-        // ok, now what do we return for the ID of the newly-inserted thing?
3052
-        if ($this->has_primary_key_field()) {
3053
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3054
-                return $wpdb->insert_id;
3055
-            }
3056
-            // it's not an auto-increment primary key, so
3057
-            // it must have been supplied
3058
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3059
-        }
3060
-        // we can't return a  primary key because there is none. instead return
3061
-        // a unique string indicating this model
3062
-        return $this->get_index_primary_key_string($fields_n_values);
3063
-    }
3064
-
3065
-
3066
-    /**
3067
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3068
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3069
-     * and there is no default, we pass it along. WPDB will take care of it)
3070
-     *
3071
-     * @param EE_Model_Field_Base $field_obj
3072
-     * @param array               $fields_n_values
3073
-     * @return mixed string|int|float depending on what the table column will be expecting
3074
-     * @throws EE_Error
3075
-     */
3076
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3077
-    {
3078
-        // if this field doesn't allow nullable, don't allow it
3079
-        if (
3080
-            ! $field_obj->is_nullable()
3081
-            && (
3082
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3083
-                || $fields_n_values[ $field_obj->get_name() ] === null
3084
-            )
3085
-        ) {
3086
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3087
-        }
3088
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
-            ? $fields_n_values[ $field_obj->get_name() ]
3090
-            : null;
3091
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
-    }
3093
-
3094
-
3095
-    /**
3096
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
-     * the field's prepare_for_set() method.
3099
-     *
3100
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
-     *                                   top of file)
3103
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
-     *                                   $value is a custom selection
3105
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
-     */
3107
-    private function _prepare_value_for_use_in_db($value, $field)
3108
-    {
3109
-        if ($field && $field instanceof EE_Model_Field_Base) {
3110
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
-            switch ($this->_values_already_prepared_by_model_object) {
3112
-                /** @noinspection PhpMissingBreakStatementInspection */
3113
-                case self::not_prepared_by_model_object:
3114
-                    $value = $field->prepare_for_set($value);
3115
-                // purposefully left out "return"
3116
-                case self::prepared_by_model_object:
3117
-                    /** @noinspection SuspiciousAssignmentsInspection */
3118
-                    $value = $field->prepare_for_use_in_db($value);
3119
-                case self::prepared_for_use_in_db:
3120
-                    // leave the value alone
3121
-            }
3122
-            return $value;
3123
-            // phpcs:enable
3124
-        }
3125
-        return $value;
3126
-    }
3127
-
3128
-
3129
-    /**
3130
-     * Returns the main table on this model
3131
-     *
3132
-     * @return EE_Primary_Table
3133
-     * @throws EE_Error
3134
-     */
3135
-    protected function _get_main_table()
3136
-    {
3137
-        foreach ($this->_tables as $table) {
3138
-            if ($table instanceof EE_Primary_Table) {
3139
-                return $table;
3140
-            }
3141
-        }
3142
-        throw new EE_Error(
3143
-            sprintf(
3144
-                esc_html__(
3145
-                    'There are no main tables on %s. They should be added to _tables array in the constructor',
3146
-                    'event_espresso'
3147
-                ),
3148
-                get_class($this)
3149
-            )
3150
-        );
3151
-    }
3152
-
3153
-
3154
-    /**
3155
-     * table
3156
-     * returns EE_Primary_Table table name
3157
-     *
3158
-     * @return string
3159
-     * @throws EE_Error
3160
-     */
3161
-    public function table()
3162
-    {
3163
-        return $this->_get_main_table()->get_table_name();
3164
-    }
3165
-
3166
-
3167
-    /**
3168
-     * table
3169
-     * returns first EE_Secondary_Table table name
3170
-     *
3171
-     * @return string
3172
-     */
3173
-    public function second_table()
3174
-    {
3175
-        // grab second table from tables array
3176
-        $second_table = end($this->_tables);
3177
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3178
-    }
3179
-
3180
-
3181
-    /**
3182
-     * get_table_obj_by_alias
3183
-     * returns table name given it's alias
3184
-     *
3185
-     * @param string $table_alias
3186
-     * @return EE_Primary_Table | EE_Secondary_Table
3187
-     */
3188
-    public function get_table_obj_by_alias($table_alias = '')
3189
-    {
3190
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
-    }
3192
-
3193
-
3194
-    /**
3195
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3196
-     *
3197
-     * @return EE_Secondary_Table[]
3198
-     */
3199
-    protected function _get_other_tables()
3200
-    {
3201
-        $other_tables = [];
3202
-        foreach ($this->_tables as $table_alias => $table) {
3203
-            if ($table instanceof EE_Secondary_Table) {
3204
-                $other_tables[ $table_alias ] = $table;
3205
-            }
3206
-        }
3207
-        return $other_tables;
3208
-    }
3209
-
3210
-
3211
-    /**
3212
-     * Finds all the fields that correspond to the given table
3213
-     *
3214
-     * @param string $table_alias , array key in EEM_Base::_tables
3215
-     * @return EE_Model_Field_Base[]
3216
-     */
3217
-    public function _get_fields_for_table($table_alias)
3218
-    {
3219
-        return $this->_fields[ $table_alias ];
3220
-    }
3221
-
3222
-
3223
-    /**
3224
-     * Recurses through all the where parameters, and finds all the related models we'll need
3225
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3226
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3227
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3228
-     * related Registration, Transaction, and Payment models.
3229
-     *
3230
-     * @param array $query_params see github link below for more info
3231
-     * @return EE_Model_Query_Info_Carrier
3232
-     * @throws EE_Error
3233
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3234
-     */
3235
-    public function _extract_related_models_from_query($query_params)
3236
-    {
3237
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3238
-        if (array_key_exists(0, $query_params)) {
3239
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3240
-        }
3241
-        if (array_key_exists('group_by', $query_params)) {
3242
-            if (is_array($query_params['group_by'])) {
3243
-                $this->_extract_related_models_from_sub_params_array_values(
3244
-                    $query_params['group_by'],
3245
-                    $query_info_carrier,
3246
-                    'group_by'
3247
-                );
3248
-            } elseif (! empty($query_params['group_by'])) {
3249
-                $this->_extract_related_model_info_from_query_param(
3250
-                    $query_params['group_by'],
3251
-                    $query_info_carrier,
3252
-                    'group_by'
3253
-                );
3254
-            }
3255
-        }
3256
-        if (array_key_exists('having', $query_params)) {
3257
-            $this->_extract_related_models_from_sub_params_array_keys(
3258
-                $query_params[0],
3259
-                $query_info_carrier,
3260
-                'having'
3261
-            );
3262
-        }
3263
-        if (array_key_exists('order_by', $query_params)) {
3264
-            if (is_array($query_params['order_by'])) {
3265
-                $this->_extract_related_models_from_sub_params_array_keys(
3266
-                    $query_params['order_by'],
3267
-                    $query_info_carrier,
3268
-                    'order_by'
3269
-                );
3270
-            } elseif (! empty($query_params['order_by'])) {
3271
-                $this->_extract_related_model_info_from_query_param(
3272
-                    $query_params['order_by'],
3273
-                    $query_info_carrier,
3274
-                    'order_by'
3275
-                );
3276
-            }
3277
-        }
3278
-        if (array_key_exists('force_join', $query_params)) {
3279
-            $this->_extract_related_models_from_sub_params_array_values(
3280
-                $query_params['force_join'],
3281
-                $query_info_carrier,
3282
-                'force_join'
3283
-            );
3284
-        }
3285
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3286
-        return $query_info_carrier;
3287
-    }
3288
-
3289
-
3290
-    /**
3291
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3292
-     *
3293
-     * @param array                       $sub_query_params
3294
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3295
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3296
-     * @return EE_Model_Query_Info_Carrier
3297
-     * @throws EE_Error
3298
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3299
-     */
3300
-    private function _extract_related_models_from_sub_params_array_keys(
3301
-        $sub_query_params,
3302
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303
-        $query_param_type
3304
-    ) {
3305
-        if (! empty($sub_query_params)) {
3306
-            $sub_query_params = (array)$sub_query_params;
3307
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
-                $this->_extract_related_model_info_from_query_param(
3310
-                    $param,
3311
-                    $model_query_info_carrier,
3312
-                    $query_param_type
3313
-                );
3314
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3315
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3316
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3317
-                // of array('Registration.TXN_ID'=>23)
3318
-                $query_param_sans_stars =
3319
-                    $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
-                    if (! is_array($possibly_array_of_params)) {
3322
-                        throw new EE_Error(
3323
-                            sprintf(
3324
-                                esc_html__(
3325
-                                    "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'))",
3326
-                                    "event_espresso"
3327
-                                ),
3328
-                                $param,
3329
-                                $possibly_array_of_params
3330
-                            )
3331
-                        );
3332
-                    }
3333
-                    $this->_extract_related_models_from_sub_params_array_keys(
3334
-                        $possibly_array_of_params,
3335
-                        $model_query_info_carrier,
3336
-                        $query_param_type
3337
-                    );
3338
-                } elseif (
3339
-                    $query_param_type === 0 // ie WHERE
3340
-                    && is_array($possibly_array_of_params)
3341
-                    && isset($possibly_array_of_params[2])
3342
-                    && $possibly_array_of_params[2] == true
3343
-                ) {
3344
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3346
-                    // from which we should extract query parameters!
3347
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
-                        throw new EE_Error(
3349
-                            sprintf(
3350
-                                esc_html__(
3351
-                                    "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3352
-                                    "event_espresso"
3353
-                                ),
3354
-                                $query_param_type,
3355
-                                implode(",", $possibly_array_of_params)
3356
-                            )
3357
-                        );
3358
-                    }
3359
-                    $this->_extract_related_model_info_from_query_param(
3360
-                        $possibly_array_of_params[1],
3361
-                        $model_query_info_carrier,
3362
-                        $query_param_type
3363
-                    );
3364
-                }
3365
-            }
3366
-        }
3367
-        return $model_query_info_carrier;
3368
-    }
3369
-
3370
-
3371
-    /**
3372
-     * For extracting related models from forced_joins, where the array values contain the info about what
3373
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3374
-     *
3375
-     * @param array                       $sub_query_params
3376
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3377
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3378
-     * @return EE_Model_Query_Info_Carrier
3379
-     * @throws EE_Error
3380
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3381
-     */
3382
-    private function _extract_related_models_from_sub_params_array_values(
3383
-        $sub_query_params,
3384
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385
-        $query_param_type
3386
-    ) {
3387
-        if (! empty($sub_query_params)) {
3388
-            if (! is_array($sub_query_params)) {
3389
-                throw new EE_Error(
3390
-                    sprintf(
3391
-                        esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3392
-                        $sub_query_params
3393
-                    )
3394
-                );
3395
-            }
3396
-            foreach ($sub_query_params as $param) {
3397
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3398
-                $this->_extract_related_model_info_from_query_param(
3399
-                    $param,
3400
-                    $model_query_info_carrier,
3401
-                    $query_param_type
3402
-                );
3403
-            }
3404
-        }
3405
-        return $model_query_info_carrier;
3406
-    }
3407
-
3408
-
3409
-    /**
3410
-     * Extract all the query parts from  model query params
3411
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3412
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3413
-     * but use them in a different order. Eg, we need to know what models we are querying
3414
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3415
-     * other models before we can finalize the where clause SQL.
3416
-     *
3417
-     * @param array $query_params see github link below for more info
3418
-     * @return EE_Model_Query_Info_Carrier
3419
-     * @throws EE_Error
3420
-     * @throws ModelConfigurationException
3421
-     * @throws ReflectionException
3422
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
-     */
3424
-    public function _create_model_query_info_carrier($query_params)
3425
-    {
3426
-        if (! is_array($query_params)) {
3427
-            EE_Error::doing_it_wrong(
3428
-                'EEM_Base::_create_model_query_info_carrier',
3429
-                sprintf(
3430
-                    esc_html__(
3431
-                        '$query_params should be an array, you passed a variable of type %s',
3432
-                        'event_espresso'
3433
-                    ),
3434
-                    gettype($query_params)
3435
-                ),
3436
-                '4.6.0'
3437
-            );
3438
-            $query_params = [];
3439
-        }
3440
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
-        // first check if we should alter the query to account for caps or not
3442
-        // because the caps might require us to do extra joins
3443
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
-            $query_params[0] = array_replace_recursive(
3445
-                $query_params[0],
3446
-                $this->caps_where_conditions(
3447
-                    $query_params['caps']
3448
-                )
3449
-            );
3450
-        }
3451
-
3452
-        // check if we should alter the query to remove data related to protected
3453
-        // custom post types
3454
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3455
-            $where_param_key_for_password = $this->modelChainAndPassword();
3456
-            // only include if related to a cpt where no password has been set
3457
-            $query_params[0]['OR*nopassword'] = [
3458
-                $where_param_key_for_password       => '',
3459
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3460
-            ];
3461
-        }
3462
-        $query_object = $this->_extract_related_models_from_query($query_params);
3463
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3464
-        foreach ($query_params[0] as $key => $value) {
3465
-            if (is_int($key)) {
3466
-                throw new EE_Error(
3467
-                    sprintf(
3468
-                        esc_html__(
3469
-                            "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.",
3470
-                            "event_espresso"
3471
-                        ),
3472
-                        $key,
3473
-                        var_export($value, true),
3474
-                        var_export($query_params, true),
3475
-                        get_class($this)
3476
-                    )
3477
-                );
3478
-            }
3479
-        }
3480
-        if (
3481
-            array_key_exists('default_where_conditions', $query_params)
3482
-            && ! empty($query_params['default_where_conditions'])
3483
-        ) {
3484
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3485
-        } else {
3486
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3487
-        }
3488
-        $query_params[0] = array_merge(
3489
-            $this->_get_default_where_conditions_for_models_in_query(
3490
-                $query_object,
3491
-                $use_default_where_conditions,
3492
-                $query_params[0]
3493
-            ),
3494
-            $query_params[0]
3495
-        );
3496
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3497
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3498
-        // So we need to setup a subquery and use that for the main join.
3499
-        // Note for now this only works on the primary table for the model.
3500
-        // So for instance, you could set the limit array like this:
3501
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3502
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3503
-            $query_object->set_main_model_join_sql(
3504
-                $this->_construct_limit_join_select(
3505
-                    $query_params['on_join_limit'][0],
3506
-                    $query_params['on_join_limit'][1]
3507
-                )
3508
-            );
3509
-        }
3510
-        // set limit
3511
-        if (array_key_exists('limit', $query_params)) {
3512
-            if (is_array($query_params['limit'])) {
3513
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
-                    $e = sprintf(
3515
-                        esc_html__(
3516
-                            "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)",
3517
-                            "event_espresso"
3518
-                        ),
3519
-                        http_build_query($query_params['limit'])
3520
-                    );
3521
-                    throw new EE_Error($e . "|" . $e);
3522
-                }
3523
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
-            } elseif (! empty($query_params['limit'])) {
3526
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3527
-            }
3528
-        }
3529
-        // set order by
3530
-        if (array_key_exists('order_by', $query_params)) {
3531
-            if (is_array($query_params['order_by'])) {
3532
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3533
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3534
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3535
-                if (array_key_exists('order', $query_params)) {
3536
-                    throw new EE_Error(
3537
-                        sprintf(
3538
-                            esc_html__(
3539
-                                "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 ",
3540
-                                "event_espresso"
3541
-                            ),
3542
-                            get_class($this),
3543
-                            implode(", ", array_keys($query_params['order_by'])),
3544
-                            implode(", ", $query_params['order_by']),
3545
-                            $query_params['order']
3546
-                        )
3547
-                    );
3548
-                }
3549
-                $this->_extract_related_models_from_sub_params_array_keys(
3550
-                    $query_params['order_by'],
3551
-                    $query_object,
3552
-                    'order_by'
3553
-                );
3554
-                // assume it's an array of fields to order by
3555
-                $order_array = [];
3556
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557
-                    $order         = $this->_extract_order($order);
3558
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
-                }
3560
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
-            } elseif (! empty($query_params['order_by'])) {
3562
-                $this->_extract_related_model_info_from_query_param(
3563
-                    $query_params['order_by'],
3564
-                    $query_object,
3565
-                    'order',
3566
-                    $query_params['order_by']
3567
-                );
3568
-                $order = isset($query_params['order'])
3569
-                    ? $this->_extract_order($query_params['order'])
3570
-                    : 'DESC';
3571
-                $query_object->set_order_by_sql(
3572
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
-                );
3574
-            }
3575
-        }
3576
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3577
-        if (
3578
-            ! array_key_exists('order_by', $query_params)
3579
-            && array_key_exists('order', $query_params)
3580
-            && ! empty($query_params['order'])
3581
-        ) {
3582
-            $pk_field = $this->get_primary_key_field();
3583
-            $order    = $this->_extract_order($query_params['order']);
3584
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
-        }
3586
-        // set group by
3587
-        if (array_key_exists('group_by', $query_params)) {
3588
-            if (is_array($query_params['group_by'])) {
3589
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3590
-                $group_by_array = [];
3591
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593
-                }
3594
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
-            } elseif (! empty($query_params['group_by'])) {
3596
-                $query_object->set_group_by_sql(
3597
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
-                );
3599
-            }
3600
-        }
3601
-        // set having
3602
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3603
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3604
-        }
3605
-        // now, just verify they didn't pass anything wack
3606
-        foreach ($query_params as $query_key => $query_value) {
3607
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
-                throw new EE_Error(
3609
-                    sprintf(
3610
-                        esc_html__(
3611
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3612
-                            'event_espresso'
3613
-                        ),
3614
-                        $query_key,
3615
-                        get_class($this),
3616
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3617
-                        implode(',', $this->_allowed_query_params)
3618
-                    )
3619
-                );
3620
-            }
3621
-        }
3622
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3623
-        if (empty($main_model_join_sql)) {
3624
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3625
-        }
3626
-        return $query_object;
3627
-    }
3628
-
3629
-
3630
-    /**
3631
-     * Gets the where conditions that should be imposed on the query based on the
3632
-     * context (eg reading frontend, backend, edit or delete).
3633
-     *
3634
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3635
-     * @return array
3636
-     * @throws EE_Error
3637
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
-     */
3639
-    public function caps_where_conditions($context = self::caps_read)
3640
-    {
3641
-        EEM_Base::verify_is_valid_cap_context($context);
3642
-        $cap_where_conditions = [];
3643
-        $cap_restrictions     = $this->caps_missing($context);
3644
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3645
-            $cap_where_conditions = array_replace_recursive(
3646
-                $cap_where_conditions,
3647
-                $restriction_if_no_cap->get_default_where_conditions()
3648
-            );
3649
-        }
3650
-        return apply_filters(
3651
-            'FHEE__EEM_Base__caps_where_conditions__return',
3652
-            $cap_where_conditions,
3653
-            $this,
3654
-            $context,
3655
-            $cap_restrictions
3656
-        );
3657
-    }
3658
-
3659
-
3660
-    /**
3661
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3662
-     * otherwise throws an exception
3663
-     *
3664
-     * @param string $should_be_order_string
3665
-     * @return string either ASC, asc, DESC or desc
3666
-     * @throws EE_Error
3667
-     */
3668
-    private function _extract_order($should_be_order_string)
3669
-    {
3670
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3671
-            return $should_be_order_string;
3672
-        }
3673
-        throw new EE_Error(
3674
-            sprintf(
3675
-                esc_html__(
3676
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3677
-                    "event_espresso"
3678
-                ),
3679
-                get_class($this),
3680
-                $should_be_order_string
3681
-            )
3682
-        );
3683
-    }
3684
-
3685
-
3686
-    /**
3687
-     * Looks at all the models which are included in this query, and asks each
3688
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3689
-     * so they can be merged
3690
-     *
3691
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3692
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3693
-     *                                                                  'none' means NO default where conditions will
3694
-     *                                                                  be used AT ALL during this query.
3695
-     *                                                                  'other_models_only' means default where
3696
-     *                                                                  conditions from other models will be used, but
3697
-     *                                                                  not for this primary model. 'all', the default,
3698
-     *                                                                  means default where conditions will apply as
3699
-     *                                                                  normal
3700
-     * @param array                       $where_query_params
3701
-     * @return array
3702
-     * @throws EE_Error
3703
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3704
-     */
3705
-    private function _get_default_where_conditions_for_models_in_query(
3706
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3707
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3708
-        $where_query_params = []
3709
-    ) {
3710
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712
-            throw new EE_Error(
3713
-                sprintf(
3714
-                    esc_html__(
3715
-                        "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3716
-                        "event_espresso"
3717
-                    ),
3718
-                    $use_default_where_conditions,
3719
-                    implode(", ", $allowed_used_default_where_conditions_values)
3720
-                )
3721
-            );
3722
-        }
3723
-        $universal_query_params = [];
3724
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3725
-            $universal_query_params = $this->_get_default_where_conditions();
3726
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3727
-            $universal_query_params = $this->_get_minimum_where_conditions();
3728
-        }
3729
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3730
-            $related_model = $this->get_related_model_obj($model_name);
3731
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3732
-                $related_model_universal_where_params =
3733
-                    $related_model->_get_default_where_conditions($model_relation_path);
3734
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3735
-                $related_model_universal_where_params =
3736
-                    $related_model->_get_minimum_where_conditions($model_relation_path);
3737
-            } else {
3738
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3739
-                continue;
3740
-            }
3741
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3742
-                $related_model_universal_where_params,
3743
-                $where_query_params,
3744
-                $related_model,
3745
-                $model_relation_path
3746
-            );
3747
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3748
-                $universal_query_params,
3749
-                $overrides
3750
-            );
3751
-        }
3752
-        return $universal_query_params;
3753
-    }
3754
-
3755
-
3756
-    /**
3757
-     * Determines whether or not we should use default where conditions for the model in question
3758
-     * (this model, or other related models).
3759
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3760
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3761
-     * We should use default where conditions on related models when they requested to use default where conditions
3762
-     * on all models, or specifically just on other related models
3763
-     *
3764
-     * @param      $default_where_conditions_value
3765
-     * @param bool $for_this_model false means this is for OTHER related models
3766
-     * @return bool
3767
-     */
3768
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3769
-    {
3770
-        return (
3771
-                   $for_this_model
3772
-                   && in_array(
3773
-                       $default_where_conditions_value,
3774
-                       [
3775
-                           EEM_Base::default_where_conditions_all,
3776
-                           EEM_Base::default_where_conditions_this_only,
3777
-                           EEM_Base::default_where_conditions_minimum_others,
3778
-                       ],
3779
-                       true
3780
-                   )
3781
-               )
3782
-               || (
3783
-                   ! $for_this_model
3784
-                   && in_array(
3785
-                       $default_where_conditions_value,
3786
-                       [
3787
-                           EEM_Base::default_where_conditions_all,
3788
-                           EEM_Base::default_where_conditions_others_only,
3789
-                       ],
3790
-                       true
3791
-                   )
3792
-               );
3793
-    }
3794
-
3795
-
3796
-    /**
3797
-     * Determines whether or not we should use default minimum conditions for the model in question
3798
-     * (this model, or other related models).
3799
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
-     * where conditions.
3801
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
-     * on this model or others
3803
-     *
3804
-     * @param      $default_where_conditions_value
3805
-     * @param bool $for_this_model false means this is for OTHER related models
3806
-     * @return bool
3807
-     */
3808
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3809
-    {
3810
-        return (
3811
-                   $for_this_model
3812
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3813
-               )
3814
-               || (
3815
-                   ! $for_this_model
3816
-                   && in_array(
3817
-                       $default_where_conditions_value,
3818
-                       [
3819
-                           EEM_Base::default_where_conditions_minimum_others,
3820
-                           EEM_Base::default_where_conditions_minimum_all,
3821
-                       ],
3822
-                       true
3823
-                   )
3824
-               );
3825
-    }
3826
-
3827
-
3828
-    /**
3829
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3830
-     * then we also add a special where condition which allows for that model's primary key
3831
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3832
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3833
-     *
3834
-     * @param array    $default_where_conditions
3835
-     * @param array    $provided_where_conditions
3836
-     * @param EEM_Base $model
3837
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3838
-     * @return array
3839
-     * @throws EE_Error
3840
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
-     */
3842
-    private function _override_defaults_or_make_null_friendly(
3843
-        $default_where_conditions,
3844
-        $provided_where_conditions,
3845
-        $model,
3846
-        $model_relation_path
3847
-    ) {
3848
-        $null_friendly_where_conditions = [];
3849
-        $none_overridden                = true;
3850
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3851
-        foreach ($default_where_conditions as $key => $val) {
3852
-            if (isset($provided_where_conditions[ $key ])) {
3853
-                $none_overridden = false;
3854
-            } else {
3855
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
-            }
3857
-        }
3858
-        if ($none_overridden && $default_where_conditions) {
3859
-            if ($model->has_primary_key_field()) {
3860
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
-                                                                                   . "."
3862
-                                                                                   . $model->primary_key_name() ] =
3863
-                    ['IS NULL'];
3864
-            }/*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 null $timezone
565
+	 * @throws EE_Error
566
+	 */
567
+	protected function __construct($timezone = null)
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 blogid 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 ($this->_cap_restriction_generators !== false) {
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 there are cap restriction generators, use them to make the default cap restrictions
689
+		if ($this->_cap_restriction_generators !== false) {
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 = null)
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
+		// we might have a timezone set, let set_timezone decide what to do with it
764
+		static::$_instance->set_timezone($timezone);
765
+		// Espresso_model object
766
+		return static::$_instance;
767
+	}
768
+
769
+
770
+	/**
771
+	 * resets the model and returns it
772
+	 *
773
+	 * @param null | string $timezone
774
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
775
+	 * all its properties reset; if it wasn't instantiated, returns null)
776
+	 * @throws EE_Error
777
+	 * @throws ReflectionException
778
+	 * @throws InvalidArgumentException
779
+	 * @throws InvalidDataTypeException
780
+	 * @throws InvalidInterfaceException
781
+	 */
782
+	public static function reset($timezone = null)
783
+	{
784
+		if (static::$_instance instanceof EEM_Base) {
785
+			// let's try to NOT swap out the current instance for a new one
786
+			// because if someone has a reference to it, we can't remove their reference
787
+			// so it's best to keep using the same reference, but change the original object
788
+			// reset all its properties to their original values as defined in the class
789
+			$r                 = new ReflectionClass(get_class(static::$_instance));
790
+			$static_properties = $r->getStaticProperties();
791
+			foreach ($r->getDefaultProperties() as $property => $value) {
792
+				// don't set instance to null like it was originally,
793
+				// but it's static anyways, and we're ignoring static properties (for now at least)
794
+				if (! isset($static_properties[ $property ])) {
795
+					static::$_instance->{$property} = $value;
796
+				}
797
+			}
798
+			// and then directly call its constructor again, like we would if we were creating a new one
799
+			static::$_instance->__construct(
800
+				$timezone,
801
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
802
+			);
803
+			return self::instance();
804
+		}
805
+		return null;
806
+	}
807
+
808
+
809
+	/**
810
+	 * @return LoaderInterface
811
+	 * @throws InvalidArgumentException
812
+	 * @throws InvalidDataTypeException
813
+	 * @throws InvalidInterfaceException
814
+	 */
815
+	private static function getLoader()
816
+	{
817
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
818
+			EEM_Base::$loader = LoaderFactory::getLoader();
819
+		}
820
+		return EEM_Base::$loader;
821
+	}
822
+
823
+
824
+	/**
825
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
826
+	 *
827
+	 * @param boolean $translated return localized strings or JUST the array.
828
+	 * @return array
829
+	 * @throws EE_Error
830
+	 * @throws InvalidArgumentException
831
+	 * @throws InvalidDataTypeException
832
+	 * @throws InvalidInterfaceException
833
+	 * @throws ReflectionException
834
+	 */
835
+	public function status_array($translated = false)
836
+	{
837
+		if (! array_key_exists('Status', $this->_model_relations)) {
838
+			return [];
839
+		}
840
+		$model_name   = $this->get_this_model_name();
841
+		$status_type  = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
842
+		$stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
843
+		$status_array = [];
844
+		foreach ($stati as $status) {
845
+			$status_array[ $status->ID() ] = $status->get('STS_code');
846
+		}
847
+		return $translated
848
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
849
+			: $status_array;
850
+	}
851
+
852
+
853
+	/**
854
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
855
+	 *
856
+	 * @param array $query_params             see github link below for more info
857
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
858
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object
859
+	 *                                        IDs (if there is a primary key on the model. if not, numerically indexed)
860
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
861
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
862
+	 *                                        'OR'=>array(
863
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
864
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
865
+	 *                                        )
866
+	 *                                        ),
867
+	 *                                        'limit'=>10,
868
+	 *                                        'group_by'=>'TXN_ID'
869
+	 *                                        ));
870
+	 *                                        get all the answers to the question titled "shirt size" for event with id
871
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
872
+	 *                                        'Question.QST_display_text'=>'shirt size',
873
+	 *                                        'Registration.Event.EVT_ID'=>12
874
+	 *                                        ),
875
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
876
+	 *                                        ));
877
+	 * @throws EE_Error
878
+	 * @throws ReflectionException
879
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
880
+	 *                                        or if you have the development copy of EE you can view this at the path:
881
+	 *                                        /docs/G--Model-System/model-query-params.md
882
+	 */
883
+	public function get_all($query_params = [])
884
+	{
885
+		if (
886
+			isset($query_params['limit'])
887
+			&& ! isset($query_params['group_by'])
888
+		) {
889
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
890
+		}
891
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params));
892
+	}
893
+
894
+
895
+	/**
896
+	 * Modifies the query parameters so we only get back model objects
897
+	 * that "belong" to the current user
898
+	 *
899
+	 * @param array $query_params see github link below for more info
900
+	 * @return array
901
+	 * @throws ReflectionException
902
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
903
+	 */
904
+	public function alter_query_params_to_only_include_mine($query_params = [])
905
+	{
906
+		$wp_user_field_name = $this->wp_user_field_name();
907
+		if ($wp_user_field_name) {
908
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
909
+		}
910
+		return $query_params;
911
+	}
912
+
913
+
914
+	/**
915
+	 * Returns the name of the field's name that points to the WP_User table
916
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
917
+	 * foreign key to the WP_User table)
918
+	 *
919
+	 * @return string|boolean string on success, boolean false when there is no
920
+	 * foreign key to the WP_User table
921
+	 * @throws ReflectionException
922
+	 */
923
+	public function wp_user_field_name()
924
+	{
925
+		try {
926
+			if (! empty($this->_model_chain_to_wp_user)) {
927
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
928
+				$last_model_name              = end($models_to_follow_to_wp_users);
929
+				$model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
930
+				$model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
931
+			} else {
932
+				$model_with_fk_to_wp_users = $this;
933
+				$model_chain_to_wp_user    = '';
934
+			}
935
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
936
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
937
+		} catch (EE_Error $e) {
938
+			return false;
939
+		}
940
+	}
941
+
942
+
943
+	/**
944
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
945
+	 * (or transiently-related model) has a foreign key to the wp_users table;
946
+	 * useful for finding if model objects of this type are 'owned' by the current user.
947
+	 * This is an empty string when the foreign key is on this model and when it isn't,
948
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
949
+	 * (or transiently-related model)
950
+	 *
951
+	 * @return string
952
+	 */
953
+	public function model_chain_to_wp_user()
954
+	{
955
+		return $this->_model_chain_to_wp_user;
956
+	}
957
+
958
+
959
+	/**
960
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
961
+	 * like how registrations don't have a foreign key to wp_users, but the
962
+	 * events they are for are), or is unrelated to wp users.
963
+	 * generally available
964
+	 *
965
+	 * @return boolean
966
+	 */
967
+	public function is_owned()
968
+	{
969
+		if ($this->model_chain_to_wp_user()) {
970
+			return true;
971
+		}
972
+		try {
973
+			$this->get_foreign_key_to('WP_User');
974
+			return true;
975
+		} catch (EE_Error $e) {
976
+			return false;
977
+		}
978
+	}
979
+
980
+
981
+	/**
982
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
983
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
984
+	 * the model)
985
+	 *
986
+	 * @param array  $query_params
987
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
990
+	 *                                  override this and set the select to "*", or a specific column name, like
991
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
+	 *                                  the aliases used to refer to this selection, and values are to be
994
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
+	 * @throws EE_Error
998
+	 * @throws InvalidArgumentException
999
+	 * @throws ReflectionException
1000
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1001
+	 */
1002
+	protected function _get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1003
+	{
1004
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
1005
+		$model_query_info         = $this->_create_model_query_info_carrier($query_params);
1006
+		$select_expressions       = $columns_to_select === null
1007
+			? $this->_construct_default_select_sql($model_query_info)
1008
+			: '';
1009
+		if ($this->_custom_selections instanceof CustomSelects) {
1010
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1011
+			$select_expressions .= $select_expressions
1012
+				? ', ' . $custom_expressions
1013
+				: $custom_expressions;
1014
+		}
1015
+
1016
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1017
+		return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1023
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1024
+	 * method of including extra select information.
1025
+	 *
1026
+	 * @param array             $query_params
1027
+	 * @param null|array|string $columns_to_select
1028
+	 * @return null|CustomSelects
1029
+	 * @throws InvalidArgumentException
1030
+	 */
1031
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1032
+	{
1033
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1034
+			return null;
1035
+		}
1036
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1037
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1038
+		return new CustomSelects($selects);
1039
+	}
1040
+
1041
+
1042
+	/**
1043
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1044
+	 * but you can use the model query params to more easily
1045
+	 * take care of joins, field preparation etc.
1046
+	 *
1047
+	 * @param array  $query_params
1048
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1049
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1050
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1051
+	 *                                  override this and set the select to "*", or a specific column name, like
1052
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1053
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1054
+	 *                                  the aliases used to refer to this selection, and values are to be
1055
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1056
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1057
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1058
+	 * @throws EE_Error
1059
+	 * @throws ReflectionException
1060
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1061
+	 */
1062
+	public function get_all_wpdb_results($query_params = [], $output = ARRAY_A, $columns_to_select = null)
1063
+	{
1064
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1065
+	}
1066
+
1067
+
1068
+	/**
1069
+	 * For creating a custom select statement
1070
+	 *
1071
+	 * @param array|string $columns_to_select either a string to be inserted directly as the select statement,
1072
+	 *                                        or an array where keys are aliases, and values are arrays where 0=>the
1073
+	 *                                        selection SQL, and 1=>is the datatype
1074
+	 * @return string
1075
+	 * @throws EE_Error
1076
+	 */
1077
+	private function _construct_select_from_input($columns_to_select)
1078
+	{
1079
+		if (is_array($columns_to_select)) {
1080
+			$select_sql_array = [];
1081
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083
+					throw new EE_Error(
1084
+						sprintf(
1085
+							esc_html__(
1086
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1087
+								'event_espresso'
1088
+							),
1089
+							$selection_and_datatype,
1090
+							$alias
1091
+						)
1092
+					);
1093
+				}
1094
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1095
+					throw new EE_Error(
1096
+						sprintf(
1097
+							esc_html__(
1098
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1099
+								'event_espresso'
1100
+							),
1101
+							$selection_and_datatype[1],
1102
+							$selection_and_datatype[0],
1103
+							$alias,
1104
+							implode(', ', $this->_valid_wpdb_data_types)
1105
+						)
1106
+					);
1107
+				}
1108
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1109
+			}
1110
+			$columns_to_select_string = implode(', ', $select_sql_array);
1111
+		} else {
1112
+			$columns_to_select_string = $columns_to_select;
1113
+		}
1114
+		return $columns_to_select_string;
1115
+	}
1116
+
1117
+
1118
+	/**
1119
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1120
+	 *
1121
+	 * @return string
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function primary_key_name()
1125
+	{
1126
+		return $this->get_primary_key_field()->get_name();
1127
+	}
1128
+
1129
+
1130
+	/**
1131
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1132
+	 * If there is no primary key on this model, $id is treated as primary key string
1133
+	 *
1134
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1135
+	 * @return EE_Base_Class
1136
+	 * @throws EE_Error
1137
+	 * @throws ReflectionException
1138
+	 */
1139
+	public function get_one_by_ID($id)
1140
+	{
1141
+		if ($this->get_from_entity_map($id)) {
1142
+			return $this->get_from_entity_map($id);
1143
+		}
1144
+		return $this->get_one(
1145
+			$this->alter_query_params_to_restrict_by_ID(
1146
+				$id,
1147
+				['default_where_conditions' => EEM_Base::default_where_conditions_minimum_all]
1148
+			)
1149
+		);
1150
+	}
1151
+
1152
+
1153
+	/**
1154
+	 * Alters query parameters to only get items with this ID are returned.
1155
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1156
+	 * or could just be a simple primary key ID
1157
+	 *
1158
+	 * @param int   $id
1159
+	 * @param array $query_params see github link below for more info
1160
+	 * @return array of normal query params,
1161
+	 * @throws EE_Error
1162
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1163
+	 */
1164
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1165
+	{
1166
+		if (! isset($query_params[0])) {
1167
+			$query_params[0] = [];
1168
+		}
1169
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1170
+		if ($conditions_from_id === null) {
1171
+			$query_params[0][ $this->primary_key_name() ] = $id;
1172
+		} else {
1173
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1174
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1175
+		}
1176
+		return $query_params;
1177
+	}
1178
+
1179
+
1180
+	/**
1181
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1182
+	 * array. If no item is found, null is returned.
1183
+	 *
1184
+	 * @param array $query_params like EEM_Base's $query_params variable.
1185
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1186
+	 * @throws EE_Error
1187
+	 * @throws ReflectionException
1188
+	 */
1189
+	public function get_one($query_params = [])
1190
+	{
1191
+		if (! is_array($query_params)) {
1192
+			EE_Error::doing_it_wrong(
1193
+				'EEM_Base::get_one',
1194
+				sprintf(
1195
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1196
+					gettype($query_params)
1197
+				),
1198
+				'4.6.0'
1199
+			);
1200
+			$query_params = [];
1201
+		}
1202
+		$query_params['limit'] = 1;
1203
+		$items                 = $this->get_all($query_params);
1204
+		if (empty($items)) {
1205
+			return null;
1206
+		}
1207
+		return array_shift($items);
1208
+	}
1209
+
1210
+
1211
+	/**
1212
+	 * Returns the next x number of items in sequence from the given value as
1213
+	 * found in the database matching the given query conditions.
1214
+	 *
1215
+	 * @param mixed $current_field_value    Value used for the reference point.
1216
+	 * @param null  $field_to_order_by      What field is used for the
1217
+	 *                                      reference point.
1218
+	 * @param int   $limit                  How many to return.
1219
+	 * @param array $query_params           Extra conditions on the query.
1220
+	 * @param null  $columns_to_select      If left null, then an array of
1221
+	 *                                      EE_Base_Class objects is returned,
1222
+	 *                                      otherwise you can indicate just the
1223
+	 *                                      columns you want returned.
1224
+	 * @return EE_Base_Class[]|array
1225
+	 * @throws EE_Error
1226
+	 * @throws ReflectionException
1227
+	 */
1228
+	public function next_x(
1229
+		$current_field_value,
1230
+		$field_to_order_by = null,
1231
+		$limit = 1,
1232
+		$query_params = [],
1233
+		$columns_to_select = null
1234
+	) {
1235
+		return $this->_get_consecutive(
1236
+			$current_field_value,
1237
+			'>',
1238
+			$field_to_order_by,
1239
+			$limit,
1240
+			$query_params,
1241
+			$columns_to_select
1242
+		);
1243
+	}
1244
+
1245
+
1246
+	/**
1247
+	 * Returns the previous x number of items in sequence from the given value
1248
+	 * as found in the database matching the given query conditions.
1249
+	 *
1250
+	 * @param mixed $current_field_value    Value used for the reference point.
1251
+	 * @param null  $field_to_order_by      What field is used for the
1252
+	 *                                      reference point.
1253
+	 * @param int   $limit                  How many to return.
1254
+	 * @param array $query_params           Extra conditions on the query.
1255
+	 * @param null  $columns_to_select      If left null, then an array of
1256
+	 *                                      EE_Base_Class objects is returned,
1257
+	 *                                      otherwise you can indicate just the
1258
+	 *                                      columns you want returned.
1259
+	 * @return EE_Base_Class[]|array
1260
+	 * @throws EE_Error
1261
+	 * @throws ReflectionException
1262
+	 */
1263
+	public function previous_x(
1264
+		$current_field_value,
1265
+		$field_to_order_by = null,
1266
+		$limit = 1,
1267
+		$query_params = [],
1268
+		$columns_to_select = null
1269
+	) {
1270
+		return $this->_get_consecutive(
1271
+			$current_field_value,
1272
+			'<',
1273
+			$field_to_order_by,
1274
+			$limit,
1275
+			$query_params,
1276
+			$columns_to_select
1277
+		);
1278
+	}
1279
+
1280
+
1281
+	/**
1282
+	 * Returns the next item in sequence from the given value as found in the
1283
+	 * database matching the given query conditions.
1284
+	 *
1285
+	 * @param mixed $current_field_value    Value used for the reference point.
1286
+	 * @param null  $field_to_order_by      What field is used for the
1287
+	 *                                      reference point.
1288
+	 * @param array $query_params           Extra conditions on the query.
1289
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1290
+	 *                                      object is returned, otherwise you
1291
+	 *                                      can indicate just the columns you
1292
+	 *                                      want and a single array indexed by
1293
+	 *                                      the columns will be returned.
1294
+	 * @return EE_Base_Class|null|array()
1295
+	 * @throws EE_Error
1296
+	 * @throws ReflectionException
1297
+	 */
1298
+	public function next(
1299
+		$current_field_value,
1300
+		$field_to_order_by = null,
1301
+		$query_params = [],
1302
+		$columns_to_select = null
1303
+	) {
1304
+		$results = $this->_get_consecutive(
1305
+			$current_field_value,
1306
+			'>',
1307
+			$field_to_order_by,
1308
+			1,
1309
+			$query_params,
1310
+			$columns_to_select
1311
+		);
1312
+		return empty($results) ? null : reset($results);
1313
+	}
1314
+
1315
+
1316
+	/**
1317
+	 * Returns the previous item in sequence from the given value as found in
1318
+	 * the database matching the given query conditions.
1319
+	 *
1320
+	 * @param mixed $current_field_value    Value used for the reference point.
1321
+	 * @param null  $field_to_order_by      What field is used for the
1322
+	 *                                      reference point.
1323
+	 * @param array $query_params           Extra conditions on the query.
1324
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1325
+	 *                                      object is returned, otherwise you
1326
+	 *                                      can indicate just the columns you
1327
+	 *                                      want and a single array indexed by
1328
+	 *                                      the columns will be returned.
1329
+	 * @return EE_Base_Class|null|array()
1330
+	 * @throws EE_Error
1331
+	 * @throws ReflectionException
1332
+	 */
1333
+	public function previous(
1334
+		$current_field_value,
1335
+		$field_to_order_by = null,
1336
+		$query_params = [],
1337
+		$columns_to_select = null
1338
+	) {
1339
+		$results = $this->_get_consecutive(
1340
+			$current_field_value,
1341
+			'<',
1342
+			$field_to_order_by,
1343
+			1,
1344
+			$query_params,
1345
+			$columns_to_select
1346
+		);
1347
+		return empty($results) ? null : reset($results);
1348
+	}
1349
+
1350
+
1351
+	/**
1352
+	 * Returns the a consecutive number of items in sequence from the given
1353
+	 * value as found in the database matching the given query conditions.
1354
+	 *
1355
+	 * @param mixed  $current_field_value   Value used for the reference point.
1356
+	 * @param string $operand               What operand is used for the sequence.
1357
+	 * @param string $field_to_order_by     What field is used for the reference point.
1358
+	 * @param int    $limit                 How many to return.
1359
+	 * @param array  $query_params          Extra conditions on the query.
1360
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1361
+	 *                                      otherwise you can indicate just the columns you want returned.
1362
+	 * @return EE_Base_Class[]|array
1363
+	 * @throws EE_Error
1364
+	 * @throws ReflectionException
1365
+	 */
1366
+	protected function _get_consecutive(
1367
+		$current_field_value,
1368
+		$operand = '>',
1369
+		$field_to_order_by = null,
1370
+		$limit = 1,
1371
+		$query_params = [],
1372
+		$columns_to_select = null
1373
+	) {
1374
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1375
+		if (empty($field_to_order_by)) {
1376
+			if ($this->has_primary_key_field()) {
1377
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1378
+			} else {
1379
+				if (WP_DEBUG) {
1380
+					throw new EE_Error(
1381
+						esc_html__(
1382
+							'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).',
1383
+							'event_espresso'
1384
+						)
1385
+					);
1386
+				}
1387
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1388
+				return [];
1389
+			}
1390
+		}
1391
+		if (! is_array($query_params)) {
1392
+			EE_Error::doing_it_wrong(
1393
+				'EEM_Base::_get_consecutive',
1394
+				sprintf(
1395
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1396
+					gettype($query_params)
1397
+				),
1398
+				'4.6.0'
1399
+			);
1400
+			$query_params = [];
1401
+		}
1402
+		// let's add the where query param for consecutive look up.
1403
+		$query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1404
+		$query_params['limit']                 = $limit;
1405
+		// set direction
1406
+		$incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1407
+		$query_params['order_by'] = $operand === '>'
1408
+			? [$field_to_order_by => 'ASC'] + $incoming_orderby
1409
+			: [$field_to_order_by => 'DESC'] + $incoming_orderby;
1410
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1411
+		if (empty($columns_to_select)) {
1412
+			return $this->get_all($query_params);
1413
+		}
1414
+		// getting just the fields
1415
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1416
+	}
1417
+
1418
+
1419
+	/**
1420
+	 * This sets the _timezone property after model object has been instantiated.
1421
+	 *
1422
+	 * @param string|null $timezone valid PHP DateTimeZone timezone string
1423
+	 */
1424
+	public function set_timezone($timezone)
1425
+	{
1426
+		// don't set the timezone if the incoming value is the same
1427
+		if (! empty($timezone) && $timezone === $this->_timezone) {
1428
+			return;
1429
+		}
1430
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
1431
+		// note we need to loop through relations and set the timezone on those objects as well.
1432
+		foreach ($this->_model_relations as $relation) {
1433
+			$relation->set_timezone($this->_timezone);
1434
+		}
1435
+		// and finally we do the same for any datetime fields
1436
+		foreach ($this->_fields as $field) {
1437
+			if ($field instanceof EE_Datetime_Field) {
1438
+				$field->set_timezone($this->_timezone);
1439
+			}
1440
+		}
1441
+	}
1442
+
1443
+
1444
+	/**
1445
+	 * This just returns whatever is set for the current timezone.
1446
+	 *
1447
+	 * @access public
1448
+	 * @return string
1449
+	 */
1450
+	public function get_timezone()
1451
+	{
1452
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1453
+		if (empty($this->_timezone)) {
1454
+			foreach ($this->_fields as $field) {
1455
+				if ($field instanceof EE_Datetime_Field) {
1456
+					$this->set_timezone($field->get_timezone());
1457
+					break;
1458
+				}
1459
+			}
1460
+		}
1461
+		// if timezone STILL empty then return the default timezone for the site.
1462
+		if (empty($this->_timezone)) {
1463
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1464
+		}
1465
+		return $this->_timezone;
1466
+	}
1467
+
1468
+
1469
+	/**
1470
+	 * This returns the date formats set for the given field name and also ensures that
1471
+	 * $this->_timezone property is set correctly.
1472
+	 *
1473
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1474
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1475
+	 * @return array formats in an array with the date format first, and the time format last.
1476
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1477
+	 * @since 4.6.x
1478
+	 */
1479
+	public function get_formats_for($field_name, $pretty = false)
1480
+	{
1481
+		$field_settings = $this->field_settings_for($field_name);
1482
+		// if not a valid EE_Datetime_Field then throw error
1483
+		if (! $field_settings instanceof EE_Datetime_Field) {
1484
+			throw new EE_Error(
1485
+				sprintf(
1486
+					esc_html__(
1487
+						'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.',
1488
+						'event_espresso'
1489
+					),
1490
+					$field_name
1491
+				)
1492
+			);
1493
+		}
1494
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1495
+		// the field.
1496
+		$this->_timezone = $field_settings->get_timezone();
1497
+		return [$field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty)];
1498
+	}
1499
+
1500
+
1501
+	/**
1502
+	 * This returns the current time in a format setup for a query on this model.
1503
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1504
+	 * it will return:
1505
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1506
+	 *  NOW
1507
+	 *  - or a unix timestamp (equivalent to time())
1508
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1509
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1510
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1511
+	 *
1512
+	 * @param string $field_name       The field the current time is needed for.
1513
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1514
+	 *                                 formatted string matching the set format for the field in the set timezone will
1515
+	 *                                 be returned.
1516
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1517
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1518
+	 *                                 exception is triggered.
1519
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1520
+	 * @throws Exception
1521
+	 * @since 4.6.x
1522
+	 */
1523
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1524
+	{
1525
+		$formats  = $this->get_formats_for($field_name);
1526
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1527
+		if ($timestamp) {
1528
+			return $DateTime->format('U');
1529
+		}
1530
+		// not returning timestamp, so return formatted string in timezone.
1531
+		switch ($what) {
1532
+			case 'time':
1533
+				return $DateTime->format($formats[1]);
1534
+			case 'date':
1535
+				return $DateTime->format($formats[0]);
1536
+			default:
1537
+				return $DateTime->format(implode(' ', $formats));
1538
+		}
1539
+	}
1540
+
1541
+
1542
+	/**
1543
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1544
+	 * for the model are.  Returns a DateTime object.
1545
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1546
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1547
+	 * ignored.
1548
+	 *
1549
+	 * @param string $field_name      The field being setup.
1550
+	 * @param string $timestring      The date time string being used.
1551
+	 * @param string $incoming_format The format for the time string.
1552
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1553
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1554
+	 *                                format is
1555
+	 *                                'U', this is ignored.
1556
+	 * @return DateTime
1557
+	 * @throws EE_Error
1558
+	 */
1559
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1560
+	{
1561
+		// just using this to ensure the timezone is set correctly internally
1562
+		$this->get_formats_for($field_name);
1563
+		// load EEH_DTT_Helper
1564
+		$set_timezone     = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1565
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1566
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1567
+		return DbSafeDateTime::createFromDateTime($incomingDateTime);
1568
+	}
1569
+
1570
+
1571
+	/**
1572
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1573
+	 *
1574
+	 * @return EE_Table_Base[]
1575
+	 */
1576
+	public function get_tables()
1577
+	{
1578
+		return $this->_tables;
1579
+	}
1580
+
1581
+
1582
+	/**
1583
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1584
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1585
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1586
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1587
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1588
+	 * model object with EVT_ID = 1
1589
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1590
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1591
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1592
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1593
+	 * are not specified)
1594
+	 *
1595
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1596
+	 *                                         columns!), values are strings, integers, floats, and maybe arrays if
1597
+	 *                                         they
1598
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1599
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1600
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1601
+	 *                                         ID=34, we'd use this method as follows:
1602
+	 *                                         EEM_Transaction::instance()->update(
1603
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1604
+	 *                                         array(array('TXN_ID'=>34)));
1605
+	 * @param array   $query_params            Eg, consider updating Question's QST_admin_label field is of type
1606
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1607
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1608
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1609
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1610
+	 *                                         TRUE, it is assumed that you've already called
1611
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1612
+	 *                                         malicious javascript. However, if
1613
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1614
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1615
+	 *                                         and every other field, before insertion. We provide this parameter
1616
+	 *                                         because model objects perform their prepare_for_set function on all
1617
+	 *                                         their values, and so don't need to be called again (and in many cases,
1618
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1619
+	 *                                         prepare_for_set method...)
1620
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1621
+	 *                                         in this model's entity map according to $fields_n_values that match
1622
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1623
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1624
+	 *                                         could get out-of-sync with the database
1625
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1626
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1627
+	 *                                         bad)
1628
+	 * @throws EE_Error
1629
+	 * @throws ReflectionException
1630
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1631
+	 */
1632
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1633
+	{
1634
+		if (! is_array($query_params)) {
1635
+			EE_Error::doing_it_wrong(
1636
+				'EEM_Base::update',
1637
+				sprintf(
1638
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1639
+					gettype($query_params)
1640
+				),
1641
+				'4.6.0'
1642
+			);
1643
+			$query_params = [];
1644
+		}
1645
+		/**
1646
+		 * Action called before a model update call has been made.
1647
+		 *
1648
+		 * @param EEM_Base $model
1649
+		 * @param array    $fields_n_values the updated fields and their new values
1650
+		 * @param array    $query_params
1651
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1652
+		 */
1653
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1654
+		/**
1655
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1656
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1657
+		 *
1658
+		 * @param array    $fields_n_values fields and their new values
1659
+		 * @param EEM_Base $model           the model being queried
1660
+		 * @param array    $query_params
1661
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1662
+		 */
1663
+		$fields_n_values = (array)apply_filters(
1664
+			'FHEE__EEM_Base__update__fields_n_values',
1665
+			$fields_n_values,
1666
+			$this,
1667
+			$query_params
1668
+		);
1669
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1670
+		// to do that, for each table, verify that it's PK isn't null.
1671
+		$tables = $this->get_tables();
1672
+		// 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
1673
+		// NOTE: we should make this code more efficient by NOT querying twice
1674
+		// before the real update, but that needs to first go through ALPHA testing
1675
+		// as it's dangerous. says Mike August 8 2014
1676
+		// we want to make sure the default_where strategy is ignored
1677
+		$this->_ignore_where_strategy = true;
1678
+		$wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1679
+		foreach ($wpdb_select_results as $wpdb_result) {
1680
+			// type cast stdClass as array
1681
+			$wpdb_result = (array)$wpdb_result;
1682
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1683
+			if ($this->has_primary_key_field()) {
1684
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1685
+			} else {
1686
+				// 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)
1687
+				$main_table_pk_value = null;
1688
+			}
1689
+			// 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
1690
+			// 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
1691
+			if (count($tables) > 1) {
1692
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1693
+				// in that table, and so we'll want to insert one
1694
+				foreach ($tables as $table_obj) {
1695
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1696
+					// if there is no private key for this table on the results, it means there's no entry
1697
+					// in this table, right? so insert a row in the current table, using any fields available
1698
+					if (
1699
+					! (array_key_exists($this_table_pk_column, $wpdb_result)
1700
+					   && $wpdb_result[ $this_table_pk_column ])
1701
+					) {
1702
+						$success = $this->_insert_into_specific_table(
1703
+							$table_obj,
1704
+							$fields_n_values,
1705
+							$main_table_pk_value
1706
+						);
1707
+						// if we died here, report the error
1708
+						if (! $success) {
1709
+							return false;
1710
+						}
1711
+					}
1712
+				}
1713
+			}
1714
+			//              //and now check that if we have cached any models by that ID on the model, that
1715
+			//              //they also get updated properly
1716
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1717
+			//              if( $model_object ){
1718
+			//                  foreach( $fields_n_values as $field => $value ){
1719
+			//                      $model_object->set($field, $value);
1720
+			// let's make sure default_where strategy is followed now
1721
+			$this->_ignore_where_strategy = false;
1722
+		}
1723
+		// if we want to keep model objects in sync, AND
1724
+		// if this wasn't called from a model object (to update itself)
1725
+		// then we want to make sure we keep all the existing
1726
+		// model objects in sync with the db
1727
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1728
+			if ($this->has_primary_key_field()) {
1729
+				$model_objs_affected_ids = $this->get_col($query_params);
1730
+			} else {
1731
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1732
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params);
1733
+				$model_objs_affected_ids     = [];
1734
+				foreach ($models_affected_key_columns as $row) {
1735
+					$combined_index_key                             = $this->get_index_primary_key_string($row);
1736
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1737
+				}
1738
+			}
1739
+			if (! $model_objs_affected_ids) {
1740
+				// wait wait wait- if nothing was affected let's stop here
1741
+				return 0;
1742
+			}
1743
+			foreach ($model_objs_affected_ids as $id) {
1744
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1745
+				if ($model_obj_in_entity_map) {
1746
+					foreach ($fields_n_values as $field => $new_value) {
1747
+						$model_obj_in_entity_map->set($field, $new_value);
1748
+					}
1749
+				}
1750
+			}
1751
+			// if there is a primary key on this model, we can now do a slight optimization
1752
+			if ($this->has_primary_key_field()) {
1753
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1754
+				$query_params = [
1755
+					[$this->primary_key_name() => ['IN', $model_objs_affected_ids]],
1756
+					'limit'                    => count($model_objs_affected_ids),
1757
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1758
+				];
1759
+			}
1760
+		}
1761
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1762
+		$SQL              = "UPDATE "
1763
+							. $model_query_info->get_full_join_sql()
1764
+							. " SET "
1765
+							. $this->_construct_update_sql($fields_n_values)
1766
+							. $model_query_info->get_where_sql(
1767
+			);// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1768
+		$rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1769
+		/**
1770
+		 * Action called after a model update call has been made.
1771
+		 *
1772
+		 * @param EEM_Base $model
1773
+		 * @param array    $fields_n_values the updated fields and their new values
1774
+		 * @param array    $query_params
1775
+		 * @param int      $rows_affected
1776
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1777
+		 */
1778
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1779
+		return $rows_affected;// how many supposedly got updated
1780
+	}
1781
+
1782
+
1783
+	/**
1784
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1785
+	 * are teh values of the field specified (or by default the primary key field)
1786
+	 * that matched the query params. Note that you should pass the name of the
1787
+	 * model FIELD, not the database table's column name.
1788
+	 *
1789
+	 * @param array  $query_params
1790
+	 * @param string $field_to_select
1791
+	 * @return array just like $wpdb->get_col()
1792
+	 * @throws EE_Error
1793
+	 * @throws ReflectionException
1794
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1795
+	 */
1796
+	public function get_col($query_params = [], $field_to_select = null)
1797
+	{
1798
+		if ($field_to_select) {
1799
+			$field = $this->field_settings_for($field_to_select);
1800
+		} elseif ($this->has_primary_key_field()) {
1801
+			$field = $this->get_primary_key_field();
1802
+		} else {
1803
+			$field_settings = $this->field_settings();
1804
+			// no primary key, just grab the first column
1805
+			$field = reset($field_settings);
1806
+		}
1807
+		$model_query_info   = $this->_create_model_query_info_carrier($query_params);
1808
+		$select_expressions = $field->get_qualified_column();
1809
+		$SQL                =
1810
+			"SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1811
+		return $this->_do_wpdb_query('get_col', [$SQL]);
1812
+	}
1813
+
1814
+
1815
+	/**
1816
+	 * Returns a single column value for a single row from the database
1817
+	 *
1818
+	 * @param array  $query_params
1819
+	 * @param string $field_to_select
1820
+	 * @return string
1821
+	 * @throws EE_Error
1822
+	 * @throws ReflectionException
1823
+	 * @see EEM_Base::get_col()
1824
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1825
+	 */
1826
+	public function get_var($query_params = [], $field_to_select = null)
1827
+	{
1828
+		$query_params['limit'] = 1;
1829
+		$col                   = $this->get_col($query_params, $field_to_select);
1830
+		if (! empty($col)) {
1831
+			return reset($col);
1832
+		}
1833
+		return null;
1834
+	}
1835
+
1836
+
1837
+	/**
1838
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1839
+	 * time?', Question.desc='what do you think?'..." Values are filtered through wpdb->prepare to avoid against SQL
1840
+	 * injection, but currently no further filtering is done
1841
+	 *
1842
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1843
+	 *                               be updated to in the DB
1844
+	 * @return string of SQL
1845
+	 * @throws EE_Error
1846
+	 * @global      $wpdb
1847
+	 */
1848
+	public function _construct_update_sql($fields_n_values)
1849
+	{
1850
+		global $wpdb;
1851
+		$cols_n_values = [];
1852
+		foreach ($fields_n_values as $field_name => $value) {
1853
+			$field_obj = $this->field_settings_for($field_name);
1854
+			// if the value is NULL, we want to assign the value to that.
1855
+			// wpdb->prepare doesn't really handle that properly
1856
+			$prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1857
+			$value_sql       = $prepared_value === null ? 'NULL'
1858
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1859
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1860
+		}
1861
+		return implode(",", $cols_n_values);
1862
+	}
1863
+
1864
+
1865
+	/**
1866
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1867
+	 * Performs a HARD delete, meaning the database row should always be removed,
1868
+	 * not just have a flag field on it switched
1869
+	 * Wrapper for EEM_Base::delete_permanently()
1870
+	 *
1871
+	 * @param mixed   $id
1872
+	 * @param boolean $allow_blocking
1873
+	 * @return int the number of rows deleted
1874
+	 * @throws EE_Error
1875
+	 * @throws ReflectionException
1876
+	 */
1877
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1878
+	{
1879
+		return $this->delete_permanently(
1880
+			[
1881
+				[$this->get_primary_key_field()->get_name() => $id],
1882
+				'limit' => 1,
1883
+			],
1884
+			$allow_blocking
1885
+		);
1886
+	}
1887
+
1888
+
1889
+	/**
1890
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1891
+	 * Wrapper for EEM_Base::delete()
1892
+	 *
1893
+	 * @param mixed   $id
1894
+	 * @param boolean $allow_blocking
1895
+	 * @return int the number of rows deleted
1896
+	 * @throws EE_Error
1897
+	 * @throws ReflectionException
1898
+	 */
1899
+	public function delete_by_ID($id, $allow_blocking = true)
1900
+	{
1901
+		return $this->delete(
1902
+			[
1903
+				[$this->get_primary_key_field()->get_name() => $id],
1904
+				'limit' => 1,
1905
+			],
1906
+			$allow_blocking
1907
+		);
1908
+	}
1909
+
1910
+
1911
+	/**
1912
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1913
+	 * meaning if the model has a field that indicates its been "trashed" or
1914
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1915
+	 *
1916
+	 * @param array   $query_params
1917
+	 * @param boolean $allow_blocking
1918
+	 * @return int how many rows got deleted
1919
+	 * @throws EE_Error
1920
+	 * @throws ReflectionException
1921
+	 * @see EEM_Base::delete_permanently
1922
+	 */
1923
+	public function delete($query_params, $allow_blocking = true)
1924
+	{
1925
+		return $this->delete_permanently($query_params, $allow_blocking);
1926
+	}
1927
+
1928
+
1929
+	/**
1930
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1931
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1932
+	 * as archived, not actually deleted
1933
+	 *
1934
+	 * @param array   $query_params
1935
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1936
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1937
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1938
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1939
+	 *                                DB
1940
+	 * @return int how many rows got deleted
1941
+	 * @throws EE_Error
1942
+	 * @throws ReflectionException
1943
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1944
+	 */
1945
+	public function delete_permanently($query_params, $allow_blocking = true)
1946
+	{
1947
+		/**
1948
+		 * Action called just before performing a real deletion query. You can use the
1949
+		 * model and its $query_params to find exactly which items will be deleted
1950
+		 *
1951
+		 * @param EEM_Base $model
1952
+		 * @param array    $query_params
1953
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1954
+		 *                                 to block (prevent) this deletion
1955
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1956
+		 */
1957
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1958
+		// some MySQL databases may be running safe mode, which may restrict
1959
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1960
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1961
+		// to delete them
1962
+		$items_for_deletion           = $this->_get_all_wpdb_results($query_params);
1963
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1964
+		$deletion_where_query_part    = $this->_build_query_part_for_deleting_from_columns_and_values(
1965
+			$columns_and_ids_for_deleting
1966
+		);
1967
+		/**
1968
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1969
+		 *
1970
+		 * @param EEM_Base $this                            The model instance being acted on.
1971
+		 * @param array    $query_params                    The incoming array of query parameters influencing what gets deleted.
1972
+		 * @param bool     $allow_blocking                  @see param description in method phpdoc block.
1973
+		 * @param array    $columns_and_ids_for_deleting    An array indicating what entities will get removed as
1974
+		 *                                                  derived from the incoming query parameters.
1975
+		 * @see details on the structure of this array in the phpdocs
1976
+		 *                                                  for the `_get_ids_for_delete_method`
1977
+		 *
1978
+		 */
1979
+		do_action(
1980
+			'AHEE__EEM_Base__delete__before_query',
1981
+			$this,
1982
+			$query_params,
1983
+			$allow_blocking,
1984
+			$columns_and_ids_for_deleting
1985
+		);
1986
+		if ($deletion_where_query_part) {
1987
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1988
+			$table_aliases    = array_keys($this->_tables);
1989
+			$SQL              = "DELETE "
1990
+								. implode(", ", $table_aliases)
1991
+								. " FROM "
1992
+								. $model_query_info->get_full_join_sql()
1993
+								. " WHERE "
1994
+								. $deletion_where_query_part;
1995
+			$rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1996
+		} else {
1997
+			$rows_deleted = 0;
1998
+		}
1999
+
2000
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2001
+		// there was no error with the delete query.
2002
+		if (
2003
+			$this->has_primary_key_field()
2004
+			&& $rows_deleted !== false
2005
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2006
+		) {
2007
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2008
+			foreach ($ids_for_removal as $id) {
2009
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2010
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2011
+				}
2012
+			}
2013
+
2014
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2015
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2016
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2017
+			// (although it is possible).
2018
+			// Note this can be skipped by using the provided filter and returning false.
2019
+			if (
2020
+			apply_filters(
2021
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2022
+				! $this instanceof EEM_Extra_Meta,
2023
+				$this
2024
+			)
2025
+			) {
2026
+				EEM_Extra_Meta::instance()->delete_permanently(
2027
+					[
2028
+						0 => [
2029
+							'EXM_type' => $this->get_this_model_name(),
2030
+							'OBJ_ID'   => [
2031
+								'IN',
2032
+								$ids_for_removal,
2033
+							],
2034
+						],
2035
+					]
2036
+				);
2037
+			}
2038
+		}
2039
+
2040
+		/**
2041
+		 * Action called just after performing a real deletion query. Although at this point the
2042
+		 * items should have been deleted
2043
+		 *
2044
+		 * @param EEM_Base $model
2045
+		 * @param array    $query_params
2046
+		 * @param int      $rows_deleted
2047
+		 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2048
+		 */
2049
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
+		return $rows_deleted;// how many supposedly got deleted
2051
+	}
2052
+
2053
+
2054
+	/**
2055
+	 * Checks all the relations that throw error messages when there are blocking related objects
2056
+	 * for related model objects. If there are any related model objects on those relations,
2057
+	 * adds an EE_Error, and return true
2058
+	 *
2059
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2060
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2061
+	 *                                                 should be ignored when determining whether there are related
2062
+	 *                                                 model objects which block this model object's deletion. Useful
2063
+	 *                                                 if you know A is related to B and are considering deleting A,
2064
+	 *                                                 but want to see if A has any other objects blocking its deletion
2065
+	 *                                                 before removing the relation between A and B
2066
+	 * @return boolean
2067
+	 * @throws EE_Error
2068
+	 * @throws ReflectionException
2069
+	 */
2070
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2071
+	{
2072
+		// first, if $ignore_this_model_obj was supplied, get its model
2073
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2074
+			$ignored_model = $ignore_this_model_obj->get_model();
2075
+		} else {
2076
+			$ignored_model = null;
2077
+		}
2078
+		// now check all the relations of $this_model_obj_or_id and see if there
2079
+		// are any related model objects blocking it?
2080
+		$is_blocked = false;
2081
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2082
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2083
+				// if $ignore_this_model_obj was supplied, then for the query
2084
+				// on that model needs to be told to ignore $ignore_this_model_obj
2085
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2086
+					$related_model_objects = $relation_obj->get_all_related(
2087
+						$this_model_obj_or_id,
2088
+						[
2089
+							[
2090
+								$ignored_model->get_primary_key_field()->get_name() => [
2091
+									'!=',
2092
+									$ignore_this_model_obj->ID(),
2093
+								],
2094
+							],
2095
+						]
2096
+					);
2097
+				} else {
2098
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2099
+				}
2100
+				if ($related_model_objects) {
2101
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2102
+					$is_blocked = true;
2103
+				}
2104
+			}
2105
+		}
2106
+		return $is_blocked;
2107
+	}
2108
+
2109
+
2110
+	/**
2111
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2112
+	 *
2113
+	 * @param array $row_results_for_deleting
2114
+	 * @param bool  $allow_blocking
2115
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2116
+	 *                              model DOES have a primary_key_field, then the array will be a simple single
2117
+	 *                              dimension array where the key is the fully qualified primary key column and the
2118
+	 *                              value is an array of ids that will be deleted. Example: array('Event.EVT_ID' =>
2119
+	 *                              array( 1,2,3)) If the model DOES NOT have a primary_key_field, then the array will
2120
+	 *                              be a two dimensional array where each element is a group of columns and values that
2121
+	 *                              get deleted. Example: array(
2122
+	 *                              0 => array(
2123
+	 *                              'Term_Relationship.object_id' => 1
2124
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2125
+	 *                              ),
2126
+	 *                              1 => array(
2127
+	 *                              'Term_Relationship.object_id' => 1
2128
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2129
+	 *                              )
2130
+	 *                              )
2131
+	 * @throws EE_Error
2132
+	 * @throws ReflectionException
2133
+	 */
2134
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2135
+	{
2136
+		$ids_to_delete_indexed_by_column = [];
2137
+		if ($this->has_primary_key_field()) {
2138
+			$primary_table                   = $this->_get_main_table();
2139
+			$ids_to_delete_indexed_by_column = $query = [];
2140
+			foreach ($row_results_for_deleting as $item_to_delete) {
2141
+				// before we mark this item for deletion,
2142
+				// make sure there's no related entities blocking its deletion (if we're checking)
2143
+				if (
2144
+					$allow_blocking
2145
+					&& $this->delete_is_blocked_by_related_models(
2146
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2147
+					)
2148
+				) {
2149
+					continue;
2150
+				}
2151
+				// primary table deletes
2152
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2153
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2154
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2155
+				}
2156
+			}
2157
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2158
+			$fields = $this->get_combined_primary_key_fields();
2159
+			foreach ($row_results_for_deleting as $item_to_delete) {
2160
+				$ids_to_delete_indexed_by_column_for_row = [];
2161
+				foreach ($fields as $cpk_field) {
2162
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2163
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2164
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2165
+					}
2166
+				}
2167
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2168
+			}
2169
+		} else {
2170
+			// so there's no primary key and no combined key...
2171
+			// sorry, can't help you
2172
+			throw new EE_Error(
2173
+				sprintf(
2174
+					esc_html__(
2175
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2176
+						"event_espresso"
2177
+					),
2178
+					get_class($this)
2179
+				)
2180
+			);
2181
+		}
2182
+		return $ids_to_delete_indexed_by_column;
2183
+	}
2184
+
2185
+
2186
+	/**
2187
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2188
+	 * the corresponding query_part for the query performing the delete.
2189
+	 *
2190
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2191
+	 * @return string
2192
+	 * @throws EE_Error
2193
+	 */
2194
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2195
+	{
2196
+		$query_part = '';
2197
+		if (empty($ids_to_delete_indexed_by_column)) {
2198
+			return $query_part;
2199
+		} elseif ($this->has_primary_key_field()) {
2200
+			$query = [];
2201
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2202
+				// make sure we have unique $ids
2203
+				$ids     = array_unique($ids);
2204
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2205
+			}
2206
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2207
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2208
+			$ways_to_identify_a_row = [];
2209
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2210
+				$values_for_each_combined_primary_key_for_a_row = [];
2211
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2212
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2213
+				}
2214
+				$ways_to_identify_a_row[] = '('
2215
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2216
+											. ')';
2217
+			}
2218
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2219
+		}
2220
+		return $query_part;
2221
+	}
2222
+
2223
+
2224
+	/**
2225
+	 * Gets the model field by the fully qualified name
2226
+	 *
2227
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2228
+	 * @return EE_Model_Field_Base
2229
+	 * @throws EE_Error
2230
+	 */
2231
+	public function get_field_by_column($qualified_column_name)
2232
+	{
2233
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2234
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2235
+				return $field_obj;
2236
+			}
2237
+		}
2238
+		throw new EE_Error(
2239
+			sprintf(
2240
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2241
+				$this->get_this_model_name(),
2242
+				$qualified_column_name
2243
+			)
2244
+		);
2245
+	}
2246
+
2247
+
2248
+	/**
2249
+	 * Count all the rows that match criteria the model query params.
2250
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2251
+	 * column
2252
+	 *
2253
+	 * @param array  $query_params
2254
+	 * @param string $field_to_count field on model to count by (not column name)
2255
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2256
+	 *                               that by the setting $distinct to TRUE;
2257
+	 * @return int
2258
+	 * @throws EE_Error
2259
+	 * @throws ReflectionException
2260
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2261
+	 */
2262
+	public function count($query_params = [], $field_to_count = null, $distinct = false)
2263
+	{
2264
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2265
+		if ($field_to_count) {
2266
+			$field_obj       = $this->field_settings_for($field_to_count);
2267
+			$column_to_count = $field_obj->get_qualified_column();
2268
+		} elseif ($this->has_primary_key_field()) {
2269
+			$pk_field_obj    = $this->get_primary_key_field();
2270
+			$column_to_count = $pk_field_obj->get_qualified_column();
2271
+		} else {
2272
+			// there's no primary key
2273
+			// if we're counting distinct items, and there's no primary key,
2274
+			// we need to list out the columns for distinction;
2275
+			// otherwise we can just use star
2276
+			if ($distinct) {
2277
+				$columns_to_use = [];
2278
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2279
+					$columns_to_use[] = $field_obj->get_qualified_column();
2280
+				}
2281
+				$column_to_count = implode(',', $columns_to_use);
2282
+			} else {
2283
+				$column_to_count = '*';
2284
+			}
2285
+		}
2286
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2287
+		$SQL             =
2288
+			"SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
+		return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2290
+	}
2291
+
2292
+
2293
+	/**
2294
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2295
+	 *
2296
+	 * @param array  $query_params
2297
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2298
+	 * @return float
2299
+	 * @throws EE_Error
2300
+	 * @throws ReflectionException
2301
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2302
+	 */
2303
+	public function sum($query_params, $field_to_sum = null)
2304
+	{
2305
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
+		if ($field_to_sum) {
2307
+			$field_obj = $this->field_settings_for($field_to_sum);
2308
+		} else {
2309
+			$field_obj = $this->get_primary_key_field();
2310
+		}
2311
+		$column_to_count = $field_obj->get_qualified_column();
2312
+		$SQL             =
2313
+			"SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2314
+		$return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315
+		$data_type       = $field_obj->get_wpdb_data_type();
2316
+		if ($data_type === '%d' || $data_type === '%s') {
2317
+			return (float)$return_value;
2318
+		}
2319
+		// must be %f
2320
+		return (float)$return_value;
2321
+	}
2322
+
2323
+
2324
+	/**
2325
+	 * Just calls the specified method on $wpdb with the given arguments
2326
+	 * Consolidates a little extra error handling code
2327
+	 *
2328
+	 * @param string $wpdb_method
2329
+	 * @param array  $arguments_to_provide
2330
+	 * @return mixed
2331
+	 * @throws EE_Error
2332
+	 * @global wpdb  $wpdb
2333
+	 */
2334
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
+	{
2336
+		// if we're in maintenance mode level 2, DON'T run any queries
2337
+		// because level 2 indicates the database needs updating and
2338
+		// is probably out of sync with the code
2339
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
+			throw new EE_Error(
2341
+				sprintf(
2342
+					esc_html__(
2343
+						"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.",
2344
+						"event_espresso"
2345
+					)
2346
+				)
2347
+			);
2348
+		}
2349
+		global $wpdb;
2350
+		if (! method_exists($wpdb, $wpdb_method)) {
2351
+			throw new EE_Error(
2352
+				sprintf(
2353
+					esc_html__(
2354
+						'There is no method named "%s" on Wordpress\' $wpdb object',
2355
+						'event_espresso'
2356
+					),
2357
+					$wpdb_method
2358
+				)
2359
+			);
2360
+		}
2361
+		$old_show_errors_value = $wpdb->show_errors;
2362
+		if (WP_DEBUG) {
2363
+			$wpdb->show_errors(false);
2364
+		}
2365
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2366
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2367
+		if (WP_DEBUG) {
2368
+			$wpdb->show_errors($old_show_errors_value);
2369
+			if (! empty($wpdb->last_error)) {
2370
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371
+			}
2372
+			if ($result === false) {
2373
+				throw new EE_Error(
2374
+					sprintf(
2375
+						esc_html__(
2376
+							'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2377
+							'event_espresso'
2378
+						),
2379
+						$wpdb_method,
2380
+						var_export($arguments_to_provide, true)
2381
+					)
2382
+				);
2383
+			}
2384
+		} elseif ($result === false) {
2385
+			EE_Error::add_error(
2386
+				sprintf(
2387
+					esc_html__(
2388
+						'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"',
2389
+						'event_espresso'
2390
+					),
2391
+					$wpdb_method,
2392
+					var_export($arguments_to_provide, true),
2393
+					$wpdb->last_error
2394
+				),
2395
+				__FILE__,
2396
+				__FUNCTION__,
2397
+				__LINE__
2398
+			);
2399
+		}
2400
+		return $result;
2401
+	}
2402
+
2403
+
2404
+	/**
2405
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2406
+	 * and if there's an error tries to verify the DB is correct. Uses
2407
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2408
+	 * we should try to fix the EE core db, the addons, or just give up
2409
+	 *
2410
+	 * @param string $wpdb_method
2411
+	 * @param array  $arguments_to_provide
2412
+	 * @return mixed
2413
+	 * @throws EE_Error
2414
+	 */
2415
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2416
+	{
2417
+		global $wpdb;
2418
+		$wpdb->last_error = null;
2419
+		$result           = call_user_func_array([$wpdb, $wpdb_method], $arguments_to_provide);
2420
+		// was there an error running the query? but we don't care on new activations
2421
+		// (we're going to setup the DB anyway on new activations)
2422
+		if (
2423
+			($result === false || ! empty($wpdb->last_error))
2424
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2425
+		) {
2426
+			switch (EEM_Base::$_db_verification_level) {
2427
+				case EEM_Base::db_verified_none:
2428
+					// let's double-check core's DB
2429
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2430
+					break;
2431
+				case EEM_Base::db_verified_core:
2432
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2433
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2434
+					break;
2435
+				case EEM_Base::db_verified_addons:
2436
+					// ummmm... you in trouble
2437
+					return $result;
2438
+			}
2439
+			if (! empty($error_message)) {
2440
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441
+				trigger_error($error_message);
2442
+			}
2443
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2444
+		}
2445
+		return $result;
2446
+	}
2447
+
2448
+
2449
+	/**
2450
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2451
+	 * EEM_Base::$_db_verification_level
2452
+	 *
2453
+	 * @param string $wpdb_method
2454
+	 * @param array  $arguments_to_provide
2455
+	 * @return string
2456
+	 * @throws EE_Error
2457
+	 */
2458
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2459
+	{
2460
+		global $wpdb;
2461
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2462
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2463
+		$error_message                    = sprintf(
2464
+			esc_html__(
2465
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2466
+				'event_espresso'
2467
+			),
2468
+			$wpdb->last_error,
2469
+			$wpdb_method,
2470
+			wp_json_encode($arguments_to_provide)
2471
+		);
2472
+		EE_System::instance()->initialize_db_if_no_migrations_required();
2473
+		return $error_message;
2474
+	}
2475
+
2476
+
2477
+	/**
2478
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2479
+	 * EEM_Base::$_db_verification_level
2480
+	 *
2481
+	 * @param $wpdb_method
2482
+	 * @param $arguments_to_provide
2483
+	 * @return string
2484
+	 * @throws EE_Error
2485
+	 */
2486
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2487
+	{
2488
+		global $wpdb;
2489
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2490
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2491
+		$error_message                    = sprintf(
2492
+			esc_html__(
2493
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2494
+				'event_espresso'
2495
+			),
2496
+			$wpdb->last_error,
2497
+			$wpdb_method,
2498
+			wp_json_encode($arguments_to_provide)
2499
+		);
2500
+		EE_System::instance()->initialize_addons();
2501
+		return $error_message;
2502
+	}
2503
+
2504
+
2505
+	/**
2506
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2507
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2508
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2509
+	 * ..."
2510
+	 *
2511
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2512
+	 * @return string
2513
+	 */
2514
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515
+	{
2516
+		return " FROM " . $model_query_info->get_full_join_sql() .
2517
+			   $model_query_info->get_where_sql() .
2518
+			   $model_query_info->get_group_by_sql() .
2519
+			   $model_query_info->get_having_sql() .
2520
+			   $model_query_info->get_order_by_sql() .
2521
+			   $model_query_info->get_limit_sql();
2522
+	}
2523
+
2524
+
2525
+	/**
2526
+	 * Set to easily debug the next X queries ran from this model.
2527
+	 *
2528
+	 * @param int $count
2529
+	 */
2530
+	public function show_next_x_db_queries($count = 1)
2531
+	{
2532
+		$this->_show_next_x_db_queries = $count;
2533
+	}
2534
+
2535
+
2536
+	/**
2537
+	 * @param $sql_query
2538
+	 */
2539
+	public function show_db_query_if_previously_requested($sql_query)
2540
+	{
2541
+		if ($this->_show_next_x_db_queries > 0) {
2542
+			echo $sql_query;
2543
+			$this->_show_next_x_db_queries--;
2544
+		}
2545
+	}
2546
+
2547
+
2548
+	/**
2549
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2550
+	 * There are the 3 cases:
2551
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2552
+	 * $otherModelObject has no ID, it is first saved.
2553
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2554
+	 * has no ID, it is first saved.
2555
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2556
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2557
+	 * join table
2558
+	 *
2559
+	 * @param EE_Base_Class                     /int $thisModelObject
2560
+	 * @param EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2561
+	 * @param string $relationName                     , key in EEM_Base::_relations
2562
+	 *                                                 an attendee to a group, you also want to specify which role they
2563
+	 *                                                 will have in that group. So you would use this parameter to
2564
+	 *                                                 specify array('role-column-name'=>'role-id')
2565
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2566
+	 *                                                 to for relation to methods that allow you to further specify
2567
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2568
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2569
+	 *                                                 because these will be inserted in any new rows created as well.
2570
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2571
+	 * @throws EE_Error
2572
+	 */
2573
+	public function add_relationship_to(
2574
+		$id_or_obj,
2575
+		$other_model_id_or_obj,
2576
+		$relationName,
2577
+		$extra_join_model_fields_n_values = []
2578
+	) {
2579
+		$relation_obj = $this->related_settings_for($relationName);
2580
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2581
+	}
2582
+
2583
+
2584
+	/**
2585
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2586
+	 * There are the 3 cases:
2587
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2588
+	 * error
2589
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2590
+	 * an error
2591
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2592
+	 *
2593
+	 * @param EE_Base_Class /int $id_or_obj
2594
+	 * @param EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2595
+	 * @param string $relationName key in EEM_Base::_relations
2596
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2597
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2598
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2599
+	 *                             because these will be inserted in any new rows created as well.
2600
+	 * @return boolean of success
2601
+	 * @throws EE_Error
2602
+	 */
2603
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = [])
2604
+	{
2605
+		$relation_obj = $this->related_settings_for($relationName);
2606
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2607
+	}
2608
+
2609
+
2610
+	/**
2611
+	 * @param mixed  $id_or_obj
2612
+	 * @param string $relationName
2613
+	 * @param array  $where_query_params
2614
+	 * @param EE_Base_Class[] objects to which relations were removed
2615
+	 * @return EE_Base_Class[]
2616
+	 * @throws EE_Error
2617
+	 */
2618
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = [])
2619
+	{
2620
+		$relation_obj = $this->related_settings_for($relationName);
2621
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2622
+	}
2623
+
2624
+
2625
+	/**
2626
+	 * Gets all the related items of the specified $model_name, using $query_params.
2627
+	 * Note: by default, we remove the "default query params"
2628
+	 * because we want to get even deleted items etc.
2629
+	 *
2630
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2631
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2632
+	 * @param array  $query_params see github link below for more info
2633
+	 * @return EE_Base_Class[]
2634
+	 * @throws EE_Error
2635
+	 * @throws ReflectionException
2636
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2637
+	 */
2638
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2639
+	{
2640
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2641
+		$relation_settings = $this->related_settings_for($model_name);
2642
+		return $relation_settings->get_all_related($model_obj, $query_params);
2643
+	}
2644
+
2645
+
2646
+	/**
2647
+	 * Deletes all the model objects across the relation indicated by $model_name
2648
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2649
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2650
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2651
+	 *
2652
+	 * @param EE_Base_Class|int|string $id_or_obj
2653
+	 * @param string                   $model_name
2654
+	 * @param array                    $query_params
2655
+	 * @return int how many deleted
2656
+	 * @throws EE_Error
2657
+	 * @throws ReflectionException
2658
+	 */
2659
+	public function delete_related($id_or_obj, $model_name, $query_params = [])
2660
+	{
2661
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2662
+		$relation_settings = $this->related_settings_for($model_name);
2663
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2664
+	}
2665
+
2666
+
2667
+	/**
2668
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2669
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2670
+	 * the model objects can't be hard deleted because of blocking related model objects,
2671
+	 * just does a soft-delete on them instead.
2672
+	 *
2673
+	 * @param EE_Base_Class|int|string $id_or_obj
2674
+	 * @param string                   $model_name
2675
+	 * @param array                    $query_params
2676
+	 * @return int how many deleted
2677
+	 * @throws EE_Error
2678
+	 * @throws ReflectionException
2679
+	 */
2680
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = [])
2681
+	{
2682
+		$model_obj         = $this->ensure_is_obj($id_or_obj);
2683
+		$relation_settings = $this->related_settings_for($model_name);
2684
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2685
+	}
2686
+
2687
+
2688
+	/**
2689
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2690
+	 * unless otherwise specified in the $query_params
2691
+	 *
2692
+	 * @param int             /EE_Base_Class $id_or_obj
2693
+	 * @param string $model_name     like 'Event', or 'Registration'
2694
+	 * @param array  $query_params
2695
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2696
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2697
+	 *                               that by the setting $distinct to TRUE;
2698
+	 * @return int
2699
+	 * @throws EE_Error
2700
+	 * @throws ReflectionException
2701
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2702
+	 */
2703
+	public function count_related(
2704
+		$id_or_obj,
2705
+		$model_name,
2706
+		$query_params = [],
2707
+		$field_to_count = null,
2708
+		$distinct = false
2709
+	) {
2710
+		$related_model = $this->get_related_model_obj($model_name);
2711
+		// we're just going to use the query params on the related model's normal get_all query,
2712
+		// except add a condition to say to match the current mod
2713
+		if (! isset($query_params['default_where_conditions'])) {
2714
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715
+		}
2716
+		$this_model_name                                                 = $this->get_this_model_name();
2717
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2719
+		return $related_model->count($query_params, $field_to_count, $distinct);
2720
+	}
2721
+
2722
+
2723
+	/**
2724
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2725
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2726
+	 *
2727
+	 * @param int           /EE_Base_Class $id_or_obj
2728
+	 * @param string $model_name   like 'Event', or 'Registration'
2729
+	 * @param array  $query_params
2730
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2731
+	 * @return float
2732
+	 * @throws EE_Error
2733
+	 * @throws ReflectionException
2734
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2735
+	 */
2736
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737
+	{
2738
+		$related_model = $this->get_related_model_obj($model_name);
2739
+		if (! is_array($query_params)) {
2740
+			EE_Error::doing_it_wrong(
2741
+				'EEM_Base::sum_related',
2742
+				sprintf(
2743
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2744
+					gettype($query_params)
2745
+				),
2746
+				'4.6.0'
2747
+			);
2748
+			$query_params = [];
2749
+		}
2750
+		// we're just going to use the query params on the related model's normal get_all query,
2751
+		// except add a condition to say to match the current mod
2752
+		if (! isset($query_params['default_where_conditions'])) {
2753
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754
+		}
2755
+		$this_model_name                                                 = $this->get_this_model_name();
2756
+		$this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2758
+		return $related_model->sum($query_params, $field_to_sum);
2759
+	}
2760
+
2761
+
2762
+	/**
2763
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2764
+	 * $modelObject
2765
+	 *
2766
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2767
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2768
+	 * @param array               $query_params     see github link below for more info
2769
+	 * @return EE_Base_Class
2770
+	 * @throws EE_Error
2771
+	 * @throws ReflectionException
2772
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2773
+	 */
2774
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2775
+	{
2776
+		$query_params['limit'] = 1;
2777
+		$results               = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2778
+		if ($results) {
2779
+			return array_shift($results);
2780
+		}
2781
+		return null;
2782
+	}
2783
+
2784
+
2785
+	/**
2786
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2787
+	 *
2788
+	 * @return string
2789
+	 */
2790
+	public function get_this_model_name()
2791
+	{
2792
+		return str_replace("EEM_", "", get_class($this));
2793
+	}
2794
+
2795
+
2796
+	/**
2797
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2798
+	 *
2799
+	 * @return EE_Any_Foreign_Model_Name_Field
2800
+	 * @throws EE_Error
2801
+	 */
2802
+	public function get_field_containing_related_model_name()
2803
+	{
2804
+		foreach ($this->field_settings(true) as $field) {
2805
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2806
+				$field_with_model_name = $field;
2807
+			}
2808
+		}
2809
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2810
+			throw new EE_Error(
2811
+				sprintf(
2812
+					esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2813
+					$this->get_this_model_name()
2814
+				)
2815
+			);
2816
+		}
2817
+		return $field_with_model_name;
2818
+	}
2819
+
2820
+
2821
+	/**
2822
+	 * Inserts a new entry into the database, for each table.
2823
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2824
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2825
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2826
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2827
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2828
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2829
+	 *
2830
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2831
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2832
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2833
+	 *                              of EEM_Base)
2834
+	 * @return int|string new primary key on main table that got inserted
2835
+	 * @throws EE_Error
2836
+	 * @throws ReflectionException
2837
+	 */
2838
+	public function insert($field_n_values)
2839
+	{
2840
+		/**
2841
+		 * Filters the fields and their values before inserting an item using the models
2842
+		 *
2843
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2844
+		 * @param EEM_Base $model           the model used
2845
+		 */
2846
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2848
+			$main_table = $this->_get_main_table();
2849
+			$new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2850
+			if ($new_id !== false) {
2851
+				foreach ($this->_get_other_tables() as $other_table) {
2852
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2853
+				}
2854
+			}
2855
+			/**
2856
+			 * Done just after attempting to insert a new model object
2857
+			 *
2858
+			 * @param EEM_Base $model           used
2859
+			 * @param array    $fields_n_values fields and their values
2860
+			 * @param int|string the              ID of the newly-inserted model object
2861
+			 */
2862
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2863
+			return $new_id;
2864
+		}
2865
+		return false;
2866
+	}
2867
+
2868
+
2869
+	/**
2870
+	 * Checks that the result would satisfy the unique indexes on this model
2871
+	 *
2872
+	 * @param array  $field_n_values
2873
+	 * @param string $action
2874
+	 * @return boolean
2875
+	 * @throws EE_Error
2876
+	 * @throws ReflectionException
2877
+	 */
2878
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2879
+	{
2880
+		foreach ($this->unique_indexes() as $index_name => $index) {
2881
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2882
+			if ($this->exists([$uniqueness_where_params])) {
2883
+				EE_Error::add_error(
2884
+					sprintf(
2885
+						esc_html__(
2886
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2887
+							"event_espresso"
2888
+						),
2889
+						$action,
2890
+						$this->_get_class_name(),
2891
+						$index_name,
2892
+						implode(",", $index->field_names()),
2893
+						http_build_query($uniqueness_where_params)
2894
+					),
2895
+					__FILE__,
2896
+					__FUNCTION__,
2897
+					__LINE__
2898
+				);
2899
+				return false;
2900
+			}
2901
+		}
2902
+		return true;
2903
+	}
2904
+
2905
+
2906
+	/**
2907
+	 * Checks the database for an item that conflicts (ie, if this item were
2908
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2909
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2910
+	 * can be either an EE_Base_Class or an array of fields n values
2911
+	 *
2912
+	 * @param EE_Base_Class|array $obj_or_fields_array
2913
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2914
+	 *                                                 when looking for conflicts
2915
+	 *                                                 (ie, if false, we ignore the model object's primary key
2916
+	 *                                                 when finding "conflicts". If true, it's also considered).
2917
+	 *                                                 Only works for INT primary key,
2918
+	 *                                                 STRING primary keys cannot be ignored
2919
+	 * @return EE_Base_Class|array
2920
+	 * @throws EE_Error
2921
+	 * @throws ReflectionException
2922
+	 */
2923
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2924
+	{
2925
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2926
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2927
+		} elseif (is_array($obj_or_fields_array)) {
2928
+			$fields_n_values = $obj_or_fields_array;
2929
+		} else {
2930
+			throw new EE_Error(
2931
+				sprintf(
2932
+					esc_html__(
2933
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2934
+						"event_espresso"
2935
+					),
2936
+					get_class($this),
2937
+					$obj_or_fields_array
2938
+				)
2939
+			);
2940
+		}
2941
+		$query_params = [];
2942
+		if (
2943
+			$this->has_primary_key_field()
2944
+			&& ($include_primary_key
2945
+				|| $this->get_primary_key_field()
2946
+				   instanceof
2947
+				   EE_Primary_Key_String_Field)
2948
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2949
+		) {
2950
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2951
+		}
2952
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953
+			$uniqueness_where_params                              =
2954
+				array_intersect_key($fields_n_values, $unique_index->fields());
2955
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2956
+		}
2957
+		// if there is nothing to base this search on, then we shouldn't find anything
2958
+		if (empty($query_params)) {
2959
+			return [];
2960
+		}
2961
+		return $this->get_one($query_params);
2962
+	}
2963
+
2964
+
2965
+	/**
2966
+	 * Like count, but is optimized and returns a boolean instead of an int
2967
+	 *
2968
+	 * @param array $query_params
2969
+	 * @return boolean
2970
+	 * @throws EE_Error
2971
+	 * @throws ReflectionException
2972
+	 */
2973
+	public function exists($query_params)
2974
+	{
2975
+		$query_params['limit'] = 1;
2976
+		return $this->count($query_params) > 0;
2977
+	}
2978
+
2979
+
2980
+	/**
2981
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2982
+	 *
2983
+	 * @param int|string $id
2984
+	 * @return boolean
2985
+	 * @throws EE_Error
2986
+	 * @throws ReflectionException
2987
+	 */
2988
+	public function exists_by_ID($id)
2989
+	{
2990
+		return $this->exists(
2991
+			[
2992
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2993
+				[
2994
+					$this->primary_key_name() => $id,
2995
+				],
2996
+			]
2997
+		);
2998
+	}
2999
+
3000
+
3001
+	/**
3002
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
3003
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
3004
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
3005
+	 * on the main table)
3006
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
3007
+	 * cases where we want to call it directly rather than via insert().
3008
+	 *
3009
+	 * @access   protected
3010
+	 * @param EE_Table_Base $table
3011
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
3012
+	 *                                       float
3013
+	 * @param int           $new_id          for now we assume only int keys
3014
+	 * @return int ID of new row inserted, or FALSE on failure
3015
+	 * @throws EE_Error
3016
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
3017
+	 */
3018
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
3019
+	{
3020
+		global $wpdb;
3021
+		$insertion_col_n_values = [];
3022
+		$format_for_insertion   = [];
3023
+		$fields_on_table        = $this->_get_fields_for_table($table->get_table_alias());
3024
+		foreach ($fields_on_table as $field_name => $field_obj) {
3025
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
3026
+			if ($field_obj->is_auto_increment()) {
3027
+				continue;
3028
+			}
3029
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
3031
+			if ($prepared_value !== null) {
3032
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3033
+				$format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034
+			}
3035
+		}
3036
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3037
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
3038
+			// so add the fk to the main table as a column
3039
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3040
+			$format_for_insertion[]                              =
3041
+				'%d';// yes right now we're only allowing these foreign keys to be INTs
3042
+		}
3043
+		// insert the new entry
3044
+		$result = $this->_do_wpdb_query(
3045
+			'insert',
3046
+			[$table->get_table_name(), $insertion_col_n_values, $format_for_insertion]
3047
+		);
3048
+		if ($result === false) {
3049
+			return false;
3050
+		}
3051
+		// ok, now what do we return for the ID of the newly-inserted thing?
3052
+		if ($this->has_primary_key_field()) {
3053
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3054
+				return $wpdb->insert_id;
3055
+			}
3056
+			// it's not an auto-increment primary key, so
3057
+			// it must have been supplied
3058
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3059
+		}
3060
+		// we can't return a  primary key because there is none. instead return
3061
+		// a unique string indicating this model
3062
+		return $this->get_index_primary_key_string($fields_n_values);
3063
+	}
3064
+
3065
+
3066
+	/**
3067
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3068
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3069
+	 * and there is no default, we pass it along. WPDB will take care of it)
3070
+	 *
3071
+	 * @param EE_Model_Field_Base $field_obj
3072
+	 * @param array               $fields_n_values
3073
+	 * @return mixed string|int|float depending on what the table column will be expecting
3074
+	 * @throws EE_Error
3075
+	 */
3076
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3077
+	{
3078
+		// if this field doesn't allow nullable, don't allow it
3079
+		if (
3080
+			! $field_obj->is_nullable()
3081
+			&& (
3082
+				! isset($fields_n_values[ $field_obj->get_name() ])
3083
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3084
+			)
3085
+		) {
3086
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3087
+		}
3088
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
+			? $fields_n_values[ $field_obj->get_name() ]
3090
+			: null;
3091
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092
+	}
3093
+
3094
+
3095
+	/**
3096
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3097
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3098
+	 * the field's prepare_for_set() method.
3099
+	 *
3100
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3101
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3102
+	 *                                   top of file)
3103
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3104
+	 *                                   $value is a custom selection
3105
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3106
+	 */
3107
+	private function _prepare_value_for_use_in_db($value, $field)
3108
+	{
3109
+		if ($field && $field instanceof EE_Model_Field_Base) {
3110
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3111
+			switch ($this->_values_already_prepared_by_model_object) {
3112
+				/** @noinspection PhpMissingBreakStatementInspection */
3113
+				case self::not_prepared_by_model_object:
3114
+					$value = $field->prepare_for_set($value);
3115
+				// purposefully left out "return"
3116
+				case self::prepared_by_model_object:
3117
+					/** @noinspection SuspiciousAssignmentsInspection */
3118
+					$value = $field->prepare_for_use_in_db($value);
3119
+				case self::prepared_for_use_in_db:
3120
+					// leave the value alone
3121
+			}
3122
+			return $value;
3123
+			// phpcs:enable
3124
+		}
3125
+		return $value;
3126
+	}
3127
+
3128
+
3129
+	/**
3130
+	 * Returns the main table on this model
3131
+	 *
3132
+	 * @return EE_Primary_Table
3133
+	 * @throws EE_Error
3134
+	 */
3135
+	protected function _get_main_table()
3136
+	{
3137
+		foreach ($this->_tables as $table) {
3138
+			if ($table instanceof EE_Primary_Table) {
3139
+				return $table;
3140
+			}
3141
+		}
3142
+		throw new EE_Error(
3143
+			sprintf(
3144
+				esc_html__(
3145
+					'There are no main tables on %s. They should be added to _tables array in the constructor',
3146
+					'event_espresso'
3147
+				),
3148
+				get_class($this)
3149
+			)
3150
+		);
3151
+	}
3152
+
3153
+
3154
+	/**
3155
+	 * table
3156
+	 * returns EE_Primary_Table table name
3157
+	 *
3158
+	 * @return string
3159
+	 * @throws EE_Error
3160
+	 */
3161
+	public function table()
3162
+	{
3163
+		return $this->_get_main_table()->get_table_name();
3164
+	}
3165
+
3166
+
3167
+	/**
3168
+	 * table
3169
+	 * returns first EE_Secondary_Table table name
3170
+	 *
3171
+	 * @return string
3172
+	 */
3173
+	public function second_table()
3174
+	{
3175
+		// grab second table from tables array
3176
+		$second_table = end($this->_tables);
3177
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3178
+	}
3179
+
3180
+
3181
+	/**
3182
+	 * get_table_obj_by_alias
3183
+	 * returns table name given it's alias
3184
+	 *
3185
+	 * @param string $table_alias
3186
+	 * @return EE_Primary_Table | EE_Secondary_Table
3187
+	 */
3188
+	public function get_table_obj_by_alias($table_alias = '')
3189
+	{
3190
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3191
+	}
3192
+
3193
+
3194
+	/**
3195
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3196
+	 *
3197
+	 * @return EE_Secondary_Table[]
3198
+	 */
3199
+	protected function _get_other_tables()
3200
+	{
3201
+		$other_tables = [];
3202
+		foreach ($this->_tables as $table_alias => $table) {
3203
+			if ($table instanceof EE_Secondary_Table) {
3204
+				$other_tables[ $table_alias ] = $table;
3205
+			}
3206
+		}
3207
+		return $other_tables;
3208
+	}
3209
+
3210
+
3211
+	/**
3212
+	 * Finds all the fields that correspond to the given table
3213
+	 *
3214
+	 * @param string $table_alias , array key in EEM_Base::_tables
3215
+	 * @return EE_Model_Field_Base[]
3216
+	 */
3217
+	public function _get_fields_for_table($table_alias)
3218
+	{
3219
+		return $this->_fields[ $table_alias ];
3220
+	}
3221
+
3222
+
3223
+	/**
3224
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3225
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3226
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3227
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3228
+	 * related Registration, Transaction, and Payment models.
3229
+	 *
3230
+	 * @param array $query_params see github link below for more info
3231
+	 * @return EE_Model_Query_Info_Carrier
3232
+	 * @throws EE_Error
3233
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3234
+	 */
3235
+	public function _extract_related_models_from_query($query_params)
3236
+	{
3237
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3238
+		if (array_key_exists(0, $query_params)) {
3239
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3240
+		}
3241
+		if (array_key_exists('group_by', $query_params)) {
3242
+			if (is_array($query_params['group_by'])) {
3243
+				$this->_extract_related_models_from_sub_params_array_values(
3244
+					$query_params['group_by'],
3245
+					$query_info_carrier,
3246
+					'group_by'
3247
+				);
3248
+			} elseif (! empty($query_params['group_by'])) {
3249
+				$this->_extract_related_model_info_from_query_param(
3250
+					$query_params['group_by'],
3251
+					$query_info_carrier,
3252
+					'group_by'
3253
+				);
3254
+			}
3255
+		}
3256
+		if (array_key_exists('having', $query_params)) {
3257
+			$this->_extract_related_models_from_sub_params_array_keys(
3258
+				$query_params[0],
3259
+				$query_info_carrier,
3260
+				'having'
3261
+			);
3262
+		}
3263
+		if (array_key_exists('order_by', $query_params)) {
3264
+			if (is_array($query_params['order_by'])) {
3265
+				$this->_extract_related_models_from_sub_params_array_keys(
3266
+					$query_params['order_by'],
3267
+					$query_info_carrier,
3268
+					'order_by'
3269
+				);
3270
+			} elseif (! empty($query_params['order_by'])) {
3271
+				$this->_extract_related_model_info_from_query_param(
3272
+					$query_params['order_by'],
3273
+					$query_info_carrier,
3274
+					'order_by'
3275
+				);
3276
+			}
3277
+		}
3278
+		if (array_key_exists('force_join', $query_params)) {
3279
+			$this->_extract_related_models_from_sub_params_array_values(
3280
+				$query_params['force_join'],
3281
+				$query_info_carrier,
3282
+				'force_join'
3283
+			);
3284
+		}
3285
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3286
+		return $query_info_carrier;
3287
+	}
3288
+
3289
+
3290
+	/**
3291
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3292
+	 *
3293
+	 * @param array                       $sub_query_params
3294
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3295
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3296
+	 * @return EE_Model_Query_Info_Carrier
3297
+	 * @throws EE_Error
3298
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3299
+	 */
3300
+	private function _extract_related_models_from_sub_params_array_keys(
3301
+		$sub_query_params,
3302
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303
+		$query_param_type
3304
+	) {
3305
+		if (! empty($sub_query_params)) {
3306
+			$sub_query_params = (array)$sub_query_params;
3307
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
+				$this->_extract_related_model_info_from_query_param(
3310
+					$param,
3311
+					$model_query_info_carrier,
3312
+					$query_param_type
3313
+				);
3314
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3315
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3316
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3317
+				// of array('Registration.TXN_ID'=>23)
3318
+				$query_param_sans_stars =
3319
+					$this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
+					if (! is_array($possibly_array_of_params)) {
3322
+						throw new EE_Error(
3323
+							sprintf(
3324
+								esc_html__(
3325
+									"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'))",
3326
+									"event_espresso"
3327
+								),
3328
+								$param,
3329
+								$possibly_array_of_params
3330
+							)
3331
+						);
3332
+					}
3333
+					$this->_extract_related_models_from_sub_params_array_keys(
3334
+						$possibly_array_of_params,
3335
+						$model_query_info_carrier,
3336
+						$query_param_type
3337
+					);
3338
+				} elseif (
3339
+					$query_param_type === 0 // ie WHERE
3340
+					&& is_array($possibly_array_of_params)
3341
+					&& isset($possibly_array_of_params[2])
3342
+					&& $possibly_array_of_params[2] == true
3343
+				) {
3344
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345
+					// indicating that $possible_array_of_params[1] is actually a field name,
3346
+					// from which we should extract query parameters!
3347
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348
+						throw new EE_Error(
3349
+							sprintf(
3350
+								esc_html__(
3351
+									"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3352
+									"event_espresso"
3353
+								),
3354
+								$query_param_type,
3355
+								implode(",", $possibly_array_of_params)
3356
+							)
3357
+						);
3358
+					}
3359
+					$this->_extract_related_model_info_from_query_param(
3360
+						$possibly_array_of_params[1],
3361
+						$model_query_info_carrier,
3362
+						$query_param_type
3363
+					);
3364
+				}
3365
+			}
3366
+		}
3367
+		return $model_query_info_carrier;
3368
+	}
3369
+
3370
+
3371
+	/**
3372
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3373
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3374
+	 *
3375
+	 * @param array                       $sub_query_params
3376
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3377
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3378
+	 * @return EE_Model_Query_Info_Carrier
3379
+	 * @throws EE_Error
3380
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3381
+	 */
3382
+	private function _extract_related_models_from_sub_params_array_values(
3383
+		$sub_query_params,
3384
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385
+		$query_param_type
3386
+	) {
3387
+		if (! empty($sub_query_params)) {
3388
+			if (! is_array($sub_query_params)) {
3389
+				throw new EE_Error(
3390
+					sprintf(
3391
+						esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3392
+						$sub_query_params
3393
+					)
3394
+				);
3395
+			}
3396
+			foreach ($sub_query_params as $param) {
3397
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3398
+				$this->_extract_related_model_info_from_query_param(
3399
+					$param,
3400
+					$model_query_info_carrier,
3401
+					$query_param_type
3402
+				);
3403
+			}
3404
+		}
3405
+		return $model_query_info_carrier;
3406
+	}
3407
+
3408
+
3409
+	/**
3410
+	 * Extract all the query parts from  model query params
3411
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3412
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3413
+	 * but use them in a different order. Eg, we need to know what models we are querying
3414
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3415
+	 * other models before we can finalize the where clause SQL.
3416
+	 *
3417
+	 * @param array $query_params see github link below for more info
3418
+	 * @return EE_Model_Query_Info_Carrier
3419
+	 * @throws EE_Error
3420
+	 * @throws ModelConfigurationException
3421
+	 * @throws ReflectionException
3422
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3423
+	 */
3424
+	public function _create_model_query_info_carrier($query_params)
3425
+	{
3426
+		if (! is_array($query_params)) {
3427
+			EE_Error::doing_it_wrong(
3428
+				'EEM_Base::_create_model_query_info_carrier',
3429
+				sprintf(
3430
+					esc_html__(
3431
+						'$query_params should be an array, you passed a variable of type %s',
3432
+						'event_espresso'
3433
+					),
3434
+					gettype($query_params)
3435
+				),
3436
+				'4.6.0'
3437
+			);
3438
+			$query_params = [];
3439
+		}
3440
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : [];
3441
+		// first check if we should alter the query to account for caps or not
3442
+		// because the caps might require us to do extra joins
3443
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3444
+			$query_params[0] = array_replace_recursive(
3445
+				$query_params[0],
3446
+				$this->caps_where_conditions(
3447
+					$query_params['caps']
3448
+				)
3449
+			);
3450
+		}
3451
+
3452
+		// check if we should alter the query to remove data related to protected
3453
+		// custom post types
3454
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3455
+			$where_param_key_for_password = $this->modelChainAndPassword();
3456
+			// only include if related to a cpt where no password has been set
3457
+			$query_params[0]['OR*nopassword'] = [
3458
+				$where_param_key_for_password       => '',
3459
+				$where_param_key_for_password . '*' => ['IS_NULL'],
3460
+			];
3461
+		}
3462
+		$query_object = $this->_extract_related_models_from_query($query_params);
3463
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3464
+		foreach ($query_params[0] as $key => $value) {
3465
+			if (is_int($key)) {
3466
+				throw new EE_Error(
3467
+					sprintf(
3468
+						esc_html__(
3469
+							"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.",
3470
+							"event_espresso"
3471
+						),
3472
+						$key,
3473
+						var_export($value, true),
3474
+						var_export($query_params, true),
3475
+						get_class($this)
3476
+					)
3477
+				);
3478
+			}
3479
+		}
3480
+		if (
3481
+			array_key_exists('default_where_conditions', $query_params)
3482
+			&& ! empty($query_params['default_where_conditions'])
3483
+		) {
3484
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3485
+		} else {
3486
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3487
+		}
3488
+		$query_params[0] = array_merge(
3489
+			$this->_get_default_where_conditions_for_models_in_query(
3490
+				$query_object,
3491
+				$use_default_where_conditions,
3492
+				$query_params[0]
3493
+			),
3494
+			$query_params[0]
3495
+		);
3496
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3497
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3498
+		// So we need to setup a subquery and use that for the main join.
3499
+		// Note for now this only works on the primary table for the model.
3500
+		// So for instance, you could set the limit array like this:
3501
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3502
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3503
+			$query_object->set_main_model_join_sql(
3504
+				$this->_construct_limit_join_select(
3505
+					$query_params['on_join_limit'][0],
3506
+					$query_params['on_join_limit'][1]
3507
+				)
3508
+			);
3509
+		}
3510
+		// set limit
3511
+		if (array_key_exists('limit', $query_params)) {
3512
+			if (is_array($query_params['limit'])) {
3513
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514
+					$e = sprintf(
3515
+						esc_html__(
3516
+							"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)",
3517
+							"event_espresso"
3518
+						),
3519
+						http_build_query($query_params['limit'])
3520
+					);
3521
+					throw new EE_Error($e . "|" . $e);
3522
+				}
3523
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
+			} elseif (! empty($query_params['limit'])) {
3526
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3527
+			}
3528
+		}
3529
+		// set order by
3530
+		if (array_key_exists('order_by', $query_params)) {
3531
+			if (is_array($query_params['order_by'])) {
3532
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3533
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3534
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3535
+				if (array_key_exists('order', $query_params)) {
3536
+					throw new EE_Error(
3537
+						sprintf(
3538
+							esc_html__(
3539
+								"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 ",
3540
+								"event_espresso"
3541
+							),
3542
+							get_class($this),
3543
+							implode(", ", array_keys($query_params['order_by'])),
3544
+							implode(", ", $query_params['order_by']),
3545
+							$query_params['order']
3546
+						)
3547
+					);
3548
+				}
3549
+				$this->_extract_related_models_from_sub_params_array_keys(
3550
+					$query_params['order_by'],
3551
+					$query_object,
3552
+					'order_by'
3553
+				);
3554
+				// assume it's an array of fields to order by
3555
+				$order_array = [];
3556
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557
+					$order         = $this->_extract_order($order);
3558
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3559
+				}
3560
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
+			} elseif (! empty($query_params['order_by'])) {
3562
+				$this->_extract_related_model_info_from_query_param(
3563
+					$query_params['order_by'],
3564
+					$query_object,
3565
+					'order',
3566
+					$query_params['order_by']
3567
+				);
3568
+				$order = isset($query_params['order'])
3569
+					? $this->_extract_order($query_params['order'])
3570
+					: 'DESC';
3571
+				$query_object->set_order_by_sql(
3572
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3573
+				);
3574
+			}
3575
+		}
3576
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3577
+		if (
3578
+			! array_key_exists('order_by', $query_params)
3579
+			&& array_key_exists('order', $query_params)
3580
+			&& ! empty($query_params['order'])
3581
+		) {
3582
+			$pk_field = $this->get_primary_key_field();
3583
+			$order    = $this->_extract_order($query_params['order']);
3584
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3585
+		}
3586
+		// set group by
3587
+		if (array_key_exists('group_by', $query_params)) {
3588
+			if (is_array($query_params['group_by'])) {
3589
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3590
+				$group_by_array = [];
3591
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593
+				}
3594
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
+			} elseif (! empty($query_params['group_by'])) {
3596
+				$query_object->set_group_by_sql(
3597
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3598
+				);
3599
+			}
3600
+		}
3601
+		// set having
3602
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3603
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3604
+		}
3605
+		// now, just verify they didn't pass anything wack
3606
+		foreach ($query_params as $query_key => $query_value) {
3607
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3608
+				throw new EE_Error(
3609
+					sprintf(
3610
+						esc_html__(
3611
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3612
+							'event_espresso'
3613
+						),
3614
+						$query_key,
3615
+						get_class($this),
3616
+						//                      print_r( $this->_allowed_query_params, TRUE )
3617
+						implode(',', $this->_allowed_query_params)
3618
+					)
3619
+				);
3620
+			}
3621
+		}
3622
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3623
+		if (empty($main_model_join_sql)) {
3624
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3625
+		}
3626
+		return $query_object;
3627
+	}
3628
+
3629
+
3630
+	/**
3631
+	 * Gets the where conditions that should be imposed on the query based on the
3632
+	 * context (eg reading frontend, backend, edit or delete).
3633
+	 *
3634
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3635
+	 * @return array
3636
+	 * @throws EE_Error
3637
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3638
+	 */
3639
+	public function caps_where_conditions($context = self::caps_read)
3640
+	{
3641
+		EEM_Base::verify_is_valid_cap_context($context);
3642
+		$cap_where_conditions = [];
3643
+		$cap_restrictions     = $this->caps_missing($context);
3644
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3645
+			$cap_where_conditions = array_replace_recursive(
3646
+				$cap_where_conditions,
3647
+				$restriction_if_no_cap->get_default_where_conditions()
3648
+			);
3649
+		}
3650
+		return apply_filters(
3651
+			'FHEE__EEM_Base__caps_where_conditions__return',
3652
+			$cap_where_conditions,
3653
+			$this,
3654
+			$context,
3655
+			$cap_restrictions
3656
+		);
3657
+	}
3658
+
3659
+
3660
+	/**
3661
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3662
+	 * otherwise throws an exception
3663
+	 *
3664
+	 * @param string $should_be_order_string
3665
+	 * @return string either ASC, asc, DESC or desc
3666
+	 * @throws EE_Error
3667
+	 */
3668
+	private function _extract_order($should_be_order_string)
3669
+	{
3670
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3671
+			return $should_be_order_string;
3672
+		}
3673
+		throw new EE_Error(
3674
+			sprintf(
3675
+				esc_html__(
3676
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3677
+					"event_espresso"
3678
+				),
3679
+				get_class($this),
3680
+				$should_be_order_string
3681
+			)
3682
+		);
3683
+	}
3684
+
3685
+
3686
+	/**
3687
+	 * Looks at all the models which are included in this query, and asks each
3688
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3689
+	 * so they can be merged
3690
+	 *
3691
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3692
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3693
+	 *                                                                  'none' means NO default where conditions will
3694
+	 *                                                                  be used AT ALL during this query.
3695
+	 *                                                                  'other_models_only' means default where
3696
+	 *                                                                  conditions from other models will be used, but
3697
+	 *                                                                  not for this primary model. 'all', the default,
3698
+	 *                                                                  means default where conditions will apply as
3699
+	 *                                                                  normal
3700
+	 * @param array                       $where_query_params
3701
+	 * @return array
3702
+	 * @throws EE_Error
3703
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3704
+	 */
3705
+	private function _get_default_where_conditions_for_models_in_query(
3706
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3707
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3708
+		$where_query_params = []
3709
+	) {
3710
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712
+			throw new EE_Error(
3713
+				sprintf(
3714
+					esc_html__(
3715
+						"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3716
+						"event_espresso"
3717
+					),
3718
+					$use_default_where_conditions,
3719
+					implode(", ", $allowed_used_default_where_conditions_values)
3720
+				)
3721
+			);
3722
+		}
3723
+		$universal_query_params = [];
3724
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions)) {
3725
+			$universal_query_params = $this->_get_default_where_conditions();
3726
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions)) {
3727
+			$universal_query_params = $this->_get_minimum_where_conditions();
3728
+		}
3729
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3730
+			$related_model = $this->get_related_model_obj($model_name);
3731
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3732
+				$related_model_universal_where_params =
3733
+					$related_model->_get_default_where_conditions($model_relation_path);
3734
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3735
+				$related_model_universal_where_params =
3736
+					$related_model->_get_minimum_where_conditions($model_relation_path);
3737
+			} else {
3738
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3739
+				continue;
3740
+			}
3741
+			$overrides              = $this->_override_defaults_or_make_null_friendly(
3742
+				$related_model_universal_where_params,
3743
+				$where_query_params,
3744
+				$related_model,
3745
+				$model_relation_path
3746
+			);
3747
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3748
+				$universal_query_params,
3749
+				$overrides
3750
+			);
3751
+		}
3752
+		return $universal_query_params;
3753
+	}
3754
+
3755
+
3756
+	/**
3757
+	 * Determines whether or not we should use default where conditions for the model in question
3758
+	 * (this model, or other related models).
3759
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3760
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3761
+	 * We should use default where conditions on related models when they requested to use default where conditions
3762
+	 * on all models, or specifically just on other related models
3763
+	 *
3764
+	 * @param      $default_where_conditions_value
3765
+	 * @param bool $for_this_model false means this is for OTHER related models
3766
+	 * @return bool
3767
+	 */
3768
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3769
+	{
3770
+		return (
3771
+				   $for_this_model
3772
+				   && in_array(
3773
+					   $default_where_conditions_value,
3774
+					   [
3775
+						   EEM_Base::default_where_conditions_all,
3776
+						   EEM_Base::default_where_conditions_this_only,
3777
+						   EEM_Base::default_where_conditions_minimum_others,
3778
+					   ],
3779
+					   true
3780
+				   )
3781
+			   )
3782
+			   || (
3783
+				   ! $for_this_model
3784
+				   && in_array(
3785
+					   $default_where_conditions_value,
3786
+					   [
3787
+						   EEM_Base::default_where_conditions_all,
3788
+						   EEM_Base::default_where_conditions_others_only,
3789
+					   ],
3790
+					   true
3791
+				   )
3792
+			   );
3793
+	}
3794
+
3795
+
3796
+	/**
3797
+	 * Determines whether or not we should use default minimum conditions for the model in question
3798
+	 * (this model, or other related models).
3799
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3800
+	 * where conditions.
3801
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3802
+	 * on this model or others
3803
+	 *
3804
+	 * @param      $default_where_conditions_value
3805
+	 * @param bool $for_this_model false means this is for OTHER related models
3806
+	 * @return bool
3807
+	 */
3808
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3809
+	{
3810
+		return (
3811
+				   $for_this_model
3812
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3813
+			   )
3814
+			   || (
3815
+				   ! $for_this_model
3816
+				   && in_array(
3817
+					   $default_where_conditions_value,
3818
+					   [
3819
+						   EEM_Base::default_where_conditions_minimum_others,
3820
+						   EEM_Base::default_where_conditions_minimum_all,
3821
+					   ],
3822
+					   true
3823
+				   )
3824
+			   );
3825
+	}
3826
+
3827
+
3828
+	/**
3829
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3830
+	 * then we also add a special where condition which allows for that model's primary key
3831
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3832
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3833
+	 *
3834
+	 * @param array    $default_where_conditions
3835
+	 * @param array    $provided_where_conditions
3836
+	 * @param EEM_Base $model
3837
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3838
+	 * @return array
3839
+	 * @throws EE_Error
3840
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3841
+	 */
3842
+	private function _override_defaults_or_make_null_friendly(
3843
+		$default_where_conditions,
3844
+		$provided_where_conditions,
3845
+		$model,
3846
+		$model_relation_path
3847
+	) {
3848
+		$null_friendly_where_conditions = [];
3849
+		$none_overridden                = true;
3850
+		$or_condition_key_for_defaults  = 'OR*' . get_class($model);
3851
+		foreach ($default_where_conditions as $key => $val) {
3852
+			if (isset($provided_where_conditions[ $key ])) {
3853
+				$none_overridden = false;
3854
+			} else {
3855
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3856
+			}
3857
+		}
3858
+		if ($none_overridden && $default_where_conditions) {
3859
+			if ($model->has_primary_key_field()) {
3860
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3861
+																				   . "."
3862
+																				   . $model->primary_key_name() ] =
3863
+					['IS NULL'];
3864
+			}/*else{
3865 3865
                 //@todo NO PK, use other defaults
3866 3866
             }*/
3867
-        }
3868
-        return $null_friendly_where_conditions;
3869
-    }
3870
-
3871
-
3872
-    /**
3873
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3874
-     * default where conditions on all get_all, update, and delete queries done by this model.
3875
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3876
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3877
-     *
3878
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3879
-     * @return array
3880
-     * @throws EE_Error
3881
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3882
-     */
3883
-    private function _get_default_where_conditions($model_relation_path = '')
3884
-    {
3885
-        if ($this->_ignore_where_strategy) {
3886
-            return [];
3887
-        }
3888
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3889
-    }
3890
-
3891
-
3892
-    /**
3893
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3897
-     * Similar to _get_default_where_conditions
3898
-     *
3899
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
-     * @return array
3901
-     * @throws EE_Error
3902
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
-     */
3904
-    protected function _get_minimum_where_conditions($model_relation_path = '')
3905
-    {
3906
-        if ($this->_ignore_where_strategy) {
3907
-            return [];
3908
-        }
3909
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
-    }
3911
-
3912
-
3913
-    /**
3914
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
-     *
3917
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3918
-     * @return string
3919
-     * @throws EE_Error
3920
-     */
3921
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
-    {
3923
-        $selects = $this->_get_columns_to_select_for_this_model();
3924
-        foreach (
3925
-            $model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
-        ) {
3927
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
-            $other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
-            foreach ($other_model_selects as $key => $value) {
3930
-                $selects[] = $value;
3931
-            }
3932
-        }
3933
-        return implode(", ", $selects);
3934
-    }
3935
-
3936
-
3937
-    /**
3938
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
-     * So that's going to be the columns for all the fields on the model
3940
-     *
3941
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
-     */
3944
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
-    {
3946
-        $fields                                       = $this->field_settings();
3947
-        $selects                                      = [];
3948
-        $table_alias_with_model_relation_chain_prefix =
3949
-            EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
-                $model_relation_chain,
3951
-                $this->get_this_model_name()
3952
-            );
3953
-        foreach ($fields as $field_obj) {
3954
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3955
-                         . $field_obj->get_table_alias()
3956
-                         . "."
3957
-                         . $field_obj->get_table_column()
3958
-                         . " AS '"
3959
-                         . $table_alias_with_model_relation_chain_prefix
3960
-                         . $field_obj->get_table_alias()
3961
-                         . "."
3962
-                         . $field_obj->get_table_column()
3963
-                         . "'";
3964
-        }
3965
-        // make sure we are also getting the PKs of each table
3966
-        $tables = $this->get_tables();
3967
-        if (count($tables) > 1) {
3968
-            foreach ($tables as $table_obj) {
3969
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
-                                       . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3972
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
-                }
3974
-            }
3975
-        }
3976
-        return $selects;
3977
-    }
3978
-
3979
-
3980
-    /**
3981
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
-     * SQL for joining, and the data types
3985
-     *
3986
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
-     * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3989
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3991
-     *                                                          or 'Registration's
3992
-     * @param string|null                 $original_query_param what it originally was (eg
3993
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
-     *                                                          matches $query_param
3995
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
-     * @throws EE_Error
3997
-     */
3998
-    private function _extract_related_model_info_from_query_param(
3999
-        $query_param,
4000
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
-        $query_param_type,
4002
-        $original_query_param = null
4003
-    ) {
4004
-        if ($original_query_param === null) {
4005
-            $original_query_param = $query_param;
4006
-        }
4007
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
-        // whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4009
-        $allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4010
-        $allow_fields             = in_array(
4011
-            $query_param_type,
4012
-            ['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4013
-            true
4014
-        );
4015
-        // check to see if we have a field on this model
4016
-        $this_model_fields = $this->field_settings(true);
4017
-        if (array_key_exists($query_param, $this_model_fields)) {
4018
-            if ($allow_fields) {
4019
-                return;
4020
-            }
4021
-            throw new EE_Error(
4022
-                sprintf(
4023
-                    esc_html__(
4024
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
-                        "event_espresso"
4026
-                    ),
4027
-                    $query_param,
4028
-                    get_class($this),
4029
-                    $query_param_type,
4030
-                    $original_query_param
4031
-                )
4032
-            );
4033
-        }
4034
-        // check if this is a special logic query param
4035
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
-            if ($allow_logic_query_params) {
4037
-                return;
4038
-            }
4039
-            throw new EE_Error(
4040
-                sprintf(
4041
-                    esc_html__(
4042
-                        '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',
4043
-                        'event_espresso'
4044
-                    ),
4045
-                    implode('", "', $this->_logic_query_param_keys),
4046
-                    $query_param,
4047
-                    get_class($this),
4048
-                    '<br />',
4049
-                    "\t"
4050
-                    . ' $passed_in_query_info = <pre>'
4051
-                    . print_r($passed_in_query_info, true)
4052
-                    . '</pre>'
4053
-                    . "\n\t"
4054
-                    . ' $query_param_type = '
4055
-                    . $query_param_type
4056
-                    . "\n\t"
4057
-                    . ' $original_query_param = '
4058
-                    . $original_query_param
4059
-                )
4060
-            );
4061
-        }
4062
-        // check if it's a custom selection
4063
-        if (
4064
-            $this->_custom_selections instanceof CustomSelects
4065
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
-        ) {
4067
-            return;
4068
-        }
4069
-        // check if has a model name at the beginning
4070
-        // and
4071
-        // check if it's a field on a related model
4072
-        if (
4073
-        $this->extractJoinModelFromQueryParams(
4074
-            $passed_in_query_info,
4075
-            $query_param,
4076
-            $original_query_param,
4077
-            $query_param_type
4078
-        )
4079
-        ) {
4080
-            return;
4081
-        }
4082
-
4083
-        // ok so $query_param didn't start with a model name
4084
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4085
-        // it's wack, that's what it is
4086
-        throw new EE_Error(
4087
-            sprintf(
4088
-                esc_html__(
4089
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
-                    "event_espresso"
4091
-                ),
4092
-                $query_param,
4093
-                get_class($this),
4094
-                $query_param_type,
4095
-                $original_query_param
4096
-            )
4097
-        );
4098
-    }
4099
-
4100
-
4101
-    /**
4102
-     * Extracts any possible join model information from the provided possible_join_string.
4103
-     * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
-     * join
4105
-     * parts that should be added to the query.
4106
-     *
4107
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
-     * @param null|string                 $original_query_param
4110
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
-     *                                                           etc.)
4113
-     * @return bool  returns true if a join was added and false if not.
4114
-     * @throws EE_Error
4115
-     */
4116
-    private function extractJoinModelFromQueryParams(
4117
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4118
-        $possible_join_string,
4119
-        $original_query_param,
4120
-        $query_parameter_type
4121
-    ) {
4122
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
-                if ($possible_join_string === '') {
4127
-                    // nothing left to $query_param
4128
-                    // we should actually end in a field name, not a model like this!
4129
-                    throw new EE_Error(
4130
-                        sprintf(
4131
-                            esc_html__(
4132
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
-                                "event_espresso"
4134
-                            ),
4135
-                            $possible_join_string,
4136
-                            $query_parameter_type,
4137
-                            get_class($this),
4138
-                            $valid_related_model_name
4139
-                        )
4140
-                    );
4141
-                }
4142
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
-                $related_model_obj->_extract_related_model_info_from_query_param(
4144
-                    $possible_join_string,
4145
-                    $query_info_carrier,
4146
-                    $query_parameter_type,
4147
-                    $original_query_param
4148
-                );
4149
-                return true;
4150
-            }
4151
-            if ($possible_join_string === $valid_related_model_name) {
4152
-                $this->_add_join_to_model(
4153
-                    $valid_related_model_name,
4154
-                    $query_info_carrier,
4155
-                    $original_query_param
4156
-                );
4157
-                return true;
4158
-            }
4159
-        }
4160
-        return false;
4161
-    }
4162
-
4163
-
4164
-    /**
4165
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
-     *
4167
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
-     * @throws EE_Error
4169
-     */
4170
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
-    {
4172
-        if (
4173
-            $this->_custom_selections instanceof CustomSelects
4174
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4175
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4176
-            )
4177
-        ) {
4178
-            $original_selects = $this->_custom_selections->originalSelects();
4179
-            foreach ($original_selects as $alias => $select_configuration) {
4180
-                $this->extractJoinModelFromQueryParams(
4181
-                    $query_info_carrier,
4182
-                    $select_configuration[0],
4183
-                    $select_configuration[0],
4184
-                    'custom_selects'
4185
-                );
4186
-            }
4187
-        }
4188
-    }
4189
-
4190
-
4191
-    /**
4192
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4193
-     * and store it on $passed_in_query_info
4194
-     *
4195
-     * @param string                      $model_name
4196
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4197
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4198
-     *                                                          model and $model_name. Eg, if we are querying Event,
4199
-     *                                                          and are adding a join to 'Payment' with the original
4200
-     *                                                          query param key
4201
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4202
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4203
-     *                                                          Payment wants to add default query params so that it
4204
-     *                                                          will know what models to prepend onto its default query
4205
-     *                                                          params or in case it wants to rename tables (in case
4206
-     *                                                          there are multiple joins to the same table)
4207
-     * @return void
4208
-     * @throws EE_Error
4209
-     */
4210
-    private function _add_join_to_model(
4211
-        $model_name,
4212
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4213
-        $original_query_param
4214
-    ) {
4215
-        $relation_obj         = $this->related_settings_for($model_name);
4216
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4217
-        // check if the relation is HABTM, because then we're essentially doing two joins
4218
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4219
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4220
-            $join_model_obj = $relation_obj->get_join_model();
4221
-            // replace the model specified with the join model for this relation chain, whi
4222
-            $relation_chain_to_join_model =
4223
-                EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4224
-                    $model_name,
4225
-                    $join_model_obj->get_this_model_name(),
4226
-                    $model_relation_chain
4227
-                );
4228
-            $passed_in_query_info->merge(
4229
-                new EE_Model_Query_Info_Carrier(
4230
-                    [$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4231
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4232
-                )
4233
-            );
4234
-        }
4235
-        // now just join to the other table pointed to by the relation object, and add its data types
4236
-        $passed_in_query_info->merge(
4237
-            new EE_Model_Query_Info_Carrier(
4238
-                [$model_relation_chain => $model_name],
4239
-                $relation_obj->get_join_statement($model_relation_chain)
4240
-            )
4241
-        );
4242
-    }
4243
-
4244
-
4245
-    /**
4246
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4247
-     *
4248
-     * @param array $where_params
4249
-     * @return string of SQL
4250
-     * @throws EE_Error
4251
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4252
-     */
4253
-    private function _construct_where_clause($where_params)
4254
-    {
4255
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256
-        if ($SQL) {
4257
-            return " WHERE " . $SQL;
4258
-        }
4259
-        return '';
4260
-    }
4261
-
4262
-
4263
-    /**
4264
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4265
-     * and should be passed HAVING parameters, not WHERE parameters
4266
-     *
4267
-     * @param array $having_params
4268
-     * @return string
4269
-     * @throws EE_Error
4270
-     */
4271
-    private function _construct_having_clause($having_params)
4272
-    {
4273
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274
-        if ($SQL) {
4275
-            return " HAVING " . $SQL;
4276
-        }
4277
-        return '';
4278
-    }
4279
-
4280
-
4281
-    /**
4282
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4283
-     * Event_Meta.meta_value = 'foo'))"
4284
-     *
4285
-     * @param array  $where_params
4286
-     * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4287
-     * @return string of SQL
4288
-     * @throws EE_Error
4289
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4290
-     */
4291
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4292
-    {
4293
-        $where_clauses = [];
4294
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4295
-            $query_param =
4296
-                $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297
-                    $query_param
4298
-                );// str_replace("*",'',$query_param);
4299
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4300
-                switch ($query_param) {
4301
-                    case 'not':
4302
-                    case 'NOT':
4303
-                        $where_clauses[] = "! ("
4304
-                                           . $this->_construct_condition_clause_recursive(
4305
-                                $op_and_value_or_sub_condition,
4306
-                                $glue
4307
-                            )
4308
-                                           . ")";
4309
-                        break;
4310
-                    case 'and':
4311
-                    case 'AND':
4312
-                        $where_clauses[] = " ("
4313
-                                           . $this->_construct_condition_clause_recursive(
4314
-                                $op_and_value_or_sub_condition,
4315
-                                ' AND '
4316
-                            )
4317
-                                           . ")";
4318
-                        break;
4319
-                    case 'or':
4320
-                    case 'OR':
4321
-                        $where_clauses[] = " ("
4322
-                                           . $this->_construct_condition_clause_recursive(
4323
-                                $op_and_value_or_sub_condition,
4324
-                                ' OR '
4325
-                            )
4326
-                                           . ")";
4327
-                        break;
4328
-                }
4329
-            } else {
4330
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4331
-                // if it's not a normal field, maybe it's a custom selection?
4332
-                if (! $field_obj) {
4333
-                    if ($this->_custom_selections instanceof CustomSelects) {
4334
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335
-                    } else {
4336
-                        throw new EE_Error(
4337
-                            sprintf(
4338
-                                esc_html__(
4339
-                                    "%s is neither a valid model field name, nor a custom selection",
4340
-                                    "event_espresso"
4341
-                                ),
4342
-                                $query_param
4343
-                            )
4344
-                        );
4345
-                    }
4346
-                }
4347
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4349
-            }
4350
-        }
4351
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4352
-    }
4353
-
4354
-
4355
-    /**
4356
-     * Takes the input parameter and extract the table name (alias) and column name
4357
-     *
4358
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4359
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4360
-     * @throws EE_Error
4361
-     */
4362
-    private function _deduce_column_name_from_query_param($query_param)
4363
-    {
4364
-        $field = $this->_deduce_field_from_query_param($query_param);
4365
-        if ($field) {
4366
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4367
-                $field->get_model_name(),
4368
-                $query_param
4369
-            );
4370
-            return $table_alias_prefix . $field->get_qualified_column();
4371
-        }
4372
-        if (
4373
-            $this->_custom_selections instanceof CustomSelects
4374
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4375
-        ) {
4376
-            // maybe it's custom selection item?
4377
-            // if so, just use it as the "column name"
4378
-            return $query_param;
4379
-        }
4380
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4381
-            ? implode(',', $this->_custom_selections->columnAliases())
4382
-            : '';
4383
-        throw new EE_Error(
4384
-            sprintf(
4385
-                esc_html__(
4386
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4387
-                    "event_espresso"
4388
-                ),
4389
-                $query_param,
4390
-                $custom_select_aliases
4391
-            )
4392
-        );
4393
-    }
4394
-
4395
-
4396
-    /**
4397
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4398
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4399
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4400
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4401
-     *
4402
-     * @param string $condition_query_param_key
4403
-     * @return string
4404
-     */
4405
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4406
-    {
4407
-        $pos_of_star = strpos($condition_query_param_key, '*');
4408
-        if ($pos_of_star === false) {
4409
-            return $condition_query_param_key;
4410
-        }
4411
-        return substr($condition_query_param_key, 0, $pos_of_star);
4412
-    }
4413
-
4414
-
4415
-    /**
4416
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4417
-     *
4418
-     * @param mixed      array | string    $op_and_value
4419
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4420
-     * @return string
4421
-     * @throws EE_Error
4422
-     */
4423
-    private function _construct_op_and_value($op_and_value, $field_obj)
4424
-    {
4425
-        if (is_array($op_and_value)) {
4426
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
-            if (! $operator) {
4428
-                $php_array_like_string = [];
4429
-                foreach ($op_and_value as $key => $value) {
4430
-                    $php_array_like_string[] = "$key=>$value";
4431
-                }
4432
-                throw new EE_Error(
4433
-                    sprintf(
4434
-                        esc_html__(
4435
-                            "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))",
4436
-                            "event_espresso"
4437
-                        ),
4438
-                        implode(",", $php_array_like_string)
4439
-                    )
4440
-                );
4441
-            }
4442
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4443
-        } else {
4444
-            $operator = '=';
4445
-            $value    = $op_and_value;
4446
-        }
4447
-        // check to see if the value is actually another field
4448
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4450
-        }
4451
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
-            // in this case, the value should be an array, or at least a comma-separated list
4453
-            // it will need to handle a little differently
4454
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4455
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4456
-            return $operator . SP . $cleaned_value;
4457
-        }
4458
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459
-            // the value should be an array with count of two.
4460
-            if (count($value) !== 2) {
4461
-                throw new EE_Error(
4462
-                    sprintf(
4463
-                        esc_html__(
4464
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4465
-                            'event_espresso'
4466
-                        ),
4467
-                        "BETWEEN"
4468
-                    )
4469
-                );
4470
-            }
4471
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
-            return $operator . SP . $cleaned_value;
4473
-        }
4474
-        if (in_array($operator, $this->valid_null_style_operators())) {
4475
-            if ($value !== null) {
4476
-                throw new EE_Error(
4477
-                    sprintf(
4478
-                        esc_html__(
4479
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4480
-                            "event_espresso"
4481
-                        ),
4482
-                        $value,
4483
-                        $operator
4484
-                    )
4485
-                );
4486
-            }
4487
-            return $operator;
4488
-        }
4489
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4491
-            // remove other junk. So just treat it as a string.
4492
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4493
-        }
4494
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4496
-        }
4497
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498
-            throw new EE_Error(
4499
-                sprintf(
4500
-                    esc_html__(
4501
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4502
-                        'event_espresso'
4503
-                    ),
4504
-                    $operator,
4505
-                    $operator
4506
-                )
4507
-            );
4508
-        }
4509
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510
-            throw new EE_Error(
4511
-                sprintf(
4512
-                    esc_html__(
4513
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4514
-                        'event_espresso'
4515
-                    ),
4516
-                    $operator,
4517
-                    $operator
4518
-                )
4519
-            );
4520
-        }
4521
-        throw new EE_Error(
4522
-            sprintf(
4523
-                esc_html__(
4524
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4525
-                    "event_espresso"
4526
-                ),
4527
-                http_build_query($op_and_value)
4528
-            )
4529
-        );
4530
-    }
4531
-
4532
-
4533
-    /**
4534
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4535
-     *
4536
-     * @param array                      $values
4537
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4538
-     *                                              '%s'
4539
-     * @return string
4540
-     * @throws EE_Error
4541
-     */
4542
-    public function _construct_between_value($values, $field_obj)
4543
-    {
4544
-        $cleaned_values = [];
4545
-        foreach ($values as $value) {
4546
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547
-        }
4548
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4549
-    }
4550
-
4551
-
4552
-    /**
4553
-     * Takes an array or a comma-separated list of $values and cleans them
4554
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4555
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4556
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4557
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4558
-     *
4559
-     * @param mixed                      $values    array or comma-separated string
4560
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4561
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4562
-     * @throws EE_Error
4563
-     */
4564
-    public function _construct_in_value($values, $field_obj)
4565
-    {
4566
-        // check if the value is a CSV list
4567
-        if (is_string($values)) {
4568
-            // in which case, turn it into an array
4569
-            $values = explode(",", $values);
4570
-        }
4571
-        $cleaned_values = [];
4572
-        foreach ($values as $value) {
4573
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4574
-        }
4575
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4576
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4577
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4578
-        if (empty($cleaned_values)) {
4579
-            $all_fields       = $this->field_settings();
4580
-            $a_field          = array_shift($all_fields);
4581
-            $main_table       = $this->_get_main_table();
4582
-            $cleaned_values[] = "SELECT "
4583
-                                . $a_field->get_table_column()
4584
-                                . " FROM "
4585
-                                . $main_table->get_table_name()
4586
-                                . " WHERE FALSE";
4587
-        }
4588
-        return "(" . implode(",", $cleaned_values) . ")";
4589
-    }
4590
-
4591
-
4592
-    /**
4593
-     * @param mixed                      $value
4594
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4595
-     * @return false|null|string
4596
-     * @throws EE_Error
4597
-     */
4598
-    private function _wpdb_prepare_using_field($value, $field_obj)
4599
-    {
4600
-        global $wpdb;
4601
-        if ($field_obj instanceof EE_Model_Field_Base) {
4602
-            return $wpdb->prepare(
4603
-                $field_obj->get_wpdb_data_type(),
4604
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4605
-            );
4606
-        } //$field_obj should really just be a data type
4607
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608
-            throw new EE_Error(
4609
-                sprintf(
4610
-                    esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4611
-                    $field_obj,
4612
-                    implode(",", $this->_valid_wpdb_data_types)
4613
-                )
4614
-            );
4615
-        }
4616
-        return $wpdb->prepare($field_obj, $value);
4617
-    }
4618
-
4619
-
4620
-    /**
4621
-     * Takes the input parameter and finds the model field that it indicates.
4622
-     *
4623
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4624
-     * @return EE_Model_Field_Base
4625
-     * @throws EE_Error
4626
-     */
4627
-    protected function _deduce_field_from_query_param($query_param_name)
4628
-    {
4629
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4630
-        // which will help us find the database table and column
4631
-        $query_param_parts = explode(".", $query_param_name);
4632
-        if (empty($query_param_parts)) {
4633
-            throw new EE_Error(
4634
-                sprintf(
4635
-                    esc_html__(
4636
-                        "_extract_column_name is empty when trying to extract column and table name from %s",
4637
-                        'event_espresso'
4638
-                    ),
4639
-                    $query_param_name
4640
-                )
4641
-            );
4642
-        }
4643
-        $number_of_parts       = count($query_param_parts);
4644
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4645
-        if ($number_of_parts === 1) {
4646
-            $field_name = $last_query_param_part;
4647
-            $model_obj  = $this;
4648
-        } else {// $number_of_parts >= 2
4649
-            // the last part is the column name, and there are only 2parts. therefore...
4650
-            $field_name = $last_query_param_part;
4651
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4652
-        }
4653
-        try {
4654
-            return $model_obj->field_settings_for($field_name);
4655
-        } catch (EE_Error $e) {
4656
-            return null;
4657
-        }
4658
-    }
4659
-
4660
-
4661
-    /**
4662
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4663
-     * alias and column which corresponds to it
4664
-     *
4665
-     * @param string $field_name
4666
-     * @return string
4667
-     * @throws EE_Error
4668
-     */
4669
-    public function _get_qualified_column_for_field($field_name)
4670
-    {
4671
-        $all_fields = $this->field_settings();
4672
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4673
-        if ($field) {
4674
-            return $field->get_qualified_column();
4675
-        }
4676
-        throw new EE_Error(
4677
-            sprintf(
4678
-                esc_html__(
4679
-                    "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.",
4680
-                    'event_espresso'
4681
-                ),
4682
-                $field_name,
4683
-                get_class($this)
4684
-            )
4685
-        );
4686
-    }
4687
-
4688
-
4689
-    /**
4690
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4691
-     * Example usage:
4692
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4693
-     *      array(),
4694
-     *      ARRAY_A,
4695
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4696
-     *  );
4697
-     * is equivalent to
4698
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4699
-     * and
4700
-     *  EEM_Event::instance()->get_all_wpdb_results(
4701
-     *      array(
4702
-     *          array(
4703
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4704
-     *          ),
4705
-     *          ARRAY_A,
4706
-     *          implode(
4707
-     *              ', ',
4708
-     *              array_merge(
4709
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4710
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4711
-     *              )
4712
-     *          )
4713
-     *      )
4714
-     *  );
4715
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4716
-     *
4717
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4718
-     *                                            and the one whose fields you are selecting for example: when querying
4719
-     *                                            tickets model and selecting fields from the tickets model you would
4720
-     *                                            leave this parameter empty, because no models are needed to join
4721
-     *                                            between the queried model and the selected one. Likewise when
4722
-     *                                            querying the datetime model and selecting fields from the tickets
4723
-     *                                            model, it would also be left empty, because there is a direct
4724
-     *                                            relation from datetimes to tickets, so no model is needed to join
4725
-     *                                            them together. However, when querying from the event model and
4726
-     *                                            selecting fields from the ticket model, you should provide the string
4727
-     *                                            'Datetime', indicating that the event model must first join to the
4728
-     *                                            datetime model in order to find its relation to ticket model.
4729
-     *                                            Also, when querying from the venue model and selecting fields from
4730
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4731
-     *                                            indicating you need to join the venue model to the event model,
4732
-     *                                            to the datetime model, in order to find its relation to the ticket
4733
-     *                                            model. This string is used to deduce the prefix that gets added onto
4734
-     *                                            the models' tables qualified columns
4735
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4736
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4737
-     *                                            qualified column names
4738
-     * @return array|string
4739
-     */
4740
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741
-    {
4742
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4743
-        $qualified_columns = [];
4744
-        foreach ($this->field_settings() as $field_name => $field) {
4745
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4746
-        }
4747
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748
-    }
4749
-
4750
-
4751
-    /**
4752
-     * constructs the select use on special limit joins
4753
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4754
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4755
-     * (as that is typically where the limits would be set).
4756
-     *
4757
-     * @param string       $table_alias The table the select is being built for
4758
-     * @param mixed|string $limit       The limit for this select
4759
-     * @return string                The final select join element for the query.
4760
-     * @throws EE_Error
4761
-     */
4762
-    public function _construct_limit_join_select($table_alias, $limit)
4763
-    {
4764
-        $SQL = '';
4765
-        foreach ($this->_tables as $table_obj) {
4766
-            if ($table_obj instanceof EE_Primary_Table) {
4767
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4768
-                    ? $table_obj->get_select_join_limit($limit)
4769
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4770
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4771
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4772
-                    ? $table_obj->get_select_join_limit_join($limit)
4773
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4774
-            }
4775
-        }
4776
-        return $SQL;
4777
-    }
4778
-
4779
-
4780
-    /**
4781
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4782
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4783
-     *
4784
-     * @return string SQL
4785
-     * @throws EE_Error
4786
-     */
4787
-    public function _construct_internal_join()
4788
-    {
4789
-        $SQL = $this->_get_main_table()->get_table_sql();
4790
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4791
-        return $SQL;
4792
-    }
4793
-
4794
-
4795
-    /**
4796
-     * Constructs the SQL for joining all the tables on this model.
4797
-     * Normally $alias should be the primary table's alias, but in cases where
4798
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4799
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4800
-     * alias, this will construct SQL like:
4801
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4802
-     * With $alias being a secondary table's alias, this will construct SQL like:
4803
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4804
-     *
4805
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4806
-     * @return string
4807
-     * @throws EE_Error
4808
-     */
4809
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4810
-    {
4811
-        $SQL               = '';
4812
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4813
-        foreach ($this->_tables as $table_obj) {
4814
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4815
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4816
-                    // so we're joining to this table, meaning the table is already in
4817
-                    // the FROM statement, BUT the primary table isn't. So we want
4818
-                    // to add the inverse join sql
4819
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4820
-                } else {
4821
-                    // just add a regular JOIN to this table from the primary table
4822
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4823
-                }
4824
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4825
-        }
4826
-        return $SQL;
4827
-    }
4828
-
4829
-
4830
-    /**
4831
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4832
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4833
-     * their data type (eg, '%s', '%d', etc)
4834
-     *
4835
-     * @return array
4836
-     */
4837
-    public function _get_data_types()
4838
-    {
4839
-        $data_types = [];
4840
-        foreach ($this->field_settings() as $field_obj) {
4841
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842
-            /** @var $field_obj EE_Model_Field_Base */
4843
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4844
-        }
4845
-        return $data_types;
4846
-    }
4847
-
4848
-
4849
-    /**
4850
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4851
-     *
4852
-     * @param string $model_name
4853
-     * @return EEM_Base
4854
-     * @throws EE_Error
4855
-     */
4856
-    public function get_related_model_obj($model_name)
4857
-    {
4858
-        $model_classname = "EEM_" . $model_name;
4859
-        if (! class_exists($model_classname)) {
4860
-            throw new EE_Error(
4861
-                sprintf(
4862
-                    esc_html__(
4863
-                        "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4864
-                        'event_espresso'
4865
-                    ),
4866
-                    $model_name,
4867
-                    $model_classname
4868
-                )
4869
-            );
4870
-        }
4871
-        return call_user_func($model_classname . "::instance");
4872
-    }
4873
-
4874
-
4875
-    /**
4876
-     * Returns the array of EE_ModelRelations for this model.
4877
-     *
4878
-     * @return EE_Model_Relation_Base[]
4879
-     */
4880
-    public function relation_settings()
4881
-    {
4882
-        return $this->_model_relations;
4883
-    }
4884
-
4885
-
4886
-    /**
4887
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4888
-     * because without THOSE models, this model probably doesn't have much purpose.
4889
-     * (Eg, without an event, datetimes have little purpose.)
4890
-     *
4891
-     * @return EE_Belongs_To_Relation[]
4892
-     */
4893
-    public function belongs_to_relations()
4894
-    {
4895
-        $belongs_to_relations = [];
4896
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4899
-            }
4900
-        }
4901
-        return $belongs_to_relations;
4902
-    }
4903
-
4904
-
4905
-    /**
4906
-     * Returns the specified EE_Model_Relation, or throws an exception
4907
-     *
4908
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4909
-     * @return EE_Model_Relation_Base
4910
-     * @throws EE_Error
4911
-     */
4912
-    public function related_settings_for($relation_name)
4913
-    {
4914
-        $relatedModels = $this->relation_settings();
4915
-        if (! array_key_exists($relation_name, $relatedModels)) {
4916
-            throw new EE_Error(
4917
-                sprintf(
4918
-                    esc_html__(
4919
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4920
-                        'event_espresso'
4921
-                    ),
4922
-                    $relation_name,
4923
-                    $this->_get_class_name(),
4924
-                    implode(', ', array_keys($relatedModels))
4925
-                )
4926
-            );
4927
-        }
4928
-        return $relatedModels[ $relation_name ];
4929
-    }
4930
-
4931
-
4932
-    /**
4933
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4934
-     * fields
4935
-     *
4936
-     * @param string  $fieldName
4937
-     * @param boolean $include_db_only_fields
4938
-     * @return EE_Model_Field_Base
4939
-     * @throws EE_Error
4940
-     */
4941
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4942
-    {
4943
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4944
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4945
-            throw new EE_Error(
4946
-                sprintf(
4947
-                    esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4948
-                    $fieldName,
4949
-                    get_class($this)
4950
-                )
4951
-            );
4952
-        }
4953
-        return $fieldSettings[ $fieldName ];
4954
-    }
4955
-
4956
-
4957
-    /**
4958
-     * Checks if this field exists on this model
4959
-     *
4960
-     * @param string $fieldName a key in the model's _field_settings array
4961
-     * @return boolean
4962
-     */
4963
-    public function has_field($fieldName)
4964
-    {
4965
-        $fieldSettings = $this->field_settings(true);
4966
-        if (isset($fieldSettings[ $fieldName ])) {
4967
-            return true;
4968
-        }
4969
-        return false;
4970
-    }
4971
-
4972
-
4973
-    /**
4974
-     * Returns whether or not this model has a relation to the specified model
4975
-     *
4976
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4977
-     * @return boolean
4978
-     */
4979
-    public function has_relation($relation_name)
4980
-    {
4981
-        $relations = $this->relation_settings();
4982
-        if (isset($relations[ $relation_name ])) {
4983
-            return true;
4984
-        }
4985
-        return false;
4986
-    }
4987
-
4988
-
4989
-    /**
4990
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991
-     * Eg, on EE_Answer that would be ANS_ID field object
4992
-     *
4993
-     * @param $field_obj
4994
-     * @return boolean
4995
-     */
4996
-    public function is_primary_key_field($field_obj)
4997
-    {
4998
-        return $field_obj instanceof EE_Primary_Key_Field_Base;
4999
-    }
5000
-
5001
-
5002
-    /**
5003
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
-     * Eg, on EE_Answer that would be ANS_ID field object
5005
-     *
5006
-     * @return EE_Model_Field_Base
5007
-     * @throws EE_Error
5008
-     */
5009
-    public function get_primary_key_field()
5010
-    {
5011
-        if ($this->_primary_key_field === null) {
5012
-            foreach ($this->field_settings(true) as $field_obj) {
5013
-                if ($this->is_primary_key_field($field_obj)) {
5014
-                    $this->_primary_key_field = $field_obj;
5015
-                    break;
5016
-                }
5017
-            }
5018
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019
-                throw new EE_Error(
5020
-                    sprintf(
5021
-                        esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5022
-                        get_class($this)
5023
-                    )
5024
-                );
5025
-            }
5026
-        }
5027
-        return $this->_primary_key_field;
5028
-    }
5029
-
5030
-
5031
-    /**
5032
-     * Returns whether or not not there is a primary key on this model.
5033
-     * Internally does some caching.
5034
-     *
5035
-     * @return boolean
5036
-     */
5037
-    public function has_primary_key_field()
5038
-    {
5039
-        if ($this->_has_primary_key_field === null) {
5040
-            try {
5041
-                $this->get_primary_key_field();
5042
-                $this->_has_primary_key_field = true;
5043
-            } catch (EE_Error $e) {
5044
-                $this->_has_primary_key_field = false;
5045
-            }
5046
-        }
5047
-        return $this->_has_primary_key_field;
5048
-    }
5049
-
5050
-
5051
-    /**
5052
-     * Finds the first field of type $field_class_name.
5053
-     *
5054
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5055
-     *                                 EE_Foreign_Key_Field, etc
5056
-     * @return EE_Model_Field_Base or null if none is found
5057
-     */
5058
-    public function get_a_field_of_type($field_class_name)
5059
-    {
5060
-        foreach ($this->field_settings() as $field) {
5061
-            if ($field instanceof $field_class_name) {
5062
-                return $field;
5063
-            }
5064
-        }
5065
-        return null;
5066
-    }
5067
-
5068
-
5069
-    /**
5070
-     * Gets a foreign key field pointing to model.
5071
-     *
5072
-     * @param string $model_name eg Event, Registration, not EEM_Event
5073
-     * @return EE_Foreign_Key_Field_Base
5074
-     * @throws EE_Error
5075
-     */
5076
-    public function get_foreign_key_to($model_name)
5077
-    {
5078
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
-            foreach ($this->field_settings() as $field) {
5080
-                if (
5081
-                    $field instanceof EE_Foreign_Key_Field_Base
5082
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5083
-                ) {
5084
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5085
-                    break;
5086
-                }
5087
-            }
5088
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5089
-                throw new EE_Error(
5090
-                    sprintf(
5091
-                        esc_html__(
5092
-                            "There is no foreign key field pointing to model %s on model %s",
5093
-                            'event_espresso'
5094
-                        ),
5095
-                        $model_name,
5096
-                        get_class($this)
5097
-                    )
5098
-                );
5099
-            }
5100
-        }
5101
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5102
-    }
5103
-
5104
-
5105
-    /**
5106
-     * Gets the table name (including $wpdb->prefix) for the table alias
5107
-     *
5108
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5109
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5110
-     *                            Either one works
5111
-     * @return string
5112
-     */
5113
-    public function get_table_for_alias($table_alias)
5114
-    {
5115
-        $table_alias_sans_model_relation_chain_prefix =
5116
-            EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5118
-    }
5119
-
5120
-
5121
-    /**
5122
-     * Returns a flat array of all field son this model, instead of organizing them
5123
-     * by table_alias as they are in the constructor.
5124
-     *
5125
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5126
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5127
-     */
5128
-    public function field_settings($include_db_only_fields = false)
5129
-    {
5130
-        if ($include_db_only_fields) {
5131
-            if ($this->_cached_fields === null) {
5132
-                $this->_cached_fields = [];
5133
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5134
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5136
-                    }
5137
-                }
5138
-            }
5139
-            return $this->_cached_fields;
5140
-        }
5141
-        if ($this->_cached_fields_non_db_only === null) {
5142
-            $this->_cached_fields_non_db_only = [];
5143
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5144
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145
-                    /** @var $field_obj EE_Model_Field_Base */
5146
-                    if (! $field_obj->is_db_only_field()) {
5147
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5148
-                    }
5149
-                }
5150
-            }
5151
-        }
5152
-        return $this->_cached_fields_non_db_only;
5153
-    }
5154
-
5155
-
5156
-    /**
5157
-     *        cycle though array of attendees and create objects out of each item
5158
-     *
5159
-     * @access        private
5160
-     * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5161
-     * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5162
-     *                           numerically indexed)
5163
-     * @throws EE_Error
5164
-     * @throws ReflectionException
5165
-     */
5166
-    protected function _create_objects($rows = [])
5167
-    {
5168
-        $array_of_objects = [];
5169
-        if (empty($rows)) {
5170
-            return [];
5171
-        }
5172
-        $count_if_model_has_no_primary_key = 0;
5173
-        $has_primary_key                   = $this->has_primary_key_field();
5174
-        $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
-        foreach ((array)$rows as $row) {
5176
-            if (empty($row)) {
5177
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178
-                return [];
5179
-            }
5180
-            // check if we've already set this object in the results array,
5181
-            // in which case there's no need to process it further (again)
5182
-            if ($has_primary_key) {
5183
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5184
-                    $row,
5185
-                    $primary_key_field->get_qualified_column(),
5186
-                    $primary_key_field->get_table_column()
5187
-                );
5188
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5189
-                    continue;
5190
-                }
5191
-            }
5192
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5193
-            if (! $classInstance) {
5194
-                throw new EE_Error(
5195
-                    sprintf(
5196
-                        esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5197
-                        $this->get_this_model_name(),
5198
-                        http_build_query($row)
5199
-                    )
5200
-                );
5201
-            }
5202
-            // set the timezone on the instantiated objects
5203
-            $classInstance->set_timezone($this->_timezone);
5204
-            // make sure if there is any timezone setting present that we set the timezone for the object
5205
-            $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
-            $array_of_objects[ $key ] = $classInstance;
5207
-            // also, for all the relations of type BelongsTo, see if we can cache
5208
-            // those related models
5209
-            // (we could do this for other relations too, but if there are conditions
5210
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5211
-            // so it requires a little more thought than just caching them immediately...)
5212
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5213
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5214
-                    // check if this model's INFO is present. If so, cache it on the model
5215
-                    $other_model           = $relation_obj->get_other_model();
5216
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5217
-                    // if we managed to make a model object from the results, cache it on the main model object
5218
-                    if ($other_model_obj_maybe) {
5219
-                        // set timezone on these other model objects if they are present
5220
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5221
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5222
-                    }
5223
-                }
5224
-            }
5225
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5226
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5227
-            // the field in the CustomSelects object
5228
-            if ($this->_custom_selections instanceof CustomSelects) {
5229
-                $classInstance->setCustomSelectsValues(
5230
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5231
-                );
5232
-            }
5233
-        }
5234
-        return $array_of_objects;
5235
-    }
5236
-
5237
-
5238
-    /**
5239
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5240
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5241
-     *
5242
-     * @param array $db_results_row
5243
-     * @return array
5244
-     */
5245
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5246
-    {
5247
-        $results = [];
5248
-        if ($this->_custom_selections instanceof CustomSelects) {
5249
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
-                if (isset($db_results_row[ $alias ])) {
5251
-                    $results[ $alias ] = $this->convertValueToDataType(
5252
-                        $db_results_row[ $alias ],
5253
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5254
-                    );
5255
-                }
5256
-            }
5257
-        }
5258
-        return $results;
5259
-    }
5260
-
5261
-
5262
-    /**
5263
-     * This will set the value for the given alias
5264
-     *
5265
-     * @param string $value
5266
-     * @param string $datatype (one of %d, %s, %f)
5267
-     * @return int|string|float (int for %d, string for %s, float for %f)
5268
-     */
5269
-    protected function convertValueToDataType($value, $datatype)
5270
-    {
5271
-        switch ($datatype) {
5272
-            case '%f':
5273
-                return (float)$value;
5274
-            case '%d':
5275
-                return (int)$value;
5276
-            default:
5277
-                return (string)$value;
5278
-        }
5279
-    }
5280
-
5281
-
5282
-    /**
5283
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5284
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5285
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5286
-     * object (as set in the model_field!).
5287
-     *
5288
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5289
-     * @throws EE_Error
5290
-     * @throws ReflectionException
5291
-     */
5292
-    public function create_default_object()
5293
-    {
5294
-        $this_model_fields_and_values = [];
5295
-        // setup the row using default values;
5296
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5297
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5298
-        }
5299
-        $className = $this->_get_class_name();
5300
-        return EE_Registry::instance()->load_class(
5301
-            $className,
5302
-            [$this_model_fields_and_values],
5303
-            false,
5304
-            false
5305
-        );
5306
-    }
5307
-
5308
-
5309
-    /**
5310
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5311
-     *                             or an stdClass where each property is the name of a column,
5312
-     * @return EE_Base_Class
5313
-     * @throws EE_Error
5314
-     * @throws ReflectionException
5315
-     */
5316
-    public function instantiate_class_from_array_or_object($cols_n_values)
5317
-    {
5318
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5319
-            $cols_n_values = get_object_vars($cols_n_values);
5320
-        }
5321
-        $primary_key = null;
5322
-        // make sure the array only has keys that are fields/columns on this model
5323
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5326
-        }
5327
-        $className = $this->_get_class_name();
5328
-        // check we actually found results that we can use to build our model object
5329
-        // if not, return null
5330
-        if ($this->has_primary_key_field()) {
5331
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5332
-                return null;
5333
-            }
5334
-        } elseif ($this->unique_indexes()) {
5335
-            $first_column = reset($this_model_fields_n_values);
5336
-            if (empty($first_column)) {
5337
-                return null;
5338
-            }
5339
-        }
5340
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341
-        if ($primary_key) {
5342
-            $classInstance = $this->get_from_entity_map($primary_key);
5343
-            if (! $classInstance) {
5344
-                $classInstance = EE_Registry::instance()->load_class(
5345
-                    $className,
5346
-                    [$this_model_fields_n_values, $this->_timezone],
5347
-                    true,
5348
-                    false
5349
-                );
5350
-                // add this new object to the entity map
5351
-                $classInstance = $this->add_to_entity_map($classInstance);
5352
-            }
5353
-        } else {
5354
-            $classInstance = EE_Registry::instance()->load_class(
5355
-                $className,
5356
-                [$this_model_fields_n_values, $this->_timezone],
5357
-                true,
5358
-                false
5359
-            );
5360
-        }
5361
-        return $classInstance;
5362
-    }
5363
-
5364
-
5365
-    /**
5366
-     * Gets the model object from the  entity map if it exists
5367
-     *
5368
-     * @param int|string $id the ID of the model object
5369
-     * @return EE_Base_Class
5370
-     */
5371
-    public function get_from_entity_map($id)
5372
-    {
5373
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5375
-    }
5376
-
5377
-
5378
-    /**
5379
-     * add_to_entity_map
5380
-     * Adds the object to the model's entity mappings
5381
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5382
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5383
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5384
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5385
-     *        then this method should be called immediately after the update query
5386
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5387
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5388
-     *
5389
-     * @param EE_Base_Class $object
5390
-     * @return EE_Base_Class
5391
-     * @throws EE_Error
5392
-     * @throws ReflectionException
5393
-     */
5394
-    public function add_to_entity_map(EE_Base_Class $object)
5395
-    {
5396
-        $className = $this->_get_class_name();
5397
-        if (! $object instanceof $className) {
5398
-            throw new EE_Error(
5399
-                sprintf(
5400
-                    esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5401
-                    is_object($object) ? get_class($object) : $object,
5402
-                    $className
5403
-                )
5404
-            );
5405
-        }
5406
-        if (! $object->ID()) {
5407
-            throw new EE_Error(
5408
-                sprintf(
5409
-                    esc_html__(
5410
-                        "You tried storing a model object with NO ID in the %s entity mapper.",
5411
-                        "event_espresso"
5412
-                    ),
5413
-                    get_class($this)
5414
-                )
5415
-            );
5416
-        }
5417
-        // double check it's not already there
5418
-        $classInstance = $this->get_from_entity_map($object->ID());
5419
-        if ($classInstance) {
5420
-            return $classInstance;
5421
-        }
5422
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5423
-        return $object;
5424
-    }
5425
-
5426
-
5427
-    /**
5428
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5429
-     * if no identifier is provided, then the entire entity map is emptied
5430
-     *
5431
-     * @param int|string $id the ID of the model object
5432
-     * @return boolean
5433
-     */
5434
-    public function clear_entity_map($id = null)
5435
-    {
5436
-        if (empty($id)) {
5437
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5438
-            return true;
5439
-        }
5440
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5442
-            return true;
5443
-        }
5444
-        return false;
5445
-    }
5446
-
5447
-
5448
-    /**
5449
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5450
-     * Given an array where keys are column (or column alias) names and values,
5451
-     * returns an array of their corresponding field names and database values
5452
-     *
5453
-     * @param array $cols_n_values
5454
-     * @return array
5455
-     */
5456
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5457
-    {
5458
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5459
-    }
5460
-
5461
-
5462
-    /**
5463
-     * _deduce_fields_n_values_from_cols_n_values
5464
-     * Given an array where keys are column (or column alias) names and values,
5465
-     * returns an array of their corresponding field names and database values
5466
-     *
5467
-     * @param array $cols_n_values
5468
-     * @return array
5469
-     */
5470
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5471
-    {
5472
-        $this_model_fields_n_values = [];
5473
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
-                $cols_n_values,
5476
-                $table_obj->get_fully_qualified_pk_column(),
5477
-                $table_obj->get_pk_column()
5478
-            );
5479
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5480
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5483
-                        // prepare field as if its coming from db
5484
-                        $prepared_value                            =
5485
-                            $field_obj->prepare_for_set($field_obj->get_default_value());
5486
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5487
-                    }
5488
-                }
5489
-            } else {
5490
-                // the table's rows existed. Use their values
5491
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
-                    if (! $field_obj->is_db_only_field()) {
5493
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5494
-                            $cols_n_values,
5495
-                            $field_obj->get_qualified_column(),
5496
-                            $field_obj->get_table_column()
5497
-                        );
5498
-                    }
5499
-                }
5500
-            }
5501
-        }
5502
-        return $this_model_fields_n_values;
5503
-    }
5504
-
5505
-
5506
-    /**
5507
-     * @param array  $cols_n_values
5508
-     * @param string $qualified_column
5509
-     * @param string $regular_column
5510
-     * @return null
5511
-     */
5512
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5513
-    {
5514
-        $value = null;
5515
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516
-        // does the field on the model relate to this column retrieved from the db?
5517
-        // or is it a db-only field? (not relating to the model)
5518
-        if (isset($cols_n_values[ $qualified_column ])) {
5519
-            $value = $cols_n_values[ $qualified_column ];
5520
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5521
-            $value = $cols_n_values[ $regular_column ];
5522
-        } elseif (! empty($this->foreign_key_aliases)) {
5523
-            // no PK?  ok check if there is a foreign key alias set for this table
5524
-            // then check if that alias exists in the incoming data
5525
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
-                    $value = $cols_n_values[ $FK_alias ];
5529
-                    break;
5530
-                }
5531
-            }
5532
-        }
5533
-        return $value;
5534
-    }
5535
-
5536
-
5537
-    /**
5538
-     * refresh_entity_map_from_db
5539
-     * Makes sure the model object in the entity map at $id assumes the values
5540
-     * of the database (opposite of EE_base_Class::save())
5541
-     *
5542
-     * @param int|string $id
5543
-     * @return EE_Base_Class
5544
-     * @throws EE_Error
5545
-     * @throws ReflectionException
5546
-     */
5547
-    public function refresh_entity_map_from_db($id)
5548
-    {
5549
-        $obj_in_map = $this->get_from_entity_map($id);
5550
-        if ($obj_in_map) {
5551
-            $wpdb_results = $this->_get_all_wpdb_results(
5552
-                [[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5553
-            );
5554
-            if ($wpdb_results && is_array($wpdb_results)) {
5555
-                $one_row = reset($wpdb_results);
5556
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5557
-                    $obj_in_map->set_from_db($field_name, $db_value);
5558
-                }
5559
-                // clear the cache of related model objects
5560
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5561
-                    $obj_in_map->clear_cache($relation_name, null, true);
5562
-                }
5563
-            }
5564
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5565
-            return $obj_in_map;
5566
-        }
5567
-        return $this->get_one_by_ID($id);
5568
-    }
5569
-
5570
-
5571
-    /**
5572
-     * refresh_entity_map_with
5573
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5574
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5575
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5576
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5577
-     *
5578
-     * @param int|string    $id
5579
-     * @param EE_Base_Class $replacing_model_obj
5580
-     * @return EE_Base_Class
5581
-     * @throws EE_Error
5582
-     * @throws ReflectionException
5583
-     */
5584
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5585
-    {
5586
-        $obj_in_map = $this->get_from_entity_map($id);
5587
-        if ($obj_in_map) {
5588
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5589
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5590
-                    $obj_in_map->set($field_name, $value);
5591
-                }
5592
-                // make the model object in the entity map's cache match the $replacing_model_obj
5593
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5594
-                    $obj_in_map->clear_cache($relation_name, null, true);
5595
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5596
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5597
-                    }
5598
-                }
5599
-            }
5600
-            return $obj_in_map;
5601
-        }
5602
-        $this->add_to_entity_map($replacing_model_obj);
5603
-        return $replacing_model_obj;
5604
-    }
5605
-
5606
-
5607
-    /**
5608
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5609
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5610
-     * require_once($this->_getClassName().".class.php");
5611
-     *
5612
-     * @return string
5613
-     */
5614
-    private function _get_class_name()
5615
-    {
5616
-        return "EE_" . $this->get_this_model_name();
5617
-    }
5618
-
5619
-
5620
-    /**
5621
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5622
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5623
-     * it would be 'Events'.
5624
-     *
5625
-     * @param int $quantity
5626
-     * @return string
5627
-     */
5628
-    public function item_name($quantity = 1)
5629
-    {
5630
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5631
-    }
5632
-
5633
-
5634
-    /**
5635
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5636
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5637
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5638
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5639
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5640
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5641
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5642
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5643
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5644
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5645
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5646
-     *        return $previousReturnValue.$returnString;
5647
-     * }
5648
-     * require('EEM_Answer.model.php');
5649
-     * $answer=EEM_Answer::instance();
5650
-     * echo $answer->my_callback('monkeys',100);
5651
-     * //will output "you called my_callback! and passed args:monkeys,100"
5652
-     *
5653
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5654
-     * @param array  $args       array of original arguments passed to the function
5655
-     * @return mixed whatever the plugin which calls add_filter decides
5656
-     * @throws EE_Error
5657
-     */
5658
-    public function __call($methodName, $args)
5659
-    {
5660
-        $className = get_class($this);
5661
-        $tagName   = "FHEE__{$className}__{$methodName}";
5662
-        if (! has_filter($tagName)) {
5663
-            throw new EE_Error(
5664
-                sprintf(
5665
-                    esc_html__(
5666
-                        '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 );',
5667
-                        'event_espresso'
5668
-                    ),
5669
-                    $methodName,
5670
-                    $className,
5671
-                    $tagName,
5672
-                    '<br />'
5673
-                )
5674
-            );
5675
-        }
5676
-        return apply_filters($tagName, null, $this, $args);
5677
-    }
5678
-
5679
-
5680
-    /**
5681
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
-     *
5684
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5686
-     *                                                       the object's class name
5687
-     *                                                       or object's ID
5688
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
-     *                                                       exists in the database. If it does not, we add it
5690
-     * @return EE_Base_Class
5691
-     * @throws EE_Error
5692
-     * @throws ReflectionException
5693
-     */
5694
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5695
-    {
5696
-        $className = $this->_get_class_name();
5697
-        if ($base_class_obj_or_id instanceof $className) {
5698
-            $model_object = $base_class_obj_or_id;
5699
-        } else {
5700
-            $primary_key_field = $this->get_primary_key_field();
5701
-            if (
5702
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5703
-                && (
5704
-                    is_int($base_class_obj_or_id)
5705
-                    || is_string($base_class_obj_or_id)
5706
-                )
5707
-            ) {
5708
-                // assume it's an ID.
5709
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5710
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5711
-            } elseif (
5712
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5713
-                && is_string($base_class_obj_or_id)
5714
-            ) {
5715
-                // assume its a string representation of the object
5716
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5717
-            } else {
5718
-                throw new EE_Error(
5719
-                    sprintf(
5720
-                        esc_html__(
5721
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5722
-                            'event_espresso'
5723
-                        ),
5724
-                        $base_class_obj_or_id,
5725
-                        $this->_get_class_name(),
5726
-                        print_r($base_class_obj_or_id, true)
5727
-                    )
5728
-                );
5729
-            }
5730
-        }
5731
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5732
-            $model_object->save();
5733
-        }
5734
-        return $model_object;
5735
-    }
5736
-
5737
-
5738
-    /**
5739
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
-     * returns it ID.
5742
-     *
5743
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
-     * @return int|string depending on the type of this model object's ID
5745
-     * @throws EE_Error
5746
-     * @throws ReflectionException
5747
-     */
5748
-    public function ensure_is_ID($base_class_obj_or_id)
5749
-    {
5750
-        $className = $this->_get_class_name();
5751
-        if ($base_class_obj_or_id instanceof $className) {
5752
-            $id = $base_class_obj_or_id->ID();
5753
-        } elseif (is_int($base_class_obj_or_id)) {
5754
-            // assume it's an ID
5755
-            $id = $base_class_obj_or_id;
5756
-        } elseif (is_string($base_class_obj_or_id)) {
5757
-            // assume its a string representation of the object
5758
-            $id = $base_class_obj_or_id;
5759
-        } else {
5760
-            throw new EE_Error(
5761
-                sprintf(
5762
-                    esc_html__(
5763
-                        "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5764
-                        'event_espresso'
5765
-                    ),
5766
-                    $base_class_obj_or_id,
5767
-                    $this->_get_class_name(),
5768
-                    print_r($base_class_obj_or_id, true)
5769
-                )
5770
-            );
5771
-        }
5772
-        return $id;
5773
-    }
5774
-
5775
-
5776
-    /**
5777
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5778
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5779
-     * been sanitized and converted into the appropriate domain.
5780
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5781
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5782
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5783
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5784
-     * $EVT = EEM_Event::instance(); $old_setting =
5785
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5786
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5787
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5788
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5789
-     *
5790
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5791
-     * @return void
5792
-     */
5793
-    public function assume_values_already_prepared_by_model_object(
5794
-        $values_already_prepared = self::not_prepared_by_model_object
5795
-    ) {
5796
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5797
-    }
5798
-
5799
-
5800
-    /**
5801
-     * Read comments for assume_values_already_prepared_by_model_object()
5802
-     *
5803
-     * @return int
5804
-     */
5805
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
-    {
5807
-        return $this->_values_already_prepared_by_model_object;
5808
-    }
5809
-
5810
-
5811
-    /**
5812
-     * Gets all the indexes on this model
5813
-     *
5814
-     * @return EE_Index[]
5815
-     */
5816
-    public function indexes()
5817
-    {
5818
-        return $this->_indexes;
5819
-    }
5820
-
5821
-
5822
-    /**
5823
-     * Gets all the Unique Indexes on this model
5824
-     *
5825
-     * @return EE_Unique_Index[]
5826
-     */
5827
-    public function unique_indexes()
5828
-    {
5829
-        $unique_indexes = [];
5830
-        foreach ($this->_indexes as $name => $index) {
5831
-            if ($index instanceof EE_Unique_Index) {
5832
-                $unique_indexes [ $name ] = $index;
5833
-            }
5834
-        }
5835
-        return $unique_indexes;
5836
-    }
5837
-
5838
-
5839
-    /**
5840
-     * Gets all the fields which, when combined, make the primary key.
5841
-     * This is usually just an array with 1 element (the primary key), but in cases
5842
-     * where there is no primary key, it's a combination of fields as defined
5843
-     * on a primary index
5844
-     *
5845
-     * @return EE_Model_Field_Base[] indexed by the field's name
5846
-     * @throws EE_Error
5847
-     */
5848
-    public function get_combined_primary_key_fields()
5849
-    {
5850
-        foreach ($this->indexes() as $index) {
5851
-            if ($index instanceof EE_Primary_Key_Index) {
5852
-                return $index->fields();
5853
-            }
5854
-        }
5855
-        return [$this->primary_key_name() => $this->get_primary_key_field()];
5856
-    }
5857
-
5858
-
5859
-    /**
5860
-     * Used to build a primary key string (when the model has no primary key),
5861
-     * which can be used a unique string to identify this model object.
5862
-     *
5863
-     * @param array $fields_n_values keys are field names, values are their values.
5864
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5865
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5866
-     *                               before passing it to this function (that will convert it from columns-n-values
5867
-     *                               to field-names-n-values).
5868
-     * @return string
5869
-     * @throws EE_Error
5870
-     */
5871
-    public function get_index_primary_key_string($fields_n_values)
5872
-    {
5873
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5874
-            $fields_n_values,
5875
-            $this->get_combined_primary_key_fields()
5876
-        );
5877
-        return http_build_query($cols_n_values_for_primary_key_index);
5878
-    }
5879
-
5880
-
5881
-    /**
5882
-     * Gets the field values from the primary key string
5883
-     *
5884
-     * @param string $index_primary_key_string
5885
-     * @return null|array
5886
-     * @throws EE_Error
5887
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5888
-     */
5889
-    public function parse_index_primary_key_string($index_primary_key_string)
5890
-    {
5891
-        $key_fields = $this->get_combined_primary_key_fields();
5892
-        // check all of them are in the $id
5893
-        $key_values_in_combined_pk = [];
5894
-        parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895
-        foreach ($key_fields as $key_field_name => $field_obj) {
5896
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5897
-                return null;
5898
-            }
5899
-        }
5900
-        return $key_values_in_combined_pk;
5901
-    }
5902
-
5903
-
5904
-    /**
5905
-     * verifies that an array of key-value pairs for model fields has a key
5906
-     * for each field comprising the primary key index
5907
-     *
5908
-     * @param array $key_values
5909
-     * @return boolean
5910
-     * @throws EE_Error
5911
-     */
5912
-    public function has_all_combined_primary_key_fields($key_values)
5913
-    {
5914
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
-        foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_values[ $key ])) {
5917
-                return false;
5918
-            }
5919
-        }
5920
-        return true;
5921
-    }
5922
-
5923
-
5924
-    /**
5925
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5926
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5927
-     *
5928
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5929
-     * @param array               $query_params                     see github link below for more info
5930
-     * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
-     * @throws EE_Error
5932
-     * @throws ReflectionException
5933
-     * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5934
-     *                                                              indexed)
5935
-     */
5936
-    public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5937
-    {
5938
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5939
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5940
-        } elseif (is_array($model_object_or_attributes_array)) {
5941
-            $attributes_array = $model_object_or_attributes_array;
5942
-        } else {
5943
-            throw new EE_Error(
5944
-                sprintf(
5945
-                    esc_html__(
5946
-                        "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5947
-                        "event_espresso"
5948
-                    ),
5949
-                    $model_object_or_attributes_array
5950
-                )
5951
-            );
5952
-        }
5953
-        // even copies obviously won't have the same ID, so remove the primary key
5954
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5957
-        }
5958
-        if (isset($query_params[0])) {
5959
-            $query_params[0] = array_merge($attributes_array, $query_params);
5960
-        } else {
5961
-            $query_params[0] = $attributes_array;
5962
-        }
5963
-        return $this->get_all($query_params);
5964
-    }
5965
-
5966
-
5967
-    /**
5968
-     * Gets the first copy we find. See get_all_copies for more details
5969
-     *
5970
-     * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5971
-     * @param array $query_params
5972
-     * @return EE_Base_Class
5973
-     * @throws EE_Error
5974
-     * @throws ReflectionException
5975
-     */
5976
-    public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977
-    {
5978
-        if (! is_array($query_params)) {
5979
-            EE_Error::doing_it_wrong(
5980
-                'EEM_Base::get_one_copy',
5981
-                sprintf(
5982
-                    esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
-                    gettype($query_params)
5984
-                ),
5985
-                '4.6.0'
5986
-            );
5987
-            $query_params = [];
5988
-        }
5989
-        $query_params['limit'] = 1;
5990
-        $copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
-        if (is_array($copies)) {
5992
-            return array_shift($copies);
5993
-        }
5994
-        return null;
5995
-    }
5996
-
5997
-
5998
-    /**
5999
-     * Updates the item with the specified id. Ignores default query parameters because
6000
-     * we have specified the ID, and its assumed we KNOW what we're doing
6001
-     *
6002
-     * @param array      $fields_n_values keys are field names, values are their new values
6003
-     * @param int|string $id              the value of the primary key to update
6004
-     * @return int number of rows updated
6005
-     * @throws EE_Error
6006
-     * @throws ReflectionException
6007
-     */
6008
-    public function update_by_ID($fields_n_values, $id)
6009
-    {
6010
-        $query_params = [
6011
-            0                          => [$this->get_primary_key_field()->get_name() => $id],
6012
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
-        ];
6014
-        return $this->update($fields_n_values, $query_params);
6015
-    }
6016
-
6017
-
6018
-    /**
6019
-     * Changes an operator which was supplied to the models into one usable in SQL
6020
-     *
6021
-     * @param string $operator_supplied
6022
-     * @return string an operator which can be used in SQL
6023
-     * @throws EE_Error
6024
-     */
6025
-    private function _prepare_operator_for_sql($operator_supplied)
6026
-    {
6027
-        $sql_operator =
6028
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
-                : null;
6030
-        if ($sql_operator) {
6031
-            return $sql_operator;
6032
-        }
6033
-        throw new EE_Error(
6034
-            sprintf(
6035
-                esc_html__(
6036
-                    "The operator '%s' is not in the list of valid operators: %s",
6037
-                    "event_espresso"
6038
-                ),
6039
-                $operator_supplied,
6040
-                implode(",", array_keys($this->_valid_operators))
6041
-            )
6042
-        );
6043
-    }
6044
-
6045
-
6046
-    /**
6047
-     * Gets the valid operators
6048
-     *
6049
-     * @return array keys are accepted strings, values are the SQL they are converted to
6050
-     */
6051
-    public function valid_operators()
6052
-    {
6053
-        return $this->_valid_operators;
6054
-    }
6055
-
6056
-
6057
-    /**
6058
-     * Gets the between-style operators (take 2 arguments).
6059
-     *
6060
-     * @return array keys are accepted strings, values are the SQL they are converted to
6061
-     */
6062
-    public function valid_between_style_operators()
6063
-    {
6064
-        return array_intersect(
6065
-            $this->valid_operators(),
6066
-            $this->_between_style_operators
6067
-        );
6068
-    }
6069
-
6070
-
6071
-    /**
6072
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6073
-     *
6074
-     * @return array keys are accepted strings, values are the SQL they are converted to
6075
-     */
6076
-    public function valid_like_style_operators()
6077
-    {
6078
-        return array_intersect(
6079
-            $this->valid_operators(),
6080
-            $this->_like_style_operators
6081
-        );
6082
-    }
6083
-
6084
-
6085
-    /**
6086
-     * Gets the "in"-style operators
6087
-     *
6088
-     * @return array keys are accepted strings, values are the SQL they are converted to
6089
-     */
6090
-    public function valid_in_style_operators()
6091
-    {
6092
-        return array_intersect(
6093
-            $this->valid_operators(),
6094
-            $this->_in_style_operators
6095
-        );
6096
-    }
6097
-
6098
-
6099
-    /**
6100
-     * Gets the "null"-style operators (accept no arguments)
6101
-     *
6102
-     * @return array keys are accepted strings, values are the SQL they are converted to
6103
-     */
6104
-    public function valid_null_style_operators()
6105
-    {
6106
-        return array_intersect(
6107
-            $this->valid_operators(),
6108
-            $this->_null_style_operators
6109
-        );
6110
-    }
6111
-
6112
-
6113
-    /**
6114
-     * Gets an array where keys are the primary keys and values are their 'names'
6115
-     * (as determined by the model object's name() function, which is often overridden)
6116
-     *
6117
-     * @param array $query_params like get_all's
6118
-     * @return string[]
6119
-     * @throws EE_Error
6120
-     * @throws ReflectionException
6121
-     */
6122
-    public function get_all_names($query_params = [])
6123
-    {
6124
-        $objs  = $this->get_all($query_params);
6125
-        $names = [];
6126
-        foreach ($objs as $obj) {
6127
-            $names[ $obj->ID() ] = $obj->name();
6128
-        }
6129
-        return $names;
6130
-    }
6131
-
6132
-
6133
-    /**
6134
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6135
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6136
-     * this is duplicated effort and reduces efficiency) you would be better to use
6137
-     * array_keys() on $model_objects.
6138
-     *
6139
-     * @param EE_Base_Class[] $model_objects
6140
-     * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6141
-     *                                               in the returned array
6142
-     * @return array
6143
-     * @throws EE_Error
6144
-     * @throws ReflectionException
6145
-     */
6146
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6147
-    {
6148
-        if (! $this->has_primary_key_field()) {
6149
-            if (WP_DEBUG) {
6150
-                EE_Error::add_error(
6151
-                    esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6152
-                    __FILE__,
6153
-                    __FUNCTION__,
6154
-                    __LINE__
6155
-                );
6156
-            }
6157
-        }
6158
-        $IDs = [];
6159
-        foreach ($model_objects as $model_object) {
6160
-            $id = $model_object->ID();
6161
-            if (! $id) {
6162
-                if ($filter_out_empty_ids) {
6163
-                    continue;
6164
-                }
6165
-                if (WP_DEBUG) {
6166
-                    EE_Error::add_error(
6167
-                        esc_html__(
6168
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6169
-                            'event_espresso'
6170
-                        ),
6171
-                        __FILE__,
6172
-                        __FUNCTION__,
6173
-                        __LINE__
6174
-                    );
6175
-                }
6176
-            }
6177
-            $IDs[] = $id;
6178
-        }
6179
-        return $IDs;
6180
-    }
6181
-
6182
-
6183
-    /**
6184
-     * Returns the string used in capabilities relating to this model. If there
6185
-     * are no capabilities that relate to this model returns false
6186
-     *
6187
-     * @return string|false
6188
-     */
6189
-    public function cap_slug()
6190
-    {
6191
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6192
-    }
6193
-
6194
-
6195
-    /**
6196
-     * Returns the capability-restrictions array (@param string $context
6197
-     *
6198
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6199
-     * @throws EE_Error
6200
-     * @see EEM_Base::_cap_restrictions).
6201
-     *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6202
-     *      only returns the cap restrictions array in that context (ie, the array
6203
-     *      at that key)
6204
-     *
6205
-     */
6206
-    public function cap_restrictions($context = EEM_Base::caps_read)
6207
-    {
6208
-        EEM_Base::verify_is_valid_cap_context($context);
6209
-        // check if we ought to run the restriction generator first
6210
-        if (
6211
-            isset($this->_cap_restriction_generators[ $context ])
6212
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6213
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6214
-        ) {
6215
-            $this->_cap_restrictions[ $context ] = array_merge(
6216
-                $this->_cap_restrictions[ $context ],
6217
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6218
-            );
6219
-        }
6220
-        // and make sure we've finalized the construction of each restriction
6221
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6222
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6223
-                $where_conditions_obj->_finalize_construct($this);
6224
-            }
6225
-        }
6226
-        return $this->_cap_restrictions[ $context ];
6227
-    }
6228
-
6229
-
6230
-    /**
6231
-     * Indicating whether or not this model thinks its a wp core model
6232
-     *
6233
-     * @return boolean
6234
-     */
6235
-    public function is_wp_core_model()
6236
-    {
6237
-        return $this->_wp_core_model;
6238
-    }
6239
-
6240
-
6241
-    /**
6242
-     * Gets all the caps that are missing which impose a restriction on
6243
-     * queries made in this context
6244
-     *
6245
-     * @param string $context one of EEM_Base::caps_ constants
6246
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6247
-     * @throws EE_Error
6248
-     */
6249
-    public function caps_missing($context = EEM_Base::caps_read)
6250
-    {
6251
-        $missing_caps     = [];
6252
-        $cap_restrictions = $this->cap_restrictions($context);
6253
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6254
-            if (
6255
-            ! EE_Capabilities::instance()
6256
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6257
-            ) {
6258
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6259
-            }
6260
-        }
6261
-        return $missing_caps;
6262
-    }
6263
-
6264
-
6265
-    /**
6266
-     * Gets the mapping from capability contexts to action strings used in capability names
6267
-     *
6268
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6269
-     * one of 'read', 'edit', or 'delete'
6270
-     */
6271
-    public function cap_contexts_to_cap_action_map()
6272
-    {
6273
-        return apply_filters(
6274
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6275
-            $this->_cap_contexts_to_cap_action_map,
6276
-            $this
6277
-        );
6278
-    }
6279
-
6280
-
6281
-    /**
6282
-     * Gets the action string for the specified capability context
6283
-     *
6284
-     * @param string $context
6285
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6286
-     * @throws EE_Error
6287
-     */
6288
-    public function cap_action_for_context($context)
6289
-    {
6290
-        $mapping = $this->cap_contexts_to_cap_action_map();
6291
-        if (isset($mapping[ $context ])) {
6292
-            return $mapping[ $context ];
6293
-        }
6294
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6295
-            return $action;
6296
-        }
6297
-        throw new EE_Error(
6298
-            sprintf(
6299
-                esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6300
-                $context,
6301
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6302
-            )
6303
-        );
6304
-    }
6305
-
6306
-
6307
-    /**
6308
-     * Returns all the capability contexts which are valid when querying models
6309
-     *
6310
-     * @return array
6311
-     */
6312
-    public static function valid_cap_contexts()
6313
-    {
6314
-        return apply_filters(
6315
-            'FHEE__EEM_Base__valid_cap_contexts',
6316
-            [
6317
-                self::caps_read,
6318
-                self::caps_read_admin,
6319
-                self::caps_edit,
6320
-                self::caps_delete,
6321
-            ]
6322
-        );
6323
-    }
6324
-
6325
-
6326
-    /**
6327
-     * Returns all valid options for 'default_where_conditions'
6328
-     *
6329
-     * @return array
6330
-     */
6331
-    public static function valid_default_where_conditions()
6332
-    {
6333
-        return [
6334
-            EEM_Base::default_where_conditions_all,
6335
-            EEM_Base::default_where_conditions_this_only,
6336
-            EEM_Base::default_where_conditions_others_only,
6337
-            EEM_Base::default_where_conditions_minimum_all,
6338
-            EEM_Base::default_where_conditions_minimum_others,
6339
-            EEM_Base::default_where_conditions_none,
6340
-        ];
6341
-    }
6342
-
6343
-    // public static function default_where_conditions_full
6344
-
6345
-
6346
-    /**
6347
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6348
-     *
6349
-     * @param string $context
6350
-     * @return bool
6351
-     * @throws EE_Error
6352
-     */
6353
-    public static function verify_is_valid_cap_context($context)
6354
-    {
6355
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6356
-        if (in_array($context, $valid_cap_contexts)) {
6357
-            return true;
6358
-        }
6359
-        throw new EE_Error(
6360
-            sprintf(
6361
-                esc_html__(
6362
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6363
-                    'event_espresso'
6364
-                ),
6365
-                $context,
6366
-                'EEM_Base',
6367
-                implode(',', $valid_cap_contexts)
6368
-            )
6369
-        );
6370
-    }
6371
-
6372
-
6373
-    /**
6374
-     * Clears all the models field caches. This is only useful when a sub-class
6375
-     * might have added a field or something and these caches might be invalidated
6376
-     */
6377
-    protected function _invalidate_field_caches()
6378
-    {
6379
-        $this->_cache_foreign_key_to_fields = [];
6380
-        $this->_cached_fields               = null;
6381
-        $this->_cached_fields_non_db_only   = null;
6382
-    }
6383
-
6384
-
6385
-    /**
6386
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6387
-     * (eg "and", "or", "not").
6388
-     *
6389
-     * @return array
6390
-     */
6391
-    public function logic_query_param_keys()
6392
-    {
6393
-        return $this->_logic_query_param_keys;
6394
-    }
6395
-
6396
-
6397
-    /**
6398
-     * Determines whether or not the where query param array key is for a logic query param.
6399
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6400
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6401
-     *
6402
-     * @param $query_param_key
6403
-     * @return bool
6404
-     */
6405
-    public function is_logic_query_param_key($query_param_key)
6406
-    {
6407
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6408
-            if (
6409
-                $query_param_key === $logic_query_param_key
6410
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6411
-            ) {
6412
-                return true;
6413
-            }
6414
-        }
6415
-        return false;
6416
-    }
6417
-
6418
-
6419
-    /**
6420
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6421
-     *
6422
-     * @return boolean
6423
-     * @since 4.9.74.p
6424
-     */
6425
-    public function hasPassword()
6426
-    {
6427
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6428
-        if ($this->has_password_field === null) {
6429
-            $password_field           = $this->getPasswordField();
6430
-            $this->has_password_field = $password_field instanceof EE_Password_Field;
6431
-        }
6432
-        return $this->has_password_field;
6433
-    }
6434
-
6435
-
6436
-    /**
6437
-     * Returns the password field on this model, if there is one
6438
-     *
6439
-     * @return EE_Password_Field|null
6440
-     * @since 4.9.74.p
6441
-     */
6442
-    public function getPasswordField()
6443
-    {
6444
-        // if we definitely already know there is a password field or not (because has_password_field is true or false)
6445
-        // there's no need to search for it. If we don't know yet, then find out
6446
-        if ($this->has_password_field === null && $this->password_field === null) {
6447
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6448
-        }
6449
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6450
-        return $this->password_field;
6451
-    }
6452
-
6453
-
6454
-    /**
6455
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6456
-     *
6457
-     * @return EE_Model_Field_Base[]
6458
-     * @throws EE_Error
6459
-     * @since 4.9.74.p
6460
-     */
6461
-    public function getPasswordProtectedFields()
6462
-    {
6463
-        $password_field = $this->getPasswordField();
6464
-        $fields         = [];
6465
-        if ($password_field instanceof EE_Password_Field) {
6466
-            $field_names = $password_field->protectedFields();
6467
-            foreach ($field_names as $field_name) {
6468
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6469
-            }
6470
-        }
6471
-        return $fields;
6472
-    }
6473
-
6474
-
6475
-    /**
6476
-     * Checks if the current user can perform the requested action on this model
6477
-     *
6478
-     * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6479
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6480
-     * @return bool
6481
-     * @throws EE_Error
6482
-     * @throws InvalidArgumentException
6483
-     * @throws InvalidDataTypeException
6484
-     * @throws InvalidInterfaceException
6485
-     * @throws ReflectionException
6486
-     * @throws UnexpectedEntityException
6487
-     * @since 4.9.74.p
6488
-     */
6489
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6490
-    {
6491
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6492
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6493
-        }
6494
-        if (! is_array($model_obj_or_fields_n_values)) {
6495
-            throw new UnexpectedEntityException(
6496
-                $model_obj_or_fields_n_values,
6497
-                'EE_Base_Class',
6498
-                sprintf(
6499
-                    esc_html__(
6500
-                        '%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6501
-                        'event_espresso'
6502
-                    ),
6503
-                    __FUNCTION__
6504
-                )
6505
-            );
6506
-        }
6507
-        return $this->exists(
6508
-            $this->alter_query_params_to_restrict_by_ID(
6509
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6510
-                [
6511
-                    'default_where_conditions' => 'none',
6512
-                    'caps'                     => $cap_to_check,
6513
-                ]
6514
-            )
6515
-        );
6516
-    }
6517
-
6518
-
6519
-    /**
6520
-     * Returns the query param where conditions key to the password affecting this model.
6521
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6522
-     *
6523
-     * @return null|string
6524
-     * @throws EE_Error
6525
-     * @throws InvalidArgumentException
6526
-     * @throws InvalidDataTypeException
6527
-     * @throws InvalidInterfaceException
6528
-     * @throws ModelConfigurationException
6529
-     * @throws ReflectionException
6530
-     * @since 4.9.74.p
6531
-     */
6532
-    public function modelChainAndPassword()
6533
-    {
6534
-        if ($this->model_chain_to_password === null) {
6535
-            throw new ModelConfigurationException(
6536
-                $this,
6537
-                esc_html_x(
6538
-                // @codingStandardsIgnoreStart
6539
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6540
-                    // @codingStandardsIgnoreEnd
6541
-                    '1: model name',
6542
-                    'event_espresso'
6543
-                )
6544
-            );
6545
-        }
6546
-        if ($this->model_chain_to_password === '') {
6547
-            $model_with_password = $this;
6548
-        } else {
6549
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6550
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6551
-            } else {
6552
-                $last_model_in_chain = $this->model_chain_to_password;
6553
-            }
6554
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6555
-        }
6556
-
6557
-        $password_field = $model_with_password->getPasswordField();
6558
-        if ($password_field instanceof EE_Password_Field) {
6559
-            $password_field_name = $password_field->get_name();
6560
-        } else {
6561
-            throw new ModelConfigurationException(
6562
-                $this,
6563
-                sprintf(
6564
-                    esc_html_x(
6565
-                        '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"',
6566
-                        '1: model name, 2: special string',
6567
-                        'event_espresso'
6568
-                    ),
6569
-                    $model_with_password->get_this_model_name(),
6570
-                    $this->model_chain_to_password
6571
-                )
6572
-            );
6573
-        }
6574
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6575
-    }
6576
-
6577
-
6578
-    /**
6579
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6580
-     * or if this model itself has a password affecting access to some of its other fields.
6581
-     *
6582
-     * @return boolean
6583
-     * @since 4.9.74.p
6584
-     */
6585
-    public function restrictedByRelatedModelPassword()
6586
-    {
6587
-        return $this->model_chain_to_password !== null;
6588
-    }
3867
+		}
3868
+		return $null_friendly_where_conditions;
3869
+	}
3870
+
3871
+
3872
+	/**
3873
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3874
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3875
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3876
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3877
+	 *
3878
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3879
+	 * @return array
3880
+	 * @throws EE_Error
3881
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3882
+	 */
3883
+	private function _get_default_where_conditions($model_relation_path = '')
3884
+	{
3885
+		if ($this->_ignore_where_strategy) {
3886
+			return [];
3887
+		}
3888
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3889
+	}
3890
+
3891
+
3892
+	/**
3893
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3894
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3895
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3896
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3897
+	 * Similar to _get_default_where_conditions
3898
+	 *
3899
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3900
+	 * @return array
3901
+	 * @throws EE_Error
3902
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3903
+	 */
3904
+	protected function _get_minimum_where_conditions($model_relation_path = '')
3905
+	{
3906
+		if ($this->_ignore_where_strategy) {
3907
+			return [];
3908
+		}
3909
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3910
+	}
3911
+
3912
+
3913
+	/**
3914
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3915
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3916
+	 *
3917
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3918
+	 * @return string
3919
+	 * @throws EE_Error
3920
+	 */
3921
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3922
+	{
3923
+		$selects = $this->_get_columns_to_select_for_this_model();
3924
+		foreach (
3925
+			$model_query_info->get_model_names_included() as $model_relation_chain => $name_of_other_model_included
3926
+		) {
3927
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3928
+			$other_model_selects  = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3929
+			foreach ($other_model_selects as $key => $value) {
3930
+				$selects[] = $value;
3931
+			}
3932
+		}
3933
+		return implode(", ", $selects);
3934
+	}
3935
+
3936
+
3937
+	/**
3938
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3939
+	 * So that's going to be the columns for all the fields on the model
3940
+	 *
3941
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3942
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3943
+	 */
3944
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3945
+	{
3946
+		$fields                                       = $this->field_settings();
3947
+		$selects                                      = [];
3948
+		$table_alias_with_model_relation_chain_prefix =
3949
+			EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3950
+				$model_relation_chain,
3951
+				$this->get_this_model_name()
3952
+			);
3953
+		foreach ($fields as $field_obj) {
3954
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3955
+						 . $field_obj->get_table_alias()
3956
+						 . "."
3957
+						 . $field_obj->get_table_column()
3958
+						 . " AS '"
3959
+						 . $table_alias_with_model_relation_chain_prefix
3960
+						 . $field_obj->get_table_alias()
3961
+						 . "."
3962
+						 . $field_obj->get_table_column()
3963
+						 . "'";
3964
+		}
3965
+		// make sure we are also getting the PKs of each table
3966
+		$tables = $this->get_tables();
3967
+		if (count($tables) > 1) {
3968
+			foreach ($tables as $table_obj) {
3969
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970
+									   . $table_obj->get_fully_qualified_pk_column();
3971
+				if (! in_array($qualified_pk_column, $selects)) {
3972
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973
+				}
3974
+			}
3975
+		}
3976
+		return $selects;
3977
+	}
3978
+
3979
+
3980
+	/**
3981
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3982
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3983
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3984
+	 * SQL for joining, and the data types
3985
+	 *
3986
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3987
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3988
+	 * @param string                      $query_param_type     like Registration.Transaction.TXN_ID
3989
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3990
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3991
+	 *                                                          or 'Registration's
3992
+	 * @param string|null                 $original_query_param what it originally was (eg
3993
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3994
+	 *                                                          matches $query_param
3995
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3996
+	 * @throws EE_Error
3997
+	 */
3998
+	private function _extract_related_model_info_from_query_param(
3999
+		$query_param,
4000
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4001
+		$query_param_type,
4002
+		$original_query_param = null
4003
+	) {
4004
+		if ($original_query_param === null) {
4005
+			$original_query_param = $query_param;
4006
+		}
4007
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
4008
+		// whether or not to allow logic_query_params like 'NOT','OR', or 'AND'
4009
+		$allow_logic_query_params = in_array($query_param_type, ['where', 'having', 0, 'custom_selects'], true);
4010
+		$allow_fields             = in_array(
4011
+			$query_param_type,
4012
+			['where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0],
4013
+			true
4014
+		);
4015
+		// check to see if we have a field on this model
4016
+		$this_model_fields = $this->field_settings(true);
4017
+		if (array_key_exists($query_param, $this_model_fields)) {
4018
+			if ($allow_fields) {
4019
+				return;
4020
+			}
4021
+			throw new EE_Error(
4022
+				sprintf(
4023
+					esc_html__(
4024
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
4025
+						"event_espresso"
4026
+					),
4027
+					$query_param,
4028
+					get_class($this),
4029
+					$query_param_type,
4030
+					$original_query_param
4031
+				)
4032
+			);
4033
+		}
4034
+		// check if this is a special logic query param
4035
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
4036
+			if ($allow_logic_query_params) {
4037
+				return;
4038
+			}
4039
+			throw new EE_Error(
4040
+				sprintf(
4041
+					esc_html__(
4042
+						'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',
4043
+						'event_espresso'
4044
+					),
4045
+					implode('", "', $this->_logic_query_param_keys),
4046
+					$query_param,
4047
+					get_class($this),
4048
+					'<br />',
4049
+					"\t"
4050
+					. ' $passed_in_query_info = <pre>'
4051
+					. print_r($passed_in_query_info, true)
4052
+					. '</pre>'
4053
+					. "\n\t"
4054
+					. ' $query_param_type = '
4055
+					. $query_param_type
4056
+					. "\n\t"
4057
+					. ' $original_query_param = '
4058
+					. $original_query_param
4059
+				)
4060
+			);
4061
+		}
4062
+		// check if it's a custom selection
4063
+		if (
4064
+			$this->_custom_selections instanceof CustomSelects
4065
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4066
+		) {
4067
+			return;
4068
+		}
4069
+		// check if has a model name at the beginning
4070
+		// and
4071
+		// check if it's a field on a related model
4072
+		if (
4073
+		$this->extractJoinModelFromQueryParams(
4074
+			$passed_in_query_info,
4075
+			$query_param,
4076
+			$original_query_param,
4077
+			$query_param_type
4078
+		)
4079
+		) {
4080
+			return;
4081
+		}
4082
+
4083
+		// ok so $query_param didn't start with a model name
4084
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4085
+		// it's wack, that's what it is
4086
+		throw new EE_Error(
4087
+			sprintf(
4088
+				esc_html__(
4089
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4090
+					"event_espresso"
4091
+				),
4092
+				$query_param,
4093
+				get_class($this),
4094
+				$query_param_type,
4095
+				$original_query_param
4096
+			)
4097
+		);
4098
+	}
4099
+
4100
+
4101
+	/**
4102
+	 * Extracts any possible join model information from the provided possible_join_string.
4103
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model
4104
+	 * join
4105
+	 * parts that should be added to the query.
4106
+	 *
4107
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4108
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4109
+	 * @param null|string                 $original_query_param
4110
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4111
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects'
4112
+	 *                                                           etc.)
4113
+	 * @return bool  returns true if a join was added and false if not.
4114
+	 * @throws EE_Error
4115
+	 */
4116
+	private function extractJoinModelFromQueryParams(
4117
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4118
+		$possible_join_string,
4119
+		$original_query_param,
4120
+		$query_parameter_type
4121
+	) {
4122
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4124
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4126
+				if ($possible_join_string === '') {
4127
+					// nothing left to $query_param
4128
+					// we should actually end in a field name, not a model like this!
4129
+					throw new EE_Error(
4130
+						sprintf(
4131
+							esc_html__(
4132
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4133
+								"event_espresso"
4134
+							),
4135
+							$possible_join_string,
4136
+							$query_parameter_type,
4137
+							get_class($this),
4138
+							$valid_related_model_name
4139
+						)
4140
+					);
4141
+				}
4142
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4143
+				$related_model_obj->_extract_related_model_info_from_query_param(
4144
+					$possible_join_string,
4145
+					$query_info_carrier,
4146
+					$query_parameter_type,
4147
+					$original_query_param
4148
+				);
4149
+				return true;
4150
+			}
4151
+			if ($possible_join_string === $valid_related_model_name) {
4152
+				$this->_add_join_to_model(
4153
+					$valid_related_model_name,
4154
+					$query_info_carrier,
4155
+					$original_query_param
4156
+				);
4157
+				return true;
4158
+			}
4159
+		}
4160
+		return false;
4161
+	}
4162
+
4163
+
4164
+	/**
4165
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4166
+	 *
4167
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4168
+	 * @throws EE_Error
4169
+	 */
4170
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4171
+	{
4172
+		if (
4173
+			$this->_custom_selections instanceof CustomSelects
4174
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4175
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4176
+			)
4177
+		) {
4178
+			$original_selects = $this->_custom_selections->originalSelects();
4179
+			foreach ($original_selects as $alias => $select_configuration) {
4180
+				$this->extractJoinModelFromQueryParams(
4181
+					$query_info_carrier,
4182
+					$select_configuration[0],
4183
+					$select_configuration[0],
4184
+					'custom_selects'
4185
+				);
4186
+			}
4187
+		}
4188
+	}
4189
+
4190
+
4191
+	/**
4192
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4193
+	 * and store it on $passed_in_query_info
4194
+	 *
4195
+	 * @param string                      $model_name
4196
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4197
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4198
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4199
+	 *                                                          and are adding a join to 'Payment' with the original
4200
+	 *                                                          query param key
4201
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4202
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4203
+	 *                                                          Payment wants to add default query params so that it
4204
+	 *                                                          will know what models to prepend onto its default query
4205
+	 *                                                          params or in case it wants to rename tables (in case
4206
+	 *                                                          there are multiple joins to the same table)
4207
+	 * @return void
4208
+	 * @throws EE_Error
4209
+	 */
4210
+	private function _add_join_to_model(
4211
+		$model_name,
4212
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4213
+		$original_query_param
4214
+	) {
4215
+		$relation_obj         = $this->related_settings_for($model_name);
4216
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4217
+		// check if the relation is HABTM, because then we're essentially doing two joins
4218
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4219
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4220
+			$join_model_obj = $relation_obj->get_join_model();
4221
+			// replace the model specified with the join model for this relation chain, whi
4222
+			$relation_chain_to_join_model =
4223
+				EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4224
+					$model_name,
4225
+					$join_model_obj->get_this_model_name(),
4226
+					$model_relation_chain
4227
+				);
4228
+			$passed_in_query_info->merge(
4229
+				new EE_Model_Query_Info_Carrier(
4230
+					[$relation_chain_to_join_model => $join_model_obj->get_this_model_name()],
4231
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4232
+				)
4233
+			);
4234
+		}
4235
+		// now just join to the other table pointed to by the relation object, and add its data types
4236
+		$passed_in_query_info->merge(
4237
+			new EE_Model_Query_Info_Carrier(
4238
+				[$model_relation_chain => $model_name],
4239
+				$relation_obj->get_join_statement($model_relation_chain)
4240
+			)
4241
+		);
4242
+	}
4243
+
4244
+
4245
+	/**
4246
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4247
+	 *
4248
+	 * @param array $where_params
4249
+	 * @return string of SQL
4250
+	 * @throws EE_Error
4251
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4252
+	 */
4253
+	private function _construct_where_clause($where_params)
4254
+	{
4255
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256
+		if ($SQL) {
4257
+			return " WHERE " . $SQL;
4258
+		}
4259
+		return '';
4260
+	}
4261
+
4262
+
4263
+	/**
4264
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4265
+	 * and should be passed HAVING parameters, not WHERE parameters
4266
+	 *
4267
+	 * @param array $having_params
4268
+	 * @return string
4269
+	 * @throws EE_Error
4270
+	 */
4271
+	private function _construct_having_clause($having_params)
4272
+	{
4273
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274
+		if ($SQL) {
4275
+			return " HAVING " . $SQL;
4276
+		}
4277
+		return '';
4278
+	}
4279
+
4280
+
4281
+	/**
4282
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4283
+	 * Event_Meta.meta_value = 'foo'))"
4284
+	 *
4285
+	 * @param array  $where_params
4286
+	 * @param string $glue joins each sub-clause together. Should really only be " AND " or " OR "...
4287
+	 * @return string of SQL
4288
+	 * @throws EE_Error
4289
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4290
+	 */
4291
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4292
+	{
4293
+		$where_clauses = [];
4294
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4295
+			$query_param =
4296
+				$this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297
+					$query_param
4298
+				);// str_replace("*",'',$query_param);
4299
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4300
+				switch ($query_param) {
4301
+					case 'not':
4302
+					case 'NOT':
4303
+						$where_clauses[] = "! ("
4304
+										   . $this->_construct_condition_clause_recursive(
4305
+								$op_and_value_or_sub_condition,
4306
+								$glue
4307
+							)
4308
+										   . ")";
4309
+						break;
4310
+					case 'and':
4311
+					case 'AND':
4312
+						$where_clauses[] = " ("
4313
+										   . $this->_construct_condition_clause_recursive(
4314
+								$op_and_value_or_sub_condition,
4315
+								' AND '
4316
+							)
4317
+										   . ")";
4318
+						break;
4319
+					case 'or':
4320
+					case 'OR':
4321
+						$where_clauses[] = " ("
4322
+										   . $this->_construct_condition_clause_recursive(
4323
+								$op_and_value_or_sub_condition,
4324
+								' OR '
4325
+							)
4326
+										   . ")";
4327
+						break;
4328
+				}
4329
+			} else {
4330
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4331
+				// if it's not a normal field, maybe it's a custom selection?
4332
+				if (! $field_obj) {
4333
+					if ($this->_custom_selections instanceof CustomSelects) {
4334
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335
+					} else {
4336
+						throw new EE_Error(
4337
+							sprintf(
4338
+								esc_html__(
4339
+									"%s is neither a valid model field name, nor a custom selection",
4340
+									"event_espresso"
4341
+								),
4342
+								$query_param
4343
+							)
4344
+						);
4345
+					}
4346
+				}
4347
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
+				$where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4349
+			}
4350
+		}
4351
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4352
+	}
4353
+
4354
+
4355
+	/**
4356
+	 * Takes the input parameter and extract the table name (alias) and column name
4357
+	 *
4358
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4359
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4360
+	 * @throws EE_Error
4361
+	 */
4362
+	private function _deduce_column_name_from_query_param($query_param)
4363
+	{
4364
+		$field = $this->_deduce_field_from_query_param($query_param);
4365
+		if ($field) {
4366
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4367
+				$field->get_model_name(),
4368
+				$query_param
4369
+			);
4370
+			return $table_alias_prefix . $field->get_qualified_column();
4371
+		}
4372
+		if (
4373
+			$this->_custom_selections instanceof CustomSelects
4374
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4375
+		) {
4376
+			// maybe it's custom selection item?
4377
+			// if so, just use it as the "column name"
4378
+			return $query_param;
4379
+		}
4380
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4381
+			? implode(',', $this->_custom_selections->columnAliases())
4382
+			: '';
4383
+		throw new EE_Error(
4384
+			sprintf(
4385
+				esc_html__(
4386
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4387
+					"event_espresso"
4388
+				),
4389
+				$query_param,
4390
+				$custom_select_aliases
4391
+			)
4392
+		);
4393
+	}
4394
+
4395
+
4396
+	/**
4397
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4398
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4399
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4400
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4401
+	 *
4402
+	 * @param string $condition_query_param_key
4403
+	 * @return string
4404
+	 */
4405
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4406
+	{
4407
+		$pos_of_star = strpos($condition_query_param_key, '*');
4408
+		if ($pos_of_star === false) {
4409
+			return $condition_query_param_key;
4410
+		}
4411
+		return substr($condition_query_param_key, 0, $pos_of_star);
4412
+	}
4413
+
4414
+
4415
+	/**
4416
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4417
+	 *
4418
+	 * @param mixed      array | string    $op_and_value
4419
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4420
+	 * @return string
4421
+	 * @throws EE_Error
4422
+	 */
4423
+	private function _construct_op_and_value($op_and_value, $field_obj)
4424
+	{
4425
+		if (is_array($op_and_value)) {
4426
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
+			if (! $operator) {
4428
+				$php_array_like_string = [];
4429
+				foreach ($op_and_value as $key => $value) {
4430
+					$php_array_like_string[] = "$key=>$value";
4431
+				}
4432
+				throw new EE_Error(
4433
+					sprintf(
4434
+						esc_html__(
4435
+							"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))",
4436
+							"event_espresso"
4437
+						),
4438
+						implode(",", $php_array_like_string)
4439
+					)
4440
+				);
4441
+			}
4442
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4443
+		} else {
4444
+			$operator = '=';
4445
+			$value    = $op_and_value;
4446
+		}
4447
+		// check to see if the value is actually another field
4448
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4450
+		}
4451
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452
+			// in this case, the value should be an array, or at least a comma-separated list
4453
+			// it will need to handle a little differently
4454
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4455
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4456
+			return $operator . SP . $cleaned_value;
4457
+		}
4458
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459
+			// the value should be an array with count of two.
4460
+			if (count($value) !== 2) {
4461
+				throw new EE_Error(
4462
+					sprintf(
4463
+						esc_html__(
4464
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4465
+							'event_espresso'
4466
+						),
4467
+						"BETWEEN"
4468
+					)
4469
+				);
4470
+			}
4471
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
+			return $operator . SP . $cleaned_value;
4473
+		}
4474
+		if (in_array($operator, $this->valid_null_style_operators())) {
4475
+			if ($value !== null) {
4476
+				throw new EE_Error(
4477
+					sprintf(
4478
+						esc_html__(
4479
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4480
+							"event_espresso"
4481
+						),
4482
+						$value,
4483
+						$operator
4484
+					)
4485
+				);
4486
+			}
4487
+			return $operator;
4488
+		}
4489
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4491
+			// remove other junk. So just treat it as a string.
4492
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4493
+		}
4494
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4496
+		}
4497
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498
+			throw new EE_Error(
4499
+				sprintf(
4500
+					esc_html__(
4501
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4502
+						'event_espresso'
4503
+					),
4504
+					$operator,
4505
+					$operator
4506
+				)
4507
+			);
4508
+		}
4509
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510
+			throw new EE_Error(
4511
+				sprintf(
4512
+					esc_html__(
4513
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4514
+						'event_espresso'
4515
+					),
4516
+					$operator,
4517
+					$operator
4518
+				)
4519
+			);
4520
+		}
4521
+		throw new EE_Error(
4522
+			sprintf(
4523
+				esc_html__(
4524
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4525
+					"event_espresso"
4526
+				),
4527
+				http_build_query($op_and_value)
4528
+			)
4529
+		);
4530
+	}
4531
+
4532
+
4533
+	/**
4534
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4535
+	 *
4536
+	 * @param array                      $values
4537
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4538
+	 *                                              '%s'
4539
+	 * @return string
4540
+	 * @throws EE_Error
4541
+	 */
4542
+	public function _construct_between_value($values, $field_obj)
4543
+	{
4544
+		$cleaned_values = [];
4545
+		foreach ($values as $value) {
4546
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547
+		}
4548
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4549
+	}
4550
+
4551
+
4552
+	/**
4553
+	 * Takes an array or a comma-separated list of $values and cleans them
4554
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4555
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4556
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4557
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4558
+	 *
4559
+	 * @param mixed                      $values    array or comma-separated string
4560
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4561
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4562
+	 * @throws EE_Error
4563
+	 */
4564
+	public function _construct_in_value($values, $field_obj)
4565
+	{
4566
+		// check if the value is a CSV list
4567
+		if (is_string($values)) {
4568
+			// in which case, turn it into an array
4569
+			$values = explode(",", $values);
4570
+		}
4571
+		$cleaned_values = [];
4572
+		foreach ($values as $value) {
4573
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4574
+		}
4575
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4576
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4577
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4578
+		if (empty($cleaned_values)) {
4579
+			$all_fields       = $this->field_settings();
4580
+			$a_field          = array_shift($all_fields);
4581
+			$main_table       = $this->_get_main_table();
4582
+			$cleaned_values[] = "SELECT "
4583
+								. $a_field->get_table_column()
4584
+								. " FROM "
4585
+								. $main_table->get_table_name()
4586
+								. " WHERE FALSE";
4587
+		}
4588
+		return "(" . implode(",", $cleaned_values) . ")";
4589
+	}
4590
+
4591
+
4592
+	/**
4593
+	 * @param mixed                      $value
4594
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4595
+	 * @return false|null|string
4596
+	 * @throws EE_Error
4597
+	 */
4598
+	private function _wpdb_prepare_using_field($value, $field_obj)
4599
+	{
4600
+		global $wpdb;
4601
+		if ($field_obj instanceof EE_Model_Field_Base) {
4602
+			return $wpdb->prepare(
4603
+				$field_obj->get_wpdb_data_type(),
4604
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4605
+			);
4606
+		} //$field_obj should really just be a data type
4607
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608
+			throw new EE_Error(
4609
+				sprintf(
4610
+					esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4611
+					$field_obj,
4612
+					implode(",", $this->_valid_wpdb_data_types)
4613
+				)
4614
+			);
4615
+		}
4616
+		return $wpdb->prepare($field_obj, $value);
4617
+	}
4618
+
4619
+
4620
+	/**
4621
+	 * Takes the input parameter and finds the model field that it indicates.
4622
+	 *
4623
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4624
+	 * @return EE_Model_Field_Base
4625
+	 * @throws EE_Error
4626
+	 */
4627
+	protected function _deduce_field_from_query_param($query_param_name)
4628
+	{
4629
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4630
+		// which will help us find the database table and column
4631
+		$query_param_parts = explode(".", $query_param_name);
4632
+		if (empty($query_param_parts)) {
4633
+			throw new EE_Error(
4634
+				sprintf(
4635
+					esc_html__(
4636
+						"_extract_column_name is empty when trying to extract column and table name from %s",
4637
+						'event_espresso'
4638
+					),
4639
+					$query_param_name
4640
+				)
4641
+			);
4642
+		}
4643
+		$number_of_parts       = count($query_param_parts);
4644
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4645
+		if ($number_of_parts === 1) {
4646
+			$field_name = $last_query_param_part;
4647
+			$model_obj  = $this;
4648
+		} else {// $number_of_parts >= 2
4649
+			// the last part is the column name, and there are only 2parts. therefore...
4650
+			$field_name = $last_query_param_part;
4651
+			$model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4652
+		}
4653
+		try {
4654
+			return $model_obj->field_settings_for($field_name);
4655
+		} catch (EE_Error $e) {
4656
+			return null;
4657
+		}
4658
+	}
4659
+
4660
+
4661
+	/**
4662
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4663
+	 * alias and column which corresponds to it
4664
+	 *
4665
+	 * @param string $field_name
4666
+	 * @return string
4667
+	 * @throws EE_Error
4668
+	 */
4669
+	public function _get_qualified_column_for_field($field_name)
4670
+	{
4671
+		$all_fields = $this->field_settings();
4672
+		$field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4673
+		if ($field) {
4674
+			return $field->get_qualified_column();
4675
+		}
4676
+		throw new EE_Error(
4677
+			sprintf(
4678
+				esc_html__(
4679
+					"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.",
4680
+					'event_espresso'
4681
+				),
4682
+				$field_name,
4683
+				get_class($this)
4684
+			)
4685
+		);
4686
+	}
4687
+
4688
+
4689
+	/**
4690
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4691
+	 * Example usage:
4692
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4693
+	 *      array(),
4694
+	 *      ARRAY_A,
4695
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4696
+	 *  );
4697
+	 * is equivalent to
4698
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4699
+	 * and
4700
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4701
+	 *      array(
4702
+	 *          array(
4703
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4704
+	 *          ),
4705
+	 *          ARRAY_A,
4706
+	 *          implode(
4707
+	 *              ', ',
4708
+	 *              array_merge(
4709
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4710
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4711
+	 *              )
4712
+	 *          )
4713
+	 *      )
4714
+	 *  );
4715
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4716
+	 *
4717
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4718
+	 *                                            and the one whose fields you are selecting for example: when querying
4719
+	 *                                            tickets model and selecting fields from the tickets model you would
4720
+	 *                                            leave this parameter empty, because no models are needed to join
4721
+	 *                                            between the queried model and the selected one. Likewise when
4722
+	 *                                            querying the datetime model and selecting fields from the tickets
4723
+	 *                                            model, it would also be left empty, because there is a direct
4724
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4725
+	 *                                            them together. However, when querying from the event model and
4726
+	 *                                            selecting fields from the ticket model, you should provide the string
4727
+	 *                                            'Datetime', indicating that the event model must first join to the
4728
+	 *                                            datetime model in order to find its relation to ticket model.
4729
+	 *                                            Also, when querying from the venue model and selecting fields from
4730
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4731
+	 *                                            indicating you need to join the venue model to the event model,
4732
+	 *                                            to the datetime model, in order to find its relation to the ticket
4733
+	 *                                            model. This string is used to deduce the prefix that gets added onto
4734
+	 *                                            the models' tables qualified columns
4735
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4736
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4737
+	 *                                            qualified column names
4738
+	 * @return array|string
4739
+	 */
4740
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741
+	{
4742
+		$table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4743
+		$qualified_columns = [];
4744
+		foreach ($this->field_settings() as $field_name => $field) {
4745
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4746
+		}
4747
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748
+	}
4749
+
4750
+
4751
+	/**
4752
+	 * constructs the select use on special limit joins
4753
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4754
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4755
+	 * (as that is typically where the limits would be set).
4756
+	 *
4757
+	 * @param string       $table_alias The table the select is being built for
4758
+	 * @param mixed|string $limit       The limit for this select
4759
+	 * @return string                The final select join element for the query.
4760
+	 * @throws EE_Error
4761
+	 */
4762
+	public function _construct_limit_join_select($table_alias, $limit)
4763
+	{
4764
+		$SQL = '';
4765
+		foreach ($this->_tables as $table_obj) {
4766
+			if ($table_obj instanceof EE_Primary_Table) {
4767
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4768
+					? $table_obj->get_select_join_limit($limit)
4769
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4770
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4771
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4772
+					? $table_obj->get_select_join_limit_join($limit)
4773
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4774
+			}
4775
+		}
4776
+		return $SQL;
4777
+	}
4778
+
4779
+
4780
+	/**
4781
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4782
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4783
+	 *
4784
+	 * @return string SQL
4785
+	 * @throws EE_Error
4786
+	 */
4787
+	public function _construct_internal_join()
4788
+	{
4789
+		$SQL = $this->_get_main_table()->get_table_sql();
4790
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4791
+		return $SQL;
4792
+	}
4793
+
4794
+
4795
+	/**
4796
+	 * Constructs the SQL for joining all the tables on this model.
4797
+	 * Normally $alias should be the primary table's alias, but in cases where
4798
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4799
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4800
+	 * alias, this will construct SQL like:
4801
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4802
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4803
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4804
+	 *
4805
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4806
+	 * @return string
4807
+	 * @throws EE_Error
4808
+	 */
4809
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4810
+	{
4811
+		$SQL               = '';
4812
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4813
+		foreach ($this->_tables as $table_obj) {
4814
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4815
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4816
+					// so we're joining to this table, meaning the table is already in
4817
+					// the FROM statement, BUT the primary table isn't. So we want
4818
+					// to add the inverse join sql
4819
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4820
+				} else {
4821
+					// just add a regular JOIN to this table from the primary table
4822
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4823
+				}
4824
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4825
+		}
4826
+		return $SQL;
4827
+	}
4828
+
4829
+
4830
+	/**
4831
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4832
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4833
+	 * their data type (eg, '%s', '%d', etc)
4834
+	 *
4835
+	 * @return array
4836
+	 */
4837
+	public function _get_data_types()
4838
+	{
4839
+		$data_types = [];
4840
+		foreach ($this->field_settings() as $field_obj) {
4841
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842
+			/** @var $field_obj EE_Model_Field_Base */
4843
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4844
+		}
4845
+		return $data_types;
4846
+	}
4847
+
4848
+
4849
+	/**
4850
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4851
+	 *
4852
+	 * @param string $model_name
4853
+	 * @return EEM_Base
4854
+	 * @throws EE_Error
4855
+	 */
4856
+	public function get_related_model_obj($model_name)
4857
+	{
4858
+		$model_classname = "EEM_" . $model_name;
4859
+		if (! class_exists($model_classname)) {
4860
+			throw new EE_Error(
4861
+				sprintf(
4862
+					esc_html__(
4863
+						"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4864
+						'event_espresso'
4865
+					),
4866
+					$model_name,
4867
+					$model_classname
4868
+				)
4869
+			);
4870
+		}
4871
+		return call_user_func($model_classname . "::instance");
4872
+	}
4873
+
4874
+
4875
+	/**
4876
+	 * Returns the array of EE_ModelRelations for this model.
4877
+	 *
4878
+	 * @return EE_Model_Relation_Base[]
4879
+	 */
4880
+	public function relation_settings()
4881
+	{
4882
+		return $this->_model_relations;
4883
+	}
4884
+
4885
+
4886
+	/**
4887
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4888
+	 * because without THOSE models, this model probably doesn't have much purpose.
4889
+	 * (Eg, without an event, datetimes have little purpose.)
4890
+	 *
4891
+	 * @return EE_Belongs_To_Relation[]
4892
+	 */
4893
+	public function belongs_to_relations()
4894
+	{
4895
+		$belongs_to_relations = [];
4896
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4899
+			}
4900
+		}
4901
+		return $belongs_to_relations;
4902
+	}
4903
+
4904
+
4905
+	/**
4906
+	 * Returns the specified EE_Model_Relation, or throws an exception
4907
+	 *
4908
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4909
+	 * @return EE_Model_Relation_Base
4910
+	 * @throws EE_Error
4911
+	 */
4912
+	public function related_settings_for($relation_name)
4913
+	{
4914
+		$relatedModels = $this->relation_settings();
4915
+		if (! array_key_exists($relation_name, $relatedModels)) {
4916
+			throw new EE_Error(
4917
+				sprintf(
4918
+					esc_html__(
4919
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4920
+						'event_espresso'
4921
+					),
4922
+					$relation_name,
4923
+					$this->_get_class_name(),
4924
+					implode(', ', array_keys($relatedModels))
4925
+				)
4926
+			);
4927
+		}
4928
+		return $relatedModels[ $relation_name ];
4929
+	}
4930
+
4931
+
4932
+	/**
4933
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4934
+	 * fields
4935
+	 *
4936
+	 * @param string  $fieldName
4937
+	 * @param boolean $include_db_only_fields
4938
+	 * @return EE_Model_Field_Base
4939
+	 * @throws EE_Error
4940
+	 */
4941
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4942
+	{
4943
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4944
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4945
+			throw new EE_Error(
4946
+				sprintf(
4947
+					esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
4948
+					$fieldName,
4949
+					get_class($this)
4950
+				)
4951
+			);
4952
+		}
4953
+		return $fieldSettings[ $fieldName ];
4954
+	}
4955
+
4956
+
4957
+	/**
4958
+	 * Checks if this field exists on this model
4959
+	 *
4960
+	 * @param string $fieldName a key in the model's _field_settings array
4961
+	 * @return boolean
4962
+	 */
4963
+	public function has_field($fieldName)
4964
+	{
4965
+		$fieldSettings = $this->field_settings(true);
4966
+		if (isset($fieldSettings[ $fieldName ])) {
4967
+			return true;
4968
+		}
4969
+		return false;
4970
+	}
4971
+
4972
+
4973
+	/**
4974
+	 * Returns whether or not this model has a relation to the specified model
4975
+	 *
4976
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4977
+	 * @return boolean
4978
+	 */
4979
+	public function has_relation($relation_name)
4980
+	{
4981
+		$relations = $this->relation_settings();
4982
+		if (isset($relations[ $relation_name ])) {
4983
+			return true;
4984
+		}
4985
+		return false;
4986
+	}
4987
+
4988
+
4989
+	/**
4990
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4991
+	 * Eg, on EE_Answer that would be ANS_ID field object
4992
+	 *
4993
+	 * @param $field_obj
4994
+	 * @return boolean
4995
+	 */
4996
+	public function is_primary_key_field($field_obj)
4997
+	{
4998
+		return $field_obj instanceof EE_Primary_Key_Field_Base;
4999
+	}
5000
+
5001
+
5002
+	/**
5003
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
5004
+	 * Eg, on EE_Answer that would be ANS_ID field object
5005
+	 *
5006
+	 * @return EE_Model_Field_Base
5007
+	 * @throws EE_Error
5008
+	 */
5009
+	public function get_primary_key_field()
5010
+	{
5011
+		if ($this->_primary_key_field === null) {
5012
+			foreach ($this->field_settings(true) as $field_obj) {
5013
+				if ($this->is_primary_key_field($field_obj)) {
5014
+					$this->_primary_key_field = $field_obj;
5015
+					break;
5016
+				}
5017
+			}
5018
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019
+				throw new EE_Error(
5020
+					sprintf(
5021
+						esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
5022
+						get_class($this)
5023
+					)
5024
+				);
5025
+			}
5026
+		}
5027
+		return $this->_primary_key_field;
5028
+	}
5029
+
5030
+
5031
+	/**
5032
+	 * Returns whether or not not there is a primary key on this model.
5033
+	 * Internally does some caching.
5034
+	 *
5035
+	 * @return boolean
5036
+	 */
5037
+	public function has_primary_key_field()
5038
+	{
5039
+		if ($this->_has_primary_key_field === null) {
5040
+			try {
5041
+				$this->get_primary_key_field();
5042
+				$this->_has_primary_key_field = true;
5043
+			} catch (EE_Error $e) {
5044
+				$this->_has_primary_key_field = false;
5045
+			}
5046
+		}
5047
+		return $this->_has_primary_key_field;
5048
+	}
5049
+
5050
+
5051
+	/**
5052
+	 * Finds the first field of type $field_class_name.
5053
+	 *
5054
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
5055
+	 *                                 EE_Foreign_Key_Field, etc
5056
+	 * @return EE_Model_Field_Base or null if none is found
5057
+	 */
5058
+	public function get_a_field_of_type($field_class_name)
5059
+	{
5060
+		foreach ($this->field_settings() as $field) {
5061
+			if ($field instanceof $field_class_name) {
5062
+				return $field;
5063
+			}
5064
+		}
5065
+		return null;
5066
+	}
5067
+
5068
+
5069
+	/**
5070
+	 * Gets a foreign key field pointing to model.
5071
+	 *
5072
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5073
+	 * @return EE_Foreign_Key_Field_Base
5074
+	 * @throws EE_Error
5075
+	 */
5076
+	public function get_foreign_key_to($model_name)
5077
+	{
5078
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5079
+			foreach ($this->field_settings() as $field) {
5080
+				if (
5081
+					$field instanceof EE_Foreign_Key_Field_Base
5082
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5083
+				) {
5084
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5085
+					break;
5086
+				}
5087
+			}
5088
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5089
+				throw new EE_Error(
5090
+					sprintf(
5091
+						esc_html__(
5092
+							"There is no foreign key field pointing to model %s on model %s",
5093
+							'event_espresso'
5094
+						),
5095
+						$model_name,
5096
+						get_class($this)
5097
+					)
5098
+				);
5099
+			}
5100
+		}
5101
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5102
+	}
5103
+
5104
+
5105
+	/**
5106
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5107
+	 *
5108
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5109
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5110
+	 *                            Either one works
5111
+	 * @return string
5112
+	 */
5113
+	public function get_table_for_alias($table_alias)
5114
+	{
5115
+		$table_alias_sans_model_relation_chain_prefix =
5116
+			EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5118
+	}
5119
+
5120
+
5121
+	/**
5122
+	 * Returns a flat array of all field son this model, instead of organizing them
5123
+	 * by table_alias as they are in the constructor.
5124
+	 *
5125
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5126
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5127
+	 */
5128
+	public function field_settings($include_db_only_fields = false)
5129
+	{
5130
+		if ($include_db_only_fields) {
5131
+			if ($this->_cached_fields === null) {
5132
+				$this->_cached_fields = [];
5133
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5134
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
+						$this->_cached_fields[ $field_name ] = $field_obj;
5136
+					}
5137
+				}
5138
+			}
5139
+			return $this->_cached_fields;
5140
+		}
5141
+		if ($this->_cached_fields_non_db_only === null) {
5142
+			$this->_cached_fields_non_db_only = [];
5143
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5144
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145
+					/** @var $field_obj EE_Model_Field_Base */
5146
+					if (! $field_obj->is_db_only_field()) {
5147
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5148
+					}
5149
+				}
5150
+			}
5151
+		}
5152
+		return $this->_cached_fields_non_db_only;
5153
+	}
5154
+
5155
+
5156
+	/**
5157
+	 *        cycle though array of attendees and create objects out of each item
5158
+	 *
5159
+	 * @access        private
5160
+	 * @param array $rows        of results of $wpdb->get_results($query,ARRAY_A)
5161
+	 * @return EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5162
+	 *                           numerically indexed)
5163
+	 * @throws EE_Error
5164
+	 * @throws ReflectionException
5165
+	 */
5166
+	protected function _create_objects($rows = [])
5167
+	{
5168
+		$array_of_objects = [];
5169
+		if (empty($rows)) {
5170
+			return [];
5171
+		}
5172
+		$count_if_model_has_no_primary_key = 0;
5173
+		$has_primary_key                   = $this->has_primary_key_field();
5174
+		$primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
+		foreach ((array)$rows as $row) {
5176
+			if (empty($row)) {
5177
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178
+				return [];
5179
+			}
5180
+			// check if we've already set this object in the results array,
5181
+			// in which case there's no need to process it further (again)
5182
+			if ($has_primary_key) {
5183
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5184
+					$row,
5185
+					$primary_key_field->get_qualified_column(),
5186
+					$primary_key_field->get_table_column()
5187
+				);
5188
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5189
+					continue;
5190
+				}
5191
+			}
5192
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5193
+			if (! $classInstance) {
5194
+				throw new EE_Error(
5195
+					sprintf(
5196
+						esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
5197
+						$this->get_this_model_name(),
5198
+						http_build_query($row)
5199
+					)
5200
+				);
5201
+			}
5202
+			// set the timezone on the instantiated objects
5203
+			$classInstance->set_timezone($this->_timezone);
5204
+			// make sure if there is any timezone setting present that we set the timezone for the object
5205
+			$key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
+			$array_of_objects[ $key ] = $classInstance;
5207
+			// also, for all the relations of type BelongsTo, see if we can cache
5208
+			// those related models
5209
+			// (we could do this for other relations too, but if there are conditions
5210
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5211
+			// so it requires a little more thought than just caching them immediately...)
5212
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5213
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5214
+					// check if this model's INFO is present. If so, cache it on the model
5215
+					$other_model           = $relation_obj->get_other_model();
5216
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5217
+					// if we managed to make a model object from the results, cache it on the main model object
5218
+					if ($other_model_obj_maybe) {
5219
+						// set timezone on these other model objects if they are present
5220
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5221
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5222
+					}
5223
+				}
5224
+			}
5225
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5226
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5227
+			// the field in the CustomSelects object
5228
+			if ($this->_custom_selections instanceof CustomSelects) {
5229
+				$classInstance->setCustomSelectsValues(
5230
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5231
+				);
5232
+			}
5233
+		}
5234
+		return $array_of_objects;
5235
+	}
5236
+
5237
+
5238
+	/**
5239
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5240
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5241
+	 *
5242
+	 * @param array $db_results_row
5243
+	 * @return array
5244
+	 */
5245
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5246
+	{
5247
+		$results = [];
5248
+		if ($this->_custom_selections instanceof CustomSelects) {
5249
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
+				if (isset($db_results_row[ $alias ])) {
5251
+					$results[ $alias ] = $this->convertValueToDataType(
5252
+						$db_results_row[ $alias ],
5253
+						$this->_custom_selections->getDataTypeForAlias($alias)
5254
+					);
5255
+				}
5256
+			}
5257
+		}
5258
+		return $results;
5259
+	}
5260
+
5261
+
5262
+	/**
5263
+	 * This will set the value for the given alias
5264
+	 *
5265
+	 * @param string $value
5266
+	 * @param string $datatype (one of %d, %s, %f)
5267
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5268
+	 */
5269
+	protected function convertValueToDataType($value, $datatype)
5270
+	{
5271
+		switch ($datatype) {
5272
+			case '%f':
5273
+				return (float)$value;
5274
+			case '%d':
5275
+				return (int)$value;
5276
+			default:
5277
+				return (string)$value;
5278
+		}
5279
+	}
5280
+
5281
+
5282
+	/**
5283
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5284
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5285
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5286
+	 * object (as set in the model_field!).
5287
+	 *
5288
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5289
+	 * @throws EE_Error
5290
+	 * @throws ReflectionException
5291
+	 */
5292
+	public function create_default_object()
5293
+	{
5294
+		$this_model_fields_and_values = [];
5295
+		// setup the row using default values;
5296
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5297
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5298
+		}
5299
+		$className = $this->_get_class_name();
5300
+		return EE_Registry::instance()->load_class(
5301
+			$className,
5302
+			[$this_model_fields_and_values],
5303
+			false,
5304
+			false
5305
+		);
5306
+	}
5307
+
5308
+
5309
+	/**
5310
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5311
+	 *                             or an stdClass where each property is the name of a column,
5312
+	 * @return EE_Base_Class
5313
+	 * @throws EE_Error
5314
+	 * @throws ReflectionException
5315
+	 */
5316
+	public function instantiate_class_from_array_or_object($cols_n_values)
5317
+	{
5318
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5319
+			$cols_n_values = get_object_vars($cols_n_values);
5320
+		}
5321
+		$primary_key = null;
5322
+		// make sure the array only has keys that are fields/columns on this model
5323
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5326
+		}
5327
+		$className = $this->_get_class_name();
5328
+		// check we actually found results that we can use to build our model object
5329
+		// if not, return null
5330
+		if ($this->has_primary_key_field()) {
5331
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5332
+				return null;
5333
+			}
5334
+		} elseif ($this->unique_indexes()) {
5335
+			$first_column = reset($this_model_fields_n_values);
5336
+			if (empty($first_column)) {
5337
+				return null;
5338
+			}
5339
+		}
5340
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341
+		if ($primary_key) {
5342
+			$classInstance = $this->get_from_entity_map($primary_key);
5343
+			if (! $classInstance) {
5344
+				$classInstance = EE_Registry::instance()->load_class(
5345
+					$className,
5346
+					[$this_model_fields_n_values, $this->_timezone],
5347
+					true,
5348
+					false
5349
+				);
5350
+				// add this new object to the entity map
5351
+				$classInstance = $this->add_to_entity_map($classInstance);
5352
+			}
5353
+		} else {
5354
+			$classInstance = EE_Registry::instance()->load_class(
5355
+				$className,
5356
+				[$this_model_fields_n_values, $this->_timezone],
5357
+				true,
5358
+				false
5359
+			);
5360
+		}
5361
+		return $classInstance;
5362
+	}
5363
+
5364
+
5365
+	/**
5366
+	 * Gets the model object from the  entity map if it exists
5367
+	 *
5368
+	 * @param int|string $id the ID of the model object
5369
+	 * @return EE_Base_Class
5370
+	 */
5371
+	public function get_from_entity_map($id)
5372
+	{
5373
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5375
+	}
5376
+
5377
+
5378
+	/**
5379
+	 * add_to_entity_map
5380
+	 * Adds the object to the model's entity mappings
5381
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5382
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5383
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5384
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5385
+	 *        then this method should be called immediately after the update query
5386
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5387
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5388
+	 *
5389
+	 * @param EE_Base_Class $object
5390
+	 * @return EE_Base_Class
5391
+	 * @throws EE_Error
5392
+	 * @throws ReflectionException
5393
+	 */
5394
+	public function add_to_entity_map(EE_Base_Class $object)
5395
+	{
5396
+		$className = $this->_get_class_name();
5397
+		if (! $object instanceof $className) {
5398
+			throw new EE_Error(
5399
+				sprintf(
5400
+					esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5401
+					is_object($object) ? get_class($object) : $object,
5402
+					$className
5403
+				)
5404
+			);
5405
+		}
5406
+		if (! $object->ID()) {
5407
+			throw new EE_Error(
5408
+				sprintf(
5409
+					esc_html__(
5410
+						"You tried storing a model object with NO ID in the %s entity mapper.",
5411
+						"event_espresso"
5412
+					),
5413
+					get_class($this)
5414
+				)
5415
+			);
5416
+		}
5417
+		// double check it's not already there
5418
+		$classInstance = $this->get_from_entity_map($object->ID());
5419
+		if ($classInstance) {
5420
+			return $classInstance;
5421
+		}
5422
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5423
+		return $object;
5424
+	}
5425
+
5426
+
5427
+	/**
5428
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5429
+	 * if no identifier is provided, then the entire entity map is emptied
5430
+	 *
5431
+	 * @param int|string $id the ID of the model object
5432
+	 * @return boolean
5433
+	 */
5434
+	public function clear_entity_map($id = null)
5435
+	{
5436
+		if (empty($id)) {
5437
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5438
+			return true;
5439
+		}
5440
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5442
+			return true;
5443
+		}
5444
+		return false;
5445
+	}
5446
+
5447
+
5448
+	/**
5449
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5450
+	 * Given an array where keys are column (or column alias) names and values,
5451
+	 * returns an array of their corresponding field names and database values
5452
+	 *
5453
+	 * @param array $cols_n_values
5454
+	 * @return array
5455
+	 */
5456
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5457
+	{
5458
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5459
+	}
5460
+
5461
+
5462
+	/**
5463
+	 * _deduce_fields_n_values_from_cols_n_values
5464
+	 * Given an array where keys are column (or column alias) names and values,
5465
+	 * returns an array of their corresponding field names and database values
5466
+	 *
5467
+	 * @param array $cols_n_values
5468
+	 * @return array
5469
+	 */
5470
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5471
+	{
5472
+		$this_model_fields_n_values = [];
5473
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5474
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5475
+				$cols_n_values,
5476
+				$table_obj->get_fully_qualified_pk_column(),
5477
+				$table_obj->get_pk_column()
5478
+			);
5479
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5480
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
+					if (! $field_obj->is_db_only_field()) {
5483
+						// prepare field as if its coming from db
5484
+						$prepared_value                            =
5485
+							$field_obj->prepare_for_set($field_obj->get_default_value());
5486
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5487
+					}
5488
+				}
5489
+			} else {
5490
+				// the table's rows existed. Use their values
5491
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
+					if (! $field_obj->is_db_only_field()) {
5493
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5494
+							$cols_n_values,
5495
+							$field_obj->get_qualified_column(),
5496
+							$field_obj->get_table_column()
5497
+						);
5498
+					}
5499
+				}
5500
+			}
5501
+		}
5502
+		return $this_model_fields_n_values;
5503
+	}
5504
+
5505
+
5506
+	/**
5507
+	 * @param array  $cols_n_values
5508
+	 * @param string $qualified_column
5509
+	 * @param string $regular_column
5510
+	 * @return null
5511
+	 */
5512
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5513
+	{
5514
+		$value = null;
5515
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516
+		// does the field on the model relate to this column retrieved from the db?
5517
+		// or is it a db-only field? (not relating to the model)
5518
+		if (isset($cols_n_values[ $qualified_column ])) {
5519
+			$value = $cols_n_values[ $qualified_column ];
5520
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5521
+			$value = $cols_n_values[ $regular_column ];
5522
+		} elseif (! empty($this->foreign_key_aliases)) {
5523
+			// no PK?  ok check if there is a foreign key alias set for this table
5524
+			// then check if that alias exists in the incoming data
5525
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
+					$value = $cols_n_values[ $FK_alias ];
5529
+					break;
5530
+				}
5531
+			}
5532
+		}
5533
+		return $value;
5534
+	}
5535
+
5536
+
5537
+	/**
5538
+	 * refresh_entity_map_from_db
5539
+	 * Makes sure the model object in the entity map at $id assumes the values
5540
+	 * of the database (opposite of EE_base_Class::save())
5541
+	 *
5542
+	 * @param int|string $id
5543
+	 * @return EE_Base_Class
5544
+	 * @throws EE_Error
5545
+	 * @throws ReflectionException
5546
+	 */
5547
+	public function refresh_entity_map_from_db($id)
5548
+	{
5549
+		$obj_in_map = $this->get_from_entity_map($id);
5550
+		if ($obj_in_map) {
5551
+			$wpdb_results = $this->_get_all_wpdb_results(
5552
+				[[$this->get_primary_key_field()->get_name() => $id], 'limit' => 1]
5553
+			);
5554
+			if ($wpdb_results && is_array($wpdb_results)) {
5555
+				$one_row = reset($wpdb_results);
5556
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5557
+					$obj_in_map->set_from_db($field_name, $db_value);
5558
+				}
5559
+				// clear the cache of related model objects
5560
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5561
+					$obj_in_map->clear_cache($relation_name, null, true);
5562
+				}
5563
+			}
5564
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5565
+			return $obj_in_map;
5566
+		}
5567
+		return $this->get_one_by_ID($id);
5568
+	}
5569
+
5570
+
5571
+	/**
5572
+	 * refresh_entity_map_with
5573
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5574
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5575
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5576
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5577
+	 *
5578
+	 * @param int|string    $id
5579
+	 * @param EE_Base_Class $replacing_model_obj
5580
+	 * @return EE_Base_Class
5581
+	 * @throws EE_Error
5582
+	 * @throws ReflectionException
5583
+	 */
5584
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5585
+	{
5586
+		$obj_in_map = $this->get_from_entity_map($id);
5587
+		if ($obj_in_map) {
5588
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5589
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5590
+					$obj_in_map->set($field_name, $value);
5591
+				}
5592
+				// make the model object in the entity map's cache match the $replacing_model_obj
5593
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5594
+					$obj_in_map->clear_cache($relation_name, null, true);
5595
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5596
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5597
+					}
5598
+				}
5599
+			}
5600
+			return $obj_in_map;
5601
+		}
5602
+		$this->add_to_entity_map($replacing_model_obj);
5603
+		return $replacing_model_obj;
5604
+	}
5605
+
5606
+
5607
+	/**
5608
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5609
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5610
+	 * require_once($this->_getClassName().".class.php");
5611
+	 *
5612
+	 * @return string
5613
+	 */
5614
+	private function _get_class_name()
5615
+	{
5616
+		return "EE_" . $this->get_this_model_name();
5617
+	}
5618
+
5619
+
5620
+	/**
5621
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5622
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5623
+	 * it would be 'Events'.
5624
+	 *
5625
+	 * @param int $quantity
5626
+	 * @return string
5627
+	 */
5628
+	public function item_name($quantity = 1)
5629
+	{
5630
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5631
+	}
5632
+
5633
+
5634
+	/**
5635
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5636
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5637
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5638
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5639
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5640
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5641
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5642
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5643
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5644
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5645
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5646
+	 *        return $previousReturnValue.$returnString;
5647
+	 * }
5648
+	 * require('EEM_Answer.model.php');
5649
+	 * $answer=EEM_Answer::instance();
5650
+	 * echo $answer->my_callback('monkeys',100);
5651
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5652
+	 *
5653
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5654
+	 * @param array  $args       array of original arguments passed to the function
5655
+	 * @return mixed whatever the plugin which calls add_filter decides
5656
+	 * @throws EE_Error
5657
+	 */
5658
+	public function __call($methodName, $args)
5659
+	{
5660
+		$className = get_class($this);
5661
+		$tagName   = "FHEE__{$className}__{$methodName}";
5662
+		if (! has_filter($tagName)) {
5663
+			throw new EE_Error(
5664
+				sprintf(
5665
+					esc_html__(
5666
+						'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 );',
5667
+						'event_espresso'
5668
+					),
5669
+					$methodName,
5670
+					$className,
5671
+					$tagName,
5672
+					'<br />'
5673
+				)
5674
+			);
5675
+		}
5676
+		return apply_filters($tagName, null, $this, $args);
5677
+	}
5678
+
5679
+
5680
+	/**
5681
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5682
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5683
+	 *
5684
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5685
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5686
+	 *                                                       the object's class name
5687
+	 *                                                       or object's ID
5688
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5689
+	 *                                                       exists in the database. If it does not, we add it
5690
+	 * @return EE_Base_Class
5691
+	 * @throws EE_Error
5692
+	 * @throws ReflectionException
5693
+	 */
5694
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5695
+	{
5696
+		$className = $this->_get_class_name();
5697
+		if ($base_class_obj_or_id instanceof $className) {
5698
+			$model_object = $base_class_obj_or_id;
5699
+		} else {
5700
+			$primary_key_field = $this->get_primary_key_field();
5701
+			if (
5702
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5703
+				&& (
5704
+					is_int($base_class_obj_or_id)
5705
+					|| is_string($base_class_obj_or_id)
5706
+				)
5707
+			) {
5708
+				// assume it's an ID.
5709
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5710
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5711
+			} elseif (
5712
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5713
+				&& is_string($base_class_obj_or_id)
5714
+			) {
5715
+				// assume its a string representation of the object
5716
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5717
+			} else {
5718
+				throw new EE_Error(
5719
+					sprintf(
5720
+						esc_html__(
5721
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5722
+							'event_espresso'
5723
+						),
5724
+						$base_class_obj_or_id,
5725
+						$this->_get_class_name(),
5726
+						print_r($base_class_obj_or_id, true)
5727
+					)
5728
+				);
5729
+			}
5730
+		}
5731
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5732
+			$model_object->save();
5733
+		}
5734
+		return $model_object;
5735
+	}
5736
+
5737
+
5738
+	/**
5739
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5740
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5741
+	 * returns it ID.
5742
+	 *
5743
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5744
+	 * @return int|string depending on the type of this model object's ID
5745
+	 * @throws EE_Error
5746
+	 * @throws ReflectionException
5747
+	 */
5748
+	public function ensure_is_ID($base_class_obj_or_id)
5749
+	{
5750
+		$className = $this->_get_class_name();
5751
+		if ($base_class_obj_or_id instanceof $className) {
5752
+			$id = $base_class_obj_or_id->ID();
5753
+		} elseif (is_int($base_class_obj_or_id)) {
5754
+			// assume it's an ID
5755
+			$id = $base_class_obj_or_id;
5756
+		} elseif (is_string($base_class_obj_or_id)) {
5757
+			// assume its a string representation of the object
5758
+			$id = $base_class_obj_or_id;
5759
+		} else {
5760
+			throw new EE_Error(
5761
+				sprintf(
5762
+					esc_html__(
5763
+						"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5764
+						'event_espresso'
5765
+					),
5766
+					$base_class_obj_or_id,
5767
+					$this->_get_class_name(),
5768
+					print_r($base_class_obj_or_id, true)
5769
+				)
5770
+			);
5771
+		}
5772
+		return $id;
5773
+	}
5774
+
5775
+
5776
+	/**
5777
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5778
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5779
+	 * been sanitized and converted into the appropriate domain.
5780
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5781
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5782
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5783
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5784
+	 * $EVT = EEM_Event::instance(); $old_setting =
5785
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5786
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5787
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5788
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5789
+	 *
5790
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5791
+	 * @return void
5792
+	 */
5793
+	public function assume_values_already_prepared_by_model_object(
5794
+		$values_already_prepared = self::not_prepared_by_model_object
5795
+	) {
5796
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5797
+	}
5798
+
5799
+
5800
+	/**
5801
+	 * Read comments for assume_values_already_prepared_by_model_object()
5802
+	 *
5803
+	 * @return int
5804
+	 */
5805
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5806
+	{
5807
+		return $this->_values_already_prepared_by_model_object;
5808
+	}
5809
+
5810
+
5811
+	/**
5812
+	 * Gets all the indexes on this model
5813
+	 *
5814
+	 * @return EE_Index[]
5815
+	 */
5816
+	public function indexes()
5817
+	{
5818
+		return $this->_indexes;
5819
+	}
5820
+
5821
+
5822
+	/**
5823
+	 * Gets all the Unique Indexes on this model
5824
+	 *
5825
+	 * @return EE_Unique_Index[]
5826
+	 */
5827
+	public function unique_indexes()
5828
+	{
5829
+		$unique_indexes = [];
5830
+		foreach ($this->_indexes as $name => $index) {
5831
+			if ($index instanceof EE_Unique_Index) {
5832
+				$unique_indexes [ $name ] = $index;
5833
+			}
5834
+		}
5835
+		return $unique_indexes;
5836
+	}
5837
+
5838
+
5839
+	/**
5840
+	 * Gets all the fields which, when combined, make the primary key.
5841
+	 * This is usually just an array with 1 element (the primary key), but in cases
5842
+	 * where there is no primary key, it's a combination of fields as defined
5843
+	 * on a primary index
5844
+	 *
5845
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5846
+	 * @throws EE_Error
5847
+	 */
5848
+	public function get_combined_primary_key_fields()
5849
+	{
5850
+		foreach ($this->indexes() as $index) {
5851
+			if ($index instanceof EE_Primary_Key_Index) {
5852
+				return $index->fields();
5853
+			}
5854
+		}
5855
+		return [$this->primary_key_name() => $this->get_primary_key_field()];
5856
+	}
5857
+
5858
+
5859
+	/**
5860
+	 * Used to build a primary key string (when the model has no primary key),
5861
+	 * which can be used a unique string to identify this model object.
5862
+	 *
5863
+	 * @param array $fields_n_values keys are field names, values are their values.
5864
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5865
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5866
+	 *                               before passing it to this function (that will convert it from columns-n-values
5867
+	 *                               to field-names-n-values).
5868
+	 * @return string
5869
+	 * @throws EE_Error
5870
+	 */
5871
+	public function get_index_primary_key_string($fields_n_values)
5872
+	{
5873
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5874
+			$fields_n_values,
5875
+			$this->get_combined_primary_key_fields()
5876
+		);
5877
+		return http_build_query($cols_n_values_for_primary_key_index);
5878
+	}
5879
+
5880
+
5881
+	/**
5882
+	 * Gets the field values from the primary key string
5883
+	 *
5884
+	 * @param string $index_primary_key_string
5885
+	 * @return null|array
5886
+	 * @throws EE_Error
5887
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5888
+	 */
5889
+	public function parse_index_primary_key_string($index_primary_key_string)
5890
+	{
5891
+		$key_fields = $this->get_combined_primary_key_fields();
5892
+		// check all of them are in the $id
5893
+		$key_values_in_combined_pk = [];
5894
+		parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895
+		foreach ($key_fields as $key_field_name => $field_obj) {
5896
+			if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5897
+				return null;
5898
+			}
5899
+		}
5900
+		return $key_values_in_combined_pk;
5901
+	}
5902
+
5903
+
5904
+	/**
5905
+	 * verifies that an array of key-value pairs for model fields has a key
5906
+	 * for each field comprising the primary key index
5907
+	 *
5908
+	 * @param array $key_values
5909
+	 * @return boolean
5910
+	 * @throws EE_Error
5911
+	 */
5912
+	public function has_all_combined_primary_key_fields($key_values)
5913
+	{
5914
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915
+		foreach ($keys_it_should_have as $key) {
5916
+			if (! isset($key_values[ $key ])) {
5917
+				return false;
5918
+			}
5919
+		}
5920
+		return true;
5921
+	}
5922
+
5923
+
5924
+	/**
5925
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5926
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5927
+	 *
5928
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5929
+	 * @param array               $query_params                     see github link below for more info
5930
+	 * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5931
+	 * @throws EE_Error
5932
+	 * @throws ReflectionException
5933
+	 * @return EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5934
+	 *                                                              indexed)
5935
+	 */
5936
+	public function get_all_copies($model_object_or_attributes_array, $query_params = [])
5937
+	{
5938
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5939
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5940
+		} elseif (is_array($model_object_or_attributes_array)) {
5941
+			$attributes_array = $model_object_or_attributes_array;
5942
+		} else {
5943
+			throw new EE_Error(
5944
+				sprintf(
5945
+					esc_html__(
5946
+						"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5947
+						"event_espresso"
5948
+					),
5949
+					$model_object_or_attributes_array
5950
+				)
5951
+			);
5952
+		}
5953
+		// even copies obviously won't have the same ID, so remove the primary key
5954
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
+			unset($attributes_array[ $this->primary_key_name() ]);
5957
+		}
5958
+		if (isset($query_params[0])) {
5959
+			$query_params[0] = array_merge($attributes_array, $query_params);
5960
+		} else {
5961
+			$query_params[0] = $attributes_array;
5962
+		}
5963
+		return $this->get_all($query_params);
5964
+	}
5965
+
5966
+
5967
+	/**
5968
+	 * Gets the first copy we find. See get_all_copies for more details
5969
+	 *
5970
+	 * @param mixed EE_Base_Class | array        $model_object_or_attributes_array
5971
+	 * @param array $query_params
5972
+	 * @return EE_Base_Class
5973
+	 * @throws EE_Error
5974
+	 * @throws ReflectionException
5975
+	 */
5976
+	public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977
+	{
5978
+		if (! is_array($query_params)) {
5979
+			EE_Error::doing_it_wrong(
5980
+				'EEM_Base::get_one_copy',
5981
+				sprintf(
5982
+					esc_html__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5983
+					gettype($query_params)
5984
+				),
5985
+				'4.6.0'
5986
+			);
5987
+			$query_params = [];
5988
+		}
5989
+		$query_params['limit'] = 1;
5990
+		$copies                = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5991
+		if (is_array($copies)) {
5992
+			return array_shift($copies);
5993
+		}
5994
+		return null;
5995
+	}
5996
+
5997
+
5998
+	/**
5999
+	 * Updates the item with the specified id. Ignores default query parameters because
6000
+	 * we have specified the ID, and its assumed we KNOW what we're doing
6001
+	 *
6002
+	 * @param array      $fields_n_values keys are field names, values are their new values
6003
+	 * @param int|string $id              the value of the primary key to update
6004
+	 * @return int number of rows updated
6005
+	 * @throws EE_Error
6006
+	 * @throws ReflectionException
6007
+	 */
6008
+	public function update_by_ID($fields_n_values, $id)
6009
+	{
6010
+		$query_params = [
6011
+			0                          => [$this->get_primary_key_field()->get_name() => $id],
6012
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
6013
+		];
6014
+		return $this->update($fields_n_values, $query_params);
6015
+	}
6016
+
6017
+
6018
+	/**
6019
+	 * Changes an operator which was supplied to the models into one usable in SQL
6020
+	 *
6021
+	 * @param string $operator_supplied
6022
+	 * @return string an operator which can be used in SQL
6023
+	 * @throws EE_Error
6024
+	 */
6025
+	private function _prepare_operator_for_sql($operator_supplied)
6026
+	{
6027
+		$sql_operator =
6028
+			isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6029
+				: null;
6030
+		if ($sql_operator) {
6031
+			return $sql_operator;
6032
+		}
6033
+		throw new EE_Error(
6034
+			sprintf(
6035
+				esc_html__(
6036
+					"The operator '%s' is not in the list of valid operators: %s",
6037
+					"event_espresso"
6038
+				),
6039
+				$operator_supplied,
6040
+				implode(",", array_keys($this->_valid_operators))
6041
+			)
6042
+		);
6043
+	}
6044
+
6045
+
6046
+	/**
6047
+	 * Gets the valid operators
6048
+	 *
6049
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6050
+	 */
6051
+	public function valid_operators()
6052
+	{
6053
+		return $this->_valid_operators;
6054
+	}
6055
+
6056
+
6057
+	/**
6058
+	 * Gets the between-style operators (take 2 arguments).
6059
+	 *
6060
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6061
+	 */
6062
+	public function valid_between_style_operators()
6063
+	{
6064
+		return array_intersect(
6065
+			$this->valid_operators(),
6066
+			$this->_between_style_operators
6067
+		);
6068
+	}
6069
+
6070
+
6071
+	/**
6072
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6073
+	 *
6074
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6075
+	 */
6076
+	public function valid_like_style_operators()
6077
+	{
6078
+		return array_intersect(
6079
+			$this->valid_operators(),
6080
+			$this->_like_style_operators
6081
+		);
6082
+	}
6083
+
6084
+
6085
+	/**
6086
+	 * Gets the "in"-style operators
6087
+	 *
6088
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6089
+	 */
6090
+	public function valid_in_style_operators()
6091
+	{
6092
+		return array_intersect(
6093
+			$this->valid_operators(),
6094
+			$this->_in_style_operators
6095
+		);
6096
+	}
6097
+
6098
+
6099
+	/**
6100
+	 * Gets the "null"-style operators (accept no arguments)
6101
+	 *
6102
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6103
+	 */
6104
+	public function valid_null_style_operators()
6105
+	{
6106
+		return array_intersect(
6107
+			$this->valid_operators(),
6108
+			$this->_null_style_operators
6109
+		);
6110
+	}
6111
+
6112
+
6113
+	/**
6114
+	 * Gets an array where keys are the primary keys and values are their 'names'
6115
+	 * (as determined by the model object's name() function, which is often overridden)
6116
+	 *
6117
+	 * @param array $query_params like get_all's
6118
+	 * @return string[]
6119
+	 * @throws EE_Error
6120
+	 * @throws ReflectionException
6121
+	 */
6122
+	public function get_all_names($query_params = [])
6123
+	{
6124
+		$objs  = $this->get_all($query_params);
6125
+		$names = [];
6126
+		foreach ($objs as $obj) {
6127
+			$names[ $obj->ID() ] = $obj->name();
6128
+		}
6129
+		return $names;
6130
+	}
6131
+
6132
+
6133
+	/**
6134
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6135
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6136
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6137
+	 * array_keys() on $model_objects.
6138
+	 *
6139
+	 * @param EE_Base_Class[] $model_objects
6140
+	 * @param boolean         $filter_out_empty_ids  if a model object has an ID of '' or 0, don't bother including it
6141
+	 *                                               in the returned array
6142
+	 * @return array
6143
+	 * @throws EE_Error
6144
+	 * @throws ReflectionException
6145
+	 */
6146
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6147
+	{
6148
+		if (! $this->has_primary_key_field()) {
6149
+			if (WP_DEBUG) {
6150
+				EE_Error::add_error(
6151
+					esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6152
+					__FILE__,
6153
+					__FUNCTION__,
6154
+					__LINE__
6155
+				);
6156
+			}
6157
+		}
6158
+		$IDs = [];
6159
+		foreach ($model_objects as $model_object) {
6160
+			$id = $model_object->ID();
6161
+			if (! $id) {
6162
+				if ($filter_out_empty_ids) {
6163
+					continue;
6164
+				}
6165
+				if (WP_DEBUG) {
6166
+					EE_Error::add_error(
6167
+						esc_html__(
6168
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6169
+							'event_espresso'
6170
+						),
6171
+						__FILE__,
6172
+						__FUNCTION__,
6173
+						__LINE__
6174
+					);
6175
+				}
6176
+			}
6177
+			$IDs[] = $id;
6178
+		}
6179
+		return $IDs;
6180
+	}
6181
+
6182
+
6183
+	/**
6184
+	 * Returns the string used in capabilities relating to this model. If there
6185
+	 * are no capabilities that relate to this model returns false
6186
+	 *
6187
+	 * @return string|false
6188
+	 */
6189
+	public function cap_slug()
6190
+	{
6191
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6192
+	}
6193
+
6194
+
6195
+	/**
6196
+	 * Returns the capability-restrictions array (@param string $context
6197
+	 *
6198
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6199
+	 * @throws EE_Error
6200
+	 * @see EEM_Base::_cap_restrictions).
6201
+	 *      If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6202
+	 *      only returns the cap restrictions array in that context (ie, the array
6203
+	 *      at that key)
6204
+	 *
6205
+	 */
6206
+	public function cap_restrictions($context = EEM_Base::caps_read)
6207
+	{
6208
+		EEM_Base::verify_is_valid_cap_context($context);
6209
+		// check if we ought to run the restriction generator first
6210
+		if (
6211
+			isset($this->_cap_restriction_generators[ $context ])
6212
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6213
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6214
+		) {
6215
+			$this->_cap_restrictions[ $context ] = array_merge(
6216
+				$this->_cap_restrictions[ $context ],
6217
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6218
+			);
6219
+		}
6220
+		// and make sure we've finalized the construction of each restriction
6221
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6222
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6223
+				$where_conditions_obj->_finalize_construct($this);
6224
+			}
6225
+		}
6226
+		return $this->_cap_restrictions[ $context ];
6227
+	}
6228
+
6229
+
6230
+	/**
6231
+	 * Indicating whether or not this model thinks its a wp core model
6232
+	 *
6233
+	 * @return boolean
6234
+	 */
6235
+	public function is_wp_core_model()
6236
+	{
6237
+		return $this->_wp_core_model;
6238
+	}
6239
+
6240
+
6241
+	/**
6242
+	 * Gets all the caps that are missing which impose a restriction on
6243
+	 * queries made in this context
6244
+	 *
6245
+	 * @param string $context one of EEM_Base::caps_ constants
6246
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6247
+	 * @throws EE_Error
6248
+	 */
6249
+	public function caps_missing($context = EEM_Base::caps_read)
6250
+	{
6251
+		$missing_caps     = [];
6252
+		$cap_restrictions = $this->cap_restrictions($context);
6253
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6254
+			if (
6255
+			! EE_Capabilities::instance()
6256
+							 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6257
+			) {
6258
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6259
+			}
6260
+		}
6261
+		return $missing_caps;
6262
+	}
6263
+
6264
+
6265
+	/**
6266
+	 * Gets the mapping from capability contexts to action strings used in capability names
6267
+	 *
6268
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6269
+	 * one of 'read', 'edit', or 'delete'
6270
+	 */
6271
+	public function cap_contexts_to_cap_action_map()
6272
+	{
6273
+		return apply_filters(
6274
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6275
+			$this->_cap_contexts_to_cap_action_map,
6276
+			$this
6277
+		);
6278
+	}
6279
+
6280
+
6281
+	/**
6282
+	 * Gets the action string for the specified capability context
6283
+	 *
6284
+	 * @param string $context
6285
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6286
+	 * @throws EE_Error
6287
+	 */
6288
+	public function cap_action_for_context($context)
6289
+	{
6290
+		$mapping = $this->cap_contexts_to_cap_action_map();
6291
+		if (isset($mapping[ $context ])) {
6292
+			return $mapping[ $context ];
6293
+		}
6294
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6295
+			return $action;
6296
+		}
6297
+		throw new EE_Error(
6298
+			sprintf(
6299
+				esc_html__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6300
+				$context,
6301
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6302
+			)
6303
+		);
6304
+	}
6305
+
6306
+
6307
+	/**
6308
+	 * Returns all the capability contexts which are valid when querying models
6309
+	 *
6310
+	 * @return array
6311
+	 */
6312
+	public static function valid_cap_contexts()
6313
+	{
6314
+		return apply_filters(
6315
+			'FHEE__EEM_Base__valid_cap_contexts',
6316
+			[
6317
+				self::caps_read,
6318
+				self::caps_read_admin,
6319
+				self::caps_edit,
6320
+				self::caps_delete,
6321
+			]
6322
+		);
6323
+	}
6324
+
6325
+
6326
+	/**
6327
+	 * Returns all valid options for 'default_where_conditions'
6328
+	 *
6329
+	 * @return array
6330
+	 */
6331
+	public static function valid_default_where_conditions()
6332
+	{
6333
+		return [
6334
+			EEM_Base::default_where_conditions_all,
6335
+			EEM_Base::default_where_conditions_this_only,
6336
+			EEM_Base::default_where_conditions_others_only,
6337
+			EEM_Base::default_where_conditions_minimum_all,
6338
+			EEM_Base::default_where_conditions_minimum_others,
6339
+			EEM_Base::default_where_conditions_none,
6340
+		];
6341
+	}
6342
+
6343
+	// public static function default_where_conditions_full
6344
+
6345
+
6346
+	/**
6347
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6348
+	 *
6349
+	 * @param string $context
6350
+	 * @return bool
6351
+	 * @throws EE_Error
6352
+	 */
6353
+	public static function verify_is_valid_cap_context($context)
6354
+	{
6355
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6356
+		if (in_array($context, $valid_cap_contexts)) {
6357
+			return true;
6358
+		}
6359
+		throw new EE_Error(
6360
+			sprintf(
6361
+				esc_html__(
6362
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6363
+					'event_espresso'
6364
+				),
6365
+				$context,
6366
+				'EEM_Base',
6367
+				implode(',', $valid_cap_contexts)
6368
+			)
6369
+		);
6370
+	}
6371
+
6372
+
6373
+	/**
6374
+	 * Clears all the models field caches. This is only useful when a sub-class
6375
+	 * might have added a field or something and these caches might be invalidated
6376
+	 */
6377
+	protected function _invalidate_field_caches()
6378
+	{
6379
+		$this->_cache_foreign_key_to_fields = [];
6380
+		$this->_cached_fields               = null;
6381
+		$this->_cached_fields_non_db_only   = null;
6382
+	}
6383
+
6384
+
6385
+	/**
6386
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6387
+	 * (eg "and", "or", "not").
6388
+	 *
6389
+	 * @return array
6390
+	 */
6391
+	public function logic_query_param_keys()
6392
+	{
6393
+		return $this->_logic_query_param_keys;
6394
+	}
6395
+
6396
+
6397
+	/**
6398
+	 * Determines whether or not the where query param array key is for a logic query param.
6399
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6400
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6401
+	 *
6402
+	 * @param $query_param_key
6403
+	 * @return bool
6404
+	 */
6405
+	public function is_logic_query_param_key($query_param_key)
6406
+	{
6407
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6408
+			if (
6409
+				$query_param_key === $logic_query_param_key
6410
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6411
+			) {
6412
+				return true;
6413
+			}
6414
+		}
6415
+		return false;
6416
+	}
6417
+
6418
+
6419
+	/**
6420
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6421
+	 *
6422
+	 * @return boolean
6423
+	 * @since 4.9.74.p
6424
+	 */
6425
+	public function hasPassword()
6426
+	{
6427
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6428
+		if ($this->has_password_field === null) {
6429
+			$password_field           = $this->getPasswordField();
6430
+			$this->has_password_field = $password_field instanceof EE_Password_Field;
6431
+		}
6432
+		return $this->has_password_field;
6433
+	}
6434
+
6435
+
6436
+	/**
6437
+	 * Returns the password field on this model, if there is one
6438
+	 *
6439
+	 * @return EE_Password_Field|null
6440
+	 * @since 4.9.74.p
6441
+	 */
6442
+	public function getPasswordField()
6443
+	{
6444
+		// if we definitely already know there is a password field or not (because has_password_field is true or false)
6445
+		// there's no need to search for it. If we don't know yet, then find out
6446
+		if ($this->has_password_field === null && $this->password_field === null) {
6447
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6448
+		}
6449
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6450
+		return $this->password_field;
6451
+	}
6452
+
6453
+
6454
+	/**
6455
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6456
+	 *
6457
+	 * @return EE_Model_Field_Base[]
6458
+	 * @throws EE_Error
6459
+	 * @since 4.9.74.p
6460
+	 */
6461
+	public function getPasswordProtectedFields()
6462
+	{
6463
+		$password_field = $this->getPasswordField();
6464
+		$fields         = [];
6465
+		if ($password_field instanceof EE_Password_Field) {
6466
+			$field_names = $password_field->protectedFields();
6467
+			foreach ($field_names as $field_name) {
6468
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6469
+			}
6470
+		}
6471
+		return $fields;
6472
+	}
6473
+
6474
+
6475
+	/**
6476
+	 * Checks if the current user can perform the requested action on this model
6477
+	 *
6478
+	 * @param string              $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6479
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6480
+	 * @return bool
6481
+	 * @throws EE_Error
6482
+	 * @throws InvalidArgumentException
6483
+	 * @throws InvalidDataTypeException
6484
+	 * @throws InvalidInterfaceException
6485
+	 * @throws ReflectionException
6486
+	 * @throws UnexpectedEntityException
6487
+	 * @since 4.9.74.p
6488
+	 */
6489
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6490
+	{
6491
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6492
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6493
+		}
6494
+		if (! is_array($model_obj_or_fields_n_values)) {
6495
+			throw new UnexpectedEntityException(
6496
+				$model_obj_or_fields_n_values,
6497
+				'EE_Base_Class',
6498
+				sprintf(
6499
+					esc_html__(
6500
+						'%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.',
6501
+						'event_espresso'
6502
+					),
6503
+					__FUNCTION__
6504
+				)
6505
+			);
6506
+		}
6507
+		return $this->exists(
6508
+			$this->alter_query_params_to_restrict_by_ID(
6509
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6510
+				[
6511
+					'default_where_conditions' => 'none',
6512
+					'caps'                     => $cap_to_check,
6513
+				]
6514
+			)
6515
+		);
6516
+	}
6517
+
6518
+
6519
+	/**
6520
+	 * Returns the query param where conditions key to the password affecting this model.
6521
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6522
+	 *
6523
+	 * @return null|string
6524
+	 * @throws EE_Error
6525
+	 * @throws InvalidArgumentException
6526
+	 * @throws InvalidDataTypeException
6527
+	 * @throws InvalidInterfaceException
6528
+	 * @throws ModelConfigurationException
6529
+	 * @throws ReflectionException
6530
+	 * @since 4.9.74.p
6531
+	 */
6532
+	public function modelChainAndPassword()
6533
+	{
6534
+		if ($this->model_chain_to_password === null) {
6535
+			throw new ModelConfigurationException(
6536
+				$this,
6537
+				esc_html_x(
6538
+				// @codingStandardsIgnoreStart
6539
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6540
+					// @codingStandardsIgnoreEnd
6541
+					'1: model name',
6542
+					'event_espresso'
6543
+				)
6544
+			);
6545
+		}
6546
+		if ($this->model_chain_to_password === '') {
6547
+			$model_with_password = $this;
6548
+		} else {
6549
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6550
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6551
+			} else {
6552
+				$last_model_in_chain = $this->model_chain_to_password;
6553
+			}
6554
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6555
+		}
6556
+
6557
+		$password_field = $model_with_password->getPasswordField();
6558
+		if ($password_field instanceof EE_Password_Field) {
6559
+			$password_field_name = $password_field->get_name();
6560
+		} else {
6561
+			throw new ModelConfigurationException(
6562
+				$this,
6563
+				sprintf(
6564
+					esc_html_x(
6565
+						'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"',
6566
+						'1: model name, 2: special string',
6567
+						'event_espresso'
6568
+					),
6569
+					$model_with_password->get_this_model_name(),
6570
+					$this->model_chain_to_password
6571
+				)
6572
+			);
6573
+		}
6574
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6575
+	}
6576
+
6577
+
6578
+	/**
6579
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6580
+	 * or if this model itself has a password affecting access to some of its other fields.
6581
+	 *
6582
+	 * @return boolean
6583
+	 * @since 4.9.74.p
6584
+	 */
6585
+	public function restrictedByRelatedModelPassword()
6586
+	{
6587
+		return $this->model_chain_to_password !== null;
6588
+	}
6589 6589
 }
Please login to merge, or discard this patch.
Spacing   +245 added lines, -245 removed lines patch added patch discarded remove patch
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
     protected function __construct($timezone = null)
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
         }
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
         // initialize the standard cap restriction generators if none were specified by the child constructor
676 676
         if ($this->_cap_restriction_generators !== false) {
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 there are cap restriction generators, use them to make the default cap restrictions
689 689
         if ($this->_cap_restriction_generators !== false) {
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 = null)
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,
@@ -791,7 +791,7 @@  discard block
 block discarded – undo
791 791
             foreach ($r->getDefaultProperties() as $property => $value) {
792 792
                 // don't set instance to null like it was originally,
793 793
                 // but it's static anyways, and we're ignoring static properties (for now at least)
794
-                if (! isset($static_properties[ $property ])) {
794
+                if ( ! isset($static_properties[$property])) {
795 795
                     static::$_instance->{$property} = $value;
796 796
                 }
797 797
             }
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
      */
815 815
     private static function getLoader()
816 816
     {
817
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
817
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
818 818
             EEM_Base::$loader = LoaderFactory::getLoader();
819 819
         }
820 820
         return EEM_Base::$loader;
@@ -834,7 +834,7 @@  discard block
 block discarded – undo
834 834
      */
835 835
     public function status_array($translated = false)
836 836
     {
837
-        if (! array_key_exists('Status', $this->_model_relations)) {
837
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
838 838
             return [];
839 839
         }
840 840
         $model_name   = $this->get_this_model_name();
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
         $stati        = EEM_Status::instance()->get_all([['STS_type' => $status_type]]);
843 843
         $status_array = [];
844 844
         foreach ($stati as $status) {
845
-            $status_array[ $status->ID() ] = $status->get('STS_code');
845
+            $status_array[$status->ID()] = $status->get('STS_code');
846 846
         }
847 847
         return $translated
848 848
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -905,7 +905,7 @@  discard block
 block discarded – undo
905 905
     {
906 906
         $wp_user_field_name = $this->wp_user_field_name();
907 907
         if ($wp_user_field_name) {
908
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
908
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
909 909
         }
910 910
         return $query_params;
911 911
     }
@@ -923,17 +923,17 @@  discard block
 block discarded – undo
923 923
     public function wp_user_field_name()
924 924
     {
925 925
         try {
926
-            if (! empty($this->_model_chain_to_wp_user)) {
926
+            if ( ! empty($this->_model_chain_to_wp_user)) {
927 927
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
928 928
                 $last_model_name              = end($models_to_follow_to_wp_users);
929 929
                 $model_with_fk_to_wp_users    = EE_Registry::instance()->load_model($last_model_name);
930
-                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user . '.';
930
+                $model_chain_to_wp_user       = $this->_model_chain_to_wp_user.'.';
931 931
             } else {
932 932
                 $model_with_fk_to_wp_users = $this;
933 933
                 $model_chain_to_wp_user    = '';
934 934
             }
935 935
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
936
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
936
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
937 937
         } catch (EE_Error $e) {
938 938
             return false;
939 939
         }
@@ -1009,11 +1009,11 @@  discard block
 block discarded – undo
1009 1009
         if ($this->_custom_selections instanceof CustomSelects) {
1010 1010
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1011 1011
             $select_expressions .= $select_expressions
1012
-                ? ', ' . $custom_expressions
1012
+                ? ', '.$custom_expressions
1013 1013
                 : $custom_expressions;
1014 1014
         }
1015 1015
 
1016
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1016
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1017 1017
         return $this->_do_wpdb_query('get_results', [$SQL, $output]);
1018 1018
     }
1019 1019
 
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
      */
1031 1031
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1032 1032
     {
1033
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1033
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1034 1034
             return null;
1035 1035
         }
1036 1036
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1079,7 +1079,7 @@  discard block
 block discarded – undo
1079 1079
         if (is_array($columns_to_select)) {
1080 1080
             $select_sql_array = [];
1081 1081
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1082
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1082
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1083 1083
                     throw new EE_Error(
1084 1084
                         sprintf(
1085 1085
                             esc_html__(
@@ -1091,7 +1091,7 @@  discard block
 block discarded – undo
1091 1091
                         )
1092 1092
                     );
1093 1093
                 }
1094
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1094
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1095 1095
                     throw new EE_Error(
1096 1096
                         sprintf(
1097 1097
                             esc_html__(
@@ -1163,12 +1163,12 @@  discard block
 block discarded – undo
1163 1163
      */
1164 1164
     public function alter_query_params_to_restrict_by_ID($id, $query_params = [])
1165 1165
     {
1166
-        if (! isset($query_params[0])) {
1166
+        if ( ! isset($query_params[0])) {
1167 1167
             $query_params[0] = [];
1168 1168
         }
1169 1169
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1170 1170
         if ($conditions_from_id === null) {
1171
-            $query_params[0][ $this->primary_key_name() ] = $id;
1171
+            $query_params[0][$this->primary_key_name()] = $id;
1172 1172
         } else {
1173 1173
             // no primary key, so the $id must be from the get_index_primary_key_string()
1174 1174
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
      */
1189 1189
     public function get_one($query_params = [])
1190 1190
     {
1191
-        if (! is_array($query_params)) {
1191
+        if ( ! is_array($query_params)) {
1192 1192
             EE_Error::doing_it_wrong(
1193 1193
                 'EEM_Base::get_one',
1194 1194
                 sprintf(
@@ -1388,7 +1388,7 @@  discard block
 block discarded – undo
1388 1388
                 return [];
1389 1389
             }
1390 1390
         }
1391
-        if (! is_array($query_params)) {
1391
+        if ( ! is_array($query_params)) {
1392 1392
             EE_Error::doing_it_wrong(
1393 1393
                 'EEM_Base::_get_consecutive',
1394 1394
                 sprintf(
@@ -1400,10 +1400,10 @@  discard block
 block discarded – undo
1400 1400
             $query_params = [];
1401 1401
         }
1402 1402
         // let's add the where query param for consecutive look up.
1403
-        $query_params[0][ $field_to_order_by ] = [$operand, $current_field_value];
1403
+        $query_params[0][$field_to_order_by] = [$operand, $current_field_value];
1404 1404
         $query_params['limit']                 = $limit;
1405 1405
         // set direction
1406
-        $incoming_orderby         = isset($query_params['order_by']) ? (array)$query_params['order_by'] : [];
1406
+        $incoming_orderby         = isset($query_params['order_by']) ? (array) $query_params['order_by'] : [];
1407 1407
         $query_params['order_by'] = $operand === '>'
1408 1408
             ? [$field_to_order_by => 'ASC'] + $incoming_orderby
1409 1409
             : [$field_to_order_by => 'DESC'] + $incoming_orderby;
@@ -1424,7 +1424,7 @@  discard block
 block discarded – undo
1424 1424
     public function set_timezone($timezone)
1425 1425
     {
1426 1426
         // don't set the timezone if the incoming value is the same
1427
-        if (! empty($timezone) && $timezone === $this->_timezone) {
1427
+        if ( ! empty($timezone) && $timezone === $this->_timezone) {
1428 1428
             return;
1429 1429
         }
1430 1430
         $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
@@ -1480,7 +1480,7 @@  discard block
 block discarded – undo
1480 1480
     {
1481 1481
         $field_settings = $this->field_settings_for($field_name);
1482 1482
         // if not a valid EE_Datetime_Field then throw error
1483
-        if (! $field_settings instanceof EE_Datetime_Field) {
1483
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1484 1484
             throw new EE_Error(
1485 1485
                 sprintf(
1486 1486
                     esc_html__(
@@ -1631,7 +1631,7 @@  discard block
 block discarded – undo
1631 1631
      */
1632 1632
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1633 1633
     {
1634
-        if (! is_array($query_params)) {
1634
+        if ( ! is_array($query_params)) {
1635 1635
             EE_Error::doing_it_wrong(
1636 1636
                 'EEM_Base::update',
1637 1637
                 sprintf(
@@ -1660,7 +1660,7 @@  discard block
 block discarded – undo
1660 1660
          * @param array    $query_params
1661 1661
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1662 1662
          */
1663
-        $fields_n_values = (array)apply_filters(
1663
+        $fields_n_values = (array) apply_filters(
1664 1664
             'FHEE__EEM_Base__update__fields_n_values',
1665 1665
             $fields_n_values,
1666 1666
             $this,
@@ -1678,10 +1678,10 @@  discard block
 block discarded – undo
1678 1678
         $wpdb_select_results          = $this->_get_all_wpdb_results($query_params);
1679 1679
         foreach ($wpdb_select_results as $wpdb_result) {
1680 1680
             // type cast stdClass as array
1681
-            $wpdb_result = (array)$wpdb_result;
1681
+            $wpdb_result = (array) $wpdb_result;
1682 1682
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1683 1683
             if ($this->has_primary_key_field()) {
1684
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1684
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1685 1685
             } else {
1686 1686
                 // 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)
1687 1687
                 $main_table_pk_value = null;
@@ -1697,7 +1697,7 @@  discard block
 block discarded – undo
1697 1697
                     // in this table, right? so insert a row in the current table, using any fields available
1698 1698
                     if (
1699 1699
                     ! (array_key_exists($this_table_pk_column, $wpdb_result)
1700
-                       && $wpdb_result[ $this_table_pk_column ])
1700
+                       && $wpdb_result[$this_table_pk_column])
1701 1701
                     ) {
1702 1702
                         $success = $this->_insert_into_specific_table(
1703 1703
                             $table_obj,
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
                             $main_table_pk_value
1706 1706
                         );
1707 1707
                         // if we died here, report the error
1708
-                        if (! $success) {
1708
+                        if ( ! $success) {
1709 1709
                             return false;
1710 1710
                         }
1711 1711
                     }
@@ -1733,10 +1733,10 @@  discard block
 block discarded – undo
1733 1733
                 $model_objs_affected_ids     = [];
1734 1734
                 foreach ($models_affected_key_columns as $row) {
1735 1735
                     $combined_index_key                             = $this->get_index_primary_key_string($row);
1736
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1736
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1737 1737
                 }
1738 1738
             }
1739
-            if (! $model_objs_affected_ids) {
1739
+            if ( ! $model_objs_affected_ids) {
1740 1740
                 // wait wait wait- if nothing was affected let's stop here
1741 1741
                 return 0;
1742 1742
             }
@@ -1764,8 +1764,8 @@  discard block
 block discarded – undo
1764 1764
                             . " SET "
1765 1765
                             . $this->_construct_update_sql($fields_n_values)
1766 1766
                             . $model_query_info->get_where_sql(
1767
-            );// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1768
-        $rows_affected    = $this->_do_wpdb_query('query', [$SQL]);
1767
+            ); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1768
+        $rows_affected = $this->_do_wpdb_query('query', [$SQL]);
1769 1769
         /**
1770 1770
          * Action called after a model update call has been made.
1771 1771
          *
@@ -1776,7 +1776,7 @@  discard block
 block discarded – undo
1776 1776
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
1777 1777
          */
1778 1778
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1779
-        return $rows_affected;// how many supposedly got updated
1779
+        return $rows_affected; // how many supposedly got updated
1780 1780
     }
1781 1781
 
1782 1782
 
@@ -1807,7 +1807,7 @@  discard block
 block discarded – undo
1807 1807
         $model_query_info   = $this->_create_model_query_info_carrier($query_params);
1808 1808
         $select_expressions = $field->get_qualified_column();
1809 1809
         $SQL                =
1810
-            "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1810
+            "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1811 1811
         return $this->_do_wpdb_query('get_col', [$SQL]);
1812 1812
     }
1813 1813
 
@@ -1827,7 +1827,7 @@  discard block
 block discarded – undo
1827 1827
     {
1828 1828
         $query_params['limit'] = 1;
1829 1829
         $col                   = $this->get_col($query_params, $field_to_select);
1830
-        if (! empty($col)) {
1830
+        if ( ! empty($col)) {
1831 1831
             return reset($col);
1832 1832
         }
1833 1833
         return null;
@@ -1856,7 +1856,7 @@  discard block
 block discarded – undo
1856 1856
             $prepared_value  = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1857 1857
             $value_sql       = $prepared_value === null ? 'NULL'
1858 1858
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1859
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1859
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1860 1860
         }
1861 1861
         return implode(",", $cols_n_values);
1862 1862
     }
@@ -1992,7 +1992,7 @@  discard block
 block discarded – undo
1992 1992
                                 . $model_query_info->get_full_join_sql()
1993 1993
                                 . " WHERE "
1994 1994
                                 . $deletion_where_query_part;
1995
-            $rows_deleted     = $this->_do_wpdb_query('query', [$SQL]);
1995
+            $rows_deleted = $this->_do_wpdb_query('query', [$SQL]);
1996 1996
         } else {
1997 1997
             $rows_deleted = 0;
1998 1998
         }
@@ -2002,12 +2002,12 @@  discard block
 block discarded – undo
2002 2002
         if (
2003 2003
             $this->has_primary_key_field()
2004 2004
             && $rows_deleted !== false
2005
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
2005
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2006 2006
         ) {
2007
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
2007
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2008 2008
             foreach ($ids_for_removal as $id) {
2009
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
2010
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
2009
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2010
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2011 2011
                 }
2012 2012
             }
2013 2013
 
@@ -2047,7 +2047,7 @@  discard block
 block discarded – undo
2047 2047
          * @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
2048 2048
          */
2049 2049
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2050
-        return $rows_deleted;// how many supposedly got deleted
2050
+        return $rows_deleted; // how many supposedly got deleted
2051 2051
     }
2052 2052
 
2053 2053
 
@@ -2143,15 +2143,15 @@  discard block
 block discarded – undo
2143 2143
                 if (
2144 2144
                     $allow_blocking
2145 2145
                     && $this->delete_is_blocked_by_related_models(
2146
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2146
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2147 2147
                     )
2148 2148
                 ) {
2149 2149
                     continue;
2150 2150
                 }
2151 2151
                 // primary table deletes
2152
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2153
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2154
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2152
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2153
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2154
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2155 2155
                 }
2156 2156
             }
2157 2157
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2160,8 +2160,8 @@  discard block
 block discarded – undo
2160 2160
                 $ids_to_delete_indexed_by_column_for_row = [];
2161 2161
                 foreach ($fields as $cpk_field) {
2162 2162
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2163
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2164
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2163
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2164
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2165 2165
                     }
2166 2166
                 }
2167 2167
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2201,7 +2201,7 @@  discard block
 block discarded – undo
2201 2201
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2202 2202
                 // make sure we have unique $ids
2203 2203
                 $ids     = array_unique($ids);
2204
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2204
+                $query[] = $column.' IN('.implode(',', $ids).')';
2205 2205
             }
2206 2206
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2207 2207
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2209,7 +2209,7 @@  discard block
 block discarded – undo
2209 2209
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2210 2210
                 $values_for_each_combined_primary_key_for_a_row = [];
2211 2211
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2212
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2212
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2213 2213
                 }
2214 2214
                 $ways_to_identify_a_row[] = '('
2215 2215
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2283,10 +2283,10 @@  discard block
 block discarded – undo
2283 2283
                 $column_to_count = '*';
2284 2284
             }
2285 2285
         }
2286
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2286
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2287 2287
         $SQL             =
2288
-            "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2289
-        return (int)$this->_do_wpdb_query('get_var', [$SQL]);
2288
+            "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2289
+        return (int) $this->_do_wpdb_query('get_var', [$SQL]);
2290 2290
     }
2291 2291
 
2292 2292
 
@@ -2310,14 +2310,14 @@  discard block
 block discarded – undo
2310 2310
         }
2311 2311
         $column_to_count = $field_obj->get_qualified_column();
2312 2312
         $SQL             =
2313
-            "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+            "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2314 2314
         $return_value    = $this->_do_wpdb_query('get_var', [$SQL]);
2315 2315
         $data_type       = $field_obj->get_wpdb_data_type();
2316 2316
         if ($data_type === '%d' || $data_type === '%s') {
2317
-            return (float)$return_value;
2317
+            return (float) $return_value;
2318 2318
         }
2319 2319
         // must be %f
2320
-        return (float)$return_value;
2320
+        return (float) $return_value;
2321 2321
     }
2322 2322
 
2323 2323
 
@@ -2336,7 +2336,7 @@  discard block
 block discarded – undo
2336 2336
         // if we're in maintenance mode level 2, DON'T run any queries
2337 2337
         // because level 2 indicates the database needs updating and
2338 2338
         // is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2339
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2340 2340
             throw new EE_Error(
2341 2341
                 sprintf(
2342 2342
                     esc_html__(
@@ -2347,7 +2347,7 @@  discard block
 block discarded – undo
2347 2347
             );
2348 2348
         }
2349 2349
         global $wpdb;
2350
-        if (! method_exists($wpdb, $wpdb_method)) {
2350
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2351 2351
             throw new EE_Error(
2352 2352
                 sprintf(
2353 2353
                     esc_html__(
@@ -2366,7 +2366,7 @@  discard block
 block discarded – undo
2366 2366
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2367 2367
         if (WP_DEBUG) {
2368 2368
             $wpdb->show_errors($old_show_errors_value);
2369
-            if (! empty($wpdb->last_error)) {
2369
+            if ( ! empty($wpdb->last_error)) {
2370 2370
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2371 2371
             }
2372 2372
             if ($result === false) {
@@ -2436,7 +2436,7 @@  discard block
 block discarded – undo
2436 2436
                     // ummmm... you in trouble
2437 2437
                     return $result;
2438 2438
             }
2439
-            if (! empty($error_message)) {
2439
+            if ( ! empty($error_message)) {
2440 2440
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2441 2441
                 trigger_error($error_message);
2442 2442
             }
@@ -2513,11 +2513,11 @@  discard block
 block discarded – undo
2513 2513
      */
2514 2514
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2515 2515
     {
2516
-        return " FROM " . $model_query_info->get_full_join_sql() .
2517
-               $model_query_info->get_where_sql() .
2518
-               $model_query_info->get_group_by_sql() .
2519
-               $model_query_info->get_having_sql() .
2520
-               $model_query_info->get_order_by_sql() .
2516
+        return " FROM ".$model_query_info->get_full_join_sql().
2517
+               $model_query_info->get_where_sql().
2518
+               $model_query_info->get_group_by_sql().
2519
+               $model_query_info->get_having_sql().
2520
+               $model_query_info->get_order_by_sql().
2521 2521
                $model_query_info->get_limit_sql();
2522 2522
     }
2523 2523
 
@@ -2710,12 +2710,12 @@  discard block
 block discarded – undo
2710 2710
         $related_model = $this->get_related_model_obj($model_name);
2711 2711
         // we're just going to use the query params on the related model's normal get_all query,
2712 2712
         // except add a condition to say to match the current mod
2713
-        if (! isset($query_params['default_where_conditions'])) {
2713
+        if ( ! isset($query_params['default_where_conditions'])) {
2714 2714
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2715 2715
         }
2716 2716
         $this_model_name                                                 = $this->get_this_model_name();
2717 2717
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2718
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2718
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2719 2719
         return $related_model->count($query_params, $field_to_count, $distinct);
2720 2720
     }
2721 2721
 
@@ -2736,7 +2736,7 @@  discard block
 block discarded – undo
2736 2736
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2737 2737
     {
2738 2738
         $related_model = $this->get_related_model_obj($model_name);
2739
-        if (! is_array($query_params)) {
2739
+        if ( ! is_array($query_params)) {
2740 2740
             EE_Error::doing_it_wrong(
2741 2741
                 'EEM_Base::sum_related',
2742 2742
                 sprintf(
@@ -2749,12 +2749,12 @@  discard block
 block discarded – undo
2749 2749
         }
2750 2750
         // we're just going to use the query params on the related model's normal get_all query,
2751 2751
         // except add a condition to say to match the current mod
2752
-        if (! isset($query_params['default_where_conditions'])) {
2752
+        if ( ! isset($query_params['default_where_conditions'])) {
2753 2753
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2754 2754
         }
2755 2755
         $this_model_name                                                 = $this->get_this_model_name();
2756 2756
         $this_pk_field_name                                              = $this->get_primary_key_field()->get_name();
2757
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2757
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2758 2758
         return $related_model->sum($query_params, $field_to_sum);
2759 2759
     }
2760 2760
 
@@ -2806,7 +2806,7 @@  discard block
 block discarded – undo
2806 2806
                 $field_with_model_name = $field;
2807 2807
             }
2808 2808
         }
2809
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2809
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2810 2810
             throw new EE_Error(
2811 2811
                 sprintf(
2812 2812
                     esc_html__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
@@ -2843,7 +2843,7 @@  discard block
 block discarded – undo
2843 2843
          * @param array    $fields_n_values keys are the fields and values are their new values
2844 2844
          * @param EEM_Base $model           the model used
2845 2845
          */
2846
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2846
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2847 2847
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2848 2848
             $main_table = $this->_get_main_table();
2849 2849
             $new_id     = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2945,14 +2945,14 @@  discard block
 block discarded – undo
2945 2945
                 || $this->get_primary_key_field()
2946 2946
                    instanceof
2947 2947
                    EE_Primary_Key_String_Field)
2948
-            && isset($fields_n_values[ $this->primary_key_name() ])
2948
+            && isset($fields_n_values[$this->primary_key_name()])
2949 2949
         ) {
2950
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2950
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2951 2951
         }
2952 2952
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2953 2953
             $uniqueness_where_params                              =
2954 2954
                 array_intersect_key($fields_n_values, $unique_index->fields());
2955
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2955
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2956 2956
         }
2957 2957
         // if there is nothing to base this search on, then we shouldn't find anything
2958 2958
         if (empty($query_params)) {
@@ -3029,16 +3029,16 @@  discard block
 block discarded – undo
3029 3029
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3030 3030
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
3031 3031
             if ($prepared_value !== null) {
3032
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
3032
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3033 3033
                 $format_for_insertion[]                                   = $field_obj->get_wpdb_data_type();
3034 3034
             }
3035 3035
         }
3036 3036
         if ($table instanceof EE_Secondary_Table && $new_id) {
3037 3037
             // its not the main table, so we should have already saved the main table's PK which we just inserted
3038 3038
             // so add the fk to the main table as a column
3039
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
3039
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3040 3040
             $format_for_insertion[]                              =
3041
-                '%d';// yes right now we're only allowing these foreign keys to be INTs
3041
+                '%d'; // yes right now we're only allowing these foreign keys to be INTs
3042 3042
         }
3043 3043
         // insert the new entry
3044 3044
         $result = $this->_do_wpdb_query(
@@ -3055,7 +3055,7 @@  discard block
 block discarded – undo
3055 3055
             }
3056 3056
             // it's not an auto-increment primary key, so
3057 3057
             // it must have been supplied
3058
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3058
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3059 3059
         }
3060 3060
         // we can't return a  primary key because there is none. instead return
3061 3061
         // a unique string indicating this model
@@ -3079,14 +3079,14 @@  discard block
 block discarded – undo
3079 3079
         if (
3080 3080
             ! $field_obj->is_nullable()
3081 3081
             && (
3082
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3083
-                || $fields_n_values[ $field_obj->get_name() ] === null
3082
+                ! isset($fields_n_values[$field_obj->get_name()])
3083
+                || $fields_n_values[$field_obj->get_name()] === null
3084 3084
             )
3085 3085
         ) {
3086
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3086
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3087 3087
         }
3088
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3089
-            ? $fields_n_values[ $field_obj->get_name() ]
3088
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3089
+            ? $fields_n_values[$field_obj->get_name()]
3090 3090
             : null;
3091 3091
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3092 3092
     }
@@ -3187,7 +3187,7 @@  discard block
 block discarded – undo
3187 3187
      */
3188 3188
     public function get_table_obj_by_alias($table_alias = '')
3189 3189
     {
3190
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3190
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3191 3191
     }
3192 3192
 
3193 3193
 
@@ -3201,7 +3201,7 @@  discard block
 block discarded – undo
3201 3201
         $other_tables = [];
3202 3202
         foreach ($this->_tables as $table_alias => $table) {
3203 3203
             if ($table instanceof EE_Secondary_Table) {
3204
-                $other_tables[ $table_alias ] = $table;
3204
+                $other_tables[$table_alias] = $table;
3205 3205
             }
3206 3206
         }
3207 3207
         return $other_tables;
@@ -3216,7 +3216,7 @@  discard block
 block discarded – undo
3216 3216
      */
3217 3217
     public function _get_fields_for_table($table_alias)
3218 3218
     {
3219
-        return $this->_fields[ $table_alias ];
3219
+        return $this->_fields[$table_alias];
3220 3220
     }
3221 3221
 
3222 3222
 
@@ -3245,7 +3245,7 @@  discard block
 block discarded – undo
3245 3245
                     $query_info_carrier,
3246 3246
                     'group_by'
3247 3247
                 );
3248
-            } elseif (! empty($query_params['group_by'])) {
3248
+            } elseif ( ! empty($query_params['group_by'])) {
3249 3249
                 $this->_extract_related_model_info_from_query_param(
3250 3250
                     $query_params['group_by'],
3251 3251
                     $query_info_carrier,
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
                     $query_info_carrier,
3268 3268
                     'order_by'
3269 3269
                 );
3270
-            } elseif (! empty($query_params['order_by'])) {
3270
+            } elseif ( ! empty($query_params['order_by'])) {
3271 3271
                 $this->_extract_related_model_info_from_query_param(
3272 3272
                     $query_params['order_by'],
3273 3273
                     $query_info_carrier,
@@ -3302,8 +3302,8 @@  discard block
 block discarded – undo
3302 3302
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3303 3303
         $query_param_type
3304 3304
     ) {
3305
-        if (! empty($sub_query_params)) {
3306
-            $sub_query_params = (array)$sub_query_params;
3305
+        if ( ! empty($sub_query_params)) {
3306
+            $sub_query_params = (array) $sub_query_params;
3307 3307
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3308 3308
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309 3309
                 $this->_extract_related_model_info_from_query_param(
@@ -3318,7 +3318,7 @@  discard block
 block discarded – undo
3318 3318
                 $query_param_sans_stars =
3319 3319
                     $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3320 3320
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3321
-                    if (! is_array($possibly_array_of_params)) {
3321
+                    if ( ! is_array($possibly_array_of_params)) {
3322 3322
                         throw new EE_Error(
3323 3323
                             sprintf(
3324 3324
                                 esc_html__(
@@ -3344,7 +3344,7 @@  discard block
 block discarded – undo
3344 3344
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3345 3345
                     // indicating that $possible_array_of_params[1] is actually a field name,
3346 3346
                     // from which we should extract query parameters!
3347
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3347
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3348 3348
                         throw new EE_Error(
3349 3349
                             sprintf(
3350 3350
                                 esc_html__(
@@ -3384,8 +3384,8 @@  discard block
 block discarded – undo
3384 3384
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3385 3385
         $query_param_type
3386 3386
     ) {
3387
-        if (! empty($sub_query_params)) {
3388
-            if (! is_array($sub_query_params)) {
3387
+        if ( ! empty($sub_query_params)) {
3388
+            if ( ! is_array($sub_query_params)) {
3389 3389
                 throw new EE_Error(
3390 3390
                     sprintf(
3391 3391
                         esc_html__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
@@ -3423,7 +3423,7 @@  discard block
 block discarded – undo
3423 3423
      */
3424 3424
     public function _create_model_query_info_carrier($query_params)
3425 3425
     {
3426
-        if (! is_array($query_params)) {
3426
+        if ( ! is_array($query_params)) {
3427 3427
             EE_Error::doing_it_wrong(
3428 3428
                 'EEM_Base::_create_model_query_info_carrier',
3429 3429
                 sprintf(
@@ -3456,7 +3456,7 @@  discard block
 block discarded – undo
3456 3456
             // only include if related to a cpt where no password has been set
3457 3457
             $query_params[0]['OR*nopassword'] = [
3458 3458
                 $where_param_key_for_password       => '',
3459
-                $where_param_key_for_password . '*' => ['IS_NULL'],
3459
+                $where_param_key_for_password.'*' => ['IS_NULL'],
3460 3460
             ];
3461 3461
         }
3462 3462
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3510,7 +3510,7 @@  discard block
 block discarded – undo
3510 3510
         // set limit
3511 3511
         if (array_key_exists('limit', $query_params)) {
3512 3512
             if (is_array($query_params['limit'])) {
3513
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3513
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3514 3514
                     $e = sprintf(
3515 3515
                         esc_html__(
3516 3516
                             "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)",
@@ -3518,12 +3518,12 @@  discard block
 block discarded – undo
3518 3518
                         ),
3519 3519
                         http_build_query($query_params['limit'])
3520 3520
                     );
3521
-                    throw new EE_Error($e . "|" . $e);
3521
+                    throw new EE_Error($e."|".$e);
3522 3522
                 }
3523 3523
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3524
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3525
-            } elseif (! empty($query_params['limit'])) {
3526
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3524
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3525
+            } elseif ( ! empty($query_params['limit'])) {
3526
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3527 3527
             }
3528 3528
         }
3529 3529
         // set order by
@@ -3555,10 +3555,10 @@  discard block
 block discarded – undo
3555 3555
                 $order_array = [];
3556 3556
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3557 3557
                     $order         = $this->_extract_order($order);
3558
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3558
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3559 3559
                 }
3560
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3561
-            } elseif (! empty($query_params['order_by'])) {
3560
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3561
+            } elseif ( ! empty($query_params['order_by'])) {
3562 3562
                 $this->_extract_related_model_info_from_query_param(
3563 3563
                     $query_params['order_by'],
3564 3564
                     $query_object,
@@ -3569,7 +3569,7 @@  discard block
 block discarded – undo
3569 3569
                     ? $this->_extract_order($query_params['order'])
3570 3570
                     : 'DESC';
3571 3571
                 $query_object->set_order_by_sql(
3572
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3572
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3573 3573
                 );
3574 3574
             }
3575 3575
         }
@@ -3581,7 +3581,7 @@  discard block
 block discarded – undo
3581 3581
         ) {
3582 3582
             $pk_field = $this->get_primary_key_field();
3583 3583
             $order    = $this->_extract_order($query_params['order']);
3584
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3584
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3585 3585
         }
3586 3586
         // set group by
3587 3587
         if (array_key_exists('group_by', $query_params)) {
@@ -3591,10 +3591,10 @@  discard block
 block discarded – undo
3591 3591
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3592 3592
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3593 3593
                 }
3594
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3595
-            } elseif (! empty($query_params['group_by'])) {
3594
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3595
+            } elseif ( ! empty($query_params['group_by'])) {
3596 3596
                 $query_object->set_group_by_sql(
3597
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3597
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3598 3598
                 );
3599 3599
             }
3600 3600
         }
@@ -3604,7 +3604,7 @@  discard block
 block discarded – undo
3604 3604
         }
3605 3605
         // now, just verify they didn't pass anything wack
3606 3606
         foreach ($query_params as $query_key => $query_value) {
3607
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3607
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3608 3608
                 throw new EE_Error(
3609 3609
                     sprintf(
3610 3610
                         esc_html__(
@@ -3708,7 +3708,7 @@  discard block
 block discarded – undo
3708 3708
         $where_query_params = []
3709 3709
     ) {
3710 3710
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3711
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3711
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3712 3712
             throw new EE_Error(
3713 3713
                 sprintf(
3714 3714
                     esc_html__(
@@ -3738,7 +3738,7 @@  discard block
 block discarded – undo
3738 3738
                 // we don't want to add full or even minimum default where conditions from this model, so just continue
3739 3739
                 continue;
3740 3740
             }
3741
-            $overrides              = $this->_override_defaults_or_make_null_friendly(
3741
+            $overrides = $this->_override_defaults_or_make_null_friendly(
3742 3742
                 $related_model_universal_where_params,
3743 3743
                 $where_query_params,
3744 3744
                 $related_model,
@@ -3847,19 +3847,19 @@  discard block
 block discarded – undo
3847 3847
     ) {
3848 3848
         $null_friendly_where_conditions = [];
3849 3849
         $none_overridden                = true;
3850
-        $or_condition_key_for_defaults  = 'OR*' . get_class($model);
3850
+        $or_condition_key_for_defaults  = 'OR*'.get_class($model);
3851 3851
         foreach ($default_where_conditions as $key => $val) {
3852
-            if (isset($provided_where_conditions[ $key ])) {
3852
+            if (isset($provided_where_conditions[$key])) {
3853 3853
                 $none_overridden = false;
3854 3854
             } else {
3855
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3855
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3856 3856
             }
3857 3857
         }
3858 3858
         if ($none_overridden && $default_where_conditions) {
3859 3859
             if ($model->has_primary_key_field()) {
3860
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3860
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3861 3861
                                                                                    . "."
3862
-                                                                                   . $model->primary_key_name() ] =
3862
+                                                                                   . $model->primary_key_name()] =
3863 3863
                     ['IS NULL'];
3864 3864
             }/*else{
3865 3865
                 //@todo NO PK, use other defaults
@@ -3968,7 +3968,7 @@  discard block
 block discarded – undo
3968 3968
             foreach ($tables as $table_obj) {
3969 3969
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3970 3970
                                        . $table_obj->get_fully_qualified_pk_column();
3971
-                if (! in_array($qualified_pk_column, $selects)) {
3971
+                if ( ! in_array($qualified_pk_column, $selects)) {
3972 3972
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3973 3973
                 }
3974 3974
             }
@@ -4120,9 +4120,9 @@  discard block
 block discarded – undo
4120 4120
         $query_parameter_type
4121 4121
     ) {
4122 4122
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4123
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4123
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4124 4124
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4125
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4125
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4126 4126
                 if ($possible_join_string === '') {
4127 4127
                     // nothing left to $query_param
4128 4128
                     // we should actually end in a field name, not a model like this!
@@ -4254,7 +4254,7 @@  discard block
 block discarded – undo
4254 4254
     {
4255 4255
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4256 4256
         if ($SQL) {
4257
-            return " WHERE " . $SQL;
4257
+            return " WHERE ".$SQL;
4258 4258
         }
4259 4259
         return '';
4260 4260
     }
@@ -4272,7 +4272,7 @@  discard block
 block discarded – undo
4272 4272
     {
4273 4273
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4274 4274
         if ($SQL) {
4275
-            return " HAVING " . $SQL;
4275
+            return " HAVING ".$SQL;
4276 4276
         }
4277 4277
         return '';
4278 4278
     }
@@ -4295,7 +4295,7 @@  discard block
 block discarded – undo
4295 4295
             $query_param =
4296 4296
                 $this->_remove_stars_and_anything_after_from_condition_query_param_key(
4297 4297
                     $query_param
4298
-                );// str_replace("*",'',$query_param);
4298
+                ); // str_replace("*",'',$query_param);
4299 4299
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4300 4300
                 switch ($query_param) {
4301 4301
                     case 'not':
@@ -4329,7 +4329,7 @@  discard block
 block discarded – undo
4329 4329
             } else {
4330 4330
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4331 4331
                 // if it's not a normal field, maybe it's a custom selection?
4332
-                if (! $field_obj) {
4332
+                if ( ! $field_obj) {
4333 4333
                     if ($this->_custom_selections instanceof CustomSelects) {
4334 4334
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4335 4335
                     } else {
@@ -4345,7 +4345,7 @@  discard block
 block discarded – undo
4345 4345
                     }
4346 4346
                 }
4347 4347
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4348
-                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4348
+                $where_clauses[]  = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4349 4349
             }
4350 4350
         }
4351 4351
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4367,7 +4367,7 @@  discard block
 block discarded – undo
4367 4367
                 $field->get_model_name(),
4368 4368
                 $query_param
4369 4369
             );
4370
-            return $table_alias_prefix . $field->get_qualified_column();
4370
+            return $table_alias_prefix.$field->get_qualified_column();
4371 4371
         }
4372 4372
         if (
4373 4373
             $this->_custom_selections instanceof CustomSelects
@@ -4424,7 +4424,7 @@  discard block
 block discarded – undo
4424 4424
     {
4425 4425
         if (is_array($op_and_value)) {
4426 4426
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4427
-            if (! $operator) {
4427
+            if ( ! $operator) {
4428 4428
                 $php_array_like_string = [];
4429 4429
                 foreach ($op_and_value as $key => $value) {
4430 4430
                     $php_array_like_string[] = "$key=>$value";
@@ -4446,14 +4446,14 @@  discard block
 block discarded – undo
4446 4446
         }
4447 4447
         // check to see if the value is actually another field
4448 4448
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4449
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4449
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4450 4450
         }
4451 4451
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4452 4452
             // in this case, the value should be an array, or at least a comma-separated list
4453 4453
             // it will need to handle a little differently
4454 4454
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4455 4455
             // note: $cleaned_value has already been run through $wpdb->prepare()
4456
-            return $operator . SP . $cleaned_value;
4456
+            return $operator.SP.$cleaned_value;
4457 4457
         }
4458 4458
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4459 4459
             // the value should be an array with count of two.
@@ -4469,7 +4469,7 @@  discard block
 block discarded – undo
4469 4469
                 );
4470 4470
             }
4471 4471
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4472
-            return $operator . SP . $cleaned_value;
4472
+            return $operator.SP.$cleaned_value;
4473 4473
         }
4474 4474
         if (in_array($operator, $this->valid_null_style_operators())) {
4475 4475
             if ($value !== null) {
@@ -4489,10 +4489,10 @@  discard block
 block discarded – undo
4489 4489
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4490 4490
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4491 4491
             // remove other junk. So just treat it as a string.
4492
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4492
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4493 4493
         }
4494
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4494
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4495
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4496 4496
         }
4497 4497
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4498 4498
             throw new EE_Error(
@@ -4506,7 +4506,7 @@  discard block
 block discarded – undo
4506 4506
                 )
4507 4507
             );
4508 4508
         }
4509
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4509
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4510 4510
             throw new EE_Error(
4511 4511
                 sprintf(
4512 4512
                     esc_html__(
@@ -4545,7 +4545,7 @@  discard block
 block discarded – undo
4545 4545
         foreach ($values as $value) {
4546 4546
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4547 4547
         }
4548
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4548
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4549 4549
     }
4550 4550
 
4551 4551
 
@@ -4585,7 +4585,7 @@  discard block
 block discarded – undo
4585 4585
                                 . $main_table->get_table_name()
4586 4586
                                 . " WHERE FALSE";
4587 4587
         }
4588
-        return "(" . implode(",", $cleaned_values) . ")";
4588
+        return "(".implode(",", $cleaned_values).")";
4589 4589
     }
4590 4590
 
4591 4591
 
@@ -4604,7 +4604,7 @@  discard block
 block discarded – undo
4604 4604
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4605 4605
             );
4606 4606
         } //$field_obj should really just be a data type
4607
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4607
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4608 4608
             throw new EE_Error(
4609 4609
                 sprintf(
4610 4610
                     esc_html__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4641,14 +4641,14 @@  discard block
 block discarded – undo
4641 4641
             );
4642 4642
         }
4643 4643
         $number_of_parts       = count($query_param_parts);
4644
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4644
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4645 4645
         if ($number_of_parts === 1) {
4646 4646
             $field_name = $last_query_param_part;
4647 4647
             $model_obj  = $this;
4648 4648
         } else {// $number_of_parts >= 2
4649 4649
             // the last part is the column name, and there are only 2parts. therefore...
4650 4650
             $field_name = $last_query_param_part;
4651
-            $model_obj  = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4651
+            $model_obj  = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4652 4652
         }
4653 4653
         try {
4654 4654
             return $model_obj->field_settings_for($field_name);
@@ -4669,7 +4669,7 @@  discard block
 block discarded – undo
4669 4669
     public function _get_qualified_column_for_field($field_name)
4670 4670
     {
4671 4671
         $all_fields = $this->field_settings();
4672
-        $field      = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4672
+        $field      = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4673 4673
         if ($field) {
4674 4674
             return $field->get_qualified_column();
4675 4675
         }
@@ -4739,10 +4739,10 @@  discard block
 block discarded – undo
4739 4739
      */
4740 4740
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4741 4741
     {
4742
-        $table_prefix      = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4742
+        $table_prefix      = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4743 4743
         $qualified_columns = [];
4744 4744
         foreach ($this->field_settings() as $field_name => $field) {
4745
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4745
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4746 4746
         }
4747 4747
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4748 4748
     }
@@ -4766,11 +4766,11 @@  discard block
 block discarded – undo
4766 4766
             if ($table_obj instanceof EE_Primary_Table) {
4767 4767
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4768 4768
                     ? $table_obj->get_select_join_limit($limit)
4769
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4769
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4770 4770
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4771 4771
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4772 4772
                     ? $table_obj->get_select_join_limit_join($limit)
4773
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4773
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4774 4774
             }
4775 4775
         }
4776 4776
         return $SQL;
@@ -4840,7 +4840,7 @@  discard block
 block discarded – undo
4840 4840
         foreach ($this->field_settings() as $field_obj) {
4841 4841
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4842 4842
             /** @var $field_obj EE_Model_Field_Base */
4843
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4843
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4844 4844
         }
4845 4845
         return $data_types;
4846 4846
     }
@@ -4855,8 +4855,8 @@  discard block
 block discarded – undo
4855 4855
      */
4856 4856
     public function get_related_model_obj($model_name)
4857 4857
     {
4858
-        $model_classname = "EEM_" . $model_name;
4859
-        if (! class_exists($model_classname)) {
4858
+        $model_classname = "EEM_".$model_name;
4859
+        if ( ! class_exists($model_classname)) {
4860 4860
             throw new EE_Error(
4861 4861
                 sprintf(
4862 4862
                     esc_html__(
@@ -4868,7 +4868,7 @@  discard block
 block discarded – undo
4868 4868
                 )
4869 4869
             );
4870 4870
         }
4871
-        return call_user_func($model_classname . "::instance");
4871
+        return call_user_func($model_classname."::instance");
4872 4872
     }
4873 4873
 
4874 4874
 
@@ -4895,7 +4895,7 @@  discard block
 block discarded – undo
4895 4895
         $belongs_to_relations = [];
4896 4896
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4897 4897
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4898
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4898
+                $belongs_to_relations[$model_name] = $relation_obj;
4899 4899
             }
4900 4900
         }
4901 4901
         return $belongs_to_relations;
@@ -4912,7 +4912,7 @@  discard block
 block discarded – undo
4912 4912
     public function related_settings_for($relation_name)
4913 4913
     {
4914 4914
         $relatedModels = $this->relation_settings();
4915
-        if (! array_key_exists($relation_name, $relatedModels)) {
4915
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4916 4916
             throw new EE_Error(
4917 4917
                 sprintf(
4918 4918
                     esc_html__(
@@ -4925,7 +4925,7 @@  discard block
 block discarded – undo
4925 4925
                 )
4926 4926
             );
4927 4927
         }
4928
-        return $relatedModels[ $relation_name ];
4928
+        return $relatedModels[$relation_name];
4929 4929
     }
4930 4930
 
4931 4931
 
@@ -4941,7 +4941,7 @@  discard block
 block discarded – undo
4941 4941
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4942 4942
     {
4943 4943
         $fieldSettings = $this->field_settings($include_db_only_fields);
4944
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4944
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4945 4945
             throw new EE_Error(
4946 4946
                 sprintf(
4947 4947
                     esc_html__("There is no field/column '%s' on '%s'", 'event_espresso'),
@@ -4950,7 +4950,7 @@  discard block
 block discarded – undo
4950 4950
                 )
4951 4951
             );
4952 4952
         }
4953
-        return $fieldSettings[ $fieldName ];
4953
+        return $fieldSettings[$fieldName];
4954 4954
     }
4955 4955
 
4956 4956
 
@@ -4963,7 +4963,7 @@  discard block
 block discarded – undo
4963 4963
     public function has_field($fieldName)
4964 4964
     {
4965 4965
         $fieldSettings = $this->field_settings(true);
4966
-        if (isset($fieldSettings[ $fieldName ])) {
4966
+        if (isset($fieldSettings[$fieldName])) {
4967 4967
             return true;
4968 4968
         }
4969 4969
         return false;
@@ -4979,7 +4979,7 @@  discard block
 block discarded – undo
4979 4979
     public function has_relation($relation_name)
4980 4980
     {
4981 4981
         $relations = $this->relation_settings();
4982
-        if (isset($relations[ $relation_name ])) {
4982
+        if (isset($relations[$relation_name])) {
4983 4983
             return true;
4984 4984
         }
4985 4985
         return false;
@@ -5015,7 +5015,7 @@  discard block
 block discarded – undo
5015 5015
                     break;
5016 5016
                 }
5017 5017
             }
5018
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5018
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
5019 5019
                 throw new EE_Error(
5020 5020
                     sprintf(
5021 5021
                         esc_html__("There is no Primary Key defined on model %s", 'event_espresso'),
@@ -5075,17 +5075,17 @@  discard block
 block discarded – undo
5075 5075
      */
5076 5076
     public function get_foreign_key_to($model_name)
5077 5077
     {
5078
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5078
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5079 5079
             foreach ($this->field_settings() as $field) {
5080 5080
                 if (
5081 5081
                     $field instanceof EE_Foreign_Key_Field_Base
5082 5082
                     && in_array($model_name, $field->get_model_names_pointed_to())
5083 5083
                 ) {
5084
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5084
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5085 5085
                     break;
5086 5086
                 }
5087 5087
             }
5088
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5088
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5089 5089
                 throw new EE_Error(
5090 5090
                     sprintf(
5091 5091
                         esc_html__(
@@ -5098,7 +5098,7 @@  discard block
 block discarded – undo
5098 5098
                 );
5099 5099
             }
5100 5100
         }
5101
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5101
+        return $this->_cache_foreign_key_to_fields[$model_name];
5102 5102
     }
5103 5103
 
5104 5104
 
@@ -5114,7 +5114,7 @@  discard block
 block discarded – undo
5114 5114
     {
5115 5115
         $table_alias_sans_model_relation_chain_prefix =
5116 5116
             EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5117
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5117
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5118 5118
     }
5119 5119
 
5120 5120
 
@@ -5132,7 +5132,7 @@  discard block
 block discarded – undo
5132 5132
                 $this->_cached_fields = [];
5133 5133
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5134 5134
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5135
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5135
+                        $this->_cached_fields[$field_name] = $field_obj;
5136 5136
                     }
5137 5137
                 }
5138 5138
             }
@@ -5143,8 +5143,8 @@  discard block
 block discarded – undo
5143 5143
             foreach ($this->_fields as $fields_corresponding_to_table) {
5144 5144
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5145 5145
                     /** @var $field_obj EE_Model_Field_Base */
5146
-                    if (! $field_obj->is_db_only_field()) {
5147
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5146
+                    if ( ! $field_obj->is_db_only_field()) {
5147
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5148 5148
                     }
5149 5149
                 }
5150 5150
             }
@@ -5172,7 +5172,7 @@  discard block
 block discarded – undo
5172 5172
         $count_if_model_has_no_primary_key = 0;
5173 5173
         $has_primary_key                   = $this->has_primary_key_field();
5174 5174
         $primary_key_field                 = $has_primary_key ? $this->get_primary_key_field() : null;
5175
-        foreach ((array)$rows as $row) {
5175
+        foreach ((array) $rows as $row) {
5176 5176
             if (empty($row)) {
5177 5177
                 // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5178 5178
                 return [];
@@ -5185,12 +5185,12 @@  discard block
 block discarded – undo
5185 5185
                     $primary_key_field->get_qualified_column(),
5186 5186
                     $primary_key_field->get_table_column()
5187 5187
                 );
5188
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5188
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5189 5189
                     continue;
5190 5190
                 }
5191 5191
             }
5192 5192
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5193
-            if (! $classInstance) {
5193
+            if ( ! $classInstance) {
5194 5194
                 throw new EE_Error(
5195 5195
                     sprintf(
5196 5196
                         esc_html__('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5203,7 +5203,7 @@  discard block
 block discarded – undo
5203 5203
             $classInstance->set_timezone($this->_timezone);
5204 5204
             // make sure if there is any timezone setting present that we set the timezone for the object
5205 5205
             $key                      = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5206
-            $array_of_objects[ $key ] = $classInstance;
5206
+            $array_of_objects[$key] = $classInstance;
5207 5207
             // also, for all the relations of type BelongsTo, see if we can cache
5208 5208
             // those related models
5209 5209
             // (we could do this for other relations too, but if there are conditions
@@ -5247,9 +5247,9 @@  discard block
 block discarded – undo
5247 5247
         $results = [];
5248 5248
         if ($this->_custom_selections instanceof CustomSelects) {
5249 5249
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5250
-                if (isset($db_results_row[ $alias ])) {
5251
-                    $results[ $alias ] = $this->convertValueToDataType(
5252
-                        $db_results_row[ $alias ],
5250
+                if (isset($db_results_row[$alias])) {
5251
+                    $results[$alias] = $this->convertValueToDataType(
5252
+                        $db_results_row[$alias],
5253 5253
                         $this->_custom_selections->getDataTypeForAlias($alias)
5254 5254
                     );
5255 5255
                 }
@@ -5270,11 +5270,11 @@  discard block
 block discarded – undo
5270 5270
     {
5271 5271
         switch ($datatype) {
5272 5272
             case '%f':
5273
-                return (float)$value;
5273
+                return (float) $value;
5274 5274
             case '%d':
5275
-                return (int)$value;
5275
+                return (int) $value;
5276 5276
             default:
5277
-                return (string)$value;
5277
+                return (string) $value;
5278 5278
         }
5279 5279
     }
5280 5280
 
@@ -5294,7 +5294,7 @@  discard block
 block discarded – undo
5294 5294
         $this_model_fields_and_values = [];
5295 5295
         // setup the row using default values;
5296 5296
         foreach ($this->field_settings() as $field_name => $field_obj) {
5297
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5297
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5298 5298
         }
5299 5299
         $className = $this->_get_class_name();
5300 5300
         return EE_Registry::instance()->load_class(
@@ -5315,20 +5315,20 @@  discard block
 block discarded – undo
5315 5315
      */
5316 5316
     public function instantiate_class_from_array_or_object($cols_n_values)
5317 5317
     {
5318
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5318
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5319 5319
             $cols_n_values = get_object_vars($cols_n_values);
5320 5320
         }
5321 5321
         $primary_key = null;
5322 5322
         // make sure the array only has keys that are fields/columns on this model
5323 5323
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5324
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5325
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5324
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5325
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5326 5326
         }
5327 5327
         $className = $this->_get_class_name();
5328 5328
         // check we actually found results that we can use to build our model object
5329 5329
         // if not, return null
5330 5330
         if ($this->has_primary_key_field()) {
5331
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5331
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5332 5332
                 return null;
5333 5333
             }
5334 5334
         } elseif ($this->unique_indexes()) {
@@ -5340,7 +5340,7 @@  discard block
 block discarded – undo
5340 5340
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5341 5341
         if ($primary_key) {
5342 5342
             $classInstance = $this->get_from_entity_map($primary_key);
5343
-            if (! $classInstance) {
5343
+            if ( ! $classInstance) {
5344 5344
                 $classInstance = EE_Registry::instance()->load_class(
5345 5345
                     $className,
5346 5346
                     [$this_model_fields_n_values, $this->_timezone],
@@ -5370,8 +5370,8 @@  discard block
 block discarded – undo
5370 5370
      */
5371 5371
     public function get_from_entity_map($id)
5372 5372
     {
5373
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5374
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5373
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5374
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5375 5375
     }
5376 5376
 
5377 5377
 
@@ -5394,7 +5394,7 @@  discard block
 block discarded – undo
5394 5394
     public function add_to_entity_map(EE_Base_Class $object)
5395 5395
     {
5396 5396
         $className = $this->_get_class_name();
5397
-        if (! $object instanceof $className) {
5397
+        if ( ! $object instanceof $className) {
5398 5398
             throw new EE_Error(
5399 5399
                 sprintf(
5400 5400
                     esc_html__("You tried adding a %s to a mapping of %ss", "event_espresso"),
@@ -5403,7 +5403,7 @@  discard block
 block discarded – undo
5403 5403
                 )
5404 5404
             );
5405 5405
         }
5406
-        if (! $object->ID()) {
5406
+        if ( ! $object->ID()) {
5407 5407
             throw new EE_Error(
5408 5408
                 sprintf(
5409 5409
                     esc_html__(
@@ -5419,7 +5419,7 @@  discard block
 block discarded – undo
5419 5419
         if ($classInstance) {
5420 5420
             return $classInstance;
5421 5421
         }
5422
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5422
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5423 5423
         return $object;
5424 5424
     }
5425 5425
 
@@ -5434,11 +5434,11 @@  discard block
 block discarded – undo
5434 5434
     public function clear_entity_map($id = null)
5435 5435
     {
5436 5436
         if (empty($id)) {
5437
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = [];
5437
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = [];
5438 5438
             return true;
5439 5439
         }
5440
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5441
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5440
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5441
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5442 5442
             return true;
5443 5443
         }
5444 5444
         return false;
@@ -5479,18 +5479,18 @@  discard block
 block discarded – undo
5479 5479
             // there is a primary key on this table and its not set. Use defaults for all its columns
5480 5480
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5481 5481
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5482
-                    if (! $field_obj->is_db_only_field()) {
5482
+                    if ( ! $field_obj->is_db_only_field()) {
5483 5483
                         // prepare field as if its coming from db
5484 5484
                         $prepared_value                            =
5485 5485
                             $field_obj->prepare_for_set($field_obj->get_default_value());
5486
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5486
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5487 5487
                     }
5488 5488
                 }
5489 5489
             } else {
5490 5490
                 // the table's rows existed. Use their values
5491 5491
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5492
-                    if (! $field_obj->is_db_only_field()) {
5493
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5492
+                    if ( ! $field_obj->is_db_only_field()) {
5493
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5494 5494
                             $cols_n_values,
5495 5495
                             $field_obj->get_qualified_column(),
5496 5496
                             $field_obj->get_table_column()
@@ -5515,17 +5515,17 @@  discard block
 block discarded – undo
5515 5515
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5516 5516
         // does the field on the model relate to this column retrieved from the db?
5517 5517
         // or is it a db-only field? (not relating to the model)
5518
-        if (isset($cols_n_values[ $qualified_column ])) {
5519
-            $value = $cols_n_values[ $qualified_column ];
5520
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5521
-            $value = $cols_n_values[ $regular_column ];
5522
-        } elseif (! empty($this->foreign_key_aliases)) {
5518
+        if (isset($cols_n_values[$qualified_column])) {
5519
+            $value = $cols_n_values[$qualified_column];
5520
+        } elseif (isset($cols_n_values[$regular_column])) {
5521
+            $value = $cols_n_values[$regular_column];
5522
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5523 5523
             // no PK?  ok check if there is a foreign key alias set for this table
5524 5524
             // then check if that alias exists in the incoming data
5525 5525
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5526 5526
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5527
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5528
-                    $value = $cols_n_values[ $FK_alias ];
5527
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5528
+                    $value = $cols_n_values[$FK_alias];
5529 5529
                     break;
5530 5530
                 }
5531 5531
             }
@@ -5561,7 +5561,7 @@  discard block
 block discarded – undo
5561 5561
                     $obj_in_map->clear_cache($relation_name, null, true);
5562 5562
                 }
5563 5563
             }
5564
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5564
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5565 5565
             return $obj_in_map;
5566 5566
         }
5567 5567
         return $this->get_one_by_ID($id);
@@ -5613,7 +5613,7 @@  discard block
 block discarded – undo
5613 5613
      */
5614 5614
     private function _get_class_name()
5615 5615
     {
5616
-        return "EE_" . $this->get_this_model_name();
5616
+        return "EE_".$this->get_this_model_name();
5617 5617
     }
5618 5618
 
5619 5619
 
@@ -5627,7 +5627,7 @@  discard block
 block discarded – undo
5627 5627
      */
5628 5628
     public function item_name($quantity = 1)
5629 5629
     {
5630
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5630
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5631 5631
     }
5632 5632
 
5633 5633
 
@@ -5659,7 +5659,7 @@  discard block
 block discarded – undo
5659 5659
     {
5660 5660
         $className = get_class($this);
5661 5661
         $tagName   = "FHEE__{$className}__{$methodName}";
5662
-        if (! has_filter($tagName)) {
5662
+        if ( ! has_filter($tagName)) {
5663 5663
             throw new EE_Error(
5664 5664
                 sprintf(
5665 5665
                     esc_html__(
@@ -5829,7 +5829,7 @@  discard block
 block discarded – undo
5829 5829
         $unique_indexes = [];
5830 5830
         foreach ($this->_indexes as $name => $index) {
5831 5831
             if ($index instanceof EE_Unique_Index) {
5832
-                $unique_indexes [ $name ] = $index;
5832
+                $unique_indexes [$name] = $index;
5833 5833
             }
5834 5834
         }
5835 5835
         return $unique_indexes;
@@ -5893,7 +5893,7 @@  discard block
 block discarded – undo
5893 5893
         $key_values_in_combined_pk = [];
5894 5894
         parse_str($index_primary_key_string, $key_values_in_combined_pk);
5895 5895
         foreach ($key_fields as $key_field_name => $field_obj) {
5896
-            if (! isset($key_values_in_combined_pk[ $key_field_name ])) {
5896
+            if ( ! isset($key_values_in_combined_pk[$key_field_name])) {
5897 5897
                 return null;
5898 5898
             }
5899 5899
         }
@@ -5913,7 +5913,7 @@  discard block
 block discarded – undo
5913 5913
     {
5914 5914
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5915 5915
         foreach ($keys_it_should_have as $key) {
5916
-            if (! isset($key_values[ $key ])) {
5916
+            if ( ! isset($key_values[$key])) {
5917 5917
                 return false;
5918 5918
             }
5919 5919
         }
@@ -5952,8 +5952,8 @@  discard block
 block discarded – undo
5952 5952
         }
5953 5953
         // even copies obviously won't have the same ID, so remove the primary key
5954 5954
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5955
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5956
-            unset($attributes_array[ $this->primary_key_name() ]);
5955
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5956
+            unset($attributes_array[$this->primary_key_name()]);
5957 5957
         }
5958 5958
         if (isset($query_params[0])) {
5959 5959
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5975,7 +5975,7 @@  discard block
 block discarded – undo
5975 5975
      */
5976 5976
     public function get_one_copy($model_object_or_attributes_array, $query_params = [])
5977 5977
     {
5978
-        if (! is_array($query_params)) {
5978
+        if ( ! is_array($query_params)) {
5979 5979
             EE_Error::doing_it_wrong(
5980 5980
                 'EEM_Base::get_one_copy',
5981 5981
                 sprintf(
@@ -6025,7 +6025,7 @@  discard block
 block discarded – undo
6025 6025
     private function _prepare_operator_for_sql($operator_supplied)
6026 6026
     {
6027 6027
         $sql_operator =
6028
-            isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
6028
+            isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
6029 6029
                 : null;
6030 6030
         if ($sql_operator) {
6031 6031
             return $sql_operator;
@@ -6124,7 +6124,7 @@  discard block
 block discarded – undo
6124 6124
         $objs  = $this->get_all($query_params);
6125 6125
         $names = [];
6126 6126
         foreach ($objs as $obj) {
6127
-            $names[ $obj->ID() ] = $obj->name();
6127
+            $names[$obj->ID()] = $obj->name();
6128 6128
         }
6129 6129
         return $names;
6130 6130
     }
@@ -6145,7 +6145,7 @@  discard block
 block discarded – undo
6145 6145
      */
6146 6146
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6147 6147
     {
6148
-        if (! $this->has_primary_key_field()) {
6148
+        if ( ! $this->has_primary_key_field()) {
6149 6149
             if (WP_DEBUG) {
6150 6150
                 EE_Error::add_error(
6151 6151
                     esc_html__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6158,7 +6158,7 @@  discard block
 block discarded – undo
6158 6158
         $IDs = [];
6159 6159
         foreach ($model_objects as $model_object) {
6160 6160
             $id = $model_object->ID();
6161
-            if (! $id) {
6161
+            if ( ! $id) {
6162 6162
                 if ($filter_out_empty_ids) {
6163 6163
                     continue;
6164 6164
                 }
@@ -6208,22 +6208,22 @@  discard block
 block discarded – undo
6208 6208
         EEM_Base::verify_is_valid_cap_context($context);
6209 6209
         // check if we ought to run the restriction generator first
6210 6210
         if (
6211
-            isset($this->_cap_restriction_generators[ $context ])
6212
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6213
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6211
+            isset($this->_cap_restriction_generators[$context])
6212
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6213
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6214 6214
         ) {
6215
-            $this->_cap_restrictions[ $context ] = array_merge(
6216
-                $this->_cap_restrictions[ $context ],
6217
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6215
+            $this->_cap_restrictions[$context] = array_merge(
6216
+                $this->_cap_restrictions[$context],
6217
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6218 6218
             );
6219 6219
         }
6220 6220
         // and make sure we've finalized the construction of each restriction
6221
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6221
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6222 6222
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6223 6223
                 $where_conditions_obj->_finalize_construct($this);
6224 6224
             }
6225 6225
         }
6226
-        return $this->_cap_restrictions[ $context ];
6226
+        return $this->_cap_restrictions[$context];
6227 6227
     }
6228 6228
 
6229 6229
 
@@ -6253,9 +6253,9 @@  discard block
 block discarded – undo
6253 6253
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6254 6254
             if (
6255 6255
             ! EE_Capabilities::instance()
6256
-                             ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6256
+                             ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6257 6257
             ) {
6258
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6258
+                $missing_caps[$cap] = $restriction_if_no_cap;
6259 6259
             }
6260 6260
         }
6261 6261
         return $missing_caps;
@@ -6288,8 +6288,8 @@  discard block
 block discarded – undo
6288 6288
     public function cap_action_for_context($context)
6289 6289
     {
6290 6290
         $mapping = $this->cap_contexts_to_cap_action_map();
6291
-        if (isset($mapping[ $context ])) {
6292
-            return $mapping[ $context ];
6291
+        if (isset($mapping[$context])) {
6292
+            return $mapping[$context];
6293 6293
         }
6294 6294
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6295 6295
             return $action;
@@ -6407,7 +6407,7 @@  discard block
 block discarded – undo
6407 6407
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6408 6408
             if (
6409 6409
                 $query_param_key === $logic_query_param_key
6410
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6410
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6411 6411
             ) {
6412 6412
                 return true;
6413 6413
             }
@@ -6465,7 +6465,7 @@  discard block
 block discarded – undo
6465 6465
         if ($password_field instanceof EE_Password_Field) {
6466 6466
             $field_names = $password_field->protectedFields();
6467 6467
             foreach ($field_names as $field_name) {
6468
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6468
+                $fields[$field_name] = $this->field_settings_for($field_name);
6469 6469
             }
6470 6470
         }
6471 6471
         return $fields;
@@ -6491,7 +6491,7 @@  discard block
 block discarded – undo
6491 6491
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6492 6492
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6493 6493
         }
6494
-        if (! is_array($model_obj_or_fields_n_values)) {
6494
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6495 6495
             throw new UnexpectedEntityException(
6496 6496
                 $model_obj_or_fields_n_values,
6497 6497
                 'EE_Base_Class',
@@ -6571,7 +6571,7 @@  discard block
 block discarded – undo
6571 6571
                 )
6572 6572
             );
6573 6573
         }
6574
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6574
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6575 6575
     }
6576 6576
 
6577 6577
 
Please login to merge, or discard this patch.
core/db_classes/EE_Answer.class.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@
 block discarded – undo
64 64
     /**
65 65
      * Set Answer value
66 66
      *
67
-     * @param mixed $ANS_value
67
+     * @param string $ANS_value
68 68
      * @throws EE_Error
69 69
      * @throws ReflectionException
70 70
      */
Please login to merge, or discard this patch.
Indentation   +149 added lines, -149 removed lines patch added patch discarded remove patch
@@ -10,153 +10,153 @@
 block discarded – undo
10 10
 class EE_Answer extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Answer
16
-     * @throws EE_Error
17
-     * @throws ReflectionException
18
-     */
19
-    public static function new_instance($props_n_values = [])
20
-    {
21
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
-        return $has_object ? $has_object : new self($props_n_values);
23
-    }
24
-
25
-
26
-    /**
27
-     * @param array $props_n_values
28
-     * @return EE_Answer
29
-     * @throws EE_Error
30
-     * @throws ReflectionException
31
-     */
32
-    public static function new_instance_from_db($props_n_values = [])
33
-    {
34
-        return new self($props_n_values, true);
35
-    }
36
-
37
-
38
-    /**
39
-     * Set Question ID
40
-     *
41
-     * @param int $QST_ID
42
-     * @throws EE_Error
43
-     * @throws ReflectionException
44
-     */
45
-    public function set_question($QST_ID = 0)
46
-    {
47
-        $this->set('QST_ID', $QST_ID);
48
-    }
49
-
50
-
51
-    /**
52
-     * Set Registration ID
53
-     *
54
-     * @param int $REG_ID
55
-     * @throws EE_Error
56
-     * @throws ReflectionException
57
-     */
58
-    public function set_registration($REG_ID = 0)
59
-    {
60
-        $this->set('REG_ID', $REG_ID);
61
-    }
62
-
63
-
64
-    /**
65
-     * Set Answer value
66
-     *
67
-     * @param mixed $ANS_value
68
-     * @throws EE_Error
69
-     * @throws ReflectionException
70
-     */
71
-    public function set_value($ANS_value = '')
72
-    {
73
-        $this->set('ANS_value', $ANS_value);
74
-    }
75
-
76
-
77
-    /**
78
-     * get Attendee First Name
79
-     *
80
-     * @return        int
81
-     * @throws EE_Error
82
-     */
83
-    public function registration_ID()
84
-    {
85
-        return $this->get('REG_ID');
86
-    }
87
-
88
-
89
-    /**
90
-     * get Attendee Last Name
91
-     *
92
-     * @return        int
93
-     * @throws EE_Error
94
-     */
95
-    public function question_ID()
96
-    {
97
-        return $this->get('QST_ID');
98
-    }
99
-
100
-
101
-    /**
102
-     * get Attendee Address
103
-     *
104
-     * @return        string
105
-     * @throws EE_Error
106
-     */
107
-    public function value()
108
-    {
109
-        return $this->get('ANS_value');
110
-    }
111
-
112
-
113
-    /**
114
-     * Gets a pretty form of the value (mostly applies to answers that have multiple answers)
115
-     *
116
-     * @param null $schema
117
-     * @return string
118
-     * @throws EE_Error
119
-     */
120
-    public function pretty_value($schema = null)
121
-    {
122
-        return $this->get_pretty('ANS_value', $schema);
123
-    }
124
-
125
-
126
-    /**
127
-     * Echoes out a pretty value (even for multi-choice options)
128
-     *
129
-     * @param string $schema
130
-     * @throws EE_Error
131
-     */
132
-    public function e_value($schema = null)
133
-    {
134
-        $this->e('ANS_value', $schema);
135
-    }
136
-
137
-
138
-    /**
139
-     * Gets the related EE_Question to this EE_Answer
140
-     *
141
-     * @return EE_Base_Class|EE_Question
142
-     * @throws EE_Error
143
-     * @throws ReflectionException
144
-     */
145
-    public function question()
146
-    {
147
-        return $this->get_first_related('Question');
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets the related EE_Registration to this EE_Answer
153
-     *
154
-     * @return EE_Base_Class|EE_Registration
155
-     * @throws EE_Error
156
-     * @throws ReflectionException
157
-     */
158
-    public function registration()
159
-    {
160
-        return $this->get_first_related('Registration');
161
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Answer
16
+	 * @throws EE_Error
17
+	 * @throws ReflectionException
18
+	 */
19
+	public static function new_instance($props_n_values = [])
20
+	{
21
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
+		return $has_object ? $has_object : new self($props_n_values);
23
+	}
24
+
25
+
26
+	/**
27
+	 * @param array $props_n_values
28
+	 * @return EE_Answer
29
+	 * @throws EE_Error
30
+	 * @throws ReflectionException
31
+	 */
32
+	public static function new_instance_from_db($props_n_values = [])
33
+	{
34
+		return new self($props_n_values, true);
35
+	}
36
+
37
+
38
+	/**
39
+	 * Set Question ID
40
+	 *
41
+	 * @param int $QST_ID
42
+	 * @throws EE_Error
43
+	 * @throws ReflectionException
44
+	 */
45
+	public function set_question($QST_ID = 0)
46
+	{
47
+		$this->set('QST_ID', $QST_ID);
48
+	}
49
+
50
+
51
+	/**
52
+	 * Set Registration ID
53
+	 *
54
+	 * @param int $REG_ID
55
+	 * @throws EE_Error
56
+	 * @throws ReflectionException
57
+	 */
58
+	public function set_registration($REG_ID = 0)
59
+	{
60
+		$this->set('REG_ID', $REG_ID);
61
+	}
62
+
63
+
64
+	/**
65
+	 * Set Answer value
66
+	 *
67
+	 * @param mixed $ANS_value
68
+	 * @throws EE_Error
69
+	 * @throws ReflectionException
70
+	 */
71
+	public function set_value($ANS_value = '')
72
+	{
73
+		$this->set('ANS_value', $ANS_value);
74
+	}
75
+
76
+
77
+	/**
78
+	 * get Attendee First Name
79
+	 *
80
+	 * @return        int
81
+	 * @throws EE_Error
82
+	 */
83
+	public function registration_ID()
84
+	{
85
+		return $this->get('REG_ID');
86
+	}
87
+
88
+
89
+	/**
90
+	 * get Attendee Last Name
91
+	 *
92
+	 * @return        int
93
+	 * @throws EE_Error
94
+	 */
95
+	public function question_ID()
96
+	{
97
+		return $this->get('QST_ID');
98
+	}
99
+
100
+
101
+	/**
102
+	 * get Attendee Address
103
+	 *
104
+	 * @return        string
105
+	 * @throws EE_Error
106
+	 */
107
+	public function value()
108
+	{
109
+		return $this->get('ANS_value');
110
+	}
111
+
112
+
113
+	/**
114
+	 * Gets a pretty form of the value (mostly applies to answers that have multiple answers)
115
+	 *
116
+	 * @param null $schema
117
+	 * @return string
118
+	 * @throws EE_Error
119
+	 */
120
+	public function pretty_value($schema = null)
121
+	{
122
+		return $this->get_pretty('ANS_value', $schema);
123
+	}
124
+
125
+
126
+	/**
127
+	 * Echoes out a pretty value (even for multi-choice options)
128
+	 *
129
+	 * @param string $schema
130
+	 * @throws EE_Error
131
+	 */
132
+	public function e_value($schema = null)
133
+	{
134
+		$this->e('ANS_value', $schema);
135
+	}
136
+
137
+
138
+	/**
139
+	 * Gets the related EE_Question to this EE_Answer
140
+	 *
141
+	 * @return EE_Base_Class|EE_Question
142
+	 * @throws EE_Error
143
+	 * @throws ReflectionException
144
+	 */
145
+	public function question()
146
+	{
147
+		return $this->get_first_related('Question');
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets the related EE_Registration to this EE_Answer
153
+	 *
154
+	 * @return EE_Base_Class|EE_Registration
155
+	 * @throws EE_Error
156
+	 * @throws ReflectionException
157
+	 */
158
+	public function registration()
159
+	{
160
+		return $this->get_first_related('Registration');
161
+	}
162 162
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Attendee.class.php 3 patches
Doc Comments   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
      * Gets registrations of this attendee
452 452
      *
453 453
      * @param array $query_params
454
-     * @return array[]|EE_Base_Class[]|EE_Registration[]
454
+     * @return EE_Base_Class[]
455 455
      * @throws EE_Error
456 456
      * @throws ReflectionException
457 457
      */
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
     /**
498 498
      * returns any events attached to this attendee ($_Event property);
499 499
      *
500
-     * @return array
500
+     * @return EE_Base_Class[]
501 501
      * @throws EE_Error
502 502
      * @throws ReflectionException
503 503
      */
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
      * and keys are their cleaned values.
524 524
      *
525 525
      * @param EE_Payment_Method $payment_method the _gateway_name property on the gateway class
526
-     * @return EE_Form_Section_Proper|null
526
+     * @return null|EE_Billing_Info_Form
527 527
      * @throws EE_Error
528 528
      * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was
529 529
      *                                          used to save the billing info
Please login to merge, or discard this patch.
Indentation   +803 added lines, -803 removed lines patch added patch discarded remove patch
@@ -13,807 +13,807 @@
 block discarded – undo
13 13
 class EE_Attendee extends EE_CPT_Base implements EEI_Contact, EEI_Address, EEI_Admin_Links, EEI_Attendee
14 14
 {
15 15
 
16
-    /**
17
-     * Sets some dynamic defaults
18
-     *
19
-     * @param array  $fieldValues
20
-     * @param bool   $bydb
21
-     * @param string $timezone
22
-     * @param array  $date_formats
23
-     * @throws EE_Error
24
-     * @throws ReflectionException
25
-     */
26
-    protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = [])
27
-    {
28
-        if (! isset($fieldValues['ATT_full_name'])) {
29
-            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
30
-            $lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
31
-            $fieldValues['ATT_full_name'] = $fname . $lname;
32
-        }
33
-        if (! isset($fieldValues['ATT_slug'])) {
34
-            // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
35
-            $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
36
-        }
37
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
38
-            $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
39
-        }
40
-        parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
41
-    }
42
-
43
-
44
-    /**
45
-     * @param array  $props_n_values    incoming values
46
-     * @param string $timezone          incoming timezone
47
-     *                                  (if not set the timezone set for the website will be used.)
48
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
49
-     *                                  date_format and the second value is the time format
50
-     * @return EE_Attendee
51
-     * @throws EE_Error
52
-     * @throws ReflectionException
53
-     */
54
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
55
-    {
56
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
57
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
58
-    }
59
-
60
-
61
-    /**
62
-     * @param array  $props_n_values  incoming values from the database
63
-     * @param string $timezone        incoming timezone as set by the model.
64
-     *                                If not set the timezone for the website will be used.
65
-     * @return EE_Attendee
66
-     * @throws EE_Error
67
-     * @throws EE_Error
68
-     * @throws ReflectionException
69
-     */
70
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
71
-    {
72
-        return new self($props_n_values, true, $timezone);
73
-    }
74
-
75
-
76
-    /**
77
-     * Set Attendee First Name
78
-     *
79
-     * @param string $fname
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    public function set_fname($fname = '')
84
-    {
85
-        $this->set('ATT_fname', $fname);
86
-    }
87
-
88
-
89
-    /**
90
-     * Set Attendee Last Name
91
-     *
92
-     * @param string $lname
93
-     * @throws EE_Error
94
-     * @throws ReflectionException
95
-     */
96
-    public function set_lname($lname = '')
97
-    {
98
-        $this->set('ATT_lname', $lname);
99
-    }
100
-
101
-
102
-    /**
103
-     * Set Attendee Address
104
-     *
105
-     * @param string $address
106
-     * @throws EE_Error
107
-     * @throws ReflectionException
108
-     */
109
-    public function set_address($address = '')
110
-    {
111
-        $this->set('ATT_address', $address);
112
-    }
113
-
114
-
115
-    /**
116
-     * Set Attendee Address2
117
-     *
118
-     * @param string $address2
119
-     * @throws EE_Error
120
-     * @throws ReflectionException
121
-     */
122
-    public function set_address2($address2 = '')
123
-    {
124
-        $this->set('ATT_address2', $address2);
125
-    }
126
-
127
-
128
-    /**
129
-     * Set Attendee City
130
-     *
131
-     * @param string $city
132
-     * @throws EE_Error
133
-     * @throws ReflectionException
134
-     */
135
-    public function set_city($city = '')
136
-    {
137
-        $this->set('ATT_city', $city);
138
-    }
139
-
140
-
141
-    /**
142
-     * Set Attendee State ID
143
-     *
144
-     * @param int $STA_ID
145
-     * @throws EE_Error
146
-     * @throws ReflectionException
147
-     */
148
-    public function set_state($STA_ID = 0)
149
-    {
150
-        $this->set('STA_ID', $STA_ID);
151
-    }
152
-
153
-
154
-    /**
155
-     * Set Attendee Country ISO Code
156
-     *
157
-     * @param string $CNT_ISO
158
-     * @throws EE_Error
159
-     * @throws ReflectionException
160
-     */
161
-    public function set_country($CNT_ISO = '')
162
-    {
163
-        $this->set('CNT_ISO', $CNT_ISO);
164
-    }
165
-
166
-
167
-    /**
168
-     * Set Attendee Zip/Postal Code
169
-     *
170
-     * @param string $zip
171
-     * @throws EE_Error
172
-     * @throws ReflectionException
173
-     */
174
-    public function set_zip($zip = '')
175
-    {
176
-        $this->set('ATT_zip', $zip);
177
-    }
178
-
179
-
180
-    /**
181
-     * Set Attendee Email Address
182
-     *
183
-     * @param string $email
184
-     * @throws EE_Error
185
-     * @throws ReflectionException
186
-     */
187
-    public function set_email($email = '')
188
-    {
189
-        $this->set('ATT_email', $email);
190
-    }
191
-
192
-
193
-    /**
194
-     * Set Attendee Phone
195
-     *
196
-     * @param string $phone
197
-     * @throws EE_Error
198
-     * @throws ReflectionException
199
-     */
200
-    public function set_phone($phone = '')
201
-    {
202
-        $this->set('ATT_phone', $phone);
203
-    }
204
-
205
-
206
-    /**
207
-     * set deleted
208
-     *
209
-     * @param bool $ATT_deleted
210
-     * @throws EE_Error
211
-     * @throws ReflectionException
212
-     */
213
-    public function set_deleted($ATT_deleted = false)
214
-    {
215
-        $this->set('ATT_deleted', $ATT_deleted);
216
-    }
217
-
218
-
219
-    /**
220
-     * Returns the value for the post_author id saved with the cpt
221
-     *
222
-     * @return int
223
-     * @throws EE_Error
224
-     * @since 4.5.0
225
-     */
226
-    public function wp_user()
227
-    {
228
-        return $this->get('ATT_author');
229
-    }
230
-
231
-
232
-    /**
233
-     * echoes out the attendee's first name
234
-     *
235
-     * @return void
236
-     * @throws EE_Error
237
-     */
238
-    public function e_full_name()
239
-    {
240
-        echo $this->full_name();
241
-    }
242
-
243
-
244
-    /**
245
-     * Returns the first and last name concatenated together with a space.
246
-     *
247
-     * @param bool $apply_html_entities
248
-     * @return string
249
-     * @throws EE_Error
250
-     */
251
-    public function full_name($apply_html_entities = false)
252
-    {
253
-        $full_name = [
254
-            $this->fname(),
255
-            $this->lname(),
256
-        ];
257
-        $full_name = array_filter($full_name);
258
-        $full_name = implode(' ', $full_name);
259
-        return $apply_html_entities
260
-            ? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
261
-            : $full_name;
262
-    }
263
-
264
-
265
-    /**
266
-     * get Attendee First Name
267
-     *
268
-     * @return string
269
-     * @throws EE_Error
270
-     */
271
-    public function fname()
272
-    {
273
-        return $this->get('ATT_fname');
274
-    }
275
-
276
-
277
-    /**
278
-     * get Attendee Last Name
279
-     *
280
-     * @return string
281
-     * @throws EE_Error
282
-     */
283
-    public function lname()
284
-    {
285
-        return $this->get('ATT_lname');
286
-    }
287
-
288
-
289
-    /**
290
-     * get Attendee Email Address
291
-     *
292
-     * @return string
293
-     * @throws EE_Error
294
-     */
295
-    public function email()
296
-    {
297
-        return $this->get('ATT_email');
298
-    }
299
-
300
-
301
-    /**
302
-     * get Attendee Phone #
303
-     *
304
-     * @return string
305
-     * @throws EE_Error
306
-     */
307
-    public function phone()
308
-    {
309
-        return $this->get('ATT_phone');
310
-    }
311
-
312
-
313
-    /**
314
-     * This returns the value of the `ATT_full_name` field
315
-     * which is usually equivalent to calling `full_name()`
316
-     * unless the post_title field has been directly modified
317
-     * in the db for the post (espresso_attendees post type)
318
-     * for this attendee.
319
-     *
320
-     * @param bool $apply_html_entities
321
-     * @return string
322
-     * @throws EE_Error
323
-     */
324
-    public function ATT_full_name($apply_html_entities = false)
325
-    {
326
-        return $apply_html_entities
327
-            ? htmlentities(
328
-                $this->get('ATT_full_name'),
329
-                ENT_QUOTES,
330
-                'UTF-8'
331
-            )
332
-            : $this->get('ATT_full_name');
333
-    }
334
-
335
-
336
-    /**
337
-     * get Attendee bio
338
-     *
339
-     * @return string
340
-     * @throws EE_Error
341
-     */
342
-    public function bio()
343
-    {
344
-        return $this->get('ATT_bio');
345
-    }
346
-
347
-
348
-    /**
349
-     * get Attendee short bio
350
-     *
351
-     * @return string
352
-     * @throws EE_Error
353
-     */
354
-    public function short_bio()
355
-    {
356
-        return $this->get('ATT_short_bio');
357
-    }
358
-
359
-
360
-    /**
361
-     * Gets the attendee's full address as an array
362
-     * so client code can decide hwo to display it
363
-     *
364
-     * @return array numerically indexed,
365
-     *               with each part of the address that is known.
366
-     *               Eg, if the user only responded to state and country,
367
-     *               it would be array(0=>'Alabama',1=>'USA')
368
-     * @return array
369
-     * @throws EE_Error
370
-     * @throws ReflectionException
371
-     */
372
-    public function full_address_as_array()
373
-    {
374
-        $full_address_array     = [];
375
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
376
-        foreach ($initial_address_fields as $address_field_name) {
377
-            $address_fields_value = $this->get($address_field_name);
378
-            if (! empty($address_fields_value)) {
379
-                $full_address_array[] = $address_fields_value;
380
-            }
381
-        }
382
-        // now handle state and country
383
-        $state_obj = $this->state_obj();
384
-        if ($state_obj instanceof EE_State) {
385
-            $full_address_array[] = $state_obj->name();
386
-        }
387
-        $country_obj = $this->country_obj();
388
-        if ($country_obj instanceof EE_Country) {
389
-            $full_address_array[] = $country_obj->name();
390
-        }
391
-        // lastly get the xip
392
-        $zip_value = $this->zip();
393
-        if (! empty($zip_value)) {
394
-            $full_address_array[] = $zip_value;
395
-        }
396
-        return $full_address_array;
397
-    }
398
-
399
-
400
-    /**
401
-     * Gets the state set to this attendee
402
-     *
403
-     * @return EE_Base_Class|EE_State
404
-     * @throws EE_Error
405
-     * @throws ReflectionException
406
-     */
407
-    public function state_obj()
408
-    {
409
-        return $this->get_first_related('State');
410
-    }
411
-
412
-
413
-    /**
414
-     * Gets country set for this attendee
415
-     *
416
-     * @return EE_Base_Class|EE_Country
417
-     * @throws EE_Error
418
-     * @throws ReflectionException
419
-     */
420
-    public function country_obj()
421
-    {
422
-        return $this->get_first_related('Country');
423
-    }
424
-
425
-
426
-    /**
427
-     * get Attendee Zip/Postal Code
428
-     *
429
-     * @return string
430
-     * @throws EE_Error
431
-     */
432
-    public function zip()
433
-    {
434
-        return $this->get('ATT_zip');
435
-    }
436
-
437
-
438
-    /**
439
-     * get deleted
440
-     *
441
-     * @return        bool
442
-     * @throws EE_Error
443
-     */
444
-    public function deleted()
445
-    {
446
-        return $this->get('ATT_deleted');
447
-    }
448
-
449
-
450
-    /**
451
-     * Gets registrations of this attendee
452
-     *
453
-     * @param array $query_params
454
-     * @return array[]|EE_Base_Class[]|EE_Registration[]
455
-     * @throws EE_Error
456
-     * @throws ReflectionException
457
-     */
458
-    public function get_registrations($query_params = [])
459
-    {
460
-        return $this->get_many_related('Registration', $query_params);
461
-    }
462
-
463
-
464
-    /**
465
-     * Gets the most recent registration of this attendee
466
-     *
467
-     * @return EE_Base_Class|EE_Registration
468
-     * @throws EE_Error
469
-     * @throws ReflectionException
470
-     */
471
-    public function get_most_recent_registration()
472
-    {
473
-        return $this->get_first_related(
474
-            'Registration',
475
-            ['order_by' => ['REG_date' => 'DESC']]
476
-        ); // null, 'REG_date', 'DESC', '=', 'OBJECT_K');
477
-    }
478
-
479
-
480
-    /**
481
-     * Gets the most recent registration for this attend at this event
482
-     *
483
-     * @param int $event_id
484
-     * @return EE_Base_Class|EE_Registration
485
-     * @throws EE_Error
486
-     * @throws ReflectionException
487
-     */
488
-    public function get_most_recent_registration_for_event($event_id)
489
-    {
490
-        return $this->get_first_related(
491
-            'Registration',
492
-            [['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
493
-        );
494
-    }
495
-
496
-
497
-    /**
498
-     * returns any events attached to this attendee ($_Event property);
499
-     *
500
-     * @return array
501
-     * @throws EE_Error
502
-     * @throws ReflectionException
503
-     */
504
-    public function events()
505
-    {
506
-        return $this->get_many_related('Event');
507
-    }
508
-
509
-
510
-    /**
511
-     * @return string
512
-     * @throws EE_Error
513
-     * @throws ReflectionException
514
-     */
515
-    public function state_abbrev()
516
-    {
517
-        return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
518
-    }
519
-
520
-
521
-    /**
522
-     * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
523
-     * and keys are their cleaned values.
524
-     *
525
-     * @param EE_Payment_Method $payment_method the _gateway_name property on the gateway class
526
-     * @return EE_Form_Section_Proper|null
527
-     * @throws EE_Error
528
-     * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was
529
-     *                                          used to save the billing info
530
-     */
531
-    public function billing_info_for_payment_method($payment_method)
532
-    {
533
-        $pm_type = $payment_method->type_obj();
534
-        if (! $pm_type instanceof EE_PMT_Base) {
535
-            return null;
536
-        }
537
-        $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
538
-        if (! $billing_info) {
539
-            return null;
540
-        }
541
-        $billing_form = $pm_type->billing_form();
542
-        // double-check the form isn't totally hidden, in which case pretend there is no form
543
-        $form_totally_hidden = true;
544
-        foreach ($billing_form->inputs_in_subsections() as $input) {
545
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
546
-                $form_totally_hidden = false;
547
-                break;
548
-            }
549
-        }
550
-        if ($form_totally_hidden) {
551
-            return null;
552
-        }
553
-        if ($billing_form instanceof EE_Form_Section_Proper) {
554
-            $billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
555
-        }
556
-
557
-        return $billing_form;
558
-    }
559
-
560
-
561
-    /**
562
-     * Gets the postmeta key that holds this attendee's billing info for the
563
-     * specified payment method
564
-     *
565
-     * @param EE_Payment_Method $payment_method
566
-     * @return string
567
-     * @throws EE_Error
568
-     */
569
-    public function get_billing_info_postmeta_name($payment_method)
570
-    {
571
-        if ($payment_method->type_obj() instanceof EE_PMT_Base) {
572
-            return 'billing_info_' . $payment_method->type_obj()->system_name();
573
-        }
574
-        return null;
575
-    }
576
-
577
-
578
-    /**
579
-     * Saves the billing info to the attendee. @param EE_Billing_Attendee_Info_Form $billing_form
580
-     *
581
-     * @param EE_Payment_Method $payment_method
582
-     * @return boolean
583
-     * @throws EE_Error
584
-     * @see EE_Attendee::billing_info_for_payment_method() which is used to
585
-     *      retrieve it
586
-     */
587
-    public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
588
-    {
589
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
590
-            EE_Error::add_error(
591
-                __('Cannot save billing info because there is none.', 'event_espresso'),
592
-                __FILE__,
593
-                __FUNCTION__,
594
-                __LINE__
595
-            );
596
-            return false;
597
-        }
598
-        $billing_form->clean_sensitive_data();
599
-        return update_post_meta(
600
-            $this->ID(),
601
-            $this->get_billing_info_postmeta_name($payment_method),
602
-            $billing_form->input_values(true)
603
-        );
604
-    }
605
-
606
-
607
-    /**
608
-     * Return the link to the admin details for the object.
609
-     *
610
-     * @return string
611
-     * @throws EE_Error
612
-     * @throws InvalidArgumentException
613
-     * @throws InvalidDataTypeException
614
-     * @throws InvalidInterfaceException
615
-     * @throws ReflectionException
616
-     */
617
-    public function get_admin_details_link()
618
-    {
619
-        return $this->get_admin_edit_link();
620
-    }
621
-
622
-
623
-    /**
624
-     * Returns the link to the editor for the object.  Sometimes this is the same as the details.
625
-     *
626
-     * @return string
627
-     * @throws EE_Error
628
-     * @throws InvalidArgumentException
629
-     * @throws ReflectionException
630
-     * @throws InvalidDataTypeException
631
-     * @throws InvalidInterfaceException
632
-     */
633
-    public function get_admin_edit_link()
634
-    {
635
-        EE_Registry::instance()->load_helper('URL');
636
-        return EEH_URL::add_query_args_and_nonce(
637
-            [
638
-                'page'   => 'espresso_registrations',
639
-                'action' => 'edit_attendee',
640
-                'post'   => $this->ID(),
641
-            ],
642
-            admin_url('admin.php')
643
-        );
644
-    }
645
-
646
-
647
-    /**
648
-     * get Attendee Address
649
-     *
650
-     * @return string
651
-     * @throws EE_Error
652
-     */
653
-    public function address()
654
-    {
655
-        return $this->get('ATT_address');
656
-    }
657
-
658
-
659
-    /**
660
-     * Returns the link to a settings page for the object.
661
-     *
662
-     * @return string
663
-     * @throws EE_Error
664
-     * @throws InvalidArgumentException
665
-     * @throws InvalidDataTypeException
666
-     * @throws InvalidInterfaceException
667
-     * @throws ReflectionException
668
-     */
669
-    public function get_admin_settings_link()
670
-    {
671
-        return $this->get_admin_edit_link();
672
-    }
673
-
674
-
675
-    /**
676
-     * Returns the link to the "overview" for the object (typically the "list table" view).
677
-     *
678
-     * @return string
679
-     * @throws EE_Error
680
-     * @throws InvalidArgumentException
681
-     * @throws ReflectionException
682
-     * @throws InvalidDataTypeException
683
-     * @throws InvalidInterfaceException
684
-     */
685
-    public function get_admin_overview_link()
686
-    {
687
-        EE_Registry::instance()->load_helper('URL');
688
-        return EEH_URL::add_query_args_and_nonce(
689
-            [
690
-                'page'   => 'espresso_registrations',
691
-                'action' => 'contact_list',
692
-            ],
693
-            admin_url('admin.php')
694
-        );
695
-    }
696
-
697
-
698
-
699
-
700
-
701
-
702
-
703
-
704
-    /**
705
-     * get Attendee Address2
706
-     *
707
-     * @return string
708
-     * @throws EE_Error
709
-     */
710
-    public function address2()
711
-    {
712
-        return $this->get('ATT_address2');
713
-    }
714
-
715
-
716
-    /**
717
-     * Returns the state's name, otherwise 'Unknown'
718
-     *
719
-     * @return string
720
-     * @throws EE_Error
721
-     * @throws ReflectionException
722
-     */
723
-    public function state_name()
724
-    {
725
-        if ($this->state_obj()) {
726
-            return $this->state_obj()->name();
727
-        } else {
728
-            return '';
729
-        }
730
-    }
731
-
732
-
733
-    /**
734
-     * get Attendee City
735
-     *
736
-     * @return string
737
-     * @throws EE_Error
738
-     */
739
-    public function city()
740
-    {
741
-        return $this->get('ATT_city');
742
-    }
743
-
744
-
745
-    /**
746
-     * either displays the state abbreviation or the state name, as determined
747
-     * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
748
-     * defaults to abbreviation
749
-     *
750
-     * @return string
751
-     * @throws EE_Error
752
-     * @throws ReflectionException
753
-     */
754
-    public function state()
755
-    {
756
-        if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
757
-            return $this->state_abbrev();
758
-        }
759
-        return $this->state_name();
760
-    }
761
-
762
-
763
-    /**
764
-     * get Attendee State ID
765
-     *
766
-     * @return string
767
-     * @throws EE_Error
768
-     */
769
-    public function state_ID()
770
-    {
771
-        return $this->get('STA_ID');
772
-    }
773
-
774
-
775
-    /**
776
-     * get Attendee Country ISO Code
777
-     *
778
-     * @return string
779
-     * @throws EE_Error
780
-     */
781
-    public function country_ID()
782
-    {
783
-        return $this->get('CNT_ISO');
784
-    }
785
-
786
-
787
-    /**
788
-     * Returns the country's name if known, otherwise 'Unknown'
789
-     *
790
-     * @return string
791
-     * @throws EE_Error
792
-     * @throws ReflectionException
793
-     */
794
-    public function country_name()
795
-    {
796
-        if ($this->country_obj()) {
797
-            return $this->country_obj()->name();
798
-        }
799
-        return '';
800
-    }
801
-
802
-
803
-    /**
804
-     * either displays the country ISO2 code or the country name, as determined
805
-     * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
806
-     * defaults to abbreviation
807
-     *
808
-     * @return string
809
-     * @throws EE_Error
810
-     * @throws ReflectionException
811
-     */
812
-    public function country()
813
-    {
814
-        if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
815
-            return $this->country_ID();
816
-        }
817
-        return $this->country_name();
818
-    }
16
+	/**
17
+	 * Sets some dynamic defaults
18
+	 *
19
+	 * @param array  $fieldValues
20
+	 * @param bool   $bydb
21
+	 * @param string $timezone
22
+	 * @param array  $date_formats
23
+	 * @throws EE_Error
24
+	 * @throws ReflectionException
25
+	 */
26
+	protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = [])
27
+	{
28
+		if (! isset($fieldValues['ATT_full_name'])) {
29
+			$fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
30
+			$lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
31
+			$fieldValues['ATT_full_name'] = $fname . $lname;
32
+		}
33
+		if (! isset($fieldValues['ATT_slug'])) {
34
+			// $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
35
+			$fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
36
+		}
37
+		if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
38
+			$fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
39
+		}
40
+		parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
41
+	}
42
+
43
+
44
+	/**
45
+	 * @param array  $props_n_values    incoming values
46
+	 * @param string $timezone          incoming timezone
47
+	 *                                  (if not set the timezone set for the website will be used.)
48
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
49
+	 *                                  date_format and the second value is the time format
50
+	 * @return EE_Attendee
51
+	 * @throws EE_Error
52
+	 * @throws ReflectionException
53
+	 */
54
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
55
+	{
56
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
57
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
58
+	}
59
+
60
+
61
+	/**
62
+	 * @param array  $props_n_values  incoming values from the database
63
+	 * @param string $timezone        incoming timezone as set by the model.
64
+	 *                                If not set the timezone for the website will be used.
65
+	 * @return EE_Attendee
66
+	 * @throws EE_Error
67
+	 * @throws EE_Error
68
+	 * @throws ReflectionException
69
+	 */
70
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
71
+	{
72
+		return new self($props_n_values, true, $timezone);
73
+	}
74
+
75
+
76
+	/**
77
+	 * Set Attendee First Name
78
+	 *
79
+	 * @param string $fname
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	public function set_fname($fname = '')
84
+	{
85
+		$this->set('ATT_fname', $fname);
86
+	}
87
+
88
+
89
+	/**
90
+	 * Set Attendee Last Name
91
+	 *
92
+	 * @param string $lname
93
+	 * @throws EE_Error
94
+	 * @throws ReflectionException
95
+	 */
96
+	public function set_lname($lname = '')
97
+	{
98
+		$this->set('ATT_lname', $lname);
99
+	}
100
+
101
+
102
+	/**
103
+	 * Set Attendee Address
104
+	 *
105
+	 * @param string $address
106
+	 * @throws EE_Error
107
+	 * @throws ReflectionException
108
+	 */
109
+	public function set_address($address = '')
110
+	{
111
+		$this->set('ATT_address', $address);
112
+	}
113
+
114
+
115
+	/**
116
+	 * Set Attendee Address2
117
+	 *
118
+	 * @param string $address2
119
+	 * @throws EE_Error
120
+	 * @throws ReflectionException
121
+	 */
122
+	public function set_address2($address2 = '')
123
+	{
124
+		$this->set('ATT_address2', $address2);
125
+	}
126
+
127
+
128
+	/**
129
+	 * Set Attendee City
130
+	 *
131
+	 * @param string $city
132
+	 * @throws EE_Error
133
+	 * @throws ReflectionException
134
+	 */
135
+	public function set_city($city = '')
136
+	{
137
+		$this->set('ATT_city', $city);
138
+	}
139
+
140
+
141
+	/**
142
+	 * Set Attendee State ID
143
+	 *
144
+	 * @param int $STA_ID
145
+	 * @throws EE_Error
146
+	 * @throws ReflectionException
147
+	 */
148
+	public function set_state($STA_ID = 0)
149
+	{
150
+		$this->set('STA_ID', $STA_ID);
151
+	}
152
+
153
+
154
+	/**
155
+	 * Set Attendee Country ISO Code
156
+	 *
157
+	 * @param string $CNT_ISO
158
+	 * @throws EE_Error
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function set_country($CNT_ISO = '')
162
+	{
163
+		$this->set('CNT_ISO', $CNT_ISO);
164
+	}
165
+
166
+
167
+	/**
168
+	 * Set Attendee Zip/Postal Code
169
+	 *
170
+	 * @param string $zip
171
+	 * @throws EE_Error
172
+	 * @throws ReflectionException
173
+	 */
174
+	public function set_zip($zip = '')
175
+	{
176
+		$this->set('ATT_zip', $zip);
177
+	}
178
+
179
+
180
+	/**
181
+	 * Set Attendee Email Address
182
+	 *
183
+	 * @param string $email
184
+	 * @throws EE_Error
185
+	 * @throws ReflectionException
186
+	 */
187
+	public function set_email($email = '')
188
+	{
189
+		$this->set('ATT_email', $email);
190
+	}
191
+
192
+
193
+	/**
194
+	 * Set Attendee Phone
195
+	 *
196
+	 * @param string $phone
197
+	 * @throws EE_Error
198
+	 * @throws ReflectionException
199
+	 */
200
+	public function set_phone($phone = '')
201
+	{
202
+		$this->set('ATT_phone', $phone);
203
+	}
204
+
205
+
206
+	/**
207
+	 * set deleted
208
+	 *
209
+	 * @param bool $ATT_deleted
210
+	 * @throws EE_Error
211
+	 * @throws ReflectionException
212
+	 */
213
+	public function set_deleted($ATT_deleted = false)
214
+	{
215
+		$this->set('ATT_deleted', $ATT_deleted);
216
+	}
217
+
218
+
219
+	/**
220
+	 * Returns the value for the post_author id saved with the cpt
221
+	 *
222
+	 * @return int
223
+	 * @throws EE_Error
224
+	 * @since 4.5.0
225
+	 */
226
+	public function wp_user()
227
+	{
228
+		return $this->get('ATT_author');
229
+	}
230
+
231
+
232
+	/**
233
+	 * echoes out the attendee's first name
234
+	 *
235
+	 * @return void
236
+	 * @throws EE_Error
237
+	 */
238
+	public function e_full_name()
239
+	{
240
+		echo $this->full_name();
241
+	}
242
+
243
+
244
+	/**
245
+	 * Returns the first and last name concatenated together with a space.
246
+	 *
247
+	 * @param bool $apply_html_entities
248
+	 * @return string
249
+	 * @throws EE_Error
250
+	 */
251
+	public function full_name($apply_html_entities = false)
252
+	{
253
+		$full_name = [
254
+			$this->fname(),
255
+			$this->lname(),
256
+		];
257
+		$full_name = array_filter($full_name);
258
+		$full_name = implode(' ', $full_name);
259
+		return $apply_html_entities
260
+			? htmlentities($full_name, ENT_QUOTES, 'UTF-8')
261
+			: $full_name;
262
+	}
263
+
264
+
265
+	/**
266
+	 * get Attendee First Name
267
+	 *
268
+	 * @return string
269
+	 * @throws EE_Error
270
+	 */
271
+	public function fname()
272
+	{
273
+		return $this->get('ATT_fname');
274
+	}
275
+
276
+
277
+	/**
278
+	 * get Attendee Last Name
279
+	 *
280
+	 * @return string
281
+	 * @throws EE_Error
282
+	 */
283
+	public function lname()
284
+	{
285
+		return $this->get('ATT_lname');
286
+	}
287
+
288
+
289
+	/**
290
+	 * get Attendee Email Address
291
+	 *
292
+	 * @return string
293
+	 * @throws EE_Error
294
+	 */
295
+	public function email()
296
+	{
297
+		return $this->get('ATT_email');
298
+	}
299
+
300
+
301
+	/**
302
+	 * get Attendee Phone #
303
+	 *
304
+	 * @return string
305
+	 * @throws EE_Error
306
+	 */
307
+	public function phone()
308
+	{
309
+		return $this->get('ATT_phone');
310
+	}
311
+
312
+
313
+	/**
314
+	 * This returns the value of the `ATT_full_name` field
315
+	 * which is usually equivalent to calling `full_name()`
316
+	 * unless the post_title field has been directly modified
317
+	 * in the db for the post (espresso_attendees post type)
318
+	 * for this attendee.
319
+	 *
320
+	 * @param bool $apply_html_entities
321
+	 * @return string
322
+	 * @throws EE_Error
323
+	 */
324
+	public function ATT_full_name($apply_html_entities = false)
325
+	{
326
+		return $apply_html_entities
327
+			? htmlentities(
328
+				$this->get('ATT_full_name'),
329
+				ENT_QUOTES,
330
+				'UTF-8'
331
+			)
332
+			: $this->get('ATT_full_name');
333
+	}
334
+
335
+
336
+	/**
337
+	 * get Attendee bio
338
+	 *
339
+	 * @return string
340
+	 * @throws EE_Error
341
+	 */
342
+	public function bio()
343
+	{
344
+		return $this->get('ATT_bio');
345
+	}
346
+
347
+
348
+	/**
349
+	 * get Attendee short bio
350
+	 *
351
+	 * @return string
352
+	 * @throws EE_Error
353
+	 */
354
+	public function short_bio()
355
+	{
356
+		return $this->get('ATT_short_bio');
357
+	}
358
+
359
+
360
+	/**
361
+	 * Gets the attendee's full address as an array
362
+	 * so client code can decide hwo to display it
363
+	 *
364
+	 * @return array numerically indexed,
365
+	 *               with each part of the address that is known.
366
+	 *               Eg, if the user only responded to state and country,
367
+	 *               it would be array(0=>'Alabama',1=>'USA')
368
+	 * @return array
369
+	 * @throws EE_Error
370
+	 * @throws ReflectionException
371
+	 */
372
+	public function full_address_as_array()
373
+	{
374
+		$full_address_array     = [];
375
+		$initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
376
+		foreach ($initial_address_fields as $address_field_name) {
377
+			$address_fields_value = $this->get($address_field_name);
378
+			if (! empty($address_fields_value)) {
379
+				$full_address_array[] = $address_fields_value;
380
+			}
381
+		}
382
+		// now handle state and country
383
+		$state_obj = $this->state_obj();
384
+		if ($state_obj instanceof EE_State) {
385
+			$full_address_array[] = $state_obj->name();
386
+		}
387
+		$country_obj = $this->country_obj();
388
+		if ($country_obj instanceof EE_Country) {
389
+			$full_address_array[] = $country_obj->name();
390
+		}
391
+		// lastly get the xip
392
+		$zip_value = $this->zip();
393
+		if (! empty($zip_value)) {
394
+			$full_address_array[] = $zip_value;
395
+		}
396
+		return $full_address_array;
397
+	}
398
+
399
+
400
+	/**
401
+	 * Gets the state set to this attendee
402
+	 *
403
+	 * @return EE_Base_Class|EE_State
404
+	 * @throws EE_Error
405
+	 * @throws ReflectionException
406
+	 */
407
+	public function state_obj()
408
+	{
409
+		return $this->get_first_related('State');
410
+	}
411
+
412
+
413
+	/**
414
+	 * Gets country set for this attendee
415
+	 *
416
+	 * @return EE_Base_Class|EE_Country
417
+	 * @throws EE_Error
418
+	 * @throws ReflectionException
419
+	 */
420
+	public function country_obj()
421
+	{
422
+		return $this->get_first_related('Country');
423
+	}
424
+
425
+
426
+	/**
427
+	 * get Attendee Zip/Postal Code
428
+	 *
429
+	 * @return string
430
+	 * @throws EE_Error
431
+	 */
432
+	public function zip()
433
+	{
434
+		return $this->get('ATT_zip');
435
+	}
436
+
437
+
438
+	/**
439
+	 * get deleted
440
+	 *
441
+	 * @return        bool
442
+	 * @throws EE_Error
443
+	 */
444
+	public function deleted()
445
+	{
446
+		return $this->get('ATT_deleted');
447
+	}
448
+
449
+
450
+	/**
451
+	 * Gets registrations of this attendee
452
+	 *
453
+	 * @param array $query_params
454
+	 * @return array[]|EE_Base_Class[]|EE_Registration[]
455
+	 * @throws EE_Error
456
+	 * @throws ReflectionException
457
+	 */
458
+	public function get_registrations($query_params = [])
459
+	{
460
+		return $this->get_many_related('Registration', $query_params);
461
+	}
462
+
463
+
464
+	/**
465
+	 * Gets the most recent registration of this attendee
466
+	 *
467
+	 * @return EE_Base_Class|EE_Registration
468
+	 * @throws EE_Error
469
+	 * @throws ReflectionException
470
+	 */
471
+	public function get_most_recent_registration()
472
+	{
473
+		return $this->get_first_related(
474
+			'Registration',
475
+			['order_by' => ['REG_date' => 'DESC']]
476
+		); // null, 'REG_date', 'DESC', '=', 'OBJECT_K');
477
+	}
478
+
479
+
480
+	/**
481
+	 * Gets the most recent registration for this attend at this event
482
+	 *
483
+	 * @param int $event_id
484
+	 * @return EE_Base_Class|EE_Registration
485
+	 * @throws EE_Error
486
+	 * @throws ReflectionException
487
+	 */
488
+	public function get_most_recent_registration_for_event($event_id)
489
+	{
490
+		return $this->get_first_related(
491
+			'Registration',
492
+			[['EVT_ID' => $event_id], 'order_by' => ['REG_date' => 'DESC']]
493
+		);
494
+	}
495
+
496
+
497
+	/**
498
+	 * returns any events attached to this attendee ($_Event property);
499
+	 *
500
+	 * @return array
501
+	 * @throws EE_Error
502
+	 * @throws ReflectionException
503
+	 */
504
+	public function events()
505
+	{
506
+		return $this->get_many_related('Event');
507
+	}
508
+
509
+
510
+	/**
511
+	 * @return string
512
+	 * @throws EE_Error
513
+	 * @throws ReflectionException
514
+	 */
515
+	public function state_abbrev()
516
+	{
517
+		return $this->state_obj() instanceof EE_State ? $this->state_obj()->abbrev() : '';
518
+	}
519
+
520
+
521
+	/**
522
+	 * Gets the billing info array where keys match espresso_reg_page_billing_inputs(),
523
+	 * and keys are their cleaned values.
524
+	 *
525
+	 * @param EE_Payment_Method $payment_method the _gateway_name property on the gateway class
526
+	 * @return EE_Form_Section_Proper|null
527
+	 * @throws EE_Error
528
+	 * @see EE_Attendee::save_and_clean_billing_info_for_payment_method() which was
529
+	 *                                          used to save the billing info
530
+	 */
531
+	public function billing_info_for_payment_method($payment_method)
532
+	{
533
+		$pm_type = $payment_method->type_obj();
534
+		if (! $pm_type instanceof EE_PMT_Base) {
535
+			return null;
536
+		}
537
+		$billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
538
+		if (! $billing_info) {
539
+			return null;
540
+		}
541
+		$billing_form = $pm_type->billing_form();
542
+		// double-check the form isn't totally hidden, in which case pretend there is no form
543
+		$form_totally_hidden = true;
544
+		foreach ($billing_form->inputs_in_subsections() as $input) {
545
+			if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
546
+				$form_totally_hidden = false;
547
+				break;
548
+			}
549
+		}
550
+		if ($form_totally_hidden) {
551
+			return null;
552
+		}
553
+		if ($billing_form instanceof EE_Form_Section_Proper) {
554
+			$billing_form->receive_form_submission([$billing_form->name() => $billing_info], false);
555
+		}
556
+
557
+		return $billing_form;
558
+	}
559
+
560
+
561
+	/**
562
+	 * Gets the postmeta key that holds this attendee's billing info for the
563
+	 * specified payment method
564
+	 *
565
+	 * @param EE_Payment_Method $payment_method
566
+	 * @return string
567
+	 * @throws EE_Error
568
+	 */
569
+	public function get_billing_info_postmeta_name($payment_method)
570
+	{
571
+		if ($payment_method->type_obj() instanceof EE_PMT_Base) {
572
+			return 'billing_info_' . $payment_method->type_obj()->system_name();
573
+		}
574
+		return null;
575
+	}
576
+
577
+
578
+	/**
579
+	 * Saves the billing info to the attendee. @param EE_Billing_Attendee_Info_Form $billing_form
580
+	 *
581
+	 * @param EE_Payment_Method $payment_method
582
+	 * @return boolean
583
+	 * @throws EE_Error
584
+	 * @see EE_Attendee::billing_info_for_payment_method() which is used to
585
+	 *      retrieve it
586
+	 */
587
+	public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
588
+	{
589
+		if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
590
+			EE_Error::add_error(
591
+				__('Cannot save billing info because there is none.', 'event_espresso'),
592
+				__FILE__,
593
+				__FUNCTION__,
594
+				__LINE__
595
+			);
596
+			return false;
597
+		}
598
+		$billing_form->clean_sensitive_data();
599
+		return update_post_meta(
600
+			$this->ID(),
601
+			$this->get_billing_info_postmeta_name($payment_method),
602
+			$billing_form->input_values(true)
603
+		);
604
+	}
605
+
606
+
607
+	/**
608
+	 * Return the link to the admin details for the object.
609
+	 *
610
+	 * @return string
611
+	 * @throws EE_Error
612
+	 * @throws InvalidArgumentException
613
+	 * @throws InvalidDataTypeException
614
+	 * @throws InvalidInterfaceException
615
+	 * @throws ReflectionException
616
+	 */
617
+	public function get_admin_details_link()
618
+	{
619
+		return $this->get_admin_edit_link();
620
+	}
621
+
622
+
623
+	/**
624
+	 * Returns the link to the editor for the object.  Sometimes this is the same as the details.
625
+	 *
626
+	 * @return string
627
+	 * @throws EE_Error
628
+	 * @throws InvalidArgumentException
629
+	 * @throws ReflectionException
630
+	 * @throws InvalidDataTypeException
631
+	 * @throws InvalidInterfaceException
632
+	 */
633
+	public function get_admin_edit_link()
634
+	{
635
+		EE_Registry::instance()->load_helper('URL');
636
+		return EEH_URL::add_query_args_and_nonce(
637
+			[
638
+				'page'   => 'espresso_registrations',
639
+				'action' => 'edit_attendee',
640
+				'post'   => $this->ID(),
641
+			],
642
+			admin_url('admin.php')
643
+		);
644
+	}
645
+
646
+
647
+	/**
648
+	 * get Attendee Address
649
+	 *
650
+	 * @return string
651
+	 * @throws EE_Error
652
+	 */
653
+	public function address()
654
+	{
655
+		return $this->get('ATT_address');
656
+	}
657
+
658
+
659
+	/**
660
+	 * Returns the link to a settings page for the object.
661
+	 *
662
+	 * @return string
663
+	 * @throws EE_Error
664
+	 * @throws InvalidArgumentException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws InvalidInterfaceException
667
+	 * @throws ReflectionException
668
+	 */
669
+	public function get_admin_settings_link()
670
+	{
671
+		return $this->get_admin_edit_link();
672
+	}
673
+
674
+
675
+	/**
676
+	 * Returns the link to the "overview" for the object (typically the "list table" view).
677
+	 *
678
+	 * @return string
679
+	 * @throws EE_Error
680
+	 * @throws InvalidArgumentException
681
+	 * @throws ReflectionException
682
+	 * @throws InvalidDataTypeException
683
+	 * @throws InvalidInterfaceException
684
+	 */
685
+	public function get_admin_overview_link()
686
+	{
687
+		EE_Registry::instance()->load_helper('URL');
688
+		return EEH_URL::add_query_args_and_nonce(
689
+			[
690
+				'page'   => 'espresso_registrations',
691
+				'action' => 'contact_list',
692
+			],
693
+			admin_url('admin.php')
694
+		);
695
+	}
696
+
697
+
698
+
699
+
700
+
701
+
702
+
703
+
704
+	/**
705
+	 * get Attendee Address2
706
+	 *
707
+	 * @return string
708
+	 * @throws EE_Error
709
+	 */
710
+	public function address2()
711
+	{
712
+		return $this->get('ATT_address2');
713
+	}
714
+
715
+
716
+	/**
717
+	 * Returns the state's name, otherwise 'Unknown'
718
+	 *
719
+	 * @return string
720
+	 * @throws EE_Error
721
+	 * @throws ReflectionException
722
+	 */
723
+	public function state_name()
724
+	{
725
+		if ($this->state_obj()) {
726
+			return $this->state_obj()->name();
727
+		} else {
728
+			return '';
729
+		}
730
+	}
731
+
732
+
733
+	/**
734
+	 * get Attendee City
735
+	 *
736
+	 * @return string
737
+	 * @throws EE_Error
738
+	 */
739
+	public function city()
740
+	{
741
+		return $this->get('ATT_city');
742
+	}
743
+
744
+
745
+	/**
746
+	 * either displays the state abbreviation or the state name, as determined
747
+	 * by the "FHEE__EEI_Address__state__use_abbreviation" filter.
748
+	 * defaults to abbreviation
749
+	 *
750
+	 * @return string
751
+	 * @throws EE_Error
752
+	 * @throws ReflectionException
753
+	 */
754
+	public function state()
755
+	{
756
+		if (apply_filters('FHEE__EEI_Address__state__use_abbreviation', true, $this->state_obj())) {
757
+			return $this->state_abbrev();
758
+		}
759
+		return $this->state_name();
760
+	}
761
+
762
+
763
+	/**
764
+	 * get Attendee State ID
765
+	 *
766
+	 * @return string
767
+	 * @throws EE_Error
768
+	 */
769
+	public function state_ID()
770
+	{
771
+		return $this->get('STA_ID');
772
+	}
773
+
774
+
775
+	/**
776
+	 * get Attendee Country ISO Code
777
+	 *
778
+	 * @return string
779
+	 * @throws EE_Error
780
+	 */
781
+	public function country_ID()
782
+	{
783
+		return $this->get('CNT_ISO');
784
+	}
785
+
786
+
787
+	/**
788
+	 * Returns the country's name if known, otherwise 'Unknown'
789
+	 *
790
+	 * @return string
791
+	 * @throws EE_Error
792
+	 * @throws ReflectionException
793
+	 */
794
+	public function country_name()
795
+	{
796
+		if ($this->country_obj()) {
797
+			return $this->country_obj()->name();
798
+		}
799
+		return '';
800
+	}
801
+
802
+
803
+	/**
804
+	 * either displays the country ISO2 code or the country name, as determined
805
+	 * by the "FHEE__EEI_Address__country__use_abbreviation" filter.
806
+	 * defaults to abbreviation
807
+	 *
808
+	 * @return string
809
+	 * @throws EE_Error
810
+	 * @throws ReflectionException
811
+	 */
812
+	public function country()
813
+	{
814
+		if (apply_filters('FHEE__EEI_Address__country__use_abbreviation', true, $this->country_obj())) {
815
+			return $this->country_ID();
816
+		}
817
+		return $this->country_name();
818
+	}
819 819
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -25,16 +25,16 @@  discard block
 block discarded – undo
25 25
      */
26 26
     protected function __construct($fieldValues = null, $bydb = false, $timezone = null, $date_formats = [])
27 27
     {
28
-        if (! isset($fieldValues['ATT_full_name'])) {
29
-            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'] . ' ' : '';
28
+        if ( ! isset($fieldValues['ATT_full_name'])) {
29
+            $fname                        = isset($fieldValues['ATT_fname']) ? $fieldValues['ATT_fname'].' ' : '';
30 30
             $lname                        = isset($fieldValues['ATT_lname']) ? $fieldValues['ATT_lname'] : '';
31
-            $fieldValues['ATT_full_name'] = $fname . $lname;
31
+            $fieldValues['ATT_full_name'] = $fname.$lname;
32 32
         }
33
-        if (! isset($fieldValues['ATT_slug'])) {
33
+        if ( ! isset($fieldValues['ATT_slug'])) {
34 34
             // $fieldValues['ATT_slug'] = sanitize_key(wp_generate_password(20));
35 35
             $fieldValues['ATT_slug'] = sanitize_title($fieldValues['ATT_full_name']);
36 36
         }
37
-        if (! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
37
+        if ( ! isset($fieldValues['ATT_short_bio']) && isset($fieldValues['ATT_bio'])) {
38 38
             $fieldValues['ATT_short_bio'] = substr($fieldValues['ATT_bio'], 0, 50);
39 39
         }
40 40
         parent::__construct($fieldValues, $bydb, $timezone, $date_formats);
@@ -372,10 +372,10 @@  discard block
 block discarded – undo
372 372
     public function full_address_as_array()
373 373
     {
374 374
         $full_address_array     = [];
375
-        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city',];
375
+        $initial_address_fields = ['ATT_address', 'ATT_address2', 'ATT_city', ];
376 376
         foreach ($initial_address_fields as $address_field_name) {
377 377
             $address_fields_value = $this->get($address_field_name);
378
-            if (! empty($address_fields_value)) {
378
+            if ( ! empty($address_fields_value)) {
379 379
                 $full_address_array[] = $address_fields_value;
380 380
             }
381 381
         }
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
         }
391 391
         // lastly get the xip
392 392
         $zip_value = $this->zip();
393
-        if (! empty($zip_value)) {
393
+        if ( ! empty($zip_value)) {
394 394
             $full_address_array[] = $zip_value;
395 395
         }
396 396
         return $full_address_array;
@@ -531,18 +531,18 @@  discard block
 block discarded – undo
531 531
     public function billing_info_for_payment_method($payment_method)
532 532
     {
533 533
         $pm_type = $payment_method->type_obj();
534
-        if (! $pm_type instanceof EE_PMT_Base) {
534
+        if ( ! $pm_type instanceof EE_PMT_Base) {
535 535
             return null;
536 536
         }
537 537
         $billing_info = $this->get_post_meta($this->get_billing_info_postmeta_name($payment_method), true);
538
-        if (! $billing_info) {
538
+        if ( ! $billing_info) {
539 539
             return null;
540 540
         }
541 541
         $billing_form = $pm_type->billing_form();
542 542
         // double-check the form isn't totally hidden, in which case pretend there is no form
543 543
         $form_totally_hidden = true;
544 544
         foreach ($billing_form->inputs_in_subsections() as $input) {
545
-            if (! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
545
+            if ( ! $input->get_display_strategy() instanceof EE_Hidden_Display_Strategy) {
546 546
                 $form_totally_hidden = false;
547 547
                 break;
548 548
             }
@@ -569,7 +569,7 @@  discard block
 block discarded – undo
569 569
     public function get_billing_info_postmeta_name($payment_method)
570 570
     {
571 571
         if ($payment_method->type_obj() instanceof EE_PMT_Base) {
572
-            return 'billing_info_' . $payment_method->type_obj()->system_name();
572
+            return 'billing_info_'.$payment_method->type_obj()->system_name();
573 573
         }
574 574
         return null;
575 575
     }
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
      */
587 587
     public function save_and_clean_billing_info_for_payment_method($billing_form, $payment_method)
588 588
     {
589
-        if (! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
589
+        if ( ! $billing_form instanceof EE_Billing_Attendee_Info_Form) {
590 590
             EE_Error::add_error(
591 591
                 __('Cannot save billing info because there is none.', 'event_espresso'),
592 592
                 __FILE__,
Please login to merge, or discard this patch.
core/db_classes/EE_CPT_Base.class.php 3 patches
Doc Comments   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
      *
168 168
      * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
169 169
      * @access protected
170
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
170
+     * @param string $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
171 171
      *                           representing width and height in pixels (i.e. array(32,32) ).
172 172
      * @param string|array $attr Optional. Query string or array of attributes.
173 173
      * @return string HTML image element
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
      * This is a method for restoring this_obj using details from the given $revision_id
212 212
      *
213 213
      * @param int   $revision_id       ID of the revision we're getting data from
214
-     * @param array $related_obj_names if included this will be used to restore for related obj
214
+     * @param string[] $related_obj_names if included this will be used to restore for related obj
215 215
      *                                 if not included then we just do restore on the meta.
216 216
      *                                 We will accept an array of related_obj_names for restoration here.
217 217
      * @param array $where_query       You can optionally include an array of key=>value pairs
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
      *
278 278
      * @param string  $meta_key
279 279
      * @param boolean $single
280
-     * @return mixed
280
+     * @return string|null
281 281
      * @throws EE_Error
282 282
      */
283 283
     public function get_post_meta($meta_key = null, $single = false)
@@ -312,8 +312,8 @@  discard block
 block discarded – undo
312 312
     /**
313 313
      * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
314 314
      *
315
-     * @param mixed $meta_key
316
-     * @param mixed $meta_value
315
+     * @param string $meta_key
316
+     * @param string $meta_value
317 317
      * @param bool  $unique     If postmeta for this $meta_key already exists,
318 318
      *                          whether to add an additional item or not
319 319
      * @return boolean          Boolean true, except if the $unique argument was set to true
@@ -334,7 +334,7 @@  discard block
 block discarded – undo
334 334
     /**
335 335
      * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
336 336
      *
337
-     * @param mixed $meta_key
337
+     * @param string $meta_key
338 338
      * @param mixed $meta_value
339 339
      * @return boolean False for failure. True for success.
340 340
      * @throws EE_Error
Please login to merge, or discard this patch.
Indentation   +483 added lines, -483 removed lines patch added patch discarded remove patch
@@ -12,487 +12,487 @@
 block discarded – undo
12 12
 abstract class EE_CPT_Base extends EE_Soft_Delete_Base_Class
13 13
 {
14 14
 
15
-    /**
16
-     * This is a property for holding cached feature images on CPT objects.
17
-     * Cache's are set on the first "feature_image()" method call.
18
-     * Each key in the array corresponds to the requested size.
19
-     *
20
-     * @var array
21
-     */
22
-    protected $_feature_image = [];
23
-
24
-    /**
25
-     * @var WP_Post the WP_Post that corresponds with this CPT model object
26
-     */
27
-    protected $_wp_post;
28
-
29
-
30
-    abstract public function wp_user();
31
-
32
-
33
-    /**
34
-     * Adds to the specified event category. If it category doesn't exist, creates it.
35
-     *
36
-     * @param string $category_name
37
-     * @param string $category_description    optional
38
-     * @param int    $parent_term_taxonomy_id optional
39
-     * @return EE_Term_Taxonomy
40
-     * @throws EE_Error
41
-     * @throws ReflectionException
42
-     */
43
-    public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
44
-    {
45
-        return $this->get_model()->add_event_category(
46
-            $this,
47
-            $category_name,
48
-            $category_description,
49
-            $parent_term_taxonomy_id
50
-        );
51
-    }
52
-
53
-
54
-    /**
55
-     * Removes the event category by specified name from being related ot this event
56
-     *
57
-     * @param string $category_name
58
-     * @return bool
59
-     * @throws EE_Error
60
-     * @throws ReflectionException
61
-     */
62
-    public function remove_event_category($category_name)
63
-    {
64
-        return $this->get_model()->remove_event_category($this, $category_name);
65
-    }
66
-
67
-
68
-    /**
69
-     * Removes the relation to the specified term taxonomy, and maintains the
70
-     * data integrity of the term taxonomy provided
71
-     *
72
-     * @param EE_Term_Taxonomy $term_taxonomy
73
-     * @return EE_Base_Class the relation was removed from
74
-     * @throws EE_Error
75
-     * @throws ReflectionException
76
-     */
77
-    public function remove_relation_to_term_taxonomy($term_taxonomy)
78
-    {
79
-        if (! $term_taxonomy) {
80
-            EE_Error::add_error(
81
-                sprintf(
82
-                    esc_html__(
83
-                        "No Term_Taxonomy provided which to remove from model object of type %s and id %d",
84
-                        "event_espresso"
85
-                    ),
86
-                    get_class($this),
87
-                    $this->ID()
88
-                ),
89
-                __FILE__,
90
-                __FUNCTION__,
91
-                __LINE__
92
-            );
93
-            return null;
94
-        }
95
-        $term_taxonomy->set_count($term_taxonomy->count() - 1);
96
-        $term_taxonomy->save();
97
-        return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
98
-    }
99
-
100
-
101
-    /**
102
-     * The main purpose of this method is to return the post type for the model object
103
-     *
104
-     * @return string
105
-     * @throws EE_Error
106
-     * @throws ReflectionException
107
-     */
108
-    public function post_type()
109
-    {
110
-        return $this->get_model()->post_type();
111
-    }
112
-
113
-
114
-    /**
115
-     * The main purpose of this method is to return the parent for the model object
116
-     *
117
-     * @return int
118
-     * @throws EE_Error
119
-     */
120
-    public function parent()
121
-    {
122
-        return $this->get('parent');
123
-    }
124
-
125
-
126
-    /**
127
-     * return the _status property
128
-     *
129
-     * @return string
130
-     * @throws EE_Error
131
-     */
132
-    public function status()
133
-    {
134
-        return $this->get('status');
135
-    }
136
-
137
-
138
-    /**
139
-     * @param string $status
140
-     * @throws EE_Error
141
-     * @throws ReflectionException
142
-     */
143
-    public function set_status($status)
144
-    {
145
-        $this->set('status', $status);
146
-    }
147
-
148
-
149
-    /**
150
-     * See _get_feature_image. Returns the HTML to display a featured image
151
-     *
152
-     * @param string       $size
153
-     * @param string|array $attr
154
-     * @return string of html
155
-     * @throws EE_Error
156
-     * @throws ReflectionException
157
-     */
158
-    public function feature_image($size = 'thumbnail', $attr = '')
159
-    {
160
-        return $this->_get_feature_image($size, $attr);
161
-    }
162
-
163
-
164
-    /**
165
-     * This calls the equivalent model method for retrieving the feature image
166
-     * which in turn is a wrapper for WordPress' get_the_post_thumbnail() function.
167
-     *
168
-     * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
169
-     * @access protected
170
-     * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
171
-     *                           representing width and height in pixels (i.e. array(32,32) ).
172
-     * @param string|array $attr Optional. Query string or array of attributes.
173
-     * @return string HTML image element
174
-     * @throws EE_Error
175
-     * @throws ReflectionException
176
-     */
177
-    protected function _get_feature_image($size, $attr)
178
-    {
179
-        // first let's see if we already have the _feature_image property set
180
-        // AND if it has a cached element on it FOR the given size
181
-        $attr_key                           = is_array($attr)
182
-            ? implode('_', $attr)
183
-            : $attr;
184
-        $cache_key                          = is_array($size)
185
-            ? implode('_', $size) . $attr_key
186
-            : $size . $attr_key;
187
-        $this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
188
-            ? $this->_feature_image[ $cache_key ]
189
-            : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
190
-        return $this->_feature_image[ $cache_key ];
191
-    }
192
-
193
-
194
-    /**
195
-     * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
196
-     * using the given size params.
197
-     *
198
-     * @param string|array $size  can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
199
-     *                            representing width and height in pixels eg. array(32,32).
200
-     * @return string|boolean          the url of the image or false if not found
201
-     * @throws EE_Error
202
-     */
203
-    public function feature_image_url($size = 'thumbnail')
204
-    {
205
-        $attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
206
-        return ! empty($attachment) ? $attachment[0] : false;
207
-    }
208
-
209
-
210
-    /**
211
-     * This is a method for restoring this_obj using details from the given $revision_id
212
-     *
213
-     * @param int   $revision_id       ID of the revision we're getting data from
214
-     * @param array $related_obj_names if included this will be used to restore for related obj
215
-     *                                 if not included then we just do restore on the meta.
216
-     *                                 We will accept an array of related_obj_names for restoration here.
217
-     * @param array $where_query       You can optionally include an array of key=>value pairs
218
-     *                                 that allow you to further constrict the relation to being added.
219
-     *                                 However, keep in mind that the columns (keys) given
220
-     *                                 must match a column on the JOIN table and currently
221
-     *                                 only the HABTM models accept these additional conditions.
222
-     *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
223
-     *                                 then a NEW row is created in the join table.
224
-     *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
225
-     *                                 sent);
226
-     * @return void
227
-     * @throws EE_Error
228
-     * @throws ReflectionException
229
-     */
230
-    public function restore_revision($revision_id, $related_obj_names = [], $where_query = [])
231
-    {
232
-        // get revision object
233
-        $revision_obj = $this->get_model()->get_one_by_ID($revision_id);
234
-        if ($revision_obj instanceof EE_CPT_Base) {
235
-            // no related_obj_name so we assume we're saving a revision on this object.
236
-            if (empty($related_obj_names)) {
237
-                $fields = $this->get_model()->get_meta_table_fields();
238
-                foreach ($fields as $field) {
239
-                    $this->set($field, $revision_obj->get($field));
240
-                }
241
-                $this->save();
242
-            }
243
-            $related_obj_names = (array) $related_obj_names;
244
-            foreach ($related_obj_names as $related_name) {
245
-                // related_obj_name so we're saving a revision on an object related to this object
246
-                // do we have $where_query params for this related object?  If we do then we include that.
247
-                $cols_n_values         = isset($where_query[ $related_name ])
248
-                    ? $where_query[ $related_name ]
249
-                    : [];
250
-                $where_params          = ! empty($cols_n_values) ? [$cols_n_values] : [];
251
-                $related_objs          = $this->get_many_related($related_name, $where_params);
252
-                $revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
253
-                // load helper
254
-                // remove related objs from this object that are not in revision
255
-                // array_diff *should* work cause I think objects are indexed by ID?
256
-                $related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
257
-                foreach ($related_to_remove as $rr) {
258
-                    $this->_remove_relation_to($rr, $related_name, $cols_n_values);
259
-                }
260
-                // add all related objs attached to revision to this object
261
-                foreach ($revision_related_objs as $r_obj) {
262
-                    $this->_add_relation_to($r_obj, $related_name, $cols_n_values);
263
-                }
264
-            }
265
-        }
266
-    }
267
-
268
-
269
-    /**
270
-     * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
271
-     * If only $id is set:
272
-     *  it will return all meta values in an associative array.
273
-     * If $single is set to false, or left blank:
274
-     *  the function returns an array containing all values of the specified key.
275
-     * If $single is set to true:
276
-     *  the function returns the first value of the specified key (not in an array)
277
-     *
278
-     * @param string  $meta_key
279
-     * @param boolean $single
280
-     * @return mixed
281
-     * @throws EE_Error
282
-     */
283
-    public function get_post_meta($meta_key = null, $single = false)
284
-    {
285
-        return get_post_meta($this->ID(), $meta_key, $single);
286
-    }
287
-
288
-
289
-    /**
290
-     * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
291
-     * Returns meta_id if the meta doesn't exist,
292
-     * otherwise returns true on success and false on failure.
293
-     * NOTE: If the meta_value passed to this function is the same
294
-     * as the value that is already in the database, this function returns false.
295
-     *
296
-     * @param string $meta_key
297
-     * @param mixed  $meta_value
298
-     * @param mixed  $prev_value
299
-     * @return mixed
300
-     * @throws EE_Error
301
-     * @throws ReflectionException
302
-     */
303
-    public function update_post_meta($meta_key, $meta_value, $prev_value = null)
304
-    {
305
-        if (! $this->ID()) {
306
-            $this->save();
307
-        }
308
-        return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
309
-    }
310
-
311
-
312
-    /**
313
-     * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
314
-     *
315
-     * @param mixed $meta_key
316
-     * @param mixed $meta_value
317
-     * @param bool  $unique     If postmeta for this $meta_key already exists,
318
-     *                          whether to add an additional item or not
319
-     * @return boolean          Boolean true, except if the $unique argument was set to true
320
-     *                          and a custom field with the given key already exists,
321
-     *                          in which case false is returned.
322
-     * @throws EE_Error
323
-     * @throws ReflectionException
324
-     */
325
-    public function add_post_meta($meta_key, $meta_value, $unique = false)
326
-    {
327
-        if ($this->ID()) {
328
-            $this->save();
329
-        }
330
-        return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
331
-    }
332
-
333
-
334
-    /**
335
-     * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
336
-     *
337
-     * @param mixed $meta_key
338
-     * @param mixed $meta_value
339
-     * @return boolean False for failure. True for success.
340
-     * @throws EE_Error
341
-     */
342
-    public function delete_post_meta($meta_key, $meta_value = '')
343
-    {
344
-        if (! $this->ID()) {
345
-            // there is obviously no postmeta for this if it's not saved
346
-            // so let's just report this as a success
347
-            return true;
348
-        }
349
-        return delete_post_meta($this->ID(), $meta_key, $meta_value);
350
-    }
351
-
352
-
353
-    /**
354
-     * Gets the URL for viewing this event on the front-end
355
-     *
356
-     * @return string
357
-     * @throws EE_Error
358
-     */
359
-    public function get_permalink()
360
-    {
361
-        return get_permalink($this->ID());
362
-    }
363
-
364
-
365
-    /**
366
-     * Gets all the term-taxonomies for this CPT
367
-     *
368
-     * @param array $query_params
369
-     * @return array[]|EE_Base_Class[]|EE_Term_Taxonomy
370
-     * @throws EE_Error
371
-     * @throws ReflectionException
372
-     */
373
-    public function term_taxonomies($query_params = [])
374
-    {
375
-        return $this->get_many_related('Term_Taxonomy', $query_params);
376
-    }
377
-
378
-
379
-    /**
380
-     * @return mixed
381
-     * @throws EE_Error
382
-     * @throws ReflectionException
383
-     */
384
-    public function get_custom_post_statuses()
385
-    {
386
-        return $this->get_model()->get_custom_post_statuses();
387
-    }
388
-
389
-
390
-    /**
391
-     * @return mixed
392
-     * @throws EE_Error
393
-     * @throws ReflectionException
394
-     */
395
-    public function get_all_post_statuses()
396
-    {
397
-        return $this->get_model()->get_status_array();
398
-    }
399
-
400
-
401
-    /**
402
-     * When fetching a new value for a post field that uses the global $post for rendering,
403
-     * set the global $post temporarily to be this model object; and afterwards restore it
404
-     *
405
-     * @param string $field_name
406
-     * @param bool   $pretty
407
-     * @param string $extra_cache_ref
408
-     * @return mixed
409
-     * @throws EE_Error
410
-     * @throws ReflectionException
411
-     */
412
-    protected function _get_fresh_property($field_name, $pretty = false, $extra_cache_ref = null)
413
-    {
414
-        global $post;
415
-
416
-        if (
417
-            $pretty
418
-            && (
419
-                ! (
420
-                    $post instanceof WP_Post
421
-                    && $post->ID
422
-                )
423
-                || (int) $post->ID !== $this->ID()
424
-            )
425
-            && $this->get_model()->field_settings_for($field_name) instanceof EE_Post_Content_Field
426
-        ) {
427
-            $old_post     = $post;
428
-            $post         = $this->wp_post();
429
-            $return_value = parent::_get_fresh_property($field_name, $pretty, $extra_cache_ref);
430
-            $post         = $old_post;
431
-        } else {
432
-            $return_value = parent::_get_fresh_property($field_name, $pretty, $extra_cache_ref);
433
-        }
434
-        return $return_value;
435
-    }
436
-
437
-
438
-    /**
439
-     * Returns the WP post associated with this CPT model object.
440
-     * If this CPT is saved, fetches it from the DB.
441
-     * Otherwise, create an unsaved WP_POst object. Caches the post internally.
442
-     *
443
-     * @return WP_Post
444
-     * @throws EE_Error
445
-     * @throws ReflectionException
446
-     */
447
-    public function wp_post()
448
-    {
449
-        global $wpdb;
450
-        if (! $this->_wp_post instanceof WP_Post) {
451
-            if ($this->ID()) {
452
-                $this->_wp_post = get_post($this->ID());
453
-            } else {
454
-                $simulated_db_result = new stdClass();
455
-                $field_settings      = $this->get_model()->field_settings(true);
456
-                foreach ($field_settings as $field_name => $field_obj) {
457
-                    if (
458
-                        $this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())
459
-                             ->get_table_name() === $wpdb->posts
460
-                    ) {
461
-                        $column = $field_obj->get_table_column();
462
-
463
-                        if ($field_obj instanceof EE_Datetime_Field) {
464
-                            $value_on_model_obj = $this->get_DateTime_object($field_name);
465
-                        } elseif ($field_obj->is_db_only_field()) {
466
-                            $value_on_model_obj = $field_obj->get_default_value();
467
-                        } else {
468
-                            $value_on_model_obj = $this->get_raw($field_name);
469
-                        }
470
-                        $simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
471
-                    }
472
-                }
473
-                $this->_wp_post = new WP_Post($simulated_db_result);
474
-            }
475
-            // and let's make retrieving the EE CPT object easy too
476
-            $classname = get_class($this);
477
-            if (! isset($this->_wp_post->{$classname})) {
478
-                $this->_wp_post->{$classname} = $this;
479
-            }
480
-        }
481
-        return $this->_wp_post;
482
-    }
483
-
484
-
485
-    /**
486
-     * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
487
-     *
488
-     * @return array
489
-     * @throws EE_Error
490
-     * @throws ReflectionException
491
-     */
492
-    public function __sleep()
493
-    {
494
-        $properties_to_serialize = parent::__sleep();
495
-        $properties_to_serialize = array_diff($properties_to_serialize, ['_wp_post']);
496
-        return $properties_to_serialize;
497
-    }
15
+	/**
16
+	 * This is a property for holding cached feature images on CPT objects.
17
+	 * Cache's are set on the first "feature_image()" method call.
18
+	 * Each key in the array corresponds to the requested size.
19
+	 *
20
+	 * @var array
21
+	 */
22
+	protected $_feature_image = [];
23
+
24
+	/**
25
+	 * @var WP_Post the WP_Post that corresponds with this CPT model object
26
+	 */
27
+	protected $_wp_post;
28
+
29
+
30
+	abstract public function wp_user();
31
+
32
+
33
+	/**
34
+	 * Adds to the specified event category. If it category doesn't exist, creates it.
35
+	 *
36
+	 * @param string $category_name
37
+	 * @param string $category_description    optional
38
+	 * @param int    $parent_term_taxonomy_id optional
39
+	 * @return EE_Term_Taxonomy
40
+	 * @throws EE_Error
41
+	 * @throws ReflectionException
42
+	 */
43
+	public function add_event_category($category_name, $category_description = null, $parent_term_taxonomy_id = null)
44
+	{
45
+		return $this->get_model()->add_event_category(
46
+			$this,
47
+			$category_name,
48
+			$category_description,
49
+			$parent_term_taxonomy_id
50
+		);
51
+	}
52
+
53
+
54
+	/**
55
+	 * Removes the event category by specified name from being related ot this event
56
+	 *
57
+	 * @param string $category_name
58
+	 * @return bool
59
+	 * @throws EE_Error
60
+	 * @throws ReflectionException
61
+	 */
62
+	public function remove_event_category($category_name)
63
+	{
64
+		return $this->get_model()->remove_event_category($this, $category_name);
65
+	}
66
+
67
+
68
+	/**
69
+	 * Removes the relation to the specified term taxonomy, and maintains the
70
+	 * data integrity of the term taxonomy provided
71
+	 *
72
+	 * @param EE_Term_Taxonomy $term_taxonomy
73
+	 * @return EE_Base_Class the relation was removed from
74
+	 * @throws EE_Error
75
+	 * @throws ReflectionException
76
+	 */
77
+	public function remove_relation_to_term_taxonomy($term_taxonomy)
78
+	{
79
+		if (! $term_taxonomy) {
80
+			EE_Error::add_error(
81
+				sprintf(
82
+					esc_html__(
83
+						"No Term_Taxonomy provided which to remove from model object of type %s and id %d",
84
+						"event_espresso"
85
+					),
86
+					get_class($this),
87
+					$this->ID()
88
+				),
89
+				__FILE__,
90
+				__FUNCTION__,
91
+				__LINE__
92
+			);
93
+			return null;
94
+		}
95
+		$term_taxonomy->set_count($term_taxonomy->count() - 1);
96
+		$term_taxonomy->save();
97
+		return $this->_remove_relation_to($term_taxonomy, 'Term_Taxonomy');
98
+	}
99
+
100
+
101
+	/**
102
+	 * The main purpose of this method is to return the post type for the model object
103
+	 *
104
+	 * @return string
105
+	 * @throws EE_Error
106
+	 * @throws ReflectionException
107
+	 */
108
+	public function post_type()
109
+	{
110
+		return $this->get_model()->post_type();
111
+	}
112
+
113
+
114
+	/**
115
+	 * The main purpose of this method is to return the parent for the model object
116
+	 *
117
+	 * @return int
118
+	 * @throws EE_Error
119
+	 */
120
+	public function parent()
121
+	{
122
+		return $this->get('parent');
123
+	}
124
+
125
+
126
+	/**
127
+	 * return the _status property
128
+	 *
129
+	 * @return string
130
+	 * @throws EE_Error
131
+	 */
132
+	public function status()
133
+	{
134
+		return $this->get('status');
135
+	}
136
+
137
+
138
+	/**
139
+	 * @param string $status
140
+	 * @throws EE_Error
141
+	 * @throws ReflectionException
142
+	 */
143
+	public function set_status($status)
144
+	{
145
+		$this->set('status', $status);
146
+	}
147
+
148
+
149
+	/**
150
+	 * See _get_feature_image. Returns the HTML to display a featured image
151
+	 *
152
+	 * @param string       $size
153
+	 * @param string|array $attr
154
+	 * @return string of html
155
+	 * @throws EE_Error
156
+	 * @throws ReflectionException
157
+	 */
158
+	public function feature_image($size = 'thumbnail', $attr = '')
159
+	{
160
+		return $this->_get_feature_image($size, $attr);
161
+	}
162
+
163
+
164
+	/**
165
+	 * This calls the equivalent model method for retrieving the feature image
166
+	 * which in turn is a wrapper for WordPress' get_the_post_thumbnail() function.
167
+	 *
168
+	 * @link   http://codex.wordpress.org/Function_Reference/get_the_post_thumbnail
169
+	 * @access protected
170
+	 * @param string|array $size (optional) Image size. Defaults to 'post-thumbnail' but can also be a 2-item array
171
+	 *                           representing width and height in pixels (i.e. array(32,32) ).
172
+	 * @param string|array $attr Optional. Query string or array of attributes.
173
+	 * @return string HTML image element
174
+	 * @throws EE_Error
175
+	 * @throws ReflectionException
176
+	 */
177
+	protected function _get_feature_image($size, $attr)
178
+	{
179
+		// first let's see if we already have the _feature_image property set
180
+		// AND if it has a cached element on it FOR the given size
181
+		$attr_key                           = is_array($attr)
182
+			? implode('_', $attr)
183
+			: $attr;
184
+		$cache_key                          = is_array($size)
185
+			? implode('_', $size) . $attr_key
186
+			: $size . $attr_key;
187
+		$this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
188
+			? $this->_feature_image[ $cache_key ]
189
+			: $this->get_model()->get_feature_image($this->ID(), $size, $attr);
190
+		return $this->_feature_image[ $cache_key ];
191
+	}
192
+
193
+
194
+	/**
195
+	 * This uses the wp "wp_get_attachment_image_src()" function to return the feature image for the current class
196
+	 * using the given size params.
197
+	 *
198
+	 * @param string|array $size  can either be a string: 'thumbnail', 'medium', 'large', 'full' OR 2-item array
199
+	 *                            representing width and height in pixels eg. array(32,32).
200
+	 * @return string|boolean          the url of the image or false if not found
201
+	 * @throws EE_Error
202
+	 */
203
+	public function feature_image_url($size = 'thumbnail')
204
+	{
205
+		$attachment = wp_get_attachment_image_src(get_post_thumbnail_id($this->ID()), $size);
206
+		return ! empty($attachment) ? $attachment[0] : false;
207
+	}
208
+
209
+
210
+	/**
211
+	 * This is a method for restoring this_obj using details from the given $revision_id
212
+	 *
213
+	 * @param int   $revision_id       ID of the revision we're getting data from
214
+	 * @param array $related_obj_names if included this will be used to restore for related obj
215
+	 *                                 if not included then we just do restore on the meta.
216
+	 *                                 We will accept an array of related_obj_names for restoration here.
217
+	 * @param array $where_query       You can optionally include an array of key=>value pairs
218
+	 *                                 that allow you to further constrict the relation to being added.
219
+	 *                                 However, keep in mind that the columns (keys) given
220
+	 *                                 must match a column on the JOIN table and currently
221
+	 *                                 only the HABTM models accept these additional conditions.
222
+	 *                                 Also remember that if an exact match isn't found for these extra cols/val pairs,
223
+	 *                                 then a NEW row is created in the join table.
224
+	 *                                 This array is INDEXED by RELATED OBJ NAME (so it corresponds with the obj_names
225
+	 *                                 sent);
226
+	 * @return void
227
+	 * @throws EE_Error
228
+	 * @throws ReflectionException
229
+	 */
230
+	public function restore_revision($revision_id, $related_obj_names = [], $where_query = [])
231
+	{
232
+		// get revision object
233
+		$revision_obj = $this->get_model()->get_one_by_ID($revision_id);
234
+		if ($revision_obj instanceof EE_CPT_Base) {
235
+			// no related_obj_name so we assume we're saving a revision on this object.
236
+			if (empty($related_obj_names)) {
237
+				$fields = $this->get_model()->get_meta_table_fields();
238
+				foreach ($fields as $field) {
239
+					$this->set($field, $revision_obj->get($field));
240
+				}
241
+				$this->save();
242
+			}
243
+			$related_obj_names = (array) $related_obj_names;
244
+			foreach ($related_obj_names as $related_name) {
245
+				// related_obj_name so we're saving a revision on an object related to this object
246
+				// do we have $where_query params for this related object?  If we do then we include that.
247
+				$cols_n_values         = isset($where_query[ $related_name ])
248
+					? $where_query[ $related_name ]
249
+					: [];
250
+				$where_params          = ! empty($cols_n_values) ? [$cols_n_values] : [];
251
+				$related_objs          = $this->get_many_related($related_name, $where_params);
252
+				$revision_related_objs = $revision_obj->get_many_related($related_name, $where_params);
253
+				// load helper
254
+				// remove related objs from this object that are not in revision
255
+				// array_diff *should* work cause I think objects are indexed by ID?
256
+				$related_to_remove = EEH_Array::object_array_diff($related_objs, $revision_related_objs);
257
+				foreach ($related_to_remove as $rr) {
258
+					$this->_remove_relation_to($rr, $related_name, $cols_n_values);
259
+				}
260
+				// add all related objs attached to revision to this object
261
+				foreach ($revision_related_objs as $r_obj) {
262
+					$this->_add_relation_to($r_obj, $related_name, $cols_n_values);
263
+				}
264
+			}
265
+		}
266
+	}
267
+
268
+
269
+	/**
270
+	 * Wrapper for get_post_meta, http://codex.wordpress.org/Function_Reference/get_post_meta
271
+	 * If only $id is set:
272
+	 *  it will return all meta values in an associative array.
273
+	 * If $single is set to false, or left blank:
274
+	 *  the function returns an array containing all values of the specified key.
275
+	 * If $single is set to true:
276
+	 *  the function returns the first value of the specified key (not in an array)
277
+	 *
278
+	 * @param string  $meta_key
279
+	 * @param boolean $single
280
+	 * @return mixed
281
+	 * @throws EE_Error
282
+	 */
283
+	public function get_post_meta($meta_key = null, $single = false)
284
+	{
285
+		return get_post_meta($this->ID(), $meta_key, $single);
286
+	}
287
+
288
+
289
+	/**
290
+	 * Wrapper for update_post_meta, http://codex.wordpress.org/Function_Reference/update_post_meta
291
+	 * Returns meta_id if the meta doesn't exist,
292
+	 * otherwise returns true on success and false on failure.
293
+	 * NOTE: If the meta_value passed to this function is the same
294
+	 * as the value that is already in the database, this function returns false.
295
+	 *
296
+	 * @param string $meta_key
297
+	 * @param mixed  $meta_value
298
+	 * @param mixed  $prev_value
299
+	 * @return mixed
300
+	 * @throws EE_Error
301
+	 * @throws ReflectionException
302
+	 */
303
+	public function update_post_meta($meta_key, $meta_value, $prev_value = null)
304
+	{
305
+		if (! $this->ID()) {
306
+			$this->save();
307
+		}
308
+		return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
309
+	}
310
+
311
+
312
+	/**
313
+	 * Wrapper for add_post_meta, http://codex.wordpress.org/Function_Reference/add_post_meta
314
+	 *
315
+	 * @param mixed $meta_key
316
+	 * @param mixed $meta_value
317
+	 * @param bool  $unique     If postmeta for this $meta_key already exists,
318
+	 *                          whether to add an additional item or not
319
+	 * @return boolean          Boolean true, except if the $unique argument was set to true
320
+	 *                          and a custom field with the given key already exists,
321
+	 *                          in which case false is returned.
322
+	 * @throws EE_Error
323
+	 * @throws ReflectionException
324
+	 */
325
+	public function add_post_meta($meta_key, $meta_value, $unique = false)
326
+	{
327
+		if ($this->ID()) {
328
+			$this->save();
329
+		}
330
+		return add_post_meta($this->ID(), $meta_key, $meta_value, $unique);
331
+	}
332
+
333
+
334
+	/**
335
+	 * Wrapper for delete_post_meta, http://codex.wordpress.org/Function_Reference/delete_post_meta
336
+	 *
337
+	 * @param mixed $meta_key
338
+	 * @param mixed $meta_value
339
+	 * @return boolean False for failure. True for success.
340
+	 * @throws EE_Error
341
+	 */
342
+	public function delete_post_meta($meta_key, $meta_value = '')
343
+	{
344
+		if (! $this->ID()) {
345
+			// there is obviously no postmeta for this if it's not saved
346
+			// so let's just report this as a success
347
+			return true;
348
+		}
349
+		return delete_post_meta($this->ID(), $meta_key, $meta_value);
350
+	}
351
+
352
+
353
+	/**
354
+	 * Gets the URL for viewing this event on the front-end
355
+	 *
356
+	 * @return string
357
+	 * @throws EE_Error
358
+	 */
359
+	public function get_permalink()
360
+	{
361
+		return get_permalink($this->ID());
362
+	}
363
+
364
+
365
+	/**
366
+	 * Gets all the term-taxonomies for this CPT
367
+	 *
368
+	 * @param array $query_params
369
+	 * @return array[]|EE_Base_Class[]|EE_Term_Taxonomy
370
+	 * @throws EE_Error
371
+	 * @throws ReflectionException
372
+	 */
373
+	public function term_taxonomies($query_params = [])
374
+	{
375
+		return $this->get_many_related('Term_Taxonomy', $query_params);
376
+	}
377
+
378
+
379
+	/**
380
+	 * @return mixed
381
+	 * @throws EE_Error
382
+	 * @throws ReflectionException
383
+	 */
384
+	public function get_custom_post_statuses()
385
+	{
386
+		return $this->get_model()->get_custom_post_statuses();
387
+	}
388
+
389
+
390
+	/**
391
+	 * @return mixed
392
+	 * @throws EE_Error
393
+	 * @throws ReflectionException
394
+	 */
395
+	public function get_all_post_statuses()
396
+	{
397
+		return $this->get_model()->get_status_array();
398
+	}
399
+
400
+
401
+	/**
402
+	 * When fetching a new value for a post field that uses the global $post for rendering,
403
+	 * set the global $post temporarily to be this model object; and afterwards restore it
404
+	 *
405
+	 * @param string $field_name
406
+	 * @param bool   $pretty
407
+	 * @param string $extra_cache_ref
408
+	 * @return mixed
409
+	 * @throws EE_Error
410
+	 * @throws ReflectionException
411
+	 */
412
+	protected function _get_fresh_property($field_name, $pretty = false, $extra_cache_ref = null)
413
+	{
414
+		global $post;
415
+
416
+		if (
417
+			$pretty
418
+			&& (
419
+				! (
420
+					$post instanceof WP_Post
421
+					&& $post->ID
422
+				)
423
+				|| (int) $post->ID !== $this->ID()
424
+			)
425
+			&& $this->get_model()->field_settings_for($field_name) instanceof EE_Post_Content_Field
426
+		) {
427
+			$old_post     = $post;
428
+			$post         = $this->wp_post();
429
+			$return_value = parent::_get_fresh_property($field_name, $pretty, $extra_cache_ref);
430
+			$post         = $old_post;
431
+		} else {
432
+			$return_value = parent::_get_fresh_property($field_name, $pretty, $extra_cache_ref);
433
+		}
434
+		return $return_value;
435
+	}
436
+
437
+
438
+	/**
439
+	 * Returns the WP post associated with this CPT model object.
440
+	 * If this CPT is saved, fetches it from the DB.
441
+	 * Otherwise, create an unsaved WP_POst object. Caches the post internally.
442
+	 *
443
+	 * @return WP_Post
444
+	 * @throws EE_Error
445
+	 * @throws ReflectionException
446
+	 */
447
+	public function wp_post()
448
+	{
449
+		global $wpdb;
450
+		if (! $this->_wp_post instanceof WP_Post) {
451
+			if ($this->ID()) {
452
+				$this->_wp_post = get_post($this->ID());
453
+			} else {
454
+				$simulated_db_result = new stdClass();
455
+				$field_settings      = $this->get_model()->field_settings(true);
456
+				foreach ($field_settings as $field_name => $field_obj) {
457
+					if (
458
+						$this->get_model()->get_table_obj_by_alias($field_obj->get_table_alias())
459
+							 ->get_table_name() === $wpdb->posts
460
+					) {
461
+						$column = $field_obj->get_table_column();
462
+
463
+						if ($field_obj instanceof EE_Datetime_Field) {
464
+							$value_on_model_obj = $this->get_DateTime_object($field_name);
465
+						} elseif ($field_obj->is_db_only_field()) {
466
+							$value_on_model_obj = $field_obj->get_default_value();
467
+						} else {
468
+							$value_on_model_obj = $this->get_raw($field_name);
469
+						}
470
+						$simulated_db_result->{$column} = $field_obj->prepare_for_use_in_db($value_on_model_obj);
471
+					}
472
+				}
473
+				$this->_wp_post = new WP_Post($simulated_db_result);
474
+			}
475
+			// and let's make retrieving the EE CPT object easy too
476
+			$classname = get_class($this);
477
+			if (! isset($this->_wp_post->{$classname})) {
478
+				$this->_wp_post->{$classname} = $this;
479
+			}
480
+		}
481
+		return $this->_wp_post;
482
+	}
483
+
484
+
485
+	/**
486
+	 * Don't serialize the WP Post. That's just duplicate data and we want to avoid recursion
487
+	 *
488
+	 * @return array
489
+	 * @throws EE_Error
490
+	 * @throws ReflectionException
491
+	 */
492
+	public function __sleep()
493
+	{
494
+		$properties_to_serialize = parent::__sleep();
495
+		$properties_to_serialize = array_diff($properties_to_serialize, ['_wp_post']);
496
+		return $properties_to_serialize;
497
+	}
498 498
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
      */
77 77
     public function remove_relation_to_term_taxonomy($term_taxonomy)
78 78
     {
79
-        if (! $term_taxonomy) {
79
+        if ( ! $term_taxonomy) {
80 80
             EE_Error::add_error(
81 81
                 sprintf(
82 82
                     esc_html__(
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
             ? implode('_', $attr)
183 183
             : $attr;
184 184
         $cache_key                          = is_array($size)
185
-            ? implode('_', $size) . $attr_key
186
-            : $size . $attr_key;
187
-        $this->_feature_image[ $cache_key ] = isset($this->_feature_image[ $cache_key ])
188
-            ? $this->_feature_image[ $cache_key ]
185
+            ? implode('_', $size).$attr_key
186
+            : $size.$attr_key;
187
+        $this->_feature_image[$cache_key] = isset($this->_feature_image[$cache_key])
188
+            ? $this->_feature_image[$cache_key]
189 189
             : $this->get_model()->get_feature_image($this->ID(), $size, $attr);
190
-        return $this->_feature_image[ $cache_key ];
190
+        return $this->_feature_image[$cache_key];
191 191
     }
192 192
 
193 193
 
@@ -244,8 +244,8 @@  discard block
 block discarded – undo
244 244
             foreach ($related_obj_names as $related_name) {
245 245
                 // related_obj_name so we're saving a revision on an object related to this object
246 246
                 // do we have $where_query params for this related object?  If we do then we include that.
247
-                $cols_n_values         = isset($where_query[ $related_name ])
248
-                    ? $where_query[ $related_name ]
247
+                $cols_n_values         = isset($where_query[$related_name])
248
+                    ? $where_query[$related_name]
249 249
                     : [];
250 250
                 $where_params          = ! empty($cols_n_values) ? [$cols_n_values] : [];
251 251
                 $related_objs          = $this->get_many_related($related_name, $where_params);
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
      */
303 303
     public function update_post_meta($meta_key, $meta_value, $prev_value = null)
304 304
     {
305
-        if (! $this->ID()) {
305
+        if ( ! $this->ID()) {
306 306
             $this->save();
307 307
         }
308 308
         return update_post_meta($this->ID(), $meta_key, $meta_value, $prev_value);
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
      */
342 342
     public function delete_post_meta($meta_key, $meta_value = '')
343 343
     {
344
-        if (! $this->ID()) {
344
+        if ( ! $this->ID()) {
345 345
             // there is obviously no postmeta for this if it's not saved
346 346
             // so let's just report this as a success
347 347
             return true;
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
     public function wp_post()
448 448
     {
449 449
         global $wpdb;
450
-        if (! $this->_wp_post instanceof WP_Post) {
450
+        if ( ! $this->_wp_post instanceof WP_Post) {
451 451
             if ($this->ID()) {
452 452
                 $this->_wp_post = get_post($this->ID());
453 453
             } else {
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
             }
475 475
             // and let's make retrieving the EE CPT object easy too
476 476
             $classname = get_class($this);
477
-            if (! isset($this->_wp_post->{$classname})) {
477
+            if ( ! isset($this->_wp_post->{$classname})) {
478 478
                 $this->_wp_post->{$classname} = $this;
479 479
             }
480 480
         }
Please login to merge, or discard this patch.
core/db_classes/EE_CSV.class.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -339,8 +339,8 @@
 block discarded – undo
339 339
      * and dies (in order to avoid other plugins from messing up the csv output)
340 340
      *
341 341
      * @param string $filename         the filename you want to give the file
342
-     * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
343
-     * @return bool | void writes CSV file to output and dies
342
+     * @param boolean  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
343
+     * @return boolean|null | void writes CSV file to output and dies
344 344
      * @throws EE_Error
345 345
      * @throws ReflectionException
346 346
      */
Please login to merge, or discard this patch.
Indentation   +621 added lines, -621 removed lines patch added patch discarded remove patch
@@ -13,625 +13,625 @@
 block discarded – undo
13 13
 class EE_CSV
14 14
 {
15 15
 
16
-    /**
17
-     * string used for 1st cell in exports,
18
-     * which indicates that the following 2 rows will be metadata keys and values
19
-     */
20
-    const metadata_header = 'Event Espresso Export Meta Data';
21
-
22
-
23
-    /**
24
-     * instance of the EE_CSV object
25
-     *
26
-     * @var EE_CSV
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var array
32
-     */
33
-    private $_primary_keys;
34
-
35
-
36
-    /**
37
-     * private constructor to prevent direct creation
38
-     *
39
-     * @return void
40
-     */
41
-    private function __construct()
42
-    {
43
-        global $wpdb;
44
-
45
-        $this->_primary_keys = [
46
-            $wpdb->prefix . 'esp_answer'                  => ['ANS_ID'],
47
-            $wpdb->prefix . 'esp_attendee'                => ['ATT_ID'],
48
-            $wpdb->prefix . 'esp_datetime'                => ['DTT_ID'],
49
-            $wpdb->prefix . 'esp_event_question_group'    => ['EQG_ID'],
50
-            $wpdb->prefix . 'esp_message_template'        => ['MTP_ID'],
51
-            $wpdb->prefix . 'esp_payment'                 => ['PAY_ID'],
52
-            $wpdb->prefix . 'esp_price'                   => ['PRC_ID'],
53
-            $wpdb->prefix . 'esp_price_type'              => ['PRT_ID'],
54
-            $wpdb->prefix . 'esp_question'                => ['QST_ID'],
55
-            $wpdb->prefix . 'esp_question_group'          => ['QSG_ID'],
56
-            $wpdb->prefix . 'esp_question_group_question' => ['QGQ_ID'],
57
-            $wpdb->prefix . 'esp_question_option'         => ['QSO_ID'],
58
-            $wpdb->prefix . 'esp_registration'            => ['REG_ID'],
59
-            $wpdb->prefix . 'esp_status'                  => ['STS_ID'],
60
-            $wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
61
-            $wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
62
-            $wpdb->prefix . 'events_detail'               => ['id'],
63
-            $wpdb->prefix . 'events_category_detail'      => ['id'],
64
-            $wpdb->prefix . 'events_category_rel'         => ['id'],
65
-            $wpdb->prefix . 'events_venue'                => ['id'],
66
-            $wpdb->prefix . 'events_venue_rel'            => ['emeta_id'],
67
-            $wpdb->prefix . 'events_locale'               => ['id'],
68
-            $wpdb->prefix . 'events_locale_rel'           => ['id'],
69
-            $wpdb->prefix . 'events_personnel'            => ['id'],
70
-            $wpdb->prefix . 'events_personnel_rel'        => ['id'],
71
-        ];
72
-    }
73
-
74
-
75
-    /**
76
-     *        @ singleton method used to instantiate class object
77
-     *        @ access public
78
-     *
79
-     * @return EE_CSV
80
-     */
81
-    public static function instance()
82
-    {
83
-        // check if class object is instantiated
84
-        if (! self::$_instance instanceof EE_CSV) {
85
-            self::$_instance = new self();
86
-        }
87
-        return self::$_instance;
88
-    }
89
-
90
-
91
-    /**
92
-     * @Import contents of csv file and store values in an array to be manipulated by other functions
93
-     * @access public
94
-     * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
95
-     *                                      If $model_name is provided, assumes that each row in the CSV represents a
96
-     *                                      model object for that model If $model_name ISN'T provided, assumes that
97
-     *                                      before model object data, there is a row where the first entry is simply
98
-     *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
99
-     *                                      then maybe a row of headers, and then the model data. Eg.
100
-     *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
101
-     *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
102
-     *                                      Forest
103
-     * @param string  $model_name           model name if we know what model we're importing
104
-     * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
105
-     *                                      data
106
-     * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
107
-     *                                      error message like the following array('Event'=>array(
108
-     *                                      array('EVT_ID'=>1,'EVT_name'=>'bob party',...),
109
-     *                                      array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
110
-     *                                      ...
111
-     *                                      )
112
-     *                                      'Venue'=>array(
113
-     *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
114
-     *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
115
-     *                                      ...
116
-     *                                      )
117
-     *                                      ...
118
-     *                                      )
119
-     * @throws EE_Error
120
-     */
121
-    public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
122
-    {
123
-        $multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
124
-        if (empty($multi_dimensional_array)) {
125
-            return false;
126
-        }
127
-        // gotta start somewhere
128
-        $row = 1;
129
-        // array to store csv data in
130
-        $ee_formatted_data = [];
131
-        // array to store headers (column names)
132
-        $headers = [];
133
-        foreach ($multi_dimensional_array as $data) {
134
-            // if first cell is MODEL, then second cell is the MODEL name
135
-            if ($data[0] == 'MODEL') {
136
-                $model_name = $data[1];
137
-                // don't bother looking for model data in this row.
138
-                // The rest of this row should be blank
139
-                // AND pretend this is the first row again
140
-                $row = 1;
141
-                // reset headers
142
-                $headers = [];
143
-                continue;
144
-            }
145
-            if (strpos($data[0], EE_CSV::metadata_header) !== false) {
146
-                $model_name = EE_CSV::metadata_header;
147
-                // store like model data, we just won't try importing it etc.
148
-                $row = 1;
149
-                continue;
150
-            }
151
-
152
-
153
-            // how many columns are there?
154
-            $columns = count($data);
155
-
156
-            $model_entry = [];
157
-            // loop through each column
158
-            for ($i = 0; $i < $columns; $i++) {
159
-                // replace csv_enclosures with backslashed quotes
160
-                $data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
161
-                // do we need to grab the column names?
162
-                if ($row === 1) {
163
-                    if ($first_row_is_headers) {
164
-                        // store the column names to use for keys
165
-                        $column_name = $data[ $i ];
166
-                        // check it's not blank... sometimes CSV editing programs
167
-                        // add a bunch of empty columns onto the end...
168
-                        if (! $column_name) {
169
-                            continue;
170
-                        }
171
-                        $matches = [];
172
-                        if ($model_name == EE_CSV::metadata_header) {
173
-                            $headers[ $i ] = $column_name;
174
-                        } else {
175
-                            // now get the db table name from it (the part between square brackets)
176
-                            $success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
177
-                            if (! $success) {
178
-                                EE_Error::add_error(
179
-                                    sprintf(
180
-                                        esc_html__(
181
-                                            "The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
182
-                                            "event_espresso"
183
-                                        ),
184
-                                        $column_name,
185
-                                        implode(",", $data)
186
-                                    ),
187
-                                    __FILE__,
188
-                                    __FUNCTION__,
189
-                                    __LINE__
190
-                                );
191
-                                return false;
192
-                            }
193
-                            $headers[ $i ] = $matches[2];
194
-                        }
195
-                    } else {
196
-                        // no column names means our final array will just use counters for keys
197
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
198
-                        $headers[ $i ]                 = $i;
199
-                    }
200
-                    // and we need to store csv data
201
-                } else {
202
-                    // this column isn' ta header, store it if there is a header for it
203
-                    if (isset($headers[ $i ])) {
204
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
205
-                    }
206
-                }
207
-            }
208
-            // save the row's data IF it's a non-header-row
209
-            if (! $first_row_is_headers || $row > 1) {
210
-                $ee_formatted_data[ $model_name ][] = $model_entry;
211
-            }
212
-            // advance to next row
213
-            $row++;
214
-        }
215
-
216
-        // delete the uploaded file
217
-        unlink($path_to_file);
218
-
219
-        // it's good to give back
220
-        return $ee_formatted_data;
221
-    }
222
-
223
-
224
-    /**
225
-     * Generic CSV-functionality to turn an entire CSV file into a single array that's
226
-     * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
227
-     * representing each row in the CSV file, and the second-level arrays being each column in that row
228
-     *
229
-     * @param string $path_to_file
230
-     * @return array of arrays. Top-level array has rows, second-level array has each item
231
-     * @throws EE_Error
232
-     */
233
-    public function import_csv_to_multi_dimensional_array($path_to_file)
234
-    {
235
-        // needed to deal with Mac line endings
236
-        ini_set('auto_detect_line_endings', true);
237
-        // because fgetcsv does not correctly deal with backslashed quotes such as \"
238
-        // we'll read the file into a string
239
-        $file_contents = $this->read_unicode_file($path_to_file);
240
-        // replace backslashed quotes with CSV enclosures
241
-        $file_contents = str_replace('\\"', '"""', $file_contents);
242
-        // HEY YOU! PUT THAT FILE BACK!!!
243
-        file_put_contents($path_to_file, $file_contents);
244
-
245
-        if (($file_handle = fopen($path_to_file, "r")) !== false) {
246
-            $csv_array = [];
247
-            // in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions
248
-            // of fgetcsv choke if passed more than 4 - is that crazy or what?
249
-            if (version_compare(PHP_VERSION, '5.3.0') < 0) {
250
-                //  PHP 5.2- version
251
-                // loop through each row of the file
252
-                while (($data = fgetcsv($file_handle)) !== false) {
253
-                    $csv_array[] = $data;
254
-                }
255
-            } else {
256
-                // loop through each row of the file
257
-                while (($data = fgetcsv($file_handle)) !== false) {
258
-                    $csv_array[] = $data;
259
-                }
260
-            }
261
-            # Close the File.
262
-            fclose($file_handle);
263
-            return $csv_array;
264
-        }
265
-        EE_Error::add_error(
266
-            sprintf(
267
-                esc_html__(
268
-                    "An error occurred - the file: %s could not opened.",
269
-                    "event_espresso"
270
-                ),
271
-                $path_to_file
272
-            ),
273
-            __FILE__,
274
-            __FUNCTION__,
275
-            __LINE__
276
-        );
277
-        return [];
278
-    }
279
-
280
-
281
-    /**
282
-     * Opens a unicode or utf file
283
-     * (normal file_get_contents has difficulty reading a unicode file)
284
-     *
285
-     * @param string $file_path
286
-     * @return string
287
-     * @throws EE_Error
288
-     * @see http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
289
-     */
290
-    private function read_unicode_file($file_path)
291
-    {
292
-        $fc = "";
293
-        $fh = fopen($file_path, "rb");
294
-        if (! $fh) {
295
-            throw new EE_Error(
296
-                sprintf(
297
-                    esc_html__("Cannot open file for read: %s<br>\n", 'event_espresso'),
298
-                    $file_path
299
-                )
300
-            );
301
-        }
302
-        $file_length = filesize($file_path);
303
-        $bc          = fread($fh, $file_length);
304
-        for ($i = 0; $i < $file_length; $i++) {
305
-            $c = substr($bc, $i, 1);
306
-            if ((ord($c) != 0) && (ord($c) != 13)) {
307
-                $fc = $fc . $c;
308
-            }
309
-        }
310
-        if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
311
-            $fc = substr($fc, 2);
312
-        }
313
-        return ($fc);
314
-    }
315
-
316
-
317
-    /**
318
-     * @param       $csv_data_array
319
-     * @param false $model_name
320
-     * @return bool
321
-     * @throws EE_Error
322
-     */
323
-    public function save_csv_to_db($csv_data_array, $model_name = false)
324
-    {
325
-        EE_Error::doing_it_wrong(
326
-            'save_csv_to_db',
327
-            esc_html__(
328
-                'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
329
-                'event_espresso'
330
-            ),
331
-            '4.6.7'
332
-        );
333
-        return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
334
-    }
335
-
336
-
337
-    /**
338
-     * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
339
-     * and dies (in order to avoid other plugins from messing up the csv output)
340
-     *
341
-     * @param string $filename         the filename you want to give the file
342
-     * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
343
-     * @return bool | void writes CSV file to output and dies
344
-     * @throws EE_Error
345
-     * @throws ReflectionException
346
-     */
347
-    public function export_multiple_model_data_to_csv($filename, $model_data_array)
348
-    {
349
-        $file_handle = $this->begin_sending_csv($filename);
350
-        $this->write_model_data_to_csv($file_handle, $model_data_array);
351
-        $this->end_sending_csv($file_handle);
352
-    }
353
-
354
-
355
-    /**
356
-     * Sends HTTP headers to indicate that the browser should download a file,
357
-     * and starts writing the file to PHP's output. Returns the file handle so other functions can
358
-     * also write to it
359
-     *
360
-     * @param string $filename the name of the file that the user will download
361
-     * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
362
-     */
363
-    public function begin_sending_csv($filename)
364
-    {
365
-        // grab file extension
366
-        $ext = substr(strrchr($filename, '.'), 1);
367
-        if ($ext == '.csv' or $ext == '.xls') {
368
-            str_replace($ext, '', $filename);
369
-        }
370
-        $filename .= '.csv';
371
-
372
-        // if somebody's been naughty and already started outputting stuff, trash it
373
-        // and start writing our stuff.
374
-        if (ob_get_length()) {
375
-            @ob_flush();
376
-            @flush();
377
-            @ob_end_flush();
378
-        }
379
-        @ob_start();
380
-        header("Pragma: public");
381
-        header("Expires: 0");
382
-        header("Pragma: no-cache");
383
-        header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
384
-        // header("Content-Type: application/force-download");
385
-        // header("Content-Type: application/octet-stream");
386
-        // header("Content-Type: application/download");
387
-        header('Content-disposition: attachment; filename=' . $filename);
388
-        header("Content-Type: text/csv; charset=utf-8");
389
-        do_action('AHEE__EE_CSV__begin_sending_csv__headers');
390
-        echo apply_filters(
391
-            'FHEE__EE_CSV__begin_sending_csv__start_writing',
392
-            "\xEF\xBB\xBF"
393
-        ); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
394
-        return fopen('php://output', 'w');
395
-    }
396
-
397
-
398
-    /**
399
-     * Given an open file, writes all the model data to it in the format the importer expects.
400
-     * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($file_handle).
401
-     *
402
-     * @param resource $file_handle
403
-     * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
404
-     *                                   next layer is numerically indexed to represent each model object (eg, each
405
-     *                                   individual event), and the last layer has all the attributes of that model
406
-     *                                   object (eg, the event's id, name, etc)
407
-     * @return void
408
-     * @throws EE_Error
409
-     * @throws ReflectionException
410
-     */
411
-    public function write_model_data_to_csv($file_handle, $model_data_array)
412
-    {
413
-        $this->write_metadata_to_csv($file_handle);
414
-        foreach ($model_data_array as $model_name => $model_instance_arrays) {
415
-            // first: output a special row stating the model
416
-            $this->fputcsv2($file_handle, ['MODEL', $model_name]);
417
-            // if we have items to put in the CSV, do it normally
418
-
419
-            if (! empty($model_instance_arrays)) {
420
-                $this->write_data_array_to_csv($file_handle, $model_instance_arrays);
421
-            } else {
422
-                // echo "no data to write... so just write the headers";
423
-                // so there's actually NO model objects for that model.
424
-                // probably still want to show the columns
425
-                $model        = EE_Registry::instance()->load_model($model_name);
426
-                $column_names = [];
427
-                foreach ($model->field_settings() as $field) {
428
-                    $column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
429
-                }
430
-                $this->write_data_array_to_csv($file_handle, [$column_names]);
431
-            }
432
-        }
433
-    }
434
-
435
-
436
-    /**
437
-     * Writes some meta data to the CSV as a bunch of columns. Initially we're only
438
-     * mentioning the version and timezone
439
-     *
440
-     * @param resource $file_handle
441
-     * @throws EE_Error
442
-     * @throws EE_Error
443
-     */
444
-    public function write_metadata_to_csv($file_handle)
445
-    {
446
-        $data_row = [EE_CSV::metadata_header];// do NOT translate because this exact string is used when importing
447
-        $this->fputcsv2($file_handle, $data_row);
448
-        $meta_data = [
449
-            0 => [
450
-                'version'        => espresso_version(),
451
-                'timezone'       => EEH_DTT_Helper::get_timezone(),
452
-                'time_of_export' => current_time('mysql'),
453
-                'site_url'       => site_url(),
454
-            ],
455
-        ];
456
-        $this->write_data_array_to_csv($file_handle, $meta_data);
457
-    }
458
-
459
-
460
-    /**
461
-     * @Drop   in replacement for PHP's fputcsv function - but this one works!!!
462
-     * @access private
463
-     * @param resource $fh         - file handle - what we are writing to
464
-     * @param array    $row        - individual row of csv data
465
-     * @param string   $delimiter  - csv delimiter
466
-     * @param string   $enclosure  - csv enclosure
467
-     * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
468
-     * @return void
469
-     */
470
-    private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
471
-    {
472
-        // Allow user to filter the csv delimiter and enclosure for other countries csv standards
473
-        $delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
474
-        $enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
475
-
476
-        $delimiter_esc = preg_quote($delimiter, '/');
477
-        $enclosure_esc = preg_quote($enclosure, '/');
478
-
479
-        $output = [];
480
-        foreach ($row as $field_value) {
481
-            if (is_object($field_value) || is_array($field_value)) {
482
-                $field_value = serialize($field_value);
483
-            }
484
-            if ($field_value === null && $mysql_null) {
485
-                $output[] = 'NULL';
486
-                continue;
487
-            }
488
-
489
-            $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value)
490
-                ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
491
-                : $field_value;
492
-        }
493
-
494
-        fwrite($fh, join($delimiter, $output) . PHP_EOL);
495
-    }
496
-
497
-
498
-    /**
499
-     * Writes $data to the csv file open in $file_handle. uses the array indices of $data for column headers
500
-     *
501
-     * @param resource $file_handle
502
-     * @param array    $data        2D array, first numerically-indexed,
503
-     *                              and next-level-down preferably indexed by string
504
-     * @return boolean              if we successfully wrote to the CSV or not.
505
-     *                              If there's no $data, we consider that a success
506
-     *                              (because we wrote everything there was...nothing)
507
-     * @throws EE_Error
508
-     * @throws EE_Error
509
-     */
510
-    public function write_data_array_to_csv($file_handle, $data)
511
-    {
512
-        // determine if $data is actually a 2d array
513
-        if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
514
-            // make sure top level is numerically indexed,
515
-
516
-            if (EEH_Array::is_associative_array($data)) {
517
-                throw new EE_Error(
518
-                    sprintf(
519
-                        esc_html__(
520
-                            "top-level array must be numerically indexed. Does these look like numbers to you? %s",
521
-                            "event_espresso"
522
-                        ),
523
-                        implode(",", array_keys($data))
524
-                    )
525
-                );
526
-            }
527
-            $item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
528
-            // now, is the last item in the top-level array of $data an associative or numeric array?
529
-            if (EEH_Array::is_associative_array($item_in_top_level_array)) {
530
-                // its associative, so we want to output its keys as column headers
531
-                $keys = array_keys($item_in_top_level_array);
532
-                $this->fputcsv2($file_handle, $keys);
533
-            }
534
-            // start writing data
535
-            foreach ($data as $data_row) {
536
-                $this->fputcsv2($file_handle, $data_row);
537
-            }
538
-            return true;
539
-        }
540
-        // no data TO write... so we can assume that's a success
541
-        return true;
542
-    }
543
-
544
-
545
-    /**
546
-     * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
547
-     * Calls exit to prevent polluting the CSV file with other junk
548
-     *
549
-     * @param resource $fh file_handle where we're writing the CSV to
550
-     */
551
-    public function end_sending_csv($fh)
552
-    {
553
-        fclose($fh);
554
-        exit(0);
555
-    }
556
-
557
-
558
-    /**
559
-     * @Export contents of an array to csv file
560
-     * @access public
561
-     * @param array  $data     - the array of data to be converted to csv and exported
562
-     * @param string $filename - name for newly created csv file
563
-     * @return bool TRUE on success, FALSE on fail
564
-     */
565
-    public function export_array_to_csv($data = false, $filename = false)
566
-    {
567
-        // no data file?? get outta here
568
-        if (! $data or ! is_array($data) or empty($data)) {
569
-            return false;
570
-        }
571
-
572
-        // no filename?? get outta here
573
-        if (! $filename) {
574
-            return false;
575
-        }
576
-        $fh = $this->begin_sending_csv($filename);
577
-        $this->end_sending_csv($fh);
578
-        return true;
579
-    }
580
-
581
-
582
-    /**
583
-     * @Determine the maximum upload file size based on php.ini settings
584
-     * @access    public
585
-     * @param int $percent_of_max - desired percentage of the max upload_mb
586
-     * @return int KB
587
-     */
588
-    public function get_max_upload_size($percent_of_max = false)
589
-    {
590
-        $max_upload   = (int) (ini_get('upload_max_filesize'));
591
-        $max_post     = (int) (ini_get('post_max_size'));
592
-        $memory_limit = (int) (ini_get('memory_limit'));
593
-
594
-        // determine the smallest of the three values from above
595
-        $upload_mb = min($max_upload, $max_post, $memory_limit);
596
-
597
-        // convert MB to KB
598
-        $upload_mb = $upload_mb * 1024;
599
-
600
-        // don't want the full monty? then reduce the max upload size
601
-        if ($percent_of_max) {
602
-            // is percent_of_max like this -> 50 or like this -> 0.50 ?
603
-            if ($percent_of_max > 1) {
604
-                // changes 50 to 0.50
605
-                $percent_of_max = $percent_of_max / 100;
606
-            }
607
-            // make upload_mb a percentage of the max upload_mb
608
-            $upload_mb = $upload_mb * $percent_of_max;
609
-        }
610
-
611
-        return $upload_mb;
612
-    }
613
-
614
-
615
-    /**
616
-     * Gets the date format to use in teh csv. filterable
617
-     *
618
-     * @param string $current_format
619
-     * @return string
620
-     */
621
-    public function get_date_format_for_csv($current_format = null)
622
-    {
623
-        return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
624
-    }
625
-
626
-
627
-    /**
628
-     * Gets the time format we want to use in CSV reports. Filterable
629
-     *
630
-     * @param string $current_format
631
-     * @return string
632
-     */
633
-    public function get_time_format_for_csv($current_format = null)
634
-    {
635
-        return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
636
-    }
16
+	/**
17
+	 * string used for 1st cell in exports,
18
+	 * which indicates that the following 2 rows will be metadata keys and values
19
+	 */
20
+	const metadata_header = 'Event Espresso Export Meta Data';
21
+
22
+
23
+	/**
24
+	 * instance of the EE_CSV object
25
+	 *
26
+	 * @var EE_CSV
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var array
32
+	 */
33
+	private $_primary_keys;
34
+
35
+
36
+	/**
37
+	 * private constructor to prevent direct creation
38
+	 *
39
+	 * @return void
40
+	 */
41
+	private function __construct()
42
+	{
43
+		global $wpdb;
44
+
45
+		$this->_primary_keys = [
46
+			$wpdb->prefix . 'esp_answer'                  => ['ANS_ID'],
47
+			$wpdb->prefix . 'esp_attendee'                => ['ATT_ID'],
48
+			$wpdb->prefix . 'esp_datetime'                => ['DTT_ID'],
49
+			$wpdb->prefix . 'esp_event_question_group'    => ['EQG_ID'],
50
+			$wpdb->prefix . 'esp_message_template'        => ['MTP_ID'],
51
+			$wpdb->prefix . 'esp_payment'                 => ['PAY_ID'],
52
+			$wpdb->prefix . 'esp_price'                   => ['PRC_ID'],
53
+			$wpdb->prefix . 'esp_price_type'              => ['PRT_ID'],
54
+			$wpdb->prefix . 'esp_question'                => ['QST_ID'],
55
+			$wpdb->prefix . 'esp_question_group'          => ['QSG_ID'],
56
+			$wpdb->prefix . 'esp_question_group_question' => ['QGQ_ID'],
57
+			$wpdb->prefix . 'esp_question_option'         => ['QSO_ID'],
58
+			$wpdb->prefix . 'esp_registration'            => ['REG_ID'],
59
+			$wpdb->prefix . 'esp_status'                  => ['STS_ID'],
60
+			$wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
61
+			$wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
62
+			$wpdb->prefix . 'events_detail'               => ['id'],
63
+			$wpdb->prefix . 'events_category_detail'      => ['id'],
64
+			$wpdb->prefix . 'events_category_rel'         => ['id'],
65
+			$wpdb->prefix . 'events_venue'                => ['id'],
66
+			$wpdb->prefix . 'events_venue_rel'            => ['emeta_id'],
67
+			$wpdb->prefix . 'events_locale'               => ['id'],
68
+			$wpdb->prefix . 'events_locale_rel'           => ['id'],
69
+			$wpdb->prefix . 'events_personnel'            => ['id'],
70
+			$wpdb->prefix . 'events_personnel_rel'        => ['id'],
71
+		];
72
+	}
73
+
74
+
75
+	/**
76
+	 *        @ singleton method used to instantiate class object
77
+	 *        @ access public
78
+	 *
79
+	 * @return EE_CSV
80
+	 */
81
+	public static function instance()
82
+	{
83
+		// check if class object is instantiated
84
+		if (! self::$_instance instanceof EE_CSV) {
85
+			self::$_instance = new self();
86
+		}
87
+		return self::$_instance;
88
+	}
89
+
90
+
91
+	/**
92
+	 * @Import contents of csv file and store values in an array to be manipulated by other functions
93
+	 * @access public
94
+	 * @param string  $path_to_file         - the csv file to be imported including the path to it's location.
95
+	 *                                      If $model_name is provided, assumes that each row in the CSV represents a
96
+	 *                                      model object for that model If $model_name ISN'T provided, assumes that
97
+	 *                                      before model object data, there is a row where the first entry is simply
98
+	 *                                      'MODEL', and next entry is the model's name, (untranslated) like Event, and
99
+	 *                                      then maybe a row of headers, and then the model data. Eg.
100
+	 *                                      '<br>MODEL,Event,<br>EVT_ID,EVT_name,...<br>1,Monkey
101
+	 *                                      Party,...<br>2,Llamarama,...<br>MODEL,Venue,<br>VNU_ID,VNU_name<br>1,The
102
+	 *                                      Forest
103
+	 * @param string  $model_name           model name if we know what model we're importing
104
+	 * @param boolean $first_row_is_headers - whether the first row of data is headers or not - TRUE = headers, FALSE =
105
+	 *                                      data
106
+	 * @return mixed - array on success - multi dimensional with headers as keys (if headers exist) OR string on fail -
107
+	 *                                      error message like the following array('Event'=>array(
108
+	 *                                      array('EVT_ID'=>1,'EVT_name'=>'bob party',...),
109
+	 *                                      array('EVT_ID'=>2,'EVT_name'=>'llamarama',...),
110
+	 *                                      ...
111
+	 *                                      )
112
+	 *                                      'Venue'=>array(
113
+	 *                                      array('VNU_ID'=>1,'VNU_name'=>'the shack',...),
114
+	 *                                      array('VNU_ID'=>2,'VNU_name'=>'tree house',...),
115
+	 *                                      ...
116
+	 *                                      )
117
+	 *                                      ...
118
+	 *                                      )
119
+	 * @throws EE_Error
120
+	 */
121
+	public function import_csv_to_model_data_array($path_to_file, $model_name = false, $first_row_is_headers = true)
122
+	{
123
+		$multi_dimensional_array = $this->import_csv_to_multi_dimensional_array($path_to_file);
124
+		if (empty($multi_dimensional_array)) {
125
+			return false;
126
+		}
127
+		// gotta start somewhere
128
+		$row = 1;
129
+		// array to store csv data in
130
+		$ee_formatted_data = [];
131
+		// array to store headers (column names)
132
+		$headers = [];
133
+		foreach ($multi_dimensional_array as $data) {
134
+			// if first cell is MODEL, then second cell is the MODEL name
135
+			if ($data[0] == 'MODEL') {
136
+				$model_name = $data[1];
137
+				// don't bother looking for model data in this row.
138
+				// The rest of this row should be blank
139
+				// AND pretend this is the first row again
140
+				$row = 1;
141
+				// reset headers
142
+				$headers = [];
143
+				continue;
144
+			}
145
+			if (strpos($data[0], EE_CSV::metadata_header) !== false) {
146
+				$model_name = EE_CSV::metadata_header;
147
+				// store like model data, we just won't try importing it etc.
148
+				$row = 1;
149
+				continue;
150
+			}
151
+
152
+
153
+			// how many columns are there?
154
+			$columns = count($data);
155
+
156
+			$model_entry = [];
157
+			// loop through each column
158
+			for ($i = 0; $i < $columns; $i++) {
159
+				// replace csv_enclosures with backslashed quotes
160
+				$data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
161
+				// do we need to grab the column names?
162
+				if ($row === 1) {
163
+					if ($first_row_is_headers) {
164
+						// store the column names to use for keys
165
+						$column_name = $data[ $i ];
166
+						// check it's not blank... sometimes CSV editing programs
167
+						// add a bunch of empty columns onto the end...
168
+						if (! $column_name) {
169
+							continue;
170
+						}
171
+						$matches = [];
172
+						if ($model_name == EE_CSV::metadata_header) {
173
+							$headers[ $i ] = $column_name;
174
+						} else {
175
+							// now get the db table name from it (the part between square brackets)
176
+							$success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
177
+							if (! $success) {
178
+								EE_Error::add_error(
179
+									sprintf(
180
+										esc_html__(
181
+											"The column titled %s is invalid for importing. It must be be in the format of 'Nice Name[model_field_name]' in row %s",
182
+											"event_espresso"
183
+										),
184
+										$column_name,
185
+										implode(",", $data)
186
+									),
187
+									__FILE__,
188
+									__FUNCTION__,
189
+									__LINE__
190
+								);
191
+								return false;
192
+							}
193
+							$headers[ $i ] = $matches[2];
194
+						}
195
+					} else {
196
+						// no column names means our final array will just use counters for keys
197
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
198
+						$headers[ $i ]                 = $i;
199
+					}
200
+					// and we need to store csv data
201
+				} else {
202
+					// this column isn' ta header, store it if there is a header for it
203
+					if (isset($headers[ $i ])) {
204
+						$model_entry[ $headers[ $i ] ] = $data[ $i ];
205
+					}
206
+				}
207
+			}
208
+			// save the row's data IF it's a non-header-row
209
+			if (! $first_row_is_headers || $row > 1) {
210
+				$ee_formatted_data[ $model_name ][] = $model_entry;
211
+			}
212
+			// advance to next row
213
+			$row++;
214
+		}
215
+
216
+		// delete the uploaded file
217
+		unlink($path_to_file);
218
+
219
+		// it's good to give back
220
+		return $ee_formatted_data;
221
+	}
222
+
223
+
224
+	/**
225
+	 * Generic CSV-functionality to turn an entire CSV file into a single array that's
226
+	 * NOT in a specific format to EE. It's just a 2-level array, with top-level arrays
227
+	 * representing each row in the CSV file, and the second-level arrays being each column in that row
228
+	 *
229
+	 * @param string $path_to_file
230
+	 * @return array of arrays. Top-level array has rows, second-level array has each item
231
+	 * @throws EE_Error
232
+	 */
233
+	public function import_csv_to_multi_dimensional_array($path_to_file)
234
+	{
235
+		// needed to deal with Mac line endings
236
+		ini_set('auto_detect_line_endings', true);
237
+		// because fgetcsv does not correctly deal with backslashed quotes such as \"
238
+		// we'll read the file into a string
239
+		$file_contents = $this->read_unicode_file($path_to_file);
240
+		// replace backslashed quotes with CSV enclosures
241
+		$file_contents = str_replace('\\"', '"""', $file_contents);
242
+		// HEY YOU! PUT THAT FILE BACK!!!
243
+		file_put_contents($path_to_file, $file_contents);
244
+
245
+		if (($file_handle = fopen($path_to_file, "r")) !== false) {
246
+			$csv_array = [];
247
+			// in PHP 5.3 fgetcsv accepts a 5th parameter, but the pre 5.3 versions
248
+			// of fgetcsv choke if passed more than 4 - is that crazy or what?
249
+			if (version_compare(PHP_VERSION, '5.3.0') < 0) {
250
+				//  PHP 5.2- version
251
+				// loop through each row of the file
252
+				while (($data = fgetcsv($file_handle)) !== false) {
253
+					$csv_array[] = $data;
254
+				}
255
+			} else {
256
+				// loop through each row of the file
257
+				while (($data = fgetcsv($file_handle)) !== false) {
258
+					$csv_array[] = $data;
259
+				}
260
+			}
261
+			# Close the File.
262
+			fclose($file_handle);
263
+			return $csv_array;
264
+		}
265
+		EE_Error::add_error(
266
+			sprintf(
267
+				esc_html__(
268
+					"An error occurred - the file: %s could not opened.",
269
+					"event_espresso"
270
+				),
271
+				$path_to_file
272
+			),
273
+			__FILE__,
274
+			__FUNCTION__,
275
+			__LINE__
276
+		);
277
+		return [];
278
+	}
279
+
280
+
281
+	/**
282
+	 * Opens a unicode or utf file
283
+	 * (normal file_get_contents has difficulty reading a unicode file)
284
+	 *
285
+	 * @param string $file_path
286
+	 * @return string
287
+	 * @throws EE_Error
288
+	 * @see http://stackoverflow.com/questions/15092764/how-to-read-unicode-text-file-in-php
289
+	 */
290
+	private function read_unicode_file($file_path)
291
+	{
292
+		$fc = "";
293
+		$fh = fopen($file_path, "rb");
294
+		if (! $fh) {
295
+			throw new EE_Error(
296
+				sprintf(
297
+					esc_html__("Cannot open file for read: %s<br>\n", 'event_espresso'),
298
+					$file_path
299
+				)
300
+			);
301
+		}
302
+		$file_length = filesize($file_path);
303
+		$bc          = fread($fh, $file_length);
304
+		for ($i = 0; $i < $file_length; $i++) {
305
+			$c = substr($bc, $i, 1);
306
+			if ((ord($c) != 0) && (ord($c) != 13)) {
307
+				$fc = $fc . $c;
308
+			}
309
+		}
310
+		if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
311
+			$fc = substr($fc, 2);
312
+		}
313
+		return ($fc);
314
+	}
315
+
316
+
317
+	/**
318
+	 * @param       $csv_data_array
319
+	 * @param false $model_name
320
+	 * @return bool
321
+	 * @throws EE_Error
322
+	 */
323
+	public function save_csv_to_db($csv_data_array, $model_name = false)
324
+	{
325
+		EE_Error::doing_it_wrong(
326
+			'save_csv_to_db',
327
+			esc_html__(
328
+				'Function moved to EE_Import and renamed to save_csv_data_array_to_db',
329
+				'event_espresso'
330
+			),
331
+			'4.6.7'
332
+		);
333
+		return EE_Import::instance()->save_csv_data_array_to_db($csv_data_array, $model_name);
334
+	}
335
+
336
+
337
+	/**
338
+	 * Writes the CSV file to the output buffer, with rows corresponding to $model_data_array,
339
+	 * and dies (in order to avoid other plugins from messing up the csv output)
340
+	 *
341
+	 * @param string $filename         the filename you want to give the file
342
+	 * @param array  $model_data_array 3d array, as described in EE_CSV::write_model_data_to_csv()
343
+	 * @return bool | void writes CSV file to output and dies
344
+	 * @throws EE_Error
345
+	 * @throws ReflectionException
346
+	 */
347
+	public function export_multiple_model_data_to_csv($filename, $model_data_array)
348
+	{
349
+		$file_handle = $this->begin_sending_csv($filename);
350
+		$this->write_model_data_to_csv($file_handle, $model_data_array);
351
+		$this->end_sending_csv($file_handle);
352
+	}
353
+
354
+
355
+	/**
356
+	 * Sends HTTP headers to indicate that the browser should download a file,
357
+	 * and starts writing the file to PHP's output. Returns the file handle so other functions can
358
+	 * also write to it
359
+	 *
360
+	 * @param string $filename the name of the file that the user will download
361
+	 * @return resource, like the results of fopen(), which can be used for fwrite, fputcsv2, etc.
362
+	 */
363
+	public function begin_sending_csv($filename)
364
+	{
365
+		// grab file extension
366
+		$ext = substr(strrchr($filename, '.'), 1);
367
+		if ($ext == '.csv' or $ext == '.xls') {
368
+			str_replace($ext, '', $filename);
369
+		}
370
+		$filename .= '.csv';
371
+
372
+		// if somebody's been naughty and already started outputting stuff, trash it
373
+		// and start writing our stuff.
374
+		if (ob_get_length()) {
375
+			@ob_flush();
376
+			@flush();
377
+			@ob_end_flush();
378
+		}
379
+		@ob_start();
380
+		header("Pragma: public");
381
+		header("Expires: 0");
382
+		header("Pragma: no-cache");
383
+		header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
384
+		// header("Content-Type: application/force-download");
385
+		// header("Content-Type: application/octet-stream");
386
+		// header("Content-Type: application/download");
387
+		header('Content-disposition: attachment; filename=' . $filename);
388
+		header("Content-Type: text/csv; charset=utf-8");
389
+		do_action('AHEE__EE_CSV__begin_sending_csv__headers');
390
+		echo apply_filters(
391
+			'FHEE__EE_CSV__begin_sending_csv__start_writing',
392
+			"\xEF\xBB\xBF"
393
+		); // makes excel open it as UTF-8. UTF-8 BOM, see http://stackoverflow.com/a/4440143/2773835
394
+		return fopen('php://output', 'w');
395
+	}
396
+
397
+
398
+	/**
399
+	 * Given an open file, writes all the model data to it in the format the importer expects.
400
+	 * Usually preceded by begin_sending_csv($filename), and followed by end_sending_csv($file_handle).
401
+	 *
402
+	 * @param resource $file_handle
403
+	 * @param array    $model_data_array is assumed to be a 3d array: 1st layer has keys of model names (eg 'Event'),
404
+	 *                                   next layer is numerically indexed to represent each model object (eg, each
405
+	 *                                   individual event), and the last layer has all the attributes of that model
406
+	 *                                   object (eg, the event's id, name, etc)
407
+	 * @return void
408
+	 * @throws EE_Error
409
+	 * @throws ReflectionException
410
+	 */
411
+	public function write_model_data_to_csv($file_handle, $model_data_array)
412
+	{
413
+		$this->write_metadata_to_csv($file_handle);
414
+		foreach ($model_data_array as $model_name => $model_instance_arrays) {
415
+			// first: output a special row stating the model
416
+			$this->fputcsv2($file_handle, ['MODEL', $model_name]);
417
+			// if we have items to put in the CSV, do it normally
418
+
419
+			if (! empty($model_instance_arrays)) {
420
+				$this->write_data_array_to_csv($file_handle, $model_instance_arrays);
421
+			} else {
422
+				// echo "no data to write... so just write the headers";
423
+				// so there's actually NO model objects for that model.
424
+				// probably still want to show the columns
425
+				$model        = EE_Registry::instance()->load_model($model_name);
426
+				$column_names = [];
427
+				foreach ($model->field_settings() as $field) {
428
+					$column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
429
+				}
430
+				$this->write_data_array_to_csv($file_handle, [$column_names]);
431
+			}
432
+		}
433
+	}
434
+
435
+
436
+	/**
437
+	 * Writes some meta data to the CSV as a bunch of columns. Initially we're only
438
+	 * mentioning the version and timezone
439
+	 *
440
+	 * @param resource $file_handle
441
+	 * @throws EE_Error
442
+	 * @throws EE_Error
443
+	 */
444
+	public function write_metadata_to_csv($file_handle)
445
+	{
446
+		$data_row = [EE_CSV::metadata_header];// do NOT translate because this exact string is used when importing
447
+		$this->fputcsv2($file_handle, $data_row);
448
+		$meta_data = [
449
+			0 => [
450
+				'version'        => espresso_version(),
451
+				'timezone'       => EEH_DTT_Helper::get_timezone(),
452
+				'time_of_export' => current_time('mysql'),
453
+				'site_url'       => site_url(),
454
+			],
455
+		];
456
+		$this->write_data_array_to_csv($file_handle, $meta_data);
457
+	}
458
+
459
+
460
+	/**
461
+	 * @Drop   in replacement for PHP's fputcsv function - but this one works!!!
462
+	 * @access private
463
+	 * @param resource $fh         - file handle - what we are writing to
464
+	 * @param array    $row        - individual row of csv data
465
+	 * @param string   $delimiter  - csv delimiter
466
+	 * @param string   $enclosure  - csv enclosure
467
+	 * @param string   $mysql_null - allows php NULL to be overridden with MySQl's insertable NULL value
468
+	 * @return void
469
+	 */
470
+	private function fputcsv2($fh, array $row, $delimiter = ',', $enclosure = '"', $mysql_null = false)
471
+	{
472
+		// Allow user to filter the csv delimiter and enclosure for other countries csv standards
473
+		$delimiter = apply_filters('FHEE__EE_CSV__fputcsv2__delimiter', $delimiter);
474
+		$enclosure = apply_filters('FHEE__EE_CSV__fputcsv2__enclosure', $enclosure);
475
+
476
+		$delimiter_esc = preg_quote($delimiter, '/');
477
+		$enclosure_esc = preg_quote($enclosure, '/');
478
+
479
+		$output = [];
480
+		foreach ($row as $field_value) {
481
+			if (is_object($field_value) || is_array($field_value)) {
482
+				$field_value = serialize($field_value);
483
+			}
484
+			if ($field_value === null && $mysql_null) {
485
+				$output[] = 'NULL';
486
+				continue;
487
+			}
488
+
489
+			$output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value)
490
+				? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
491
+				: $field_value;
492
+		}
493
+
494
+		fwrite($fh, join($delimiter, $output) . PHP_EOL);
495
+	}
496
+
497
+
498
+	/**
499
+	 * Writes $data to the csv file open in $file_handle. uses the array indices of $data for column headers
500
+	 *
501
+	 * @param resource $file_handle
502
+	 * @param array    $data        2D array, first numerically-indexed,
503
+	 *                              and next-level-down preferably indexed by string
504
+	 * @return boolean              if we successfully wrote to the CSV or not.
505
+	 *                              If there's no $data, we consider that a success
506
+	 *                              (because we wrote everything there was...nothing)
507
+	 * @throws EE_Error
508
+	 * @throws EE_Error
509
+	 */
510
+	public function write_data_array_to_csv($file_handle, $data)
511
+	{
512
+		// determine if $data is actually a 2d array
513
+		if ($data && is_array($data) && is_array(EEH_Array::get_one_item_from_array($data))) {
514
+			// make sure top level is numerically indexed,
515
+
516
+			if (EEH_Array::is_associative_array($data)) {
517
+				throw new EE_Error(
518
+					sprintf(
519
+						esc_html__(
520
+							"top-level array must be numerically indexed. Does these look like numbers to you? %s",
521
+							"event_espresso"
522
+						),
523
+						implode(",", array_keys($data))
524
+					)
525
+				);
526
+			}
527
+			$item_in_top_level_array = EEH_Array::get_one_item_from_array($data);
528
+			// now, is the last item in the top-level array of $data an associative or numeric array?
529
+			if (EEH_Array::is_associative_array($item_in_top_level_array)) {
530
+				// its associative, so we want to output its keys as column headers
531
+				$keys = array_keys($item_in_top_level_array);
532
+				$this->fputcsv2($file_handle, $keys);
533
+			}
534
+			// start writing data
535
+			foreach ($data as $data_row) {
536
+				$this->fputcsv2($file_handle, $data_row);
537
+			}
538
+			return true;
539
+		}
540
+		// no data TO write... so we can assume that's a success
541
+		return true;
542
+	}
543
+
544
+
545
+	/**
546
+	 * Should be called after begin_sending_csv(), and one or more write_data_array_to_csv()s.
547
+	 * Calls exit to prevent polluting the CSV file with other junk
548
+	 *
549
+	 * @param resource $fh file_handle where we're writing the CSV to
550
+	 */
551
+	public function end_sending_csv($fh)
552
+	{
553
+		fclose($fh);
554
+		exit(0);
555
+	}
556
+
557
+
558
+	/**
559
+	 * @Export contents of an array to csv file
560
+	 * @access public
561
+	 * @param array  $data     - the array of data to be converted to csv and exported
562
+	 * @param string $filename - name for newly created csv file
563
+	 * @return bool TRUE on success, FALSE on fail
564
+	 */
565
+	public function export_array_to_csv($data = false, $filename = false)
566
+	{
567
+		// no data file?? get outta here
568
+		if (! $data or ! is_array($data) or empty($data)) {
569
+			return false;
570
+		}
571
+
572
+		// no filename?? get outta here
573
+		if (! $filename) {
574
+			return false;
575
+		}
576
+		$fh = $this->begin_sending_csv($filename);
577
+		$this->end_sending_csv($fh);
578
+		return true;
579
+	}
580
+
581
+
582
+	/**
583
+	 * @Determine the maximum upload file size based on php.ini settings
584
+	 * @access    public
585
+	 * @param int $percent_of_max - desired percentage of the max upload_mb
586
+	 * @return int KB
587
+	 */
588
+	public function get_max_upload_size($percent_of_max = false)
589
+	{
590
+		$max_upload   = (int) (ini_get('upload_max_filesize'));
591
+		$max_post     = (int) (ini_get('post_max_size'));
592
+		$memory_limit = (int) (ini_get('memory_limit'));
593
+
594
+		// determine the smallest of the three values from above
595
+		$upload_mb = min($max_upload, $max_post, $memory_limit);
596
+
597
+		// convert MB to KB
598
+		$upload_mb = $upload_mb * 1024;
599
+
600
+		// don't want the full monty? then reduce the max upload size
601
+		if ($percent_of_max) {
602
+			// is percent_of_max like this -> 50 or like this -> 0.50 ?
603
+			if ($percent_of_max > 1) {
604
+				// changes 50 to 0.50
605
+				$percent_of_max = $percent_of_max / 100;
606
+			}
607
+			// make upload_mb a percentage of the max upload_mb
608
+			$upload_mb = $upload_mb * $percent_of_max;
609
+		}
610
+
611
+		return $upload_mb;
612
+	}
613
+
614
+
615
+	/**
616
+	 * Gets the date format to use in teh csv. filterable
617
+	 *
618
+	 * @param string $current_format
619
+	 * @return string
620
+	 */
621
+	public function get_date_format_for_csv($current_format = null)
622
+	{
623
+		return apply_filters('FHEE__EE_CSV__get_date_format_for_csv__format', 'Y-m-d', $current_format);
624
+	}
625
+
626
+
627
+	/**
628
+	 * Gets the time format we want to use in CSV reports. Filterable
629
+	 *
630
+	 * @param string $current_format
631
+	 * @return string
632
+	 */
633
+	public function get_time_format_for_csv($current_format = null)
634
+	{
635
+		return apply_filters('FHEE__EE_CSV__get_time_format_for_csv__format', 'H:i:s', $current_format);
636
+	}
637 637
 }
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -43,31 +43,31 @@  discard block
 block discarded – undo
43 43
         global $wpdb;
44 44
 
45 45
         $this->_primary_keys = [
46
-            $wpdb->prefix . 'esp_answer'                  => ['ANS_ID'],
47
-            $wpdb->prefix . 'esp_attendee'                => ['ATT_ID'],
48
-            $wpdb->prefix . 'esp_datetime'                => ['DTT_ID'],
49
-            $wpdb->prefix . 'esp_event_question_group'    => ['EQG_ID'],
50
-            $wpdb->prefix . 'esp_message_template'        => ['MTP_ID'],
51
-            $wpdb->prefix . 'esp_payment'                 => ['PAY_ID'],
52
-            $wpdb->prefix . 'esp_price'                   => ['PRC_ID'],
53
-            $wpdb->prefix . 'esp_price_type'              => ['PRT_ID'],
54
-            $wpdb->prefix . 'esp_question'                => ['QST_ID'],
55
-            $wpdb->prefix . 'esp_question_group'          => ['QSG_ID'],
56
-            $wpdb->prefix . 'esp_question_group_question' => ['QGQ_ID'],
57
-            $wpdb->prefix . 'esp_question_option'         => ['QSO_ID'],
58
-            $wpdb->prefix . 'esp_registration'            => ['REG_ID'],
59
-            $wpdb->prefix . 'esp_status'                  => ['STS_ID'],
60
-            $wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
61
-            $wpdb->prefix . 'esp_transaction'             => ['TXN_ID'],
62
-            $wpdb->prefix . 'events_detail'               => ['id'],
63
-            $wpdb->prefix . 'events_category_detail'      => ['id'],
64
-            $wpdb->prefix . 'events_category_rel'         => ['id'],
65
-            $wpdb->prefix . 'events_venue'                => ['id'],
66
-            $wpdb->prefix . 'events_venue_rel'            => ['emeta_id'],
67
-            $wpdb->prefix . 'events_locale'               => ['id'],
68
-            $wpdb->prefix . 'events_locale_rel'           => ['id'],
69
-            $wpdb->prefix . 'events_personnel'            => ['id'],
70
-            $wpdb->prefix . 'events_personnel_rel'        => ['id'],
46
+            $wpdb->prefix.'esp_answer'                  => ['ANS_ID'],
47
+            $wpdb->prefix.'esp_attendee'                => ['ATT_ID'],
48
+            $wpdb->prefix.'esp_datetime'                => ['DTT_ID'],
49
+            $wpdb->prefix.'esp_event_question_group'    => ['EQG_ID'],
50
+            $wpdb->prefix.'esp_message_template'        => ['MTP_ID'],
51
+            $wpdb->prefix.'esp_payment'                 => ['PAY_ID'],
52
+            $wpdb->prefix.'esp_price'                   => ['PRC_ID'],
53
+            $wpdb->prefix.'esp_price_type'              => ['PRT_ID'],
54
+            $wpdb->prefix.'esp_question'                => ['QST_ID'],
55
+            $wpdb->prefix.'esp_question_group'          => ['QSG_ID'],
56
+            $wpdb->prefix.'esp_question_group_question' => ['QGQ_ID'],
57
+            $wpdb->prefix.'esp_question_option'         => ['QSO_ID'],
58
+            $wpdb->prefix.'esp_registration'            => ['REG_ID'],
59
+            $wpdb->prefix.'esp_status'                  => ['STS_ID'],
60
+            $wpdb->prefix.'esp_transaction'             => ['TXN_ID'],
61
+            $wpdb->prefix.'esp_transaction'             => ['TXN_ID'],
62
+            $wpdb->prefix.'events_detail'               => ['id'],
63
+            $wpdb->prefix.'events_category_detail'      => ['id'],
64
+            $wpdb->prefix.'events_category_rel'         => ['id'],
65
+            $wpdb->prefix.'events_venue'                => ['id'],
66
+            $wpdb->prefix.'events_venue_rel'            => ['emeta_id'],
67
+            $wpdb->prefix.'events_locale'               => ['id'],
68
+            $wpdb->prefix.'events_locale_rel'           => ['id'],
69
+            $wpdb->prefix.'events_personnel'            => ['id'],
70
+            $wpdb->prefix.'events_personnel_rel'        => ['id'],
71 71
         ];
72 72
     }
73 73
 
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
     public static function instance()
82 82
     {
83 83
         // check if class object is instantiated
84
-        if (! self::$_instance instanceof EE_CSV) {
84
+        if ( ! self::$_instance instanceof EE_CSV) {
85 85
             self::$_instance = new self();
86 86
         }
87 87
         return self::$_instance;
@@ -157,24 +157,24 @@  discard block
 block discarded – undo
157 157
             // loop through each column
158 158
             for ($i = 0; $i < $columns; $i++) {
159 159
                 // replace csv_enclosures with backslashed quotes
160
-                $data[ $i ] = str_replace('"""', '\\"', $data[ $i ]);
160
+                $data[$i] = str_replace('"""', '\\"', $data[$i]);
161 161
                 // do we need to grab the column names?
162 162
                 if ($row === 1) {
163 163
                     if ($first_row_is_headers) {
164 164
                         // store the column names to use for keys
165
-                        $column_name = $data[ $i ];
165
+                        $column_name = $data[$i];
166 166
                         // check it's not blank... sometimes CSV editing programs
167 167
                         // add a bunch of empty columns onto the end...
168
-                        if (! $column_name) {
168
+                        if ( ! $column_name) {
169 169
                             continue;
170 170
                         }
171 171
                         $matches = [];
172 172
                         if ($model_name == EE_CSV::metadata_header) {
173
-                            $headers[ $i ] = $column_name;
173
+                            $headers[$i] = $column_name;
174 174
                         } else {
175 175
                             // now get the db table name from it (the part between square brackets)
176 176
                             $success = preg_match('~(.*)\[(.*)\]~', $column_name, $matches);
177
-                            if (! $success) {
177
+                            if ( ! $success) {
178 178
                                 EE_Error::add_error(
179 179
                                     sprintf(
180 180
                                         esc_html__(
@@ -190,24 +190,24 @@  discard block
 block discarded – undo
190 190
                                 );
191 191
                                 return false;
192 192
                             }
193
-                            $headers[ $i ] = $matches[2];
193
+                            $headers[$i] = $matches[2];
194 194
                         }
195 195
                     } else {
196 196
                         // no column names means our final array will just use counters for keys
197
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
198
-                        $headers[ $i ]                 = $i;
197
+                        $model_entry[$headers[$i]] = $data[$i];
198
+                        $headers[$i]                 = $i;
199 199
                     }
200 200
                     // and we need to store csv data
201 201
                 } else {
202 202
                     // this column isn' ta header, store it if there is a header for it
203
-                    if (isset($headers[ $i ])) {
204
-                        $model_entry[ $headers[ $i ] ] = $data[ $i ];
203
+                    if (isset($headers[$i])) {
204
+                        $model_entry[$headers[$i]] = $data[$i];
205 205
                     }
206 206
                 }
207 207
             }
208 208
             // save the row's data IF it's a non-header-row
209
-            if (! $first_row_is_headers || $row > 1) {
210
-                $ee_formatted_data[ $model_name ][] = $model_entry;
209
+            if ( ! $first_row_is_headers || $row > 1) {
210
+                $ee_formatted_data[$model_name][] = $model_entry;
211 211
             }
212 212
             // advance to next row
213 213
             $row++;
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
     {
292 292
         $fc = "";
293 293
         $fh = fopen($file_path, "rb");
294
-        if (! $fh) {
294
+        if ( ! $fh) {
295 295
             throw new EE_Error(
296 296
                 sprintf(
297 297
                     esc_html__("Cannot open file for read: %s<br>\n", 'event_espresso'),
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
         for ($i = 0; $i < $file_length; $i++) {
305 305
             $c = substr($bc, $i, 1);
306 306
             if ((ord($c) != 0) && (ord($c) != 13)) {
307
-                $fc = $fc . $c;
307
+                $fc = $fc.$c;
308 308
             }
309 309
         }
310 310
         if ((ord(substr($fc, 0, 1)) == 255) && (ord(substr($fc, 1, 1)) == 254)) {
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
         // header("Content-Type: application/force-download");
385 385
         // header("Content-Type: application/octet-stream");
386 386
         // header("Content-Type: application/download");
387
-        header('Content-disposition: attachment; filename=' . $filename);
387
+        header('Content-disposition: attachment; filename='.$filename);
388 388
         header("Content-Type: text/csv; charset=utf-8");
389 389
         do_action('AHEE__EE_CSV__begin_sending_csv__headers');
390 390
         echo apply_filters(
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
             $this->fputcsv2($file_handle, ['MODEL', $model_name]);
417 417
             // if we have items to put in the CSV, do it normally
418 418
 
419
-            if (! empty($model_instance_arrays)) {
419
+            if ( ! empty($model_instance_arrays)) {
420 420
                 $this->write_data_array_to_csv($file_handle, $model_instance_arrays);
421 421
             } else {
422 422
                 // echo "no data to write... so just write the headers";
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
                 $model        = EE_Registry::instance()->load_model($model_name);
426 426
                 $column_names = [];
427 427
                 foreach ($model->field_settings() as $field) {
428
-                    $column_names[ $field->get_nicename() . "[" . $field->get_name() . "]" ] = null;
428
+                    $column_names[$field->get_nicename()."[".$field->get_name()."]"] = null;
429 429
                 }
430 430
                 $this->write_data_array_to_csv($file_handle, [$column_names]);
431 431
             }
@@ -443,7 +443,7 @@  discard block
 block discarded – undo
443 443
      */
444 444
     public function write_metadata_to_csv($file_handle)
445 445
     {
446
-        $data_row = [EE_CSV::metadata_header];// do NOT translate because this exact string is used when importing
446
+        $data_row = [EE_CSV::metadata_header]; // do NOT translate because this exact string is used when importing
447 447
         $this->fputcsv2($file_handle, $data_row);
448 448
         $meta_data = [
449 449
             0 => [
@@ -487,11 +487,11 @@  discard block
 block discarded – undo
487 487
             }
488 488
 
489 489
             $output[] = preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field_value)
490
-                ? ($enclosure . str_replace($enclosure, $enclosure . $enclosure, $field_value) . $enclosure)
490
+                ? ($enclosure.str_replace($enclosure, $enclosure.$enclosure, $field_value).$enclosure)
491 491
                 : $field_value;
492 492
         }
493 493
 
494
-        fwrite($fh, join($delimiter, $output) . PHP_EOL);
494
+        fwrite($fh, join($delimiter, $output).PHP_EOL);
495 495
     }
496 496
 
497 497
 
@@ -565,12 +565,12 @@  discard block
 block discarded – undo
565 565
     public function export_array_to_csv($data = false, $filename = false)
566 566
     {
567 567
         // no data file?? get outta here
568
-        if (! $data or ! is_array($data) or empty($data)) {
568
+        if ( ! $data or ! is_array($data) or empty($data)) {
569 569
             return false;
570 570
         }
571 571
 
572 572
         // no filename?? get outta here
573
-        if (! $filename) {
573
+        if ( ! $filename) {
574 574
             return false;
575 575
         }
576 576
         $fh = $this->begin_sending_csv($filename);
Please login to merge, or discard this patch.
core/db_classes/EE_Currency.class.php 1 patch
Indentation   +234 added lines, -234 removed lines patch added patch discarded remove patch
@@ -10,238 +10,238 @@
 block discarded – undo
10 10
 class EE_Currency extends EE_Base_Class
11 11
 {
12 12
 
13
-    /** Currency COde
14
-     *
15
-     * @var CUR_code
16
-     */
17
-    protected $_CUR_code = null;
18
-
19
-    /** Currency Name Singular
20
-     *
21
-     * @var CUR_single
22
-     */
23
-    protected $_CUR_single = null;
24
-
25
-    /** Currency Name Plural
26
-     *
27
-     * @var CUR_plural
28
-     */
29
-    protected $_CUR_plural = null;
30
-
31
-    /** Currency Sign
32
-     *
33
-     * @var CUR_sign
34
-     */
35
-    protected $_CUR_sign = null;
36
-
37
-    /** Currency Decimal Places
38
-     *
39
-     * @var CUR_dec_plc
40
-     */
41
-    protected $_CUR_dec_plc = null;
42
-
43
-    /** Active?
44
-     *
45
-     * @var CUR_active
46
-     */
47
-    protected $_CUR_active = null;
48
-
49
-    protected $_Payment_Method;
50
-
51
-
52
-    /**
53
-     * @param array  $props_n_values          incoming values
54
-     * @param string $timezone                incoming timezone
55
-     *                                        (if not set the timezone set for the website will be used.)
56
-     * @param array  $date_formats            incoming date_formats in an array where the first value is the
57
-     *                                        date_format and the second value is the time format
58
-     * @return EE_Currency
59
-     * @throws EE_Error
60
-     * @throws ReflectionException
61
-     */
62
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
63
-    {
64
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
65
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
66
-    }
67
-
68
-
69
-    /**
70
-     * @param array  $props_n_values  incoming values from the database
71
-     * @param string $timezone        incoming timezone as set by the model.
72
-     *                                If not set the timezone for the website will be used.
73
-     * @return EE_Currency
74
-     * @throws EE_Error
75
-     * @throws ReflectionException
76
-     */
77
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
78
-    {
79
-        return new self($props_n_values, true, $timezone);
80
-    }
81
-
82
-
83
-    /**
84
-     * Sets code
85
-     *
86
-     * @param string $code
87
-     * @throws EE_Error
88
-     * @throws ReflectionException
89
-     */
90
-    public function set_code($code)
91
-    {
92
-        $this->set('CUR_code', $code);
93
-    }
94
-
95
-
96
-    /**
97
-     * Gets active
98
-     *
99
-     * @return boolean
100
-     * @throws EE_Error
101
-     */
102
-    public function active()
103
-    {
104
-        return $this->get('CUR_active');
105
-    }
106
-
107
-
108
-    /**
109
-     * Sets active
110
-     *
111
-     * @param boolean $active
112
-     * @throws EE_Error
113
-     * @throws ReflectionException
114
-     */
115
-    public function set_active($active)
116
-    {
117
-        $this->set('CUR_active', $active);
118
-    }
119
-
120
-
121
-    /**
122
-     * Gets dec_plc
123
-     *
124
-     * @return int
125
-     * @throws EE_Error
126
-     */
127
-    public function dec_plc()
128
-    {
129
-        return $this->get('CUR_dec_plc');
130
-    }
131
-
132
-
133
-    /**
134
-     * Sets dec_plc
135
-     *
136
-     * @param int $dec_plc
137
-     * @throws EE_Error
138
-     * @throws ReflectionException
139
-     */
140
-    public function set_dec_plc($dec_plc)
141
-    {
142
-        $this->set('CUR_dec_plc', $dec_plc);
143
-    }
144
-
145
-
146
-    /**
147
-     * Sets plural
148
-     *
149
-     * @param string $plural
150
-     * @throws EE_Error
151
-     * @throws ReflectionException
152
-     */
153
-    public function set_plural_name($plural)
154
-    {
155
-        $this->set('CUR_plural', $plural);
156
-    }
157
-
158
-
159
-    /**
160
-     * Gets sign
161
-     *
162
-     * @return string
163
-     * @throws EE_Error
164
-     */
165
-    public function sign()
166
-    {
167
-        return $this->get('CUR_sign');
168
-    }
169
-
170
-
171
-    /**
172
-     * Sets sign
173
-     *
174
-     * @param string $sign
175
-     * @throws EE_Error
176
-     * @throws ReflectionException
177
-     */
178
-    public function set_sign($sign)
179
-    {
180
-        $this->set('CUR_sign', $sign);
181
-    }
182
-
183
-
184
-    /**
185
-     * Gets single
186
-     *
187
-     * @return string
188
-     * @throws EE_Error
189
-     */
190
-    public function singular_name()
191
-    {
192
-        return $this->get('CUR_single');
193
-    }
194
-
195
-
196
-    /**
197
-     * Sets single
198
-     *
199
-     * @param string $single
200
-     * @throws EE_Error
201
-     * @throws ReflectionException
202
-     */
203
-    public function set_singular_name($single)
204
-    {
205
-        $this->set('CUR_single', $single);
206
-    }
207
-
208
-
209
-    /**
210
-     * Gets a prettier name
211
-     *
212
-     * @return string
213
-     * @throws EE_Error
214
-     */
215
-    public function name()
216
-    {
217
-        return sprintf(
218
-            esc_html__("%s (%s)", "event_espresso"),
219
-            $this->code(),
220
-            $this->plural_name()
221
-        );
222
-    }
223
-
224
-
225
-    /**
226
-     * Gets code
227
-     *
228
-     * @return string
229
-     * @throws EE_Error
230
-     */
231
-    public function code()
232
-    {
233
-        return $this->get('CUR_code');
234
-    }
235
-
236
-
237
-    /**
238
-     * Gets plural
239
-     *
240
-     * @return string
241
-     * @throws EE_Error
242
-     */
243
-    public function plural_name()
244
-    {
245
-        return $this->get('CUR_plural');
246
-    }
13
+	/** Currency COde
14
+	 *
15
+	 * @var CUR_code
16
+	 */
17
+	protected $_CUR_code = null;
18
+
19
+	/** Currency Name Singular
20
+	 *
21
+	 * @var CUR_single
22
+	 */
23
+	protected $_CUR_single = null;
24
+
25
+	/** Currency Name Plural
26
+	 *
27
+	 * @var CUR_plural
28
+	 */
29
+	protected $_CUR_plural = null;
30
+
31
+	/** Currency Sign
32
+	 *
33
+	 * @var CUR_sign
34
+	 */
35
+	protected $_CUR_sign = null;
36
+
37
+	/** Currency Decimal Places
38
+	 *
39
+	 * @var CUR_dec_plc
40
+	 */
41
+	protected $_CUR_dec_plc = null;
42
+
43
+	/** Active?
44
+	 *
45
+	 * @var CUR_active
46
+	 */
47
+	protected $_CUR_active = null;
48
+
49
+	protected $_Payment_Method;
50
+
51
+
52
+	/**
53
+	 * @param array  $props_n_values          incoming values
54
+	 * @param string $timezone                incoming timezone
55
+	 *                                        (if not set the timezone set for the website will be used.)
56
+	 * @param array  $date_formats            incoming date_formats in an array where the first value is the
57
+	 *                                        date_format and the second value is the time format
58
+	 * @return EE_Currency
59
+	 * @throws EE_Error
60
+	 * @throws ReflectionException
61
+	 */
62
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
63
+	{
64
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
65
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
66
+	}
67
+
68
+
69
+	/**
70
+	 * @param array  $props_n_values  incoming values from the database
71
+	 * @param string $timezone        incoming timezone as set by the model.
72
+	 *                                If not set the timezone for the website will be used.
73
+	 * @return EE_Currency
74
+	 * @throws EE_Error
75
+	 * @throws ReflectionException
76
+	 */
77
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
78
+	{
79
+		return new self($props_n_values, true, $timezone);
80
+	}
81
+
82
+
83
+	/**
84
+	 * Sets code
85
+	 *
86
+	 * @param string $code
87
+	 * @throws EE_Error
88
+	 * @throws ReflectionException
89
+	 */
90
+	public function set_code($code)
91
+	{
92
+		$this->set('CUR_code', $code);
93
+	}
94
+
95
+
96
+	/**
97
+	 * Gets active
98
+	 *
99
+	 * @return boolean
100
+	 * @throws EE_Error
101
+	 */
102
+	public function active()
103
+	{
104
+		return $this->get('CUR_active');
105
+	}
106
+
107
+
108
+	/**
109
+	 * Sets active
110
+	 *
111
+	 * @param boolean $active
112
+	 * @throws EE_Error
113
+	 * @throws ReflectionException
114
+	 */
115
+	public function set_active($active)
116
+	{
117
+		$this->set('CUR_active', $active);
118
+	}
119
+
120
+
121
+	/**
122
+	 * Gets dec_plc
123
+	 *
124
+	 * @return int
125
+	 * @throws EE_Error
126
+	 */
127
+	public function dec_plc()
128
+	{
129
+		return $this->get('CUR_dec_plc');
130
+	}
131
+
132
+
133
+	/**
134
+	 * Sets dec_plc
135
+	 *
136
+	 * @param int $dec_plc
137
+	 * @throws EE_Error
138
+	 * @throws ReflectionException
139
+	 */
140
+	public function set_dec_plc($dec_plc)
141
+	{
142
+		$this->set('CUR_dec_plc', $dec_plc);
143
+	}
144
+
145
+
146
+	/**
147
+	 * Sets plural
148
+	 *
149
+	 * @param string $plural
150
+	 * @throws EE_Error
151
+	 * @throws ReflectionException
152
+	 */
153
+	public function set_plural_name($plural)
154
+	{
155
+		$this->set('CUR_plural', $plural);
156
+	}
157
+
158
+
159
+	/**
160
+	 * Gets sign
161
+	 *
162
+	 * @return string
163
+	 * @throws EE_Error
164
+	 */
165
+	public function sign()
166
+	{
167
+		return $this->get('CUR_sign');
168
+	}
169
+
170
+
171
+	/**
172
+	 * Sets sign
173
+	 *
174
+	 * @param string $sign
175
+	 * @throws EE_Error
176
+	 * @throws ReflectionException
177
+	 */
178
+	public function set_sign($sign)
179
+	{
180
+		$this->set('CUR_sign', $sign);
181
+	}
182
+
183
+
184
+	/**
185
+	 * Gets single
186
+	 *
187
+	 * @return string
188
+	 * @throws EE_Error
189
+	 */
190
+	public function singular_name()
191
+	{
192
+		return $this->get('CUR_single');
193
+	}
194
+
195
+
196
+	/**
197
+	 * Sets single
198
+	 *
199
+	 * @param string $single
200
+	 * @throws EE_Error
201
+	 * @throws ReflectionException
202
+	 */
203
+	public function set_singular_name($single)
204
+	{
205
+		$this->set('CUR_single', $single);
206
+	}
207
+
208
+
209
+	/**
210
+	 * Gets a prettier name
211
+	 *
212
+	 * @return string
213
+	 * @throws EE_Error
214
+	 */
215
+	public function name()
216
+	{
217
+		return sprintf(
218
+			esc_html__("%s (%s)", "event_espresso"),
219
+			$this->code(),
220
+			$this->plural_name()
221
+		);
222
+	}
223
+
224
+
225
+	/**
226
+	 * Gets code
227
+	 *
228
+	 * @return string
229
+	 * @throws EE_Error
230
+	 */
231
+	public function code()
232
+	{
233
+		return $this->get('CUR_code');
234
+	}
235
+
236
+
237
+	/**
238
+	 * Gets plural
239
+	 *
240
+	 * @return string
241
+	 * @throws EE_Error
242
+	 */
243
+	public function plural_name()
244
+	{
245
+		return $this->get('CUR_plural');
246
+	}
247 247
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Country.class.php 1 patch
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -10,136 +10,136 @@
 block discarded – undo
10 10
 class EE_Country extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array $props_n_values
15
-     * @return EE_Country|mixed
16
-     * @throws EE_Error
17
-     * @throws ReflectionException
18
-     */
19
-    public static function new_instance($props_n_values = [])
20
-    {
21
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
-        return $has_object ? $has_object : new self($props_n_values);
23
-    }
24
-
25
-
26
-    /**
27
-     * @param array $props_n_values
28
-     * @return EE_Country
29
-     * @throws EE_Error
30
-     * @throws ReflectionException
31
-     */
32
-    public static function new_instance_from_db($props_n_values = [])
33
-    {
34
-        return new self($props_n_values, true);
35
-    }
36
-
37
-
38
-    /**
39
-     * Gets the country name
40
-     *
41
-     * @return string
42
-     * @throws EE_Error
43
-     */
44
-    public function name()
45
-    {
46
-        return $this->get('CNT_name');
47
-    }
48
-
49
-
50
-    /**
51
-     * gets the country's currency code
52
-     *
53
-     * @return string
54
-     * @throws EE_Error
55
-     */
56
-    public function currency_code()
57
-    {
58
-        return $this->get('CNT_cur_code');
59
-    }
60
-
61
-
62
-    /**
63
-     * gets the country's currency sign/symbol
64
-     *
65
-     * @return string
66
-     * @throws EE_Error
67
-     */
68
-    public function currency_sign()
69
-    {
70
-        $CNT_cur_sign = $this->get('CNT_cur_sign');
71
-        return $CNT_cur_sign ? $CNT_cur_sign : '';
72
-    }
73
-
74
-
75
-    /**
76
-     * Currency name singular
77
-     *
78
-     * @return string
79
-     * @throws EE_Error
80
-     */
81
-    public function currency_name_single()
82
-    {
83
-        return $this->get('CNT_cur_single');
84
-    }
85
-
86
-
87
-    /**
88
-     * Currency name plural
89
-     *
90
-     * @return string
91
-     * @throws EE_Error
92
-     */
93
-    public function currency_name_plural()
94
-    {
95
-        return $this->get('CNT_cur_plural');
96
-    }
97
-
98
-
99
-    /**
100
-     * currency_sign_before - ie: $TRUE  or  FALSE$
101
-     *
102
-     * @return boolean
103
-     * @throws EE_Error
104
-     */
105
-    public function currency_sign_before()
106
-    {
107
-        return $this->get('CNT_cur_sign_b4');
108
-    }
109
-
110
-
111
-    /**
112
-     * currency_decimal_places : 2 = 0.00   3 = 0.000
113
-     *
114
-     * @return integer
115
-     * @throws EE_Error
116
-     */
117
-    public function currency_decimal_places()
118
-    {
119
-        return $this->get('CNT_cur_dec_plc');
120
-    }
121
-
122
-
123
-    /**
124
-     * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
125
-     *
126
-     * @return string
127
-     * @throws EE_Error
128
-     */
129
-    public function currency_decimal_mark()
130
-    {
131
-        return $this->get('CNT_cur_dec_mrk');
132
-    }
133
-
134
-
135
-    /**
136
-     * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
137
-     *
138
-     * @return string
139
-     * @throws EE_Error
140
-     */
141
-    public function currency_thousands_separator()
142
-    {
143
-        return $this->get('CNT_cur_thsnds');
144
-    }
13
+	/**
14
+	 * @param array $props_n_values
15
+	 * @return EE_Country|mixed
16
+	 * @throws EE_Error
17
+	 * @throws ReflectionException
18
+	 */
19
+	public static function new_instance($props_n_values = [])
20
+	{
21
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
22
+		return $has_object ? $has_object : new self($props_n_values);
23
+	}
24
+
25
+
26
+	/**
27
+	 * @param array $props_n_values
28
+	 * @return EE_Country
29
+	 * @throws EE_Error
30
+	 * @throws ReflectionException
31
+	 */
32
+	public static function new_instance_from_db($props_n_values = [])
33
+	{
34
+		return new self($props_n_values, true);
35
+	}
36
+
37
+
38
+	/**
39
+	 * Gets the country name
40
+	 *
41
+	 * @return string
42
+	 * @throws EE_Error
43
+	 */
44
+	public function name()
45
+	{
46
+		return $this->get('CNT_name');
47
+	}
48
+
49
+
50
+	/**
51
+	 * gets the country's currency code
52
+	 *
53
+	 * @return string
54
+	 * @throws EE_Error
55
+	 */
56
+	public function currency_code()
57
+	{
58
+		return $this->get('CNT_cur_code');
59
+	}
60
+
61
+
62
+	/**
63
+	 * gets the country's currency sign/symbol
64
+	 *
65
+	 * @return string
66
+	 * @throws EE_Error
67
+	 */
68
+	public function currency_sign()
69
+	{
70
+		$CNT_cur_sign = $this->get('CNT_cur_sign');
71
+		return $CNT_cur_sign ? $CNT_cur_sign : '';
72
+	}
73
+
74
+
75
+	/**
76
+	 * Currency name singular
77
+	 *
78
+	 * @return string
79
+	 * @throws EE_Error
80
+	 */
81
+	public function currency_name_single()
82
+	{
83
+		return $this->get('CNT_cur_single');
84
+	}
85
+
86
+
87
+	/**
88
+	 * Currency name plural
89
+	 *
90
+	 * @return string
91
+	 * @throws EE_Error
92
+	 */
93
+	public function currency_name_plural()
94
+	{
95
+		return $this->get('CNT_cur_plural');
96
+	}
97
+
98
+
99
+	/**
100
+	 * currency_sign_before - ie: $TRUE  or  FALSE$
101
+	 *
102
+	 * @return boolean
103
+	 * @throws EE_Error
104
+	 */
105
+	public function currency_sign_before()
106
+	{
107
+		return $this->get('CNT_cur_sign_b4');
108
+	}
109
+
110
+
111
+	/**
112
+	 * currency_decimal_places : 2 = 0.00   3 = 0.000
113
+	 *
114
+	 * @return integer
115
+	 * @throws EE_Error
116
+	 */
117
+	public function currency_decimal_places()
118
+	{
119
+		return $this->get('CNT_cur_dec_plc');
120
+	}
121
+
122
+
123
+	/**
124
+	 * currency_decimal_mark :   (comma) ',' = 0,01   or   (decimal) '.' = 0.01
125
+	 *
126
+	 * @return string
127
+	 * @throws EE_Error
128
+	 */
129
+	public function currency_decimal_mark()
130
+	{
131
+		return $this->get('CNT_cur_dec_mrk');
132
+	}
133
+
134
+
135
+	/**
136
+	 * currency thousands separator:   (comma) ',' = 1,000   or   (decimal) '.' = 1.000
137
+	 *
138
+	 * @return string
139
+	 * @throws EE_Error
140
+	 */
141
+	public function currency_thousands_separator()
142
+	{
143
+		return $this->get('CNT_cur_thsnds');
144
+	}
145 145
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Change_Log.class.php 2 patches
Indentation   +236 added lines, -236 removed lines patch added patch discarded remove patch
@@ -10,240 +10,240 @@
 block discarded – undo
10 10
 class EE_Change_Log extends EE_Base_Class
11 11
 {
12 12
 
13
-    /**
14
-     * @param array  $props_n_values    incoming values
15
-     * @param string $timezone          incoming timezone
16
-     *                                  If not set the timezone for the website will be used.
17
-     * @param array  $date_formats      incoming date_formats in an array where the first value is the
18
-     *                                  date_format and the second value is the time format
19
-     * @return EE_Change_Log
20
-     * @throws EE_Error
21
-     * @throws ReflectionException
22
-     */
23
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
24
-    {
25
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
-    }
28
-
29
-
30
-    /**
31
-     * @param array  $props_n_values  incoming values from the database
32
-     * @param string $timezone        incoming timezone as set by the model.
33
-     *                                If not set the timezone for the website will be used.
34
-     * @return EE_Change_Log
35
-     * @throws EE_Error
36
-     * @throws ReflectionException
37
-     */
38
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
39
-    {
40
-        return new self($props_n_values, true, $timezone);
41
-    }
42
-
43
-
44
-    /**
45
-     * Gets message
46
-     *
47
-     * @return mixed
48
-     * @throws EE_Error
49
-     */
50
-    public function message()
51
-    {
52
-        return $this->get('LOG_message');
53
-    }
54
-
55
-
56
-    /**
57
-     * Sets message
58
-     *
59
-     * @param mixed $message
60
-     * @throws EE_Error
61
-     * @throws ReflectionException
62
-     */
63
-    public function set_message($message)
64
-    {
65
-        $this->set('LOG_message', $message);
66
-    }
67
-
68
-
69
-    /**
70
-     * Gets time
71
-     *
72
-     * @return string
73
-     * @throws EE_Error
74
-     */
75
-    public function time()
76
-    {
77
-        return $this->get('LOG_time');
78
-    }
79
-
80
-
81
-    /**
82
-     * Sets time
83
-     *
84
-     * @param string $time
85
-     * @throws EE_Error
86
-     * @throws ReflectionException
87
-     */
88
-    public function set_time($time)
89
-    {
90
-        $this->set('LOG_time', $time);
91
-    }
92
-
93
-
94
-    /**
95
-     * Return the localized log type label.
96
-     *
97
-     * @return string
98
-     * @throws EE_Error
99
-     */
100
-    public function log_type_label()
101
-    {
102
-        return EEM_Change_Log::get_pretty_label_for_type($this->log_type());
103
-    }
104
-
105
-
106
-    /**
107
-     * Gets log_type
108
-     *
109
-     * @return string
110
-     * @throws EE_Error
111
-     */
112
-    public function log_type()
113
-    {
114
-        return $this->get('LOG_type');
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets log_type
120
-     *
121
-     * @param string $log_type
122
-     * @throws EE_Error
123
-     * @throws ReflectionException
124
-     */
125
-    public function set_log_type($log_type)
126
-    {
127
-        $this->set('LOG_type', $log_type);
128
-    }
129
-
130
-
131
-    /**
132
-     * Gets OBJ_ID (the ID of the item related to this log)
133
-     *
134
-     * @return mixed
135
-     * @throws EE_Error
136
-     */
137
-    public function OBJ_ID()
138
-    {
139
-        return $this->get('OBJ_ID');
140
-    }
141
-
142
-
143
-    /**
144
-     * Gets wp_user
145
-     *
146
-     * @return int
147
-     * @throws EE_Error
148
-     */
149
-    public function wp_user()
150
-    {
151
-        return $this->get('LOG_wp_user');
152
-    }
153
-
154
-
155
-    /**
156
-     * Sets wp_user
157
-     *
158
-     * @param int $wp_user_id
159
-     * @throws EE_Error
160
-     * @throws ReflectionException
161
-     */
162
-    public function set_wp_user($wp_user_id)
163
-    {
164
-        $this->set('LOG_wp_user', $wp_user_id);
165
-    }
166
-
167
-
168
-    /**
169
-     * Gets the model object attached to this log
170
-     *
171
-     * @return EE_Base_Class
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     */
175
-    public function object()
176
-    {
177
-        $model_name_of_related_obj = $this->OBJ_type();
178
-        $is_model_name             = EE_Registry::instance()->is_model_name($model_name_of_related_obj);
179
-        if (! $is_model_name) {
180
-            return null;
181
-        }
182
-        return $this->get_first_related($model_name_of_related_obj);
183
-    }
184
-
185
-
186
-    /**
187
-     * Gets type of the model object related to this log
188
-     *
189
-     * @return string
190
-     * @throws EE_Error
191
-     */
192
-    public function OBJ_type()
193
-    {
194
-        return $this->get('OBJ_type');
195
-    }
196
-
197
-
198
-    /**
199
-     * Shorthand for setting the OBJ_ID and OBJ_type. Slightly handier than using
200
-     * _add_relation_to because you don't have to specify what type of model you're
201
-     * associating it with
202
-     *
203
-     * @param EE_Base_Class $object
204
-     * @param boolean       $save
205
-     * @return bool if $save=true, NULL is $save=false
206
-     * @throws EE_Error
207
-     * @throws ReflectionException
208
-     */
209
-    public function set_object($object, $save = true)
210
-    {
211
-        if ($object instanceof EE_Base_Class) {
212
-            $this->set_OBJ_type($object->get_model()->get_this_model_name());
213
-            $this->set_OBJ_ID($object->ID());
214
-        } else {
215
-            $this->set_OBJ_type(null);
216
-            $this->set_OBJ_ID(null);
217
-        }
218
-        if ($save) {
219
-            return $this->save();
220
-        }
221
-        return null;
222
-    }
223
-
224
-
225
-    /**
226
-     * Sets type
227
-     *
228
-     * @param string $type
229
-     * @throws EE_Error
230
-     * @throws ReflectionException
231
-     */
232
-    public function set_OBJ_type($type)
233
-    {
234
-        $this->set('OBJ_type', $type);
235
-    }
236
-
237
-
238
-    /**
239
-     * Sets OBJ_ID
240
-     *
241
-     * @param mixed $OBJ_ID
242
-     * @throws EE_Error
243
-     * @throws ReflectionException
244
-     */
245
-    public function set_OBJ_ID($OBJ_ID)
246
-    {
247
-        $this->set('OBJ_ID', $OBJ_ID);
248
-    }
13
+	/**
14
+	 * @param array  $props_n_values    incoming values
15
+	 * @param string $timezone          incoming timezone
16
+	 *                                  If not set the timezone for the website will be used.
17
+	 * @param array  $date_formats      incoming date_formats in an array where the first value is the
18
+	 *                                  date_format and the second value is the time format
19
+	 * @return EE_Change_Log
20
+	 * @throws EE_Error
21
+	 * @throws ReflectionException
22
+	 */
23
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
24
+	{
25
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
26
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
27
+	}
28
+
29
+
30
+	/**
31
+	 * @param array  $props_n_values  incoming values from the database
32
+	 * @param string $timezone        incoming timezone as set by the model.
33
+	 *                                If not set the timezone for the website will be used.
34
+	 * @return EE_Change_Log
35
+	 * @throws EE_Error
36
+	 * @throws ReflectionException
37
+	 */
38
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
39
+	{
40
+		return new self($props_n_values, true, $timezone);
41
+	}
42
+
43
+
44
+	/**
45
+	 * Gets message
46
+	 *
47
+	 * @return mixed
48
+	 * @throws EE_Error
49
+	 */
50
+	public function message()
51
+	{
52
+		return $this->get('LOG_message');
53
+	}
54
+
55
+
56
+	/**
57
+	 * Sets message
58
+	 *
59
+	 * @param mixed $message
60
+	 * @throws EE_Error
61
+	 * @throws ReflectionException
62
+	 */
63
+	public function set_message($message)
64
+	{
65
+		$this->set('LOG_message', $message);
66
+	}
67
+
68
+
69
+	/**
70
+	 * Gets time
71
+	 *
72
+	 * @return string
73
+	 * @throws EE_Error
74
+	 */
75
+	public function time()
76
+	{
77
+		return $this->get('LOG_time');
78
+	}
79
+
80
+
81
+	/**
82
+	 * Sets time
83
+	 *
84
+	 * @param string $time
85
+	 * @throws EE_Error
86
+	 * @throws ReflectionException
87
+	 */
88
+	public function set_time($time)
89
+	{
90
+		$this->set('LOG_time', $time);
91
+	}
92
+
93
+
94
+	/**
95
+	 * Return the localized log type label.
96
+	 *
97
+	 * @return string
98
+	 * @throws EE_Error
99
+	 */
100
+	public function log_type_label()
101
+	{
102
+		return EEM_Change_Log::get_pretty_label_for_type($this->log_type());
103
+	}
104
+
105
+
106
+	/**
107
+	 * Gets log_type
108
+	 *
109
+	 * @return string
110
+	 * @throws EE_Error
111
+	 */
112
+	public function log_type()
113
+	{
114
+		return $this->get('LOG_type');
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets log_type
120
+	 *
121
+	 * @param string $log_type
122
+	 * @throws EE_Error
123
+	 * @throws ReflectionException
124
+	 */
125
+	public function set_log_type($log_type)
126
+	{
127
+		$this->set('LOG_type', $log_type);
128
+	}
129
+
130
+
131
+	/**
132
+	 * Gets OBJ_ID (the ID of the item related to this log)
133
+	 *
134
+	 * @return mixed
135
+	 * @throws EE_Error
136
+	 */
137
+	public function OBJ_ID()
138
+	{
139
+		return $this->get('OBJ_ID');
140
+	}
141
+
142
+
143
+	/**
144
+	 * Gets wp_user
145
+	 *
146
+	 * @return int
147
+	 * @throws EE_Error
148
+	 */
149
+	public function wp_user()
150
+	{
151
+		return $this->get('LOG_wp_user');
152
+	}
153
+
154
+
155
+	/**
156
+	 * Sets wp_user
157
+	 *
158
+	 * @param int $wp_user_id
159
+	 * @throws EE_Error
160
+	 * @throws ReflectionException
161
+	 */
162
+	public function set_wp_user($wp_user_id)
163
+	{
164
+		$this->set('LOG_wp_user', $wp_user_id);
165
+	}
166
+
167
+
168
+	/**
169
+	 * Gets the model object attached to this log
170
+	 *
171
+	 * @return EE_Base_Class
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 */
175
+	public function object()
176
+	{
177
+		$model_name_of_related_obj = $this->OBJ_type();
178
+		$is_model_name             = EE_Registry::instance()->is_model_name($model_name_of_related_obj);
179
+		if (! $is_model_name) {
180
+			return null;
181
+		}
182
+		return $this->get_first_related($model_name_of_related_obj);
183
+	}
184
+
185
+
186
+	/**
187
+	 * Gets type of the model object related to this log
188
+	 *
189
+	 * @return string
190
+	 * @throws EE_Error
191
+	 */
192
+	public function OBJ_type()
193
+	{
194
+		return $this->get('OBJ_type');
195
+	}
196
+
197
+
198
+	/**
199
+	 * Shorthand for setting the OBJ_ID and OBJ_type. Slightly handier than using
200
+	 * _add_relation_to because you don't have to specify what type of model you're
201
+	 * associating it with
202
+	 *
203
+	 * @param EE_Base_Class $object
204
+	 * @param boolean       $save
205
+	 * @return bool if $save=true, NULL is $save=false
206
+	 * @throws EE_Error
207
+	 * @throws ReflectionException
208
+	 */
209
+	public function set_object($object, $save = true)
210
+	{
211
+		if ($object instanceof EE_Base_Class) {
212
+			$this->set_OBJ_type($object->get_model()->get_this_model_name());
213
+			$this->set_OBJ_ID($object->ID());
214
+		} else {
215
+			$this->set_OBJ_type(null);
216
+			$this->set_OBJ_ID(null);
217
+		}
218
+		if ($save) {
219
+			return $this->save();
220
+		}
221
+		return null;
222
+	}
223
+
224
+
225
+	/**
226
+	 * Sets type
227
+	 *
228
+	 * @param string $type
229
+	 * @throws EE_Error
230
+	 * @throws ReflectionException
231
+	 */
232
+	public function set_OBJ_type($type)
233
+	{
234
+		$this->set('OBJ_type', $type);
235
+	}
236
+
237
+
238
+	/**
239
+	 * Sets OBJ_ID
240
+	 *
241
+	 * @param mixed $OBJ_ID
242
+	 * @throws EE_Error
243
+	 * @throws ReflectionException
244
+	 */
245
+	public function set_OBJ_ID($OBJ_ID)
246
+	{
247
+		$this->set('OBJ_ID', $OBJ_ID);
248
+	}
249 249
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@
 block discarded – undo
176 176
     {
177 177
         $model_name_of_related_obj = $this->OBJ_type();
178 178
         $is_model_name             = EE_Registry::instance()->is_model_name($model_name_of_related_obj);
179
-        if (! $is_model_name) {
179
+        if ( ! $is_model_name) {
180 180
             return null;
181 181
         }
182 182
         return $this->get_first_related($model_name_of_related_obj);
Please login to merge, or discard this patch.
core/db_classes/EE_Checkin.class.php 1 patch
Indentation   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -11,107 +11,107 @@
 block discarded – undo
11 11
 {
12 12
 
13 13
 
14
-    /**
15
-     * Used to reference when a registration has been checked out.
16
-     *
17
-     * @type int
18
-     */
19
-    const status_checked_out = 0;
20
-
21
-    /**
22
-     * Used to reference when a registration has been checked in.
23
-     *
24
-     * @type int
25
-     */
26
-    const status_checked_in = 1;
27
-
28
-    /**
29
-     * Used to reference when a registration has never been checked in.
30
-     *
31
-     * @type int
32
-     */
33
-    const status_checked_never = 2;
34
-
35
-
36
-    /**
37
-     * @param array  $props_n_values    incoming values
38
-     * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
39
-     * @param array  $date_formats      incoming date_formats in an array
40
-     *                                  where the first value is the date_format
41
-     *                                  and the second value is the time format
42
-     * @return EE_Checkin
43
-     * @throws EE_Error
44
-     * @throws ReflectionException
45
-     */
46
-    public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
47
-    {
48
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
49
-        return $has_object
50
-            ? $has_object
51
-            : new self($props_n_values, false, $timezone, $date_formats);
52
-    }
53
-
54
-
55
-    /**
56
-     * @param array  $props_n_values  incoming values from the database
57
-     * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
58
-     *                                the website will be used.
59
-     * @return EE_Checkin
60
-     * @throws EE_Error
61
-     * @throws ReflectionException
62
-     */
63
-    public static function new_instance_from_db($props_n_values = [], $timezone = null)
64
-    {
65
-        return new self($props_n_values, true, $timezone);
66
-    }
67
-
68
-
69
-    /**
70
-     * @return mixed
71
-     * @throws EE_Error
72
-     */
73
-    public function ID()
74
-    {
75
-        return $this->get('CHK_ID');
76
-    }
77
-
78
-
79
-    /**
80
-     * @return mixed
81
-     * @throws EE_Error
82
-     */
83
-    public function registration_id()
84
-    {
85
-        return $this->get('REG_ID');
86
-    }
87
-
88
-
89
-    /**
90
-     * @return mixed
91
-     * @throws EE_Error
92
-     */
93
-    public function datetime_id()
94
-    {
95
-        return $this->get('DTT_ID');
96
-    }
97
-
98
-
99
-    /**
100
-     * @return mixed
101
-     * @throws EE_Error
102
-     */
103
-    public function status()
104
-    {
105
-        return $this->get('CHK_in');
106
-    }
107
-
108
-
109
-    /**
110
-     * @return mixed
111
-     * @throws EE_Error
112
-     */
113
-    public function timestamp()
114
-    {
115
-        return $this->get('CHK_timestamp');
116
-    }
14
+	/**
15
+	 * Used to reference when a registration has been checked out.
16
+	 *
17
+	 * @type int
18
+	 */
19
+	const status_checked_out = 0;
20
+
21
+	/**
22
+	 * Used to reference when a registration has been checked in.
23
+	 *
24
+	 * @type int
25
+	 */
26
+	const status_checked_in = 1;
27
+
28
+	/**
29
+	 * Used to reference when a registration has never been checked in.
30
+	 *
31
+	 * @type int
32
+	 */
33
+	const status_checked_never = 2;
34
+
35
+
36
+	/**
37
+	 * @param array  $props_n_values    incoming values
38
+	 * @param string $timezone          incoming timezone (if not set the timezone set for the website will be used.)
39
+	 * @param array  $date_formats      incoming date_formats in an array
40
+	 *                                  where the first value is the date_format
41
+	 *                                  and the second value is the time format
42
+	 * @return EE_Checkin
43
+	 * @throws EE_Error
44
+	 * @throws ReflectionException
45
+	 */
46
+	public static function new_instance($props_n_values = [], $timezone = null, $date_formats = [])
47
+	{
48
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
49
+		return $has_object
50
+			? $has_object
51
+			: new self($props_n_values, false, $timezone, $date_formats);
52
+	}
53
+
54
+
55
+	/**
56
+	 * @param array  $props_n_values  incoming values from the database
57
+	 * @param string $timezone        incoming timezone as set by the model.  If not set the timezone for
58
+	 *                                the website will be used.
59
+	 * @return EE_Checkin
60
+	 * @throws EE_Error
61
+	 * @throws ReflectionException
62
+	 */
63
+	public static function new_instance_from_db($props_n_values = [], $timezone = null)
64
+	{
65
+		return new self($props_n_values, true, $timezone);
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return mixed
71
+	 * @throws EE_Error
72
+	 */
73
+	public function ID()
74
+	{
75
+		return $this->get('CHK_ID');
76
+	}
77
+
78
+
79
+	/**
80
+	 * @return mixed
81
+	 * @throws EE_Error
82
+	 */
83
+	public function registration_id()
84
+	{
85
+		return $this->get('REG_ID');
86
+	}
87
+
88
+
89
+	/**
90
+	 * @return mixed
91
+	 * @throws EE_Error
92
+	 */
93
+	public function datetime_id()
94
+	{
95
+		return $this->get('DTT_ID');
96
+	}
97
+
98
+
99
+	/**
100
+	 * @return mixed
101
+	 * @throws EE_Error
102
+	 */
103
+	public function status()
104
+	{
105
+		return $this->get('CHK_in');
106
+	}
107
+
108
+
109
+	/**
110
+	 * @return mixed
111
+	 * @throws EE_Error
112
+	 */
113
+	public function timestamp()
114
+	{
115
+		return $this->get('CHK_timestamp');
116
+	}
117 117
 }
Please login to merge, or discard this patch.