Completed
Branch FET-9222-rest-api-writes (7bafae)
by
unknown
80:38 queued 68:21
created
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +16 added lines, -14 removed lines patch added patch discarded remove patch
@@ -950,7 +950,7 @@  discard block
 block discarded – undo
950 950
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
951 951
      * foreign key to the WP_User table)
952 952
      *
953
-     * @return string|boolean string on success, boolean false when there is no
953
+     * @return string|false string on success, boolean false when there is no
954 954
      * foreign key to the WP_User table
955 955
      */
956 956
     public function wp_user_field_name()
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
      *
1057 1057
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1058 1058
      * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1059
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1059
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1060 1060
      *                                  fields on the model, and the models we joined to in the query. However, you can
1061 1061
      *                                  override this and set the select to "*", or a specific column name, like
1062 1062
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1448,7 +1448,7 @@  discard block
 block discarded – undo
1448 1448
      * @param string $field_name The name of the field the formats are being retrieved for.
1449 1449
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1450 1450
      * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1451
-     * @return array formats in an array with the date format first, and the time format last.
1451
+     * @return string[] formats in an array with the date format first, and the time format last.
1452 1452
      */
1453 1453
     public function get_formats_for($field_name, $pretty = false)
1454 1454
     {
@@ -1481,7 +1481,7 @@  discard block
 block discarded – undo
1481 1481
      *                                 be returned.
1482 1482
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1483 1483
      * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1484
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1484
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1485 1485
      *                                 exception is triggered.
1486 1486
      */
1487 1487
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1522 1522
      *                                format is
1523 1523
      *                                'U', this is ignored.
1524
-     * @return DateTime
1524
+     * @return string
1525 1525
      * @throws \EE_Error
1526 1526
      */
1527 1527
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2337,7 +2337,7 @@  discard block
 block discarded – undo
2337 2337
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2338 2338
      * EEM_Base::$_db_verification_level
2339 2339
      *
2340
-     * @param $wpdb_method
2340
+     * @param string $wpdb_method
2341 2341
      * @param $arguments_to_provide
2342 2342
      * @return string
2343 2343
      */
@@ -2461,6 +2461,7 @@  discard block
 block discarded – undo
2461 2461
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2462 2462
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2463 2463
      *                             because these will be inserted in any new rows created as well.
2464
+     * @param EE_Base_Class $id_or_obj
2464 2465
      */
2465 2466
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2466 2467
     {
@@ -2471,7 +2472,7 @@  discard block
 block discarded – undo
2471 2472
 
2472 2473
 
2473 2474
     /**
2474
-     * @param mixed           $id_or_obj
2475
+     * @param EE_Base_Class           $id_or_obj
2475 2476
      * @param string          $relationName
2476 2477
      * @param array           $where_query_params
2477 2478
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2512,7 +2513,7 @@  discard block
 block discarded – undo
2512 2513
      * However, if the model objects can't be deleted because of blocking related model objects, then
2513 2514
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2514 2515
      *
2515
-     * @param EE_Base_Class|int|string $id_or_obj
2516
+     * @param EE_Base_Class $id_or_obj
2516 2517
      * @param string                   $model_name
2517 2518
      * @param array                    $query_params
2518 2519
      * @return int how many deleted
@@ -2533,7 +2534,7 @@  discard block
 block discarded – undo
2533 2534
      * the model objects can't be hard deleted because of blocking related model objects,
2534 2535
      * just does a soft-delete on them instead.
2535 2536
      *
2536
-     * @param EE_Base_Class|int|string $id_or_obj
2537
+     * @param EE_Base_Class $id_or_obj
2537 2538
      * @param string                   $model_name
2538 2539
      * @param array                    $query_params
2539 2540
      * @return int how many deleted
@@ -2590,6 +2591,7 @@  discard block
 block discarded – undo
2590 2591
      * @param string $model_name   like 'Event', or 'Registration'
2591 2592
      * @param array  $query_params like EEM_Base::get_all's
2592 2593
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2594
+     * @param EE_Base_Class $id_or_obj
2593 2595
      * @return float
2594 2596
      * @throws \EE_Error
2595 2597
      */
@@ -3545,7 +3547,7 @@  discard block
 block discarded – undo
3545 3547
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3546 3548
      * We should use default where conditions on related models when they requested to use default where conditions
3547 3549
      * on all models, or specifically just on other related models
3548
-     * @param      $default_where_conditions_value
3550
+     * @param      string $default_where_conditions_value
3549 3551
      * @param bool $for_this_model false means this is for OTHER related models
3550 3552
      * @return bool
3551 3553
      */
@@ -3583,7 +3585,7 @@  discard block
 block discarded – undo
3583 3585
      * where conditions.
3584 3586
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3585 3587
      * on this model or others
3586
-     * @param      $default_where_conditions_value
3588
+     * @param      string $default_where_conditions_value
3587 3589
      * @param bool $for_this_model false means this is for OTHER related models
3588 3590
      * @return bool
3589 3591
      */
@@ -4609,7 +4611,7 @@  discard block
 block discarded – undo
4609 4611
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4610 4612
      * Eg, on EE_Answer that would be ANS_ID field object
4611 4613
      *
4612
-     * @param $field_obj
4614
+     * @param EE_Model_Field_Base $field_obj
4613 4615
      * @return boolean
4614 4616
      */
4615 4617
     public function is_primary_key_field($field_obj)
@@ -4720,7 +4722,7 @@  discard block
 block discarded – undo
4720 4722
      * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4721 4723
      *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4722 4724
      *                            Either one works
4723
-     * @return EE_Table_Base
4725
+     * @return string
4724 4726
      */
4725 4727
     public function get_table_for_alias($table_alias)
4726 4728
     {
@@ -5331,7 +5333,7 @@  discard block
 block discarded – undo
5331 5333
     /**
5332 5334
      * Read comments for assume_values_already_prepared_by_model_object()
5333 5335
      *
5334
-     * @return int
5336
+     * @return boolean
5335 5337
      */
5336 5338
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5337 5339
     {
Please login to merge, or discard this patch.
Indentation   +5885 added lines, -5885 removed lines patch added patch discarded remove patch
@@ -29,5893 +29,5893 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    /**
33
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
34
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
35
-     * They almost always WILL NOT, but it's not necessarily a requirement.
36
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
37
-     *
38
-     * @var boolean
39
-     */
40
-    private $_values_already_prepared_by_model_object = 0;
41
-
42
-    /**
43
-     * when $_values_already_prepared_by_model_object equals this, we assume
44
-     * the data is just like form input that needs to have the model fields'
45
-     * prepare_for_set and prepare_for_use_in_db called on it
46
-     */
47
-    const not_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we
51
-     * assume this value is coming from a model object and doesn't need to have
52
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
53
-     */
54
-    const prepared_by_model_object = 1;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we assume
58
-     * the values are already to be used in the database (ie no processing is done
59
-     * on them by the model's fields)
60
-     */
61
-    const prepared_for_use_in_db = 2;
62
-
63
-
64
-    protected $singular_item = 'Item';
65
-
66
-    protected $plural_item   = 'Items';
67
-
68
-    /**
69
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
70
-     */
71
-    protected $_tables;
72
-
73
-    /**
74
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
75
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
76
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
77
-     *
78
-     * @var \EE_Model_Field_Base[][] $_fields
79
-     */
80
-    protected $_fields;
81
-
82
-    /**
83
-     * array of different kinds of relations
84
-     *
85
-     * @var \EE_Model_Relation_Base[] $_model_relations
86
-     */
87
-    protected $_model_relations;
88
-
89
-    /**
90
-     * @var \EE_Index[] $_indexes
91
-     */
92
-    protected $_indexes = array();
93
-
94
-    /**
95
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
96
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
97
-     * by setting the same columns as used in these queries in the query yourself.
98
-     *
99
-     * @var EE_Default_Where_Conditions
100
-     */
101
-    protected $_default_where_conditions_strategy;
102
-
103
-    /**
104
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
105
-     * This is particularly useful when you want something between 'none' and 'default'
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_minimum_where_conditions_strategy;
110
-
111
-    /**
112
-     * String describing how to find the "owner" of this model's objects.
113
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
114
-     * But when there isn't, this indicates which related model, or transiently-related model,
115
-     * has the foreign key to the wp_users table.
116
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
117
-     * related to events, and events have a foreign key to wp_users.
118
-     * On EEM_Transaction, this would be 'Transaction.Event'
119
-     *
120
-     * @var string
121
-     */
122
-    protected $_model_chain_to_wp_user = '';
123
-
124
-    /**
125
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
126
-     * don't need it (particularly CPT models)
127
-     *
128
-     * @var bool
129
-     */
130
-    protected $_ignore_where_strategy = false;
131
-
132
-    /**
133
-     * String used in caps relating to this model. Eg, if the caps relating to this
134
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
135
-     *
136
-     * @var string. If null it hasn't been initialized yet. If false then we
137
-     * have indicated capabilities don't apply to this
138
-     */
139
-    protected $_caps_slug = null;
140
-
141
-    /**
142
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
143
-     * and next-level keys are capability names, and each's value is a
144
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
145
-     * they specify which context to use (ie, frontend, backend, edit or delete)
146
-     * and then each capability in the corresponding sub-array that they're missing
147
-     * adds the where conditions onto the query.
148
-     *
149
-     * @var array
150
-     */
151
-    protected $_cap_restrictions = array(
152
-        self::caps_read       => array(),
153
-        self::caps_read_admin => array(),
154
-        self::caps_edit       => array(),
155
-        self::caps_delete     => array(),
156
-    );
157
-
158
-    /**
159
-     * Array defining which cap restriction generators to use to create default
160
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
161
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
162
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
163
-     * automatically set this to false (not just null).
164
-     *
165
-     * @var EE_Restriction_Generator_Base[]
166
-     */
167
-    protected $_cap_restriction_generators = array();
168
-
169
-    /**
170
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
171
-     */
172
-    const caps_read       = 'read';
173
-
174
-    const caps_read_admin = 'read_admin';
175
-
176
-    const caps_edit       = 'edit';
177
-
178
-    const caps_delete     = 'delete';
179
-
180
-    /**
181
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
182
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
183
-     * maps to 'read' because when looking for relevant permissions we're going to use
184
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
185
-     *
186
-     * @var array
187
-     */
188
-    protected $_cap_contexts_to_cap_action_map = array(
189
-        self::caps_read       => 'read',
190
-        self::caps_read_admin => 'read',
191
-        self::caps_edit       => 'edit',
192
-        self::caps_delete     => 'delete',
193
-    );
194
-
195
-    /**
196
-     * Timezone
197
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
198
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
199
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
200
-     * EE_Datetime_Field data type will have access to it.
201
-     *
202
-     * @var string
203
-     */
204
-    protected $_timezone;
205
-
206
-
207
-    /**
208
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
209
-     * multisite.
210
-     *
211
-     * @var int
212
-     */
213
-    protected static $_model_query_blog_id;
214
-
215
-    /**
216
-     * A copy of _fields, except the array keys are the model names pointed to by
217
-     * the field
218
-     *
219
-     * @var EE_Model_Field_Base[]
220
-     */
221
-    private $_cache_foreign_key_to_fields = array();
222
-
223
-    /**
224
-     * Cached list of all the fields on the model, indexed by their name
225
-     *
226
-     * @var EE_Model_Field_Base[]
227
-     */
228
-    private $_cached_fields = null;
229
-
230
-    /**
231
-     * Cached list of all the fields on the model, except those that are
232
-     * marked as only pertinent to the database
233
-     *
234
-     * @var EE_Model_Field_Base[]
235
-     */
236
-    private $_cached_fields_non_db_only = null;
237
-
238
-    /**
239
-     * A cached reference to the primary key for quick lookup
240
-     *
241
-     * @var EE_Model_Field_Base
242
-     */
243
-    private $_primary_key_field = null;
244
-
245
-    /**
246
-     * Flag indicating whether this model has a primary key or not
247
-     *
248
-     * @var boolean
249
-     */
250
-    protected $_has_primary_key_field = null;
251
-
252
-    /**
253
-     * Whether or not this model is based off a table in WP core only (CPTs should set
254
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
255
-     * This should be true for models that deal with data that should exist independent of EE.
256
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
257
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
258
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
259
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
260
-     * @var boolean
261
-     */
262
-    protected $_wp_core_model = false;
263
-
264
-    /**
265
-     *    List of valid operators that can be used for querying.
266
-     * The keys are all operators we'll accept, the values are the real SQL
267
-     * operators used
268
-     *
269
-     * @var array
270
-     */
271
-    protected $_valid_operators = array(
272
-        '='           => '=',
273
-        '<='          => '<=',
274
-        '<'           => '<',
275
-        '>='          => '>=',
276
-        '>'           => '>',
277
-        '!='          => '!=',
278
-        'LIKE'        => 'LIKE',
279
-        'like'        => 'LIKE',
280
-        'NOT_LIKE'    => 'NOT LIKE',
281
-        'not_like'    => 'NOT LIKE',
282
-        'NOT LIKE'    => 'NOT LIKE',
283
-        'not like'    => 'NOT LIKE',
284
-        'IN'          => 'IN',
285
-        'in'          => 'IN',
286
-        'NOT_IN'      => 'NOT IN',
287
-        'not_in'      => 'NOT IN',
288
-        'NOT IN'      => 'NOT IN',
289
-        'not in'      => 'NOT IN',
290
-        'between'     => 'BETWEEN',
291
-        'BETWEEN'     => 'BETWEEN',
292
-        'IS_NOT_NULL' => 'IS NOT NULL',
293
-        'is_not_null' => 'IS NOT NULL',
294
-        'IS NOT NULL' => 'IS NOT NULL',
295
-        'is not null' => 'IS NOT NULL',
296
-        'IS_NULL'     => 'IS NULL',
297
-        'is_null'     => 'IS NULL',
298
-        'IS NULL'     => 'IS NULL',
299
-        'is null'     => 'IS NULL',
300
-        'REGEXP'      => 'REGEXP',
301
-        'regexp'      => 'REGEXP',
302
-        'NOT_REGEXP'  => 'NOT REGEXP',
303
-        'not_regexp'  => 'NOT REGEXP',
304
-        'NOT REGEXP'  => 'NOT REGEXP',
305
-        'not regexp'  => 'NOT REGEXP',
306
-    );
307
-
308
-    /**
309
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
310
-     *
311
-     * @var array
312
-     */
313
-    protected $_in_style_operators = array('IN', 'NOT IN');
314
-
315
-    /**
316
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
317
-     * '12-31-2012'"
318
-     *
319
-     * @var array
320
-     */
321
-    protected $_between_style_operators = array('BETWEEN');
322
-
323
-    /**
324
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
325
-     * @var array
326
-     */
327
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
328
-    /**
329
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
330
-     * on a join table.
331
-     *
332
-     * @var array
333
-     */
334
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
335
-
336
-    /**
337
-     * Allowed values for $query_params['order'] for ordering in queries
338
-     *
339
-     * @var array
340
-     */
341
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
342
-
343
-    /**
344
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
345
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
346
-     *
347
-     * @var array
348
-     */
349
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
350
-
351
-    /**
352
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
353
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
354
-     *
355
-     * @var array
356
-     */
357
-    private $_allowed_query_params = array(
358
-        0,
359
-        'limit',
360
-        'order_by',
361
-        'group_by',
362
-        'having',
363
-        'force_join',
364
-        'order',
365
-        'on_join_limit',
366
-        'default_where_conditions',
367
-        'caps',
368
-    );
369
-
370
-    /**
371
-     * All the data types that can be used in $wpdb->prepare statements.
372
-     *
373
-     * @var array
374
-     */
375
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
376
-
377
-    /**
378
-     *    EE_Registry Object
379
-     *
380
-     * @var    object
381
-     * @access    protected
382
-     */
383
-    protected $EE = null;
384
-
385
-
386
-    /**
387
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
-     *
389
-     * @var int
390
-     */
391
-    protected $_show_next_x_db_queries = 0;
392
-
393
-    /**
394
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
-     *
397
-     * @var array
398
-     */
399
-    protected $_custom_selections = array();
400
-
401
-    /**
402
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
-     * caches every model object we've fetched from the DB on this request
404
-     *
405
-     * @var array
406
-     */
407
-    protected $_entity_map;
408
-
409
-    /**
410
-     * constant used to show EEM_Base has not yet verified the db on this http request
411
-     */
412
-    const db_verified_none = 0;
413
-
414
-    /**
415
-     * constant used to show EEM_Base has verified the EE core db on this http request,
416
-     * but not the addons' dbs
417
-     */
418
-    const db_verified_core = 1;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
422
-     * the EE core db too)
423
-     */
424
-    const db_verified_addons = 2;
425
-
426
-    /**
427
-     * indicates whether an EEM_Base child has already re-verified the DB
428
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
429
-     * looking like EEM_Base::db_verified_*
430
-     *
431
-     * @var int - 0 = none, 1 = core, 2 = addons
432
-     */
433
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
434
-
435
-    /**
436
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
437
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
438
-     *        registrations for non-trashed tickets for non-trashed datetimes)
439
-     */
440
-    const default_where_conditions_all = 'all';
441
-
442
-    /**
443
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
444
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
445
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
446
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
447
-     *        models which share tables with other models, this can return data for the wrong model.
448
-     */
449
-    const default_where_conditions_this_only = 'this_model_only';
450
-
451
-    /**
452
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
453
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
454
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
455
-     */
456
-    const default_where_conditions_others_only = 'other_models_only';
457
-
458
-    /**
459
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
460
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
461
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
462
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
463
-     *        (regardless of whether those events and venues are trashed)
464
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
465
-     *        events.
466
-     */
467
-    const default_where_conditions_minimum_all = 'minimum';
468
-
469
-    /**
470
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
471
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
472
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
473
-     *        not)
474
-     */
475
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
476
-
477
-    /**
478
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
479
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
480
-     *        it's possible it will return table entries for other models. You should use
481
-     *        EEM_Base::default_where_conditions_minimum_all instead.
482
-     */
483
-    const default_where_conditions_none = 'none';
484
-
485
-
486
-
487
-    /**
488
-     * About all child constructors:
489
-     * they should define the _tables, _fields and _model_relations arrays.
490
-     * Should ALWAYS be called after child constructor.
491
-     * In order to make the child constructors to be as simple as possible, this parent constructor
492
-     * finalizes constructing all the object's attributes.
493
-     * Generally, rather than requiring a child to code
494
-     * $this->_tables = array(
495
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
496
-     *        ...);
497
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
498
-     * each EE_Table has a function to set the table's alias after the constructor, using
499
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
500
-     * do something similar.
501
-     *
502
-     * @param null $timezone
503
-     * @throws \EE_Error
504
-     */
505
-    protected function __construct($timezone = null)
506
-    {
507
-        // check that the model has not been loaded too soon
508
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
-            throw new EE_Error (
510
-                sprintf(
511
-                    __('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.',
512
-                        'event_espresso'),
513
-                    get_class($this)
514
-                )
515
-            );
516
-        }
517
-        /**
518
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
519
-         */
520
-        if (empty(EEM_Base::$_model_query_blog_id)) {
521
-            EEM_Base::set_model_query_blog_id();
522
-        }
523
-        /**
524
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
525
-         * just use EE_Register_Model_Extension
526
-         *
527
-         * @var EE_Table_Base[] $_tables
528
-         */
529
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
530
-        foreach ($this->_tables as $table_alias => $table_obj) {
531
-            /** @var $table_obj EE_Table_Base */
532
-            $table_obj->_construct_finalize_with_alias($table_alias);
533
-            if ($table_obj instanceof EE_Secondary_Table) {
534
-                /** @var $table_obj EE_Secondary_Table */
535
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
536
-            }
537
-        }
538
-        /**
539
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
540
-         * EE_Register_Model_Extension
541
-         *
542
-         * @param EE_Model_Field_Base[] $_fields
543
-         */
544
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
545
-        $this->_invalidate_field_caches();
546
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
547
-            if (! array_key_exists($table_alias, $this->_tables)) {
548
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
550
-            }
551
-            foreach ($fields_for_table as $field_name => $field_obj) {
552
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
553
-                //primary key field base has a slightly different _construct_finalize
554
-                /** @var $field_obj EE_Model_Field_Base */
555
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
556
-            }
557
-        }
558
-        // everything is related to Extra_Meta
559
-        if (get_class($this) !== 'EEM_Extra_Meta') {
560
-            //make extra meta related to everything, but don't block deleting things just
561
-            //because they have related extra meta info. For now just orphan those extra meta
562
-            //in the future we should automatically delete them
563
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
564
-        }
565
-        //and change logs
566
-        if (get_class($this) !== 'EEM_Change_Log') {
567
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
568
-        }
569
-        /**
570
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
571
-         * EE_Register_Model_Extension
572
-         *
573
-         * @param EE_Model_Relation_Base[] $_model_relations
574
-         */
575
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
576
-            $this->_model_relations);
577
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
578
-            /** @var $relation_obj EE_Model_Relation_Base */
579
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
580
-        }
581
-        foreach ($this->_indexes as $index_name => $index_obj) {
582
-            /** @var $index_obj EE_Index */
583
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
584
-        }
585
-        $this->set_timezone($timezone);
586
-        //finalize default where condition strategy, or set default
587
-        if (! $this->_default_where_conditions_strategy) {
588
-            //nothing was set during child constructor, so set default
589
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590
-        }
591
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
592
-        if (! $this->_minimum_where_conditions_strategy) {
593
-            //nothing was set during child constructor, so set default
594
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595
-        }
596
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
597
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
598
-        //to indicate to NOT set it, set it to the logical default
599
-        if ($this->_caps_slug === null) {
600
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
601
-        }
602
-        //initialize the standard cap restriction generators if none were specified by the child constructor
603
-        if ($this->_cap_restriction_generators !== false) {
604
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
606
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
607
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608
-                        new EE_Restriction_Generator_Protected(),
609
-                        $cap_context,
610
-                        $this
611
-                    );
612
-                }
613
-            }
614
-        }
615
-        //if there are cap restriction generators, use them to make the default cap restrictions
616
-        if ($this->_cap_restriction_generators !== false) {
617
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
-                if (! $generator_object) {
619
-                    continue;
620
-                }
621
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
622
-                    throw new EE_Error(
623
-                        sprintf(
624
-                            __('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.',
625
-                                'event_espresso'),
626
-                            $context,
627
-                            $this->get_this_model_name()
628
-                        )
629
-                    );
630
-                }
631
-                $action = $this->cap_action_for_context($context);
632
-                if (! $generator_object->construction_finalized()) {
633
-                    $generator_object->_construct_finalize($this, $action);
634
-                }
635
-            }
636
-        }
637
-        do_action('AHEE__' . get_class($this) . '__construct__end');
638
-    }
639
-
640
-
641
-
642
-    /**
643
-     * Generates the cap restrictions for the given context, or if they were
644
-     * already generated just gets what's cached
645
-     *
646
-     * @param string $context one of EEM_Base::valid_cap_contexts()
647
-     * @return EE_Default_Where_Conditions[]
648
-     */
649
-    protected function _generate_cap_restrictions($context)
650
-    {
651
-        if (isset($this->_cap_restriction_generators[$context])
652
-            && $this->_cap_restriction_generators[$context]
653
-               instanceof
654
-               EE_Restriction_Generator_Base
655
-        ) {
656
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
657
-        } else {
658
-            return array();
659
-        }
660
-    }
661
-
662
-
663
-
664
-    /**
665
-     * Used to set the $_model_query_blog_id static property.
666
-     *
667
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
668
-     *                      value for get_current_blog_id() will be used.
669
-     */
670
-    public static function set_model_query_blog_id($blog_id = 0)
671
-    {
672
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * Returns whatever is set as the internal $model_query_blog_id.
679
-     *
680
-     * @return int
681
-     */
682
-    public static function get_model_query_blog_id()
683
-    {
684
-        return EEM_Base::$_model_query_blog_id;
685
-    }
686
-
687
-
688
-
689
-    /**
690
-     *        This function is a singleton method used to instantiate the Espresso_model object
691
-     *
692
-     * @access public
693
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
694
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
695
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
696
-     *                         timezone in the 'timezone_string' wp option)
697
-     * @return static (as in the concrete child class)
698
-     */
699
-    public static function instance($timezone = null)
700
-    {
701
-        // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
703
-            // instantiate Espresso_model
704
-            static::$_instance = new static($timezone);
705
-        }
706
-        //we might have a timezone set, let set_timezone decide what to do with it
707
-        static::$_instance->set_timezone($timezone);
708
-        // Espresso_model object
709
-        return static::$_instance;
710
-    }
711
-
712
-
713
-
714
-    /**
715
-     * resets the model and returns it
716
-     *
717
-     * @param null | string $timezone
718
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
719
-     * all its properties reset; if it wasn't instantiated, returns null)
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we
738
-            //were creating a new one
739
-            static::$_instance->__construct($timezone);
740
-            return self::instance();
741
-        }
742
-        return null;
743
-    }
744
-
745
-
746
-
747
-    /**
748
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
749
-     *
750
-     * @param  boolean $translated return localized strings or JUST the array.
751
-     * @return array
752
-     * @throws \EE_Error
753
-     */
754
-    public function status_array($translated = false)
755
-    {
756
-        if (! array_key_exists('Status', $this->_model_relations)) {
757
-            return array();
758
-        }
759
-        $model_name = $this->get_this_model_name();
760
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
761
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
762
-        $status_array = array();
763
-        foreach ($stati as $status) {
764
-            $status_array[$status->ID()] = $status->get('STS_code');
765
-        }
766
-        return $translated
767
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
768
-            : $status_array;
769
-    }
770
-
771
-
772
-
773
-    /**
774
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
775
-     *
776
-     * @param array $query_params             {
777
-     * @var array $0 (where) array {
778
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
779
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
780
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
781
-     *                                        conditions based on related models (and even
782
-     *                                        models-related-to-related-models) prepend the model's name onto the field
783
-     *                                        name. Eg,
784
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
785
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
786
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
787
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
788
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
789
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
790
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
791
-     *                                        to Venues (even when each of those models actually consisted of two
792
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
793
-     *                                        just having
794
-     *                                        "Venue.VNU_ID", you could have
795
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
796
-     *                                        events are related to Registrations, which are related to Attendees). You
797
-     *                                        can take it even further with
798
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
799
-     *                                        (from the default of '='), change the value to an numerically-indexed
800
-     *                                        array, where the first item in the list is the operator. eg: array(
801
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
802
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
803
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
804
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
805
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
806
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
807
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
808
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
809
-     *                                        the value is a field, simply provide a third array item (true) to the
810
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
811
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
812
-     *                                        Note: you can also use related model field names like you would any other
813
-     *                                        field name. eg:
814
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
815
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
816
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
817
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
818
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
819
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
820
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
821
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
822
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
823
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
824
-     *                                        "stick" until you specify an AND. eg
825
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
826
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
827
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
828
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
829
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
830
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
831
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
832
-     *                                        too, eg:
833
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
834
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
835
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
836
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
837
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
838
-     *                                        the OFFSET, the 2nd is the LIMIT
839
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
840
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
841
-     *                                        following format array('on_join_limit'
842
-     *                                        => array( 'table_alias', array(1,2) ) ).
843
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
844
-     *                                        values are either 'ASC' or 'DESC'.
845
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
846
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
847
-     *                                        DESC..." respectively. Like the
848
-     *                                        'where' conditions, these fields can be on related models. Eg
849
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
850
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
851
-     *                                        Attendee, Price, Datetime, etc.)
852
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
853
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
854
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
855
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
856
-     *                                        order by the primary key. Eg,
857
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
858
-     *                                        //(will join with the Datetime model's table(s) and order by its field
859
-     *                                        DTT_EVT_start) or
860
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
861
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
862
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
863
-     *                                        'group_by'=>'VNU_ID', or
864
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
865
-     *                                        if no
866
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
867
-     *                                        model's primary key (or combined primary keys). This avoids some
868
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
869
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
870
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
871
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
872
-     *                                        results)
873
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
874
-     *                                        array where values are models to be joined in the query.Eg
875
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
876
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
877
-     *                                        probably only want to do this in hopes of increasing efficiency, as
878
-     *                                        related models which belongs to the current model
879
-     *                                        (ie, the current model has a foreign key to them, like how Registration
880
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
881
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
882
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
883
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
884
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
885
-     *                                        default where conditions set it to 'other_models_only'. If you only want
886
-     *                                        this model's default where conditions added to the query, use
887
-     *                                        'this_model_only'. If you want to use all default where conditions
888
-     *                                        (default), set to 'all'.
889
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
890
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
891
-     *                                        everything? Or should we only show the current user items they should be
892
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
893
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
894
-     *                                        }
895
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
896
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
897
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
898
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
899
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
900
-     *                                        array( array(
901
-     *                                        'OR'=>array(
902
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
903
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
904
-     *                                        )
905
-     *                                        ),
906
-     *                                        'limit'=>10,
907
-     *                                        'group_by'=>'TXN_ID'
908
-     *                                        ));
909
-     *                                        get all the answers to the question titled "shirt size" for event with id
910
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
911
-     *                                        'Question.QST_display_text'=>'shirt size',
912
-     *                                        'Registration.Event.EVT_ID'=>12
913
-     *                                        ),
914
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
915
-     *                                        ));
916
-     * @throws \EE_Error
917
-     */
918
-    public function get_all($query_params = array())
919
-    {
920
-        if (isset($query_params['limit'])
921
-            && ! isset($query_params['group_by'])
922
-        ) {
923
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
924
-        }
925
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
926
-    }
927
-
928
-
929
-
930
-    /**
931
-     * Modifies the query parameters so we only get back model objects
932
-     * that "belong" to the current user
933
-     *
934
-     * @param array $query_params @see EEM_Base::get_all()
935
-     * @return array like EEM_Base::get_all
936
-     */
937
-    public function alter_query_params_to_only_include_mine($query_params = array())
938
-    {
939
-        $wp_user_field_name = $this->wp_user_field_name();
940
-        if ($wp_user_field_name) {
941
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
942
-        }
943
-        return $query_params;
944
-    }
945
-
946
-
947
-
948
-    /**
949
-     * Returns the name of the field's name that points to the WP_User table
950
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
951
-     * foreign key to the WP_User table)
952
-     *
953
-     * @return string|boolean string on success, boolean false when there is no
954
-     * foreign key to the WP_User table
955
-     */
956
-    public function wp_user_field_name()
957
-    {
958
-        try {
959
-            if (! empty($this->_model_chain_to_wp_user)) {
960
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
961
-                $last_model_name = end($models_to_follow_to_wp_users);
962
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
963
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
964
-            } else {
965
-                $model_with_fk_to_wp_users = $this;
966
-                $model_chain_to_wp_user = '';
967
-            }
968
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
969
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
970
-        } catch (EE_Error $e) {
971
-            return false;
972
-        }
973
-    }
974
-
975
-
976
-
977
-    /**
978
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
979
-     * (or transiently-related model) has a foreign key to the wp_users table;
980
-     * useful for finding if model objects of this type are 'owned' by the current user.
981
-     * This is an empty string when the foreign key is on this model and when it isn't,
982
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
983
-     * (or transiently-related model)
984
-     *
985
-     * @return string
986
-     */
987
-    public function model_chain_to_wp_user()
988
-    {
989
-        return $this->_model_chain_to_wp_user;
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
996
-     * like how registrations don't have a foreign key to wp_users, but the
997
-     * events they are for are), or is unrelated to wp users.
998
-     * generally available
999
-     *
1000
-     * @return boolean
1001
-     */
1002
-    public function is_owned()
1003
-    {
1004
-        if ($this->model_chain_to_wp_user()) {
1005
-            return true;
1006
-        } else {
1007
-            try {
1008
-                $this->get_foreign_key_to('WP_User');
1009
-                return true;
1010
-            } catch (EE_Error $e) {
1011
-                return false;
1012
-            }
1013
-        }
1014
-    }
1015
-
1016
-
1017
-
1018
-    /**
1019
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1020
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1021
-     * the model)
1022
-     *
1023
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1024
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1025
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1026
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1027
-     *                                  override this and set the select to "*", or a specific column name, like
1028
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1029
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1030
-     *                                  the aliases used to refer to this selection, and values are to be
1031
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1032
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1033
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1034
-     * @throws \EE_Error
1035
-     */
1036
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1037
-    {
1038
-        // remember the custom selections, if any, and type cast as array
1039
-        // (unless $columns_to_select is an object, then just set as an empty array)
1040
-        // Note: (array) 'some string' === array( 'some string' )
1041
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1042
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
-        $select_expressions = $columns_to_select !== null
1044
-            ? $this->_construct_select_from_input($columns_to_select)
1045
-            : $this->_construct_default_select_sql($model_query_info);
1046
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1047
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1048
-    }
1049
-
1050
-
1051
-
1052
-    /**
1053
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1054
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1055
-     * take care of joins, field preparation etc.
1056
-     *
1057
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1058
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1059
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1060
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1061
-     *                                  override this and set the select to "*", or a specific column name, like
1062
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1063
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1064
-     *                                  the aliases used to refer to this selection, and values are to be
1065
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1066
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1067
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1068
-     * @throws \EE_Error
1069
-     */
1070
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1071
-    {
1072
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1073
-    }
1074
-
1075
-
1076
-
1077
-    /**
1078
-     * For creating a custom select statement
1079
-     *
1080
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1081
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1082
-     *                                 SQL, and 1=>is the datatype
1083
-     * @throws EE_Error
1084
-     * @return string
1085
-     */
1086
-    private function _construct_select_from_input($columns_to_select)
1087
-    {
1088
-        if (is_array($columns_to_select)) {
1089
-            $select_sql_array = array();
1090
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1091
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1092
-                    throw new EE_Error(
1093
-                        sprintf(
1094
-                            __(
1095
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1096
-                                "event_espresso"
1097
-                            ),
1098
-                            $selection_and_datatype,
1099
-                            $alias
1100
-                        )
1101
-                    );
1102
-                }
1103
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1104
-                    throw new EE_Error(
1105
-                        sprintf(
1106
-                            __(
1107
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1108
-                                "event_espresso"
1109
-                            ),
1110
-                            $selection_and_datatype[1],
1111
-                            $selection_and_datatype[0],
1112
-                            $alias,
1113
-                            implode(",", $this->_valid_wpdb_data_types)
1114
-                        )
1115
-                    );
1116
-                }
1117
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1118
-            }
1119
-            $columns_to_select_string = implode(", ", $select_sql_array);
1120
-        } else {
1121
-            $columns_to_select_string = $columns_to_select;
1122
-        }
1123
-        return $columns_to_select_string;
1124
-    }
1125
-
1126
-
1127
-
1128
-    /**
1129
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1130
-     *
1131
-     * @return string
1132
-     * @throws \EE_Error
1133
-     */
1134
-    public function primary_key_name()
1135
-    {
1136
-        return $this->get_primary_key_field()->get_name();
1137
-    }
1138
-
1139
-
1140
-
1141
-    /**
1142
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1143
-     * If there is no primary key on this model, $id is treated as primary key string
1144
-     *
1145
-     * @param mixed $id int or string, depending on the type of the model's primary key
1146
-     * @return EE_Base_Class
1147
-     */
1148
-    public function get_one_by_ID($id)
1149
-    {
1150
-        if ($this->get_from_entity_map($id)) {
1151
-            return $this->get_from_entity_map($id);
1152
-        }
1153
-        return $this->get_one(
1154
-            $this->alter_query_params_to_restrict_by_ID(
1155
-                $id,
1156
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1157
-            )
1158
-        );
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * Alters query parameters to only get items with this ID are returned.
1165
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1166
-     * or could just be a simple primary key ID
1167
-     *
1168
-     * @param int   $id
1169
-     * @param array $query_params
1170
-     * @return array of normal query params, @see EEM_Base::get_all
1171
-     * @throws \EE_Error
1172
-     */
1173
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1174
-    {
1175
-        if (! isset($query_params[0])) {
1176
-            $query_params[0] = array();
1177
-        }
1178
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1179
-        if ($conditions_from_id === null) {
1180
-            $query_params[0][$this->primary_key_name()] = $id;
1181
-        } else {
1182
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1183
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1184
-        }
1185
-        return $query_params;
1186
-    }
1187
-
1188
-
1189
-
1190
-    /**
1191
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1192
-     * array. If no item is found, null is returned.
1193
-     *
1194
-     * @param array $query_params like EEM_Base's $query_params variable.
1195
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1196
-     * @throws \EE_Error
1197
-     */
1198
-    public function get_one($query_params = array())
1199
-    {
1200
-        if (! is_array($query_params)) {
1201
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1202
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1203
-                    gettype($query_params)), '4.6.0');
1204
-            $query_params = array();
1205
-        }
1206
-        $query_params['limit'] = 1;
1207
-        $items = $this->get_all($query_params);
1208
-        if (empty($items)) {
1209
-            return null;
1210
-        } else {
1211
-            return array_shift($items);
1212
-        }
1213
-    }
1214
-
1215
-
1216
-
1217
-    /**
1218
-     * Returns the next x number of items in sequence from the given value as
1219
-     * found in the database matching the given query conditions.
1220
-     *
1221
-     * @param mixed $current_field_value    Value used for the reference point.
1222
-     * @param null  $field_to_order_by      What field is used for the
1223
-     *                                      reference point.
1224
-     * @param int   $limit                  How many to return.
1225
-     * @param array $query_params           Extra conditions on the query.
1226
-     * @param null  $columns_to_select      If left null, then an array of
1227
-     *                                      EE_Base_Class objects is returned,
1228
-     *                                      otherwise you can indicate just the
1229
-     *                                      columns you want returned.
1230
-     * @return EE_Base_Class[]|array
1231
-     * @throws \EE_Error
1232
-     */
1233
-    public function next_x(
1234
-        $current_field_value,
1235
-        $field_to_order_by = null,
1236
-        $limit = 1,
1237
-        $query_params = array(),
1238
-        $columns_to_select = null
1239
-    ) {
1240
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $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
-     */
1262
-    public function previous_x(
1263
-        $current_field_value,
1264
-        $field_to_order_by = null,
1265
-        $limit = 1,
1266
-        $query_params = array(),
1267
-        $columns_to_select = null
1268
-    ) {
1269
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1270
-            $columns_to_select);
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next item in sequence from the given value as found in the
1277
-     * database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param array $query_params           Extra conditions on the query.
1283
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
-     *                                      object is returned, otherwise you
1285
-     *                                      can indicate just the columns you
1286
-     *                                      want and a single array indexed by
1287
-     *                                      the columns will be returned.
1288
-     * @return EE_Base_Class|null|array()
1289
-     * @throws \EE_Error
1290
-     */
1291
-    public function next(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $query_params = array(),
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1298
-            $columns_to_select);
1299
-        return empty($results) ? null : reset($results);
1300
-    }
1301
-
1302
-
1303
-
1304
-    /**
1305
-     * Returns the previous item in sequence from the given value as found in
1306
-     * the database matching the given query conditions.
1307
-     *
1308
-     * @param mixed $current_field_value    Value used for the reference point.
1309
-     * @param null  $field_to_order_by      What field is used for the
1310
-     *                                      reference point.
1311
-     * @param array $query_params           Extra conditions on the query.
1312
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1313
-     *                                      object is returned, otherwise you
1314
-     *                                      can indicate just the columns you
1315
-     *                                      want and a single array indexed by
1316
-     *                                      the columns will be returned.
1317
-     * @return EE_Base_Class|null|array()
1318
-     * @throws EE_Error
1319
-     */
1320
-    public function previous(
1321
-        $current_field_value,
1322
-        $field_to_order_by = null,
1323
-        $query_params = array(),
1324
-        $columns_to_select = null
1325
-    ) {
1326
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1327
-            $columns_to_select);
1328
-        return empty($results) ? null : reset($results);
1329
-    }
1330
-
1331
-
1332
-
1333
-    /**
1334
-     * Returns the a consecutive number of items in sequence from the given
1335
-     * value as found in the database matching the given query conditions.
1336
-     *
1337
-     * @param mixed  $current_field_value   Value used for the reference point.
1338
-     * @param string $operand               What operand is used for the sequence.
1339
-     * @param string $field_to_order_by     What field is used for the reference point.
1340
-     * @param int    $limit                 How many to return.
1341
-     * @param array  $query_params          Extra conditions on the query.
1342
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1343
-     *                                      otherwise you can indicate just the columns you want returned.
1344
-     * @return EE_Base_Class[]|array
1345
-     * @throws EE_Error
1346
-     */
1347
-    protected function _get_consecutive(
1348
-        $current_field_value,
1349
-        $operand = '>',
1350
-        $field_to_order_by = null,
1351
-        $limit = 1,
1352
-        $query_params = array(),
1353
-        $columns_to_select = null
1354
-    ) {
1355
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1356
-        if (empty($field_to_order_by)) {
1357
-            if ($this->has_primary_key_field()) {
1358
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1359
-            } else {
1360
-                if (WP_DEBUG) {
1361
-                    throw new EE_Error(__('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).',
1362
-                        'event_espresso'));
1363
-                }
1364
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1365
-                return array();
1366
-            }
1367
-        }
1368
-        if (! is_array($query_params)) {
1369
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1370
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1371
-                    gettype($query_params)), '4.6.0');
1372
-            $query_params = array();
1373
-        }
1374
-        //let's add the where query param for consecutive look up.
1375
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1376
-        $query_params['limit'] = $limit;
1377
-        //set direction
1378
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1379
-        $query_params['order_by'] = $operand === '>'
1380
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1381
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1382
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1383
-        if (empty($columns_to_select)) {
1384
-            return $this->get_all($query_params);
1385
-        } else {
1386
-            //getting just the fields
1387
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1388
-        }
1389
-    }
1390
-
1391
-
1392
-
1393
-    /**
1394
-     * This sets the _timezone property after model object has been instantiated.
1395
-     *
1396
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1397
-     */
1398
-    public function set_timezone($timezone)
1399
-    {
1400
-        if ($timezone !== null) {
1401
-            $this->_timezone = $timezone;
1402
-        }
1403
-        //note we need to loop through relations and set the timezone on those objects as well.
1404
-        foreach ($this->_model_relations as $relation) {
1405
-            $relation->set_timezone($timezone);
1406
-        }
1407
-        //and finally we do the same for any datetime fields
1408
-        foreach ($this->_fields as $field) {
1409
-            if ($field instanceof EE_Datetime_Field) {
1410
-                $field->set_timezone($timezone);
1411
-            }
1412
-        }
1413
-    }
1414
-
1415
-
1416
-
1417
-    /**
1418
-     * This just returns whatever is set for the current timezone.
1419
-     *
1420
-     * @access public
1421
-     * @return string
1422
-     */
1423
-    public function get_timezone()
1424
-    {
1425
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1426
-        if (empty($this->_timezone)) {
1427
-            foreach ($this->_fields as $field) {
1428
-                if ($field instanceof EE_Datetime_Field) {
1429
-                    $this->set_timezone($field->get_timezone());
1430
-                    break;
1431
-                }
1432
-            }
1433
-        }
1434
-        //if timezone STILL empty then return the default timezone for the site.
1435
-        if (empty($this->_timezone)) {
1436
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1437
-        }
1438
-        return $this->_timezone;
1439
-    }
1440
-
1441
-
1442
-
1443
-    /**
1444
-     * This returns the date formats set for the given field name and also ensures that
1445
-     * $this->_timezone property is set correctly.
1446
-     *
1447
-     * @since 4.6.x
1448
-     * @param string $field_name The name of the field the formats are being retrieved for.
1449
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1450
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1451
-     * @return array formats in an array with the date format first, and the time format last.
1452
-     */
1453
-    public function get_formats_for($field_name, $pretty = false)
1454
-    {
1455
-        $field_settings = $this->field_settings_for($field_name);
1456
-        //if not a valid EE_Datetime_Field then throw error
1457
-        if (! $field_settings instanceof EE_Datetime_Field) {
1458
-            throw new EE_Error(sprintf(__('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.',
1459
-                'event_espresso'), $field_name));
1460
-        }
1461
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1462
-        //the field.
1463
-        $this->_timezone = $field_settings->get_timezone();
1464
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1465
-    }
1466
-
1467
-
1468
-
1469
-    /**
1470
-     * This returns the current time in a format setup for a query on this model.
1471
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1472
-     * it will return:
1473
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1474
-     *  NOW
1475
-     *  - or a unix timestamp (equivalent to time())
1476
-     *
1477
-     * @since 4.6.x
1478
-     * @param string $field_name       The field the current time is needed for.
1479
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1480
-     *                                 formatted string matching the set format for the field in the set timezone will
1481
-     *                                 be returned.
1482
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1483
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1484
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1485
-     *                                 exception is triggered.
1486
-     */
1487
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1488
-    {
1489
-        $formats = $this->get_formats_for($field_name);
1490
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1491
-        if ($timestamp) {
1492
-            return $DateTime->format('U');
1493
-        }
1494
-        //not returning timestamp, so return formatted string in timezone.
1495
-        switch ($what) {
1496
-            case 'time' :
1497
-                return $DateTime->format($formats[1]);
1498
-                break;
1499
-            case 'date' :
1500
-                return $DateTime->format($formats[0]);
1501
-                break;
1502
-            default :
1503
-                return $DateTime->format(implode(' ', $formats));
1504
-                break;
1505
-        }
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1512
-     * for the model are.  Returns a DateTime object.
1513
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1514
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1515
-     * ignored.
1516
-     *
1517
-     * @param string $field_name      The field being setup.
1518
-     * @param string $timestring      The date time string being used.
1519
-     * @param string $incoming_format The format for the time string.
1520
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1521
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1522
-     *                                format is
1523
-     *                                'U', this is ignored.
1524
-     * @return DateTime
1525
-     * @throws \EE_Error
1526
-     */
1527
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1528
-    {
1529
-        //just using this to ensure the timezone is set correctly internally
1530
-        $this->get_formats_for($field_name);
1531
-        //load EEH_DTT_Helper
1532
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1533
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1534
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1535
-    }
1536
-
1537
-
1538
-
1539
-    /**
1540
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1541
-     *
1542
-     * @return EE_Table_Base[]
1543
-     */
1544
-    public function get_tables()
1545
-    {
1546
-        return $this->_tables;
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1553
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1554
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1555
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1556
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1557
-     * model object with EVT_ID = 1
1558
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1559
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1560
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1561
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1562
-     * are not specified)
1563
-     *
1564
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1565
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1566
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1567
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1568
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1569
-     *                                         ID=34, we'd use this method as follows:
1570
-     *                                         EEM_Transaction::instance()->update(
1571
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1572
-     *                                         array(array('TXN_ID'=>34)));
1573
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1574
-     *                                         in client code into what's expected to be stored on each field. Eg,
1575
-     *                                         consider updating Question's QST_admin_label field is of type
1576
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1577
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1578
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1579
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1580
-     *                                         TRUE, it is assumed that you've already called
1581
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1582
-     *                                         malicious javascript. However, if
1583
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1584
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1585
-     *                                         and every other field, before insertion. We provide this parameter
1586
-     *                                         because model objects perform their prepare_for_set function on all
1587
-     *                                         their values, and so don't need to be called again (and in many cases,
1588
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1589
-     *                                         prepare_for_set method...)
1590
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1591
-     *                                         in this model's entity map according to $fields_n_values that match
1592
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1593
-     *                                         by setting this to FALSE, but be aware that model objects being used
1594
-     *                                         could get out-of-sync with the database
1595
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1596
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1597
-     *                                         bad)
1598
-     * @throws \EE_Error
1599
-     */
1600
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1601
-    {
1602
-        if (! is_array($query_params)) {
1603
-            EE_Error::doing_it_wrong('EEM_Base::update',
1604
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1605
-                    gettype($query_params)), '4.6.0');
1606
-            $query_params = array();
1607
-        }
1608
-        /**
1609
-         * Action called before a model update call has been made.
1610
-         *
1611
-         * @param EEM_Base $model
1612
-         * @param array    $fields_n_values the updated fields and their new values
1613
-         * @param array    $query_params    @see EEM_Base::get_all()
1614
-         */
1615
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1616
-        /**
1617
-         * Filters the fields about to be updated given the query parameters. You can provide the
1618
-         * $query_params to $this->get_all() to find exactly which records will be updated
1619
-         *
1620
-         * @param array    $fields_n_values fields and their new values
1621
-         * @param EEM_Base $model           the model being queried
1622
-         * @param array    $query_params    see EEM_Base::get_all()
1623
-         */
1624
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1625
-            $query_params);
1626
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1627
-        //to do that, for each table, verify that it's PK isn't null.
1628
-        $tables = $this->get_tables();
1629
-        //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
1630
-        //NOTE: we should make this code more efficient by NOT querying twice
1631
-        //before the real update, but that needs to first go through ALPHA testing
1632
-        //as it's dangerous. says Mike August 8 2014
1633
-        //we want to make sure the default_where strategy is ignored
1634
-        $this->_ignore_where_strategy = true;
1635
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1636
-        foreach ($wpdb_select_results as $wpdb_result) {
1637
-            // type cast stdClass as array
1638
-            $wpdb_result = (array)$wpdb_result;
1639
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1640
-            if ($this->has_primary_key_field()) {
1641
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1642
-            } else {
1643
-                //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)
1644
-                $main_table_pk_value = null;
1645
-            }
1646
-            //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
1647
-            //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
1648
-            if (count($tables) > 1) {
1649
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1650
-                //in that table, and so we'll want to insert one
1651
-                foreach ($tables as $table_obj) {
1652
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1653
-                    //if there is no private key for this table on the results, it means there's no entry
1654
-                    //in this table, right? so insert a row in the current table, using any fields available
1655
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1656
-                           && $wpdb_result[$this_table_pk_column])
1657
-                    ) {
1658
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1659
-                            $main_table_pk_value);
1660
-                        //if we died here, report the error
1661
-                        if (! $success) {
1662
-                            return false;
1663
-                        }
1664
-                    }
1665
-                }
1666
-            }
1667
-            //				//and now check that if we have cached any models by that ID on the model, that
1668
-            //				//they also get updated properly
1669
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1670
-            //				if( $model_object ){
1671
-            //					foreach( $fields_n_values as $field => $value ){
1672
-            //						$model_object->set($field, $value);
1673
-            //let's make sure default_where strategy is followed now
1674
-            $this->_ignore_where_strategy = false;
1675
-        }
1676
-        //if we want to keep model objects in sync, AND
1677
-        //if this wasn't called from a model object (to update itself)
1678
-        //then we want to make sure we keep all the existing
1679
-        //model objects in sync with the db
1680
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1681
-            if ($this->has_primary_key_field()) {
1682
-                $model_objs_affected_ids = $this->get_col($query_params);
1683
-            } else {
1684
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1685
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1686
-                $model_objs_affected_ids = array();
1687
-                foreach ($models_affected_key_columns as $row) {
1688
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1689
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1690
-                }
1691
-            }
1692
-            if (! $model_objs_affected_ids) {
1693
-                //wait wait wait- if nothing was affected let's stop here
1694
-                return 0;
1695
-            }
1696
-            foreach ($model_objs_affected_ids as $id) {
1697
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1698
-                if ($model_obj_in_entity_map) {
1699
-                    foreach ($fields_n_values as $field => $new_value) {
1700
-                        $model_obj_in_entity_map->set($field, $new_value);
1701
-                    }
1702
-                }
1703
-            }
1704
-            //if there is a primary key on this model, we can now do a slight optimization
1705
-            if ($this->has_primary_key_field()) {
1706
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1707
-                $query_params = array(
1708
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1709
-                    'limit'                    => count($model_objs_affected_ids),
1710
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1711
-                );
1712
-            }
1713
-        }
1714
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1715
-        $SQL = "UPDATE "
1716
-               . $model_query_info->get_full_join_sql()
1717
-               . " SET "
1718
-               . $this->_construct_update_sql($fields_n_values)
1719
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1720
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1721
-        /**
1722
-         * Action called after a model update call has been made.
1723
-         *
1724
-         * @param EEM_Base $model
1725
-         * @param array    $fields_n_values the updated fields and their new values
1726
-         * @param array    $query_params    @see EEM_Base::get_all()
1727
-         * @param int      $rows_affected
1728
-         */
1729
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1730
-        return $rows_affected;//how many supposedly got updated
1731
-    }
1732
-
1733
-
1734
-
1735
-    /**
1736
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1737
-     * are teh values of the field specified (or by default the primary key field)
1738
-     * that matched the query params. Note that you should pass the name of the
1739
-     * model FIELD, not the database table's column name.
1740
-     *
1741
-     * @param array  $query_params @see EEM_Base::get_all()
1742
-     * @param string $field_to_select
1743
-     * @return array just like $wpdb->get_col()
1744
-     * @throws \EE_Error
1745
-     */
1746
-    public function get_col($query_params = array(), $field_to_select = null)
1747
-    {
1748
-        if ($field_to_select) {
1749
-            $field = $this->field_settings_for($field_to_select);
1750
-        } elseif ($this->has_primary_key_field()) {
1751
-            $field = $this->get_primary_key_field();
1752
-        } else {
1753
-            //no primary key, just grab the first column
1754
-            $field = reset($this->field_settings());
1755
-        }
1756
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1757
-        $select_expressions = $field->get_qualified_column();
1758
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1759
-        return $this->_do_wpdb_query('get_col', array($SQL));
1760
-    }
1761
-
1762
-
1763
-
1764
-    /**
1765
-     * Returns a single column value for a single row from the database
1766
-     *
1767
-     * @param array  $query_params    @see EEM_Base::get_all()
1768
-     * @param string $field_to_select @see EEM_Base::get_col()
1769
-     * @return string
1770
-     * @throws \EE_Error
1771
-     */
1772
-    public function get_var($query_params = array(), $field_to_select = null)
1773
-    {
1774
-        $query_params['limit'] = 1;
1775
-        $col = $this->get_col($query_params, $field_to_select);
1776
-        if (! empty($col)) {
1777
-            return reset($col);
1778
-        } else {
1779
-            return null;
1780
-        }
1781
-    }
1782
-
1783
-
1784
-
1785
-    /**
1786
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1787
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1788
-     * injection, but currently no further filtering is done
1789
-     *
1790
-     * @global      $wpdb
1791
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1792
-     *                               be updated to in the DB
1793
-     * @return string of SQL
1794
-     * @throws \EE_Error
1795
-     */
1796
-    public function _construct_update_sql($fields_n_values)
1797
-    {
1798
-        /** @type WPDB $wpdb */
1799
-        global $wpdb;
1800
-        $cols_n_values = array();
1801
-        foreach ($fields_n_values as $field_name => $value) {
1802
-            $field_obj = $this->field_settings_for($field_name);
1803
-            //if the value is NULL, we want to assign the value to that.
1804
-            //wpdb->prepare doesn't really handle that properly
1805
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1806
-            $value_sql = $prepared_value === null ? 'NULL'
1807
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1808
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1809
-        }
1810
-        return implode(",", $cols_n_values);
1811
-    }
1812
-
1813
-
1814
-
1815
-    /**
1816
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1817
-     * Performs a HARD delete, meaning the database row should always be removed,
1818
-     * not just have a flag field on it switched
1819
-     * Wrapper for EEM_Base::delete_permanently()
1820
-     *
1821
-     * @param mixed $id
1822
-     * @param boolean $allow_blocking
1823
-     * @return int the number of rows deleted
1824
-     * @throws \EE_Error
1825
-     */
1826
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1827
-    {
1828
-        return $this->delete_permanently(
1829
-            array(
1830
-                array($this->get_primary_key_field()->get_name() => $id),
1831
-                'limit' => 1,
1832
-            ),
1833
-            $allow_blocking
1834
-        );
1835
-    }
1836
-
1837
-
1838
-
1839
-    /**
1840
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1841
-     * Wrapper for EEM_Base::delete()
1842
-     *
1843
-     * @param mixed $id
1844
-     * @param boolean $allow_blocking
1845
-     * @return int the number of rows deleted
1846
-     * @throws \EE_Error
1847
-     */
1848
-    public function delete_by_ID($id, $allow_blocking = true)
1849
-    {
1850
-        return $this->delete(
1851
-            array(
1852
-                array($this->get_primary_key_field()->get_name() => $id),
1853
-                'limit' => 1,
1854
-            ),
1855
-            $allow_blocking
1856
-        );
1857
-    }
1858
-
1859
-
1860
-
1861
-    /**
1862
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1863
-     * meaning if the model has a field that indicates its been "trashed" or
1864
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1865
-     *
1866
-     * @see EEM_Base::delete_permanently
1867
-     * @param array   $query_params
1868
-     * @param boolean $allow_blocking
1869
-     * @return int how many rows got deleted
1870
-     * @throws \EE_Error
1871
-     */
1872
-    public function delete($query_params, $allow_blocking = true)
1873
-    {
1874
-        return $this->delete_permanently($query_params, $allow_blocking);
1875
-    }
1876
-
1877
-
1878
-
1879
-    /**
1880
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1881
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1882
-     * as archived, not actually deleted
1883
-     *
1884
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1885
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1886
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1887
-     *                                deletes regardless of other objects which may depend on it. Its generally
1888
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1889
-     *                                DB
1890
-     * @return int how many rows got deleted
1891
-     * @throws \EE_Error
1892
-     */
1893
-    public function delete_permanently($query_params, $allow_blocking = true)
1894
-    {
1895
-        /**
1896
-         * Action called just before performing a real deletion query. You can use the
1897
-         * model and its $query_params to find exactly which items will be deleted
1898
-         *
1899
-         * @param EEM_Base $model
1900
-         * @param array    $query_params   @see EEM_Base::get_all()
1901
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1902
-         *                                 to block (prevent) this deletion
1903
-         */
1904
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1905
-        //some MySQL databases may be running safe mode, which may restrict
1906
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1907
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1908
-        //to delete them
1909
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1910
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1911
-        if ($deletion_where) {
1912
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1913
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1914
-            $table_aliases = array_keys($this->_tables);
1915
-            $SQL = "DELETE "
1916
-                   . implode(", ", $table_aliases)
1917
-                   . " FROM "
1918
-                   . $model_query_info->get_full_join_sql()
1919
-                   . " WHERE "
1920
-                   . $deletion_where;
1921
-            //		/echo "delete sql:$SQL";
1922
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1923
-        } else {
1924
-            $rows_deleted = 0;
1925
-        }
1926
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1927
-        if ($this->has_primary_key_field()) {
1928
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1929
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1930
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1931
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1932
-                }
1933
-            }
1934
-        }
1935
-        /**
1936
-         * Action called just after performing a real deletion query. Although at this point the
1937
-         * items should have been deleted
1938
-         *
1939
-         * @param EEM_Base $model
1940
-         * @param array    $query_params @see EEM_Base::get_all()
1941
-         * @param int      $rows_deleted
1942
-         */
1943
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1944
-        return $rows_deleted;//how many supposedly got deleted
1945
-    }
1946
-
1947
-
1948
-
1949
-    /**
1950
-     * Checks all the relations that throw error messages when there are blocking related objects
1951
-     * for related model objects. If there are any related model objects on those relations,
1952
-     * adds an EE_Error, and return true
1953
-     *
1954
-     * @param EE_Base_Class|int $this_model_obj_or_id
1955
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1956
-     *                                                 should be ignored when determining whether there are related
1957
-     *                                                 model objects which block this model object's deletion. Useful
1958
-     *                                                 if you know A is related to B and are considering deleting A,
1959
-     *                                                 but want to see if A has any other objects blocking its deletion
1960
-     *                                                 before removing the relation between A and B
1961
-     * @return boolean
1962
-     * @throws \EE_Error
1963
-     */
1964
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1965
-    {
1966
-        //first, if $ignore_this_model_obj was supplied, get its model
1967
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1968
-            $ignored_model = $ignore_this_model_obj->get_model();
1969
-        } else {
1970
-            $ignored_model = null;
1971
-        }
1972
-        //now check all the relations of $this_model_obj_or_id and see if there
1973
-        //are any related model objects blocking it?
1974
-        $is_blocked = false;
1975
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1976
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1977
-                //if $ignore_this_model_obj was supplied, then for the query
1978
-                //on that model needs to be told to ignore $ignore_this_model_obj
1979
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1980
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1981
-                        array(
1982
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1983
-                                '!=',
1984
-                                $ignore_this_model_obj->ID(),
1985
-                            ),
1986
-                        ),
1987
-                    ));
1988
-                } else {
1989
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1990
-                }
1991
-                if ($related_model_objects) {
1992
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1993
-                    $is_blocked = true;
1994
-                }
1995
-            }
1996
-        }
1997
-        return $is_blocked;
1998
-    }
1999
-
2000
-
2001
-
2002
-    /**
2003
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2004
-     * well.
2005
-     *
2006
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2007
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2008
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
2009
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
2010
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
2011
-     *                                      easily corrupt your DB
2012
-     * @throws EE_Error
2013
-     * @return string    everything that comes after the WHERE statement.
2014
-     */
2015
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2016
-    {
2017
-        if ($this->has_primary_key_field()) {
2018
-            $primary_table = $this->_get_main_table();
2019
-            $pt_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2020
-            $other_tables = $this->_get_other_tables();
2021
-            $ot_pk_fields = array();
2022
-            $ot_fk_fields = array();
2023
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2024
-                $ot_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2025
-                $ot_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2026
-            }
2027
-            $deletes = $query = array();
2028
-            foreach ($objects_for_deletion as $delete_object) {
2029
-                //before we mark this object for deletion,
2030
-                //make sure there's no related objects blocking its deletion (if we're checking)
2031
-                if (
2032
-                    $allow_blocking
2033
-                    && $this->delete_is_blocked_by_related_models(
2034
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
-                    )
2036
-                ) {
2037
-                    continue;
2038
-                }
2039
-                //primary table deletes
2040
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
-
2042
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2043
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()],
2044
-                        $pt_pk_field
2045
-                    );
2046
-                }
2047
-                //other tables
2048
-                if (! empty($other_tables)) {
2049
-                    foreach ($other_tables as $ot_alias => $ot) {
2050
-                        $ot_pk_field = $ot_pk_fields[$ot_alias];
2051
-                        $ot_fk_field = $ot_fk_fields[$ot_alias];
2052
-                        //first check if we've got the foreign key column here.
2053
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2054
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2055
-                                $delete_object[$ot->get_fully_qualified_fk_column()],
2056
-                                $ot_fk_field
2057
-                            );
2058
-                        }
2059
-                        // wait! it's entirely possible that we'll have a the primary key
2060
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2061
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2062
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2063
-                                $delete_object[$ot->get_fully_qualified_pk_column()],
2064
-                                $ot_pk_field
2065
-                            );
2066
-                        }
2067
-                        // finally, it is possible that the fk for this table is found
2068
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2069
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2070
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2071
-                                $delete_object[$ot->get_fully_qualified_pk_column()],
2072
-                                $ot_pk_field
2073
-                            );
2074
-                        }
2075
-                    }
2076
-                }
2077
-            }
2078
-            //we should have deletes now, so let's just go through and setup the where statement
2079
-            foreach ($deletes as $column => $values) {
2080
-                //make sure we have unique $values;
2081
-                $values = array_unique($values);
2082
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2083
-            }
2084
-            return ! empty($query) ? implode(' AND ', $query) : '';
2085
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2086
-            $ways_to_identify_a_row = array();
2087
-            $fields = $this->get_combined_primary_key_fields();
2088
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2089
-            foreach ($objects_for_deletion as $delete_object) {
2090
-                $values_for_each_cpk_for_a_row = array();
2091
-                foreach ($fields as $cpk_field) {
2092
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2093
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2094
-                                                           . "="
2095
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
2096
-                    }
2097
-                }
2098
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2099
-            }
2100
-            return implode(" OR ", $ways_to_identify_a_row);
2101
-        } else {
2102
-            //so there's no primary key and no combined key...
2103
-            //sorry, can't help you
2104
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2105
-                "event_espresso"), get_class($this)));
2106
-        }
2107
-    }
2108
-
2109
-
2110
-    /**
2111
-     * Gets the model field by the fully qualified name
2112
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2113
-     * @return EE_Model_Field_Base
2114
-     */
2115
-    public function get_field_by_column($qualified_column_name)
2116
-    {
2117
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2118
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2119
-               return $field_obj;
2120
-           }
2121
-       }
2122
-        throw new EE_Error(
2123
-            sprintf(
2124
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2125
-                $this->get_this_model_name(),
2126
-                $qualified_column_name
2127
-            )
2128
-        );
2129
-    }
2130
-
2131
-
2132
-
2133
-    /**
2134
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2135
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2136
-     * column
2137
-     *
2138
-     * @param array  $query_params   like EEM_Base::get_all's
2139
-     * @param string $field_to_count field on model to count by (not column name)
2140
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2141
-     *                               that by the setting $distinct to TRUE;
2142
-     * @return int
2143
-     * @throws \EE_Error
2144
-     */
2145
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2146
-    {
2147
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2148
-        if ($field_to_count) {
2149
-            $field_obj = $this->field_settings_for($field_to_count);
2150
-            $column_to_count = $field_obj->get_qualified_column();
2151
-        } elseif ($this->has_primary_key_field()) {
2152
-            $pk_field_obj = $this->get_primary_key_field();
2153
-            $column_to_count = $pk_field_obj->get_qualified_column();
2154
-        } else {
2155
-            //there's no primary key
2156
-            //if we're counting distinct items, and there's no primary key,
2157
-            //we need to list out the columns for distinction;
2158
-            //otherwise we can just use star
2159
-            if ($distinct) {
2160
-                $columns_to_use = array();
2161
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2162
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2163
-                }
2164
-                $column_to_count = implode(',', $columns_to_use);
2165
-            } else {
2166
-                $column_to_count = '*';
2167
-            }
2168
-        }
2169
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2170
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2171
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2172
-    }
2173
-
2174
-
2175
-
2176
-    /**
2177
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2178
-     *
2179
-     * @param array  $query_params like EEM_Base::get_all
2180
-     * @param string $field_to_sum name of field (array key in $_fields array)
2181
-     * @return float
2182
-     * @throws \EE_Error
2183
-     */
2184
-    public function sum($query_params, $field_to_sum = null)
2185
-    {
2186
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2187
-        if ($field_to_sum) {
2188
-            $field_obj = $this->field_settings_for($field_to_sum);
2189
-        } else {
2190
-            $field_obj = $this->get_primary_key_field();
2191
-        }
2192
-        $column_to_count = $field_obj->get_qualified_column();
2193
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2194
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2195
-        $data_type = $field_obj->get_wpdb_data_type();
2196
-        if ($data_type === '%d' || $data_type === '%s') {
2197
-            return (float)$return_value;
2198
-        } else {//must be %f
2199
-            return (float)$return_value;
2200
-        }
2201
-    }
2202
-
2203
-
2204
-
2205
-    /**
2206
-     * Just calls the specified method on $wpdb with the given arguments
2207
-     * Consolidates a little extra error handling code
2208
-     *
2209
-     * @param string $wpdb_method
2210
-     * @param array  $arguments_to_provide
2211
-     * @throws EE_Error
2212
-     * @global wpdb  $wpdb
2213
-     * @return mixed
2214
-     */
2215
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2216
-    {
2217
-        //if we're in maintenance mode level 2, DON'T run any queries
2218
-        //because level 2 indicates the database needs updating and
2219
-        //is probably out of sync with the code
2220
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2221
-            throw new EE_Error(sprintf(__("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.",
2222
-                "event_espresso")));
2223
-        }
2224
-        /** @type WPDB $wpdb */
2225
-        global $wpdb;
2226
-        if (! method_exists($wpdb, $wpdb_method)) {
2227
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2228
-                'event_espresso'), $wpdb_method));
2229
-        }
2230
-        if (WP_DEBUG) {
2231
-            $old_show_errors_value = $wpdb->show_errors;
2232
-            $wpdb->show_errors(false);
2233
-        }
2234
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2235
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2236
-        if (WP_DEBUG) {
2237
-            $wpdb->show_errors($old_show_errors_value);
2238
-            if (! empty($wpdb->last_error)) {
2239
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2240
-            } elseif ($result === false) {
2241
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2242
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2243
-            }
2244
-        } elseif ($result === false) {
2245
-            EE_Error::add_error(
2246
-                sprintf(
2247
-                    __('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"',
2248
-                        'event_espresso'),
2249
-                    $wpdb_method,
2250
-                    var_export($arguments_to_provide, true),
2251
-                    $wpdb->last_error
2252
-                ),
2253
-                __FILE__,
2254
-                __FUNCTION__,
2255
-                __LINE__
2256
-            );
2257
-        }
2258
-        return $result;
2259
-    }
2260
-
2261
-
2262
-
2263
-    /**
2264
-     * Attempts to run the indicated WPDB method with the provided arguments,
2265
-     * and if there's an error tries to verify the DB is correct. Uses
2266
-     * the static property EEM_Base::$_db_verification_level to determine whether
2267
-     * we should try to fix the EE core db, the addons, or just give up
2268
-     *
2269
-     * @param string $wpdb_method
2270
-     * @param array  $arguments_to_provide
2271
-     * @return mixed
2272
-     */
2273
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2274
-    {
2275
-        /** @type WPDB $wpdb */
2276
-        global $wpdb;
2277
-        $wpdb->last_error = null;
2278
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2279
-        // was there an error running the query? but we don't care on new activations
2280
-        // (we're going to setup the DB anyway on new activations)
2281
-        if (($result === false || ! empty($wpdb->last_error))
2282
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2283
-        ) {
2284
-            switch (EEM_Base::$_db_verification_level) {
2285
-                case EEM_Base::db_verified_none :
2286
-                    // let's double-check core's DB
2287
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2288
-                    break;
2289
-                case EEM_Base::db_verified_core :
2290
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2291
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2292
-                    break;
2293
-                case EEM_Base::db_verified_addons :
2294
-                    // ummmm... you in trouble
2295
-                    return $result;
2296
-                    break;
2297
-            }
2298
-            if (! empty($error_message)) {
2299
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2300
-                trigger_error($error_message);
2301
-            }
2302
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2303
-        }
2304
-        return $result;
2305
-    }
2306
-
2307
-
2308
-
2309
-    /**
2310
-     * Verifies the EE core database is up-to-date and records that we've done it on
2311
-     * EEM_Base::$_db_verification_level
2312
-     *
2313
-     * @param string $wpdb_method
2314
-     * @param array  $arguments_to_provide
2315
-     * @return string
2316
-     */
2317
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2318
-    {
2319
-        /** @type WPDB $wpdb */
2320
-        global $wpdb;
2321
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2322
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2323
-        $error_message = sprintf(
2324
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2325
-                'event_espresso'),
2326
-            $wpdb->last_error,
2327
-            $wpdb_method,
2328
-            wp_json_encode($arguments_to_provide)
2329
-        );
2330
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2331
-        return $error_message;
2332
-    }
2333
-
2334
-
2335
-
2336
-    /**
2337
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2338
-     * EEM_Base::$_db_verification_level
2339
-     *
2340
-     * @param $wpdb_method
2341
-     * @param $arguments_to_provide
2342
-     * @return string
2343
-     */
2344
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2345
-    {
2346
-        /** @type WPDB $wpdb */
2347
-        global $wpdb;
2348
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2349
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2350
-        $error_message = sprintf(
2351
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2352
-                'event_espresso'),
2353
-            $wpdb->last_error,
2354
-            $wpdb_method,
2355
-            wp_json_encode($arguments_to_provide)
2356
-        );
2357
-        EE_System::instance()->initialize_addons();
2358
-        return $error_message;
2359
-    }
2360
-
2361
-
2362
-
2363
-    /**
2364
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2365
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2366
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2367
-     * ..."
2368
-     *
2369
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2370
-     * @return string
2371
-     */
2372
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2373
-    {
2374
-        return " FROM " . $model_query_info->get_full_join_sql() .
2375
-               $model_query_info->get_where_sql() .
2376
-               $model_query_info->get_group_by_sql() .
2377
-               $model_query_info->get_having_sql() .
2378
-               $model_query_info->get_order_by_sql() .
2379
-               $model_query_info->get_limit_sql();
2380
-    }
2381
-
2382
-
2383
-
2384
-    /**
2385
-     * Set to easily debug the next X queries ran from this model.
2386
-     *
2387
-     * @param int $count
2388
-     */
2389
-    public function show_next_x_db_queries($count = 1)
2390
-    {
2391
-        $this->_show_next_x_db_queries = $count;
2392
-    }
2393
-
2394
-
2395
-
2396
-    /**
2397
-     * @param $sql_query
2398
-     */
2399
-    public function show_db_query_if_previously_requested($sql_query)
2400
-    {
2401
-        if ($this->_show_next_x_db_queries > 0) {
2402
-            echo $sql_query;
2403
-            $this->_show_next_x_db_queries--;
2404
-        }
2405
-    }
2406
-
2407
-
2408
-
2409
-    /**
2410
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2411
-     * There are the 3 cases:
2412
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2413
-     * $otherModelObject has no ID, it is first saved.
2414
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2415
-     * has no ID, it is first saved.
2416
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2417
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2418
-     * join table
2419
-     *
2420
-     * @param        EE_Base_Class                     /int $thisModelObject
2421
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2422
-     * @param string $relationName                     , key in EEM_Base::_relations
2423
-     *                                                 an attendee to a group, you also want to specify which role they
2424
-     *                                                 will have in that group. So you would use this parameter to
2425
-     *                                                 specify array('role-column-name'=>'role-id')
2426
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2427
-     *                                                 to for relation to methods that allow you to further specify
2428
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2429
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2430
-     *                                                 because these will be inserted in any new rows created as well.
2431
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2432
-     * @throws \EE_Error
2433
-     */
2434
-    public function add_relationship_to(
2435
-        $id_or_obj,
2436
-        $other_model_id_or_obj,
2437
-        $relationName,
2438
-        $extra_join_model_fields_n_values = array()
2439
-    ) {
2440
-        $relation_obj = $this->related_settings_for($relationName);
2441
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2442
-    }
2443
-
2444
-
2445
-
2446
-    /**
2447
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2448
-     * There are the 3 cases:
2449
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2450
-     * error
2451
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2452
-     * an error
2453
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2454
-     *
2455
-     * @param        EE_Base_Class /int $id_or_obj
2456
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2457
-     * @param string $relationName key in EEM_Base::_relations
2458
-     * @return boolean of success
2459
-     * @throws \EE_Error
2460
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2461
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2462
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2463
-     *                             because these will be inserted in any new rows created as well.
2464
-     */
2465
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2466
-    {
2467
-        $relation_obj = $this->related_settings_for($relationName);
2468
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2469
-    }
2470
-
2471
-
2472
-
2473
-    /**
2474
-     * @param mixed           $id_or_obj
2475
-     * @param string          $relationName
2476
-     * @param array           $where_query_params
2477
-     * @param EE_Base_Class[] objects to which relations were removed
2478
-     * @return \EE_Base_Class[]
2479
-     * @throws \EE_Error
2480
-     */
2481
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2482
-    {
2483
-        $relation_obj = $this->related_settings_for($relationName);
2484
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2485
-    }
2486
-
2487
-
2488
-
2489
-    /**
2490
-     * Gets all the related items of the specified $model_name, using $query_params.
2491
-     * Note: by default, we remove the "default query params"
2492
-     * because we want to get even deleted items etc.
2493
-     *
2494
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2495
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2496
-     * @param array  $query_params like EEM_Base::get_all
2497
-     * @return EE_Base_Class[]
2498
-     * @throws \EE_Error
2499
-     */
2500
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2501
-    {
2502
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2503
-        $relation_settings = $this->related_settings_for($model_name);
2504
-        return $relation_settings->get_all_related($model_obj, $query_params);
2505
-    }
2506
-
2507
-
2508
-
2509
-    /**
2510
-     * Deletes all the model objects across the relation indicated by $model_name
2511
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2512
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2513
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2514
-     *
2515
-     * @param EE_Base_Class|int|string $id_or_obj
2516
-     * @param string                   $model_name
2517
-     * @param array                    $query_params
2518
-     * @return int how many deleted
2519
-     * @throws \EE_Error
2520
-     */
2521
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2522
-    {
2523
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2524
-        $relation_settings = $this->related_settings_for($model_name);
2525
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2526
-    }
2527
-
2528
-
2529
-
2530
-    /**
2531
-     * Hard deletes all the model objects across the relation indicated by $model_name
2532
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2533
-     * the model objects can't be hard deleted because of blocking related model objects,
2534
-     * just does a soft-delete on them instead.
2535
-     *
2536
-     * @param EE_Base_Class|int|string $id_or_obj
2537
-     * @param string                   $model_name
2538
-     * @param array                    $query_params
2539
-     * @return int how many deleted
2540
-     * @throws \EE_Error
2541
-     */
2542
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2543
-    {
2544
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2545
-        $relation_settings = $this->related_settings_for($model_name);
2546
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2547
-    }
2548
-
2549
-
2550
-
2551
-    /**
2552
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2553
-     * unless otherwise specified in the $query_params
2554
-     *
2555
-     * @param        int             /EE_Base_Class $id_or_obj
2556
-     * @param string $model_name     like 'Event', or 'Registration'
2557
-     * @param array  $query_params   like EEM_Base::get_all's
2558
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2559
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2560
-     *                               that by the setting $distinct to TRUE;
2561
-     * @return int
2562
-     * @throws \EE_Error
2563
-     */
2564
-    public function count_related(
2565
-        $id_or_obj,
2566
-        $model_name,
2567
-        $query_params = array(),
2568
-        $field_to_count = null,
2569
-        $distinct = false
2570
-    ) {
2571
-        $related_model = $this->get_related_model_obj($model_name);
2572
-        //we're just going to use the query params on the related model's normal get_all query,
2573
-        //except add a condition to say to match the current mod
2574
-        if (! isset($query_params['default_where_conditions'])) {
2575
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2576
-        }
2577
-        $this_model_name = $this->get_this_model_name();
2578
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2579
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2580
-        return $related_model->count($query_params, $field_to_count, $distinct);
2581
-    }
2582
-
2583
-
2584
-
2585
-    /**
2586
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2587
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2588
-     *
2589
-     * @param        int           /EE_Base_Class $id_or_obj
2590
-     * @param string $model_name   like 'Event', or 'Registration'
2591
-     * @param array  $query_params like EEM_Base::get_all's
2592
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2593
-     * @return float
2594
-     * @throws \EE_Error
2595
-     */
2596
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2597
-    {
2598
-        $related_model = $this->get_related_model_obj($model_name);
2599
-        if (! is_array($query_params)) {
2600
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2601
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2602
-                    gettype($query_params)), '4.6.0');
2603
-            $query_params = array();
2604
-        }
2605
-        //we're just going to use the query params on the related model's normal get_all query,
2606
-        //except add a condition to say to match the current mod
2607
-        if (! isset($query_params['default_where_conditions'])) {
2608
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2609
-        }
2610
-        $this_model_name = $this->get_this_model_name();
2611
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2612
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2613
-        return $related_model->sum($query_params, $field_to_sum);
2614
-    }
2615
-
2616
-
2617
-
2618
-    /**
2619
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2620
-     * $modelObject
2621
-     *
2622
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2623
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2624
-     * @param array               $query_params     like EEM_Base::get_all's
2625
-     * @return EE_Base_Class
2626
-     * @throws \EE_Error
2627
-     */
2628
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2629
-    {
2630
-        $query_params['limit'] = 1;
2631
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2632
-        if ($results) {
2633
-            return array_shift($results);
2634
-        } else {
2635
-            return null;
2636
-        }
2637
-    }
2638
-
2639
-
2640
-
2641
-    /**
2642
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2643
-     *
2644
-     * @return string
2645
-     */
2646
-    public function get_this_model_name()
2647
-    {
2648
-        return str_replace("EEM_", "", get_class($this));
2649
-    }
2650
-
2651
-
2652
-
2653
-    /**
2654
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2655
-     *
2656
-     * @return EE_Any_Foreign_Model_Name_Field
2657
-     * @throws EE_Error
2658
-     */
2659
-    public function get_field_containing_related_model_name()
2660
-    {
2661
-        foreach ($this->field_settings(true) as $field) {
2662
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2663
-                $field_with_model_name = $field;
2664
-            }
2665
-        }
2666
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2667
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2668
-                $this->get_this_model_name()));
2669
-        }
2670
-        return $field_with_model_name;
2671
-    }
2672
-
2673
-
2674
-
2675
-    /**
2676
-     * Inserts a new entry into the database, for each table.
2677
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2678
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2679
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2680
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2681
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2682
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2683
-     *
2684
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2685
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2686
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2687
-     *                              of EEM_Base)
2688
-     * @return int new primary key on main table that got inserted
2689
-     * @throws EE_Error
2690
-     */
2691
-    public function insert($field_n_values)
2692
-    {
2693
-        /**
2694
-         * Filters the fields and their values before inserting an item using the models
2695
-         *
2696
-         * @param array    $fields_n_values keys are the fields and values are their new values
2697
-         * @param EEM_Base $model           the model used
2698
-         */
2699
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2700
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2701
-            $main_table = $this->_get_main_table();
2702
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2703
-            if ($new_id !== false) {
2704
-                foreach ($this->_get_other_tables() as $other_table) {
2705
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2706
-                }
2707
-            }
2708
-            /**
2709
-             * Done just after attempting to insert a new model object
2710
-             *
2711
-             * @param EEM_Base   $model           used
2712
-             * @param array      $fields_n_values fields and their values
2713
-             * @param int|string the              ID of the newly-inserted model object
2714
-             */
2715
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2716
-            return $new_id;
2717
-        } else {
2718
-            return false;
2719
-        }
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Checks that the result would satisfy the unique indexes on this model
2726
-     *
2727
-     * @param array  $field_n_values
2728
-     * @param string $action
2729
-     * @return boolean
2730
-     * @throws \EE_Error
2731
-     */
2732
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2733
-    {
2734
-        foreach ($this->unique_indexes() as $index_name => $index) {
2735
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2736
-            if ($this->exists(array($uniqueness_where_params))) {
2737
-                EE_Error::add_error(
2738
-                    sprintf(
2739
-                        __(
2740
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2741
-                            "event_espresso"
2742
-                        ),
2743
-                        $action,
2744
-                        $this->_get_class_name(),
2745
-                        $index_name,
2746
-                        implode(",", $index->field_names()),
2747
-                        http_build_query($uniqueness_where_params)
2748
-                    ),
2749
-                    __FILE__,
2750
-                    __FUNCTION__,
2751
-                    __LINE__
2752
-                );
2753
-                return false;
2754
-            }
2755
-        }
2756
-        return true;
2757
-    }
2758
-
2759
-
2760
-
2761
-    /**
2762
-     * Checks the database for an item that conflicts (ie, if this item were
2763
-     * saved to the DB would break some uniqueness requirement, like a primary key
2764
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2765
-     * can be either an EE_Base_Class or an array of fields n values
2766
-     *
2767
-     * @param EE_Base_Class|array $obj_or_fields_array
2768
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2769
-     *                                                 when looking for conflicts
2770
-     *                                                 (ie, if false, we ignore the model object's primary key
2771
-     *                                                 when finding "conflicts". If true, it's also considered).
2772
-     *                                                 Only works for INT primary key,
2773
-     *                                                 STRING primary keys cannot be ignored
2774
-     * @throws EE_Error
2775
-     * @return EE_Base_Class|array
2776
-     */
2777
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2778
-    {
2779
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2780
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2781
-        } elseif (is_array($obj_or_fields_array)) {
2782
-            $fields_n_values = $obj_or_fields_array;
2783
-        } else {
2784
-            throw new EE_Error(
2785
-                sprintf(
2786
-                    __(
2787
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2788
-                        "event_espresso"
2789
-                    ),
2790
-                    get_class($this),
2791
-                    $obj_or_fields_array
2792
-                )
2793
-            );
2794
-        }
2795
-        $query_params = array();
2796
-        if ($this->has_primary_key_field()
2797
-            && ($include_primary_key
2798
-                || $this->get_primary_key_field()
2799
-                   instanceof
2800
-                   EE_Primary_Key_String_Field)
2801
-            && isset($fields_n_values[$this->primary_key_name()])
2802
-        ) {
2803
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2804
-        }
2805
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2806
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2807
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2808
-        }
2809
-        //if there is nothing to base this search on, then we shouldn't find anything
2810
-        if (empty($query_params)) {
2811
-            return array();
2812
-        } else {
2813
-            return $this->get_one($query_params);
2814
-        }
2815
-    }
2816
-
2817
-
2818
-
2819
-    /**
2820
-     * Like count, but is optimized and returns a boolean instead of an int
2821
-     *
2822
-     * @param array $query_params
2823
-     * @return boolean
2824
-     * @throws \EE_Error
2825
-     */
2826
-    public function exists($query_params)
2827
-    {
2828
-        $query_params['limit'] = 1;
2829
-        return $this->count($query_params) > 0;
2830
-    }
2831
-
2832
-
2833
-
2834
-    /**
2835
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2836
-     *
2837
-     * @param int|string $id
2838
-     * @return boolean
2839
-     * @throws \EE_Error
2840
-     */
2841
-    public function exists_by_ID($id)
2842
-    {
2843
-        return $this->exists(
2844
-            array(
2845
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2846
-                array(
2847
-                    $this->primary_key_name() => $id,
2848
-                ),
2849
-            )
2850
-        );
2851
-    }
2852
-
2853
-
2854
-
2855
-    /**
2856
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2857
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2858
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2859
-     * on the main table)
2860
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2861
-     * cases where we want to call it directly rather than via insert().
2862
-     *
2863
-     * @access   protected
2864
-     * @param EE_Table_Base $table
2865
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2866
-     *                                       float
2867
-     * @param int           $new_id          for now we assume only int keys
2868
-     * @throws EE_Error
2869
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2870
-     * @return int ID of new row inserted, or FALSE on failure
2871
-     */
2872
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2873
-    {
2874
-        global $wpdb;
2875
-        $insertion_col_n_values = array();
2876
-        $format_for_insertion = array();
2877
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2878
-        foreach ($fields_on_table as $field_name => $field_obj) {
2879
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2880
-            if ($field_obj->is_auto_increment()) {
2881
-                continue;
2882
-            }
2883
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2884
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2885
-            if ($prepared_value !== null) {
2886
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2887
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2888
-            }
2889
-        }
2890
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2891
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2892
-            //so add the fk to the main table as a column
2893
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2894
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2895
-        }
2896
-        //insert the new entry
2897
-        $result = $this->_do_wpdb_query('insert',
2898
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2899
-        if ($result === false) {
2900
-            return false;
2901
-        }
2902
-        //ok, now what do we return for the ID of the newly-inserted thing?
2903
-        if ($this->has_primary_key_field()) {
2904
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2905
-                return $wpdb->insert_id;
2906
-            } else {
2907
-                //it's not an auto-increment primary key, so
2908
-                //it must have been supplied
2909
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2910
-            }
2911
-        } else {
2912
-            //we can't return a  primary key because there is none. instead return
2913
-            //a unique string indicating this model
2914
-            return $this->get_index_primary_key_string($fields_n_values);
2915
-        }
2916
-    }
2917
-
2918
-
2919
-
2920
-    /**
2921
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2922
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2923
-     * and there is no default, we pass it along. WPDB will take care of it)
2924
-     *
2925
-     * @param EE_Model_Field_Base $field_obj
2926
-     * @param array               $fields_n_values
2927
-     * @return mixed string|int|float depending on what the table column will be expecting
2928
-     * @throws \EE_Error
2929
-     */
2930
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2931
-    {
2932
-        //if this field doesn't allow nullable, don't allow it
2933
-        if (! $field_obj->is_nullable()
2934
-            && (
2935
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2936
-        ) {
2937
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2938
-        }
2939
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2940
-            : null;
2941
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2942
-    }
2943
-
2944
-
2945
-
2946
-    /**
2947
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2948
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2949
-     * the field's prepare_for_set() method.
2950
-     *
2951
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2952
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2953
-     *                                   top of file)
2954
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2955
-     *                                   $value is a custom selection
2956
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2957
-     */
2958
-    private function _prepare_value_for_use_in_db($value, $field)
2959
-    {
2960
-        if ($field && $field instanceof EE_Model_Field_Base) {
2961
-            switch ($this->_values_already_prepared_by_model_object) {
2962
-                /** @noinspection PhpMissingBreakStatementInspection */
2963
-                case self::not_prepared_by_model_object:
2964
-                    $value = $field->prepare_for_set($value);
2965
-                //purposefully left out "return"
2966
-                case self::prepared_by_model_object:
2967
-                    $value = $field->prepare_for_use_in_db($value);
2968
-                case self::prepared_for_use_in_db:
2969
-                    //leave the value alone
2970
-            }
2971
-            return $value;
2972
-        } else {
2973
-            return $value;
2974
-        }
2975
-    }
2976
-
2977
-
2978
-
2979
-    /**
2980
-     * Returns the main table on this model
2981
-     *
2982
-     * @return EE_Primary_Table
2983
-     * @throws EE_Error
2984
-     */
2985
-    protected function _get_main_table()
2986
-    {
2987
-        foreach ($this->_tables as $table) {
2988
-            if ($table instanceof EE_Primary_Table) {
2989
-                return $table;
2990
-            }
2991
-        }
2992
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2993
-            'event_espresso'), get_class($this)));
2994
-    }
2995
-
2996
-
2997
-
2998
-    /**
2999
-     * table
3000
-     * returns EE_Primary_Table table name
3001
-     *
3002
-     * @return string
3003
-     * @throws \EE_Error
3004
-     */
3005
-    public function table()
3006
-    {
3007
-        return $this->_get_main_table()->get_table_name();
3008
-    }
3009
-
3010
-
3011
-
3012
-    /**
3013
-     * table
3014
-     * returns first EE_Secondary_Table table name
3015
-     *
3016
-     * @return string
3017
-     */
3018
-    public function second_table()
3019
-    {
3020
-        // grab second table from tables array
3021
-        $second_table = end($this->_tables);
3022
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3023
-    }
3024
-
3025
-
3026
-
3027
-    /**
3028
-     * get_table_obj_by_alias
3029
-     * returns table name given it's alias
3030
-     *
3031
-     * @param string $table_alias
3032
-     * @return EE_Primary_Table | EE_Secondary_Table
3033
-     */
3034
-    public function get_table_obj_by_alias($table_alias = '')
3035
-    {
3036
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3037
-    }
3038
-
3039
-
3040
-
3041
-    /**
3042
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3043
-     *
3044
-     * @return EE_Secondary_Table[]
3045
-     */
3046
-    protected function _get_other_tables()
3047
-    {
3048
-        $other_tables = array();
3049
-        foreach ($this->_tables as $table_alias => $table) {
3050
-            if ($table instanceof EE_Secondary_Table) {
3051
-                $other_tables[$table_alias] = $table;
3052
-            }
3053
-        }
3054
-        return $other_tables;
3055
-    }
3056
-
3057
-
3058
-
3059
-    /**
3060
-     * Finds all the fields that correspond to the given table
3061
-     *
3062
-     * @param string $table_alias , array key in EEM_Base::_tables
3063
-     * @return EE_Model_Field_Base[]
3064
-     */
3065
-    public function _get_fields_for_table($table_alias)
3066
-    {
3067
-        return $this->_fields[$table_alias];
3068
-    }
3069
-
3070
-
3071
-
3072
-    /**
3073
-     * Recurses through all the where parameters, and finds all the related models we'll need
3074
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3075
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3076
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3077
-     * related Registration, Transaction, and Payment models.
3078
-     *
3079
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3080
-     * @return EE_Model_Query_Info_Carrier
3081
-     * @throws \EE_Error
3082
-     */
3083
-    public function _extract_related_models_from_query($query_params)
3084
-    {
3085
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3086
-        if (array_key_exists(0, $query_params)) {
3087
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3088
-        }
3089
-        if (array_key_exists('group_by', $query_params)) {
3090
-            if (is_array($query_params['group_by'])) {
3091
-                $this->_extract_related_models_from_sub_params_array_values(
3092
-                    $query_params['group_by'],
3093
-                    $query_info_carrier,
3094
-                    'group_by'
3095
-                );
3096
-            } elseif (! empty ($query_params['group_by'])) {
3097
-                $this->_extract_related_model_info_from_query_param(
3098
-                    $query_params['group_by'],
3099
-                    $query_info_carrier,
3100
-                    'group_by'
3101
-                );
3102
-            }
3103
-        }
3104
-        if (array_key_exists('having', $query_params)) {
3105
-            $this->_extract_related_models_from_sub_params_array_keys(
3106
-                $query_params[0],
3107
-                $query_info_carrier,
3108
-                'having'
3109
-            );
3110
-        }
3111
-        if (array_key_exists('order_by', $query_params)) {
3112
-            if (is_array($query_params['order_by'])) {
3113
-                $this->_extract_related_models_from_sub_params_array_keys(
3114
-                    $query_params['order_by'],
3115
-                    $query_info_carrier,
3116
-                    'order_by'
3117
-                );
3118
-            } elseif (! empty($query_params['order_by'])) {
3119
-                $this->_extract_related_model_info_from_query_param(
3120
-                    $query_params['order_by'],
3121
-                    $query_info_carrier,
3122
-                    'order_by'
3123
-                );
3124
-            }
3125
-        }
3126
-        if (array_key_exists('force_join', $query_params)) {
3127
-            $this->_extract_related_models_from_sub_params_array_values(
3128
-                $query_params['force_join'],
3129
-                $query_info_carrier,
3130
-                'force_join'
3131
-            );
3132
-        }
3133
-        return $query_info_carrier;
3134
-    }
3135
-
3136
-
3137
-
3138
-    /**
3139
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3140
-     *
3141
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3142
-     *                                                      $query_params['having']
3143
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3144
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3145
-     * @throws EE_Error
3146
-     * @return \EE_Model_Query_Info_Carrier
3147
-     */
3148
-    private function _extract_related_models_from_sub_params_array_keys(
3149
-        $sub_query_params,
3150
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3151
-        $query_param_type
3152
-    ) {
3153
-        if (! empty($sub_query_params)) {
3154
-            $sub_query_params = (array)$sub_query_params;
3155
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3156
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3157
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3158
-                    $query_param_type);
3159
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3160
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3161
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3162
-                //of array('Registration.TXN_ID'=>23)
3163
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3164
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3165
-                    if (! is_array($possibly_array_of_params)) {
3166
-                        throw new EE_Error(sprintf(__("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'))",
3167
-                            "event_espresso"),
3168
-                            $param, $possibly_array_of_params));
3169
-                    } else {
3170
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3171
-                            $model_query_info_carrier, $query_param_type);
3172
-                    }
3173
-                } elseif ($query_param_type === 0 //ie WHERE
3174
-                          && is_array($possibly_array_of_params)
3175
-                          && isset($possibly_array_of_params[2])
3176
-                          && $possibly_array_of_params[2] == true
3177
-                ) {
3178
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3179
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3180
-                    //from which we should extract query parameters!
3181
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3182
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3183
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3184
-                    }
3185
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3186
-                        $model_query_info_carrier, $query_param_type);
3187
-                }
3188
-            }
3189
-        }
3190
-        return $model_query_info_carrier;
3191
-    }
3192
-
3193
-
3194
-
3195
-    /**
3196
-     * For extracting related models from forced_joins, where the array values contain the info about what
3197
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3198
-     *
3199
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3200
-     *                                                      $query_params['having']
3201
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3202
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3203
-     * @throws EE_Error
3204
-     * @return \EE_Model_Query_Info_Carrier
3205
-     */
3206
-    private function _extract_related_models_from_sub_params_array_values(
3207
-        $sub_query_params,
3208
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3209
-        $query_param_type
3210
-    ) {
3211
-        if (! empty($sub_query_params)) {
3212
-            if (! is_array($sub_query_params)) {
3213
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3214
-                    $sub_query_params));
3215
-            }
3216
-            foreach ($sub_query_params as $param) {
3217
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3218
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3219
-                    $query_param_type);
3220
-            }
3221
-        }
3222
-        return $model_query_info_carrier;
3223
-    }
3224
-
3225
-
3226
-
3227
-    /**
3228
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3229
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3230
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3231
-     * but use them in a different order. Eg, we need to know what models we are querying
3232
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3233
-     * other models before we can finalize the where clause SQL.
3234
-     *
3235
-     * @param array $query_params
3236
-     * @throws EE_Error
3237
-     * @return EE_Model_Query_Info_Carrier
3238
-     */
3239
-    public function _create_model_query_info_carrier($query_params)
3240
-    {
3241
-        if (! is_array($query_params)) {
3242
-            EE_Error::doing_it_wrong(
3243
-                'EEM_Base::_create_model_query_info_carrier',
3244
-                sprintf(
3245
-                    __(
3246
-                        '$query_params should be an array, you passed a variable of type %s',
3247
-                        'event_espresso'
3248
-                    ),
3249
-                    gettype($query_params)
3250
-                ),
3251
-                '4.6.0'
3252
-            );
3253
-            $query_params = array();
3254
-        }
3255
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3256
-        //first check if we should alter the query to account for caps or not
3257
-        //because the caps might require us to do extra joins
3258
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3259
-            $query_params[0] = $where_query_params = array_replace_recursive(
3260
-                $where_query_params,
3261
-                $this->caps_where_conditions(
3262
-                    $query_params['caps']
3263
-                )
3264
-            );
3265
-        }
3266
-        $query_object = $this->_extract_related_models_from_query($query_params);
3267
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3268
-        foreach ($where_query_params as $key => $value) {
3269
-            if (is_int($key)) {
3270
-                throw new EE_Error(
3271
-                    sprintf(
3272
-                        __(
3273
-                            "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.",
3274
-                            "event_espresso"
3275
-                        ),
3276
-                        $key,
3277
-                        var_export($value, true),
3278
-                        var_export($query_params, true),
3279
-                        get_class($this)
3280
-                    )
3281
-                );
3282
-            }
3283
-        }
3284
-        if (
3285
-            array_key_exists('default_where_conditions', $query_params)
3286
-            && ! empty($query_params['default_where_conditions'])
3287
-        ) {
3288
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3289
-        } else {
3290
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3291
-        }
3292
-        $where_query_params = array_merge(
3293
-            $this->_get_default_where_conditions_for_models_in_query(
3294
-                $query_object,
3295
-                $use_default_where_conditions,
3296
-                $where_query_params
3297
-            ),
3298
-            $where_query_params
3299
-        );
3300
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3301
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3302
-        // So we need to setup a subquery and use that for the main join.
3303
-        // Note for now this only works on the primary table for the model.
3304
-        // So for instance, you could set the limit array like this:
3305
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3306
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3307
-            $query_object->set_main_model_join_sql(
3308
-                $this->_construct_limit_join_select(
3309
-                    $query_params['on_join_limit'][0],
3310
-                    $query_params['on_join_limit'][1]
3311
-                )
3312
-            );
3313
-        }
3314
-        //set limit
3315
-        if (array_key_exists('limit', $query_params)) {
3316
-            if (is_array($query_params['limit'])) {
3317
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3318
-                    $e = sprintf(
3319
-                        __(
3320
-                            "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)",
3321
-                            "event_espresso"
3322
-                        ),
3323
-                        http_build_query($query_params['limit'])
3324
-                    );
3325
-                    throw new EE_Error($e . "|" . $e);
3326
-                }
3327
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3328
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3329
-            } elseif (! empty ($query_params['limit'])) {
3330
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3331
-            }
3332
-        }
3333
-        //set order by
3334
-        if (array_key_exists('order_by', $query_params)) {
3335
-            if (is_array($query_params['order_by'])) {
3336
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3337
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3338
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3339
-                if (array_key_exists('order', $query_params)) {
3340
-                    throw new EE_Error(
3341
-                        sprintf(
3342
-                            __(
3343
-                                "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 ",
3344
-                                "event_espresso"
3345
-                            ),
3346
-                            get_class($this),
3347
-                            implode(", ", array_keys($query_params['order_by'])),
3348
-                            implode(", ", $query_params['order_by']),
3349
-                            $query_params['order']
3350
-                        )
3351
-                    );
3352
-                }
3353
-                $this->_extract_related_models_from_sub_params_array_keys(
3354
-                    $query_params['order_by'],
3355
-                    $query_object,
3356
-                    'order_by'
3357
-                );
3358
-                //assume it's an array of fields to order by
3359
-                $order_array = array();
3360
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3361
-                    $order = $this->_extract_order($order);
3362
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3363
-                }
3364
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3365
-            } elseif (! empty ($query_params['order_by'])) {
3366
-                $this->_extract_related_model_info_from_query_param(
3367
-                    $query_params['order_by'],
3368
-                    $query_object,
3369
-                    'order',
3370
-                    $query_params['order_by']
3371
-                );
3372
-                $order = isset($query_params['order'])
3373
-                    ? $this->_extract_order($query_params['order'])
3374
-                    : 'DESC';
3375
-                $query_object->set_order_by_sql(
3376
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3377
-                );
3378
-            }
3379
-        }
3380
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3381
-        if (! array_key_exists('order_by', $query_params)
3382
-            && array_key_exists('order', $query_params)
3383
-            && ! empty($query_params['order'])
3384
-        ) {
3385
-            $pk_field = $this->get_primary_key_field();
3386
-            $order = $this->_extract_order($query_params['order']);
3387
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3388
-        }
3389
-        //set group by
3390
-        if (array_key_exists('group_by', $query_params)) {
3391
-            if (is_array($query_params['group_by'])) {
3392
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3393
-                $group_by_array = array();
3394
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3395
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3396
-                }
3397
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3398
-            } elseif (! empty ($query_params['group_by'])) {
3399
-                $query_object->set_group_by_sql(
3400
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3401
-                );
3402
-            }
3403
-        }
3404
-        //set having
3405
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3406
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3407
-        }
3408
-        //now, just verify they didn't pass anything wack
3409
-        foreach ($query_params as $query_key => $query_value) {
3410
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3411
-                throw new EE_Error(
3412
-                    sprintf(
3413
-                        __(
3414
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3415
-                            'event_espresso'
3416
-                        ),
3417
-                        $query_key,
3418
-                        get_class($this),
3419
-                        //						print_r( $this->_allowed_query_params, TRUE )
3420
-                        implode(',', $this->_allowed_query_params)
3421
-                    )
3422
-                );
3423
-            }
3424
-        }
3425
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3426
-        if (empty($main_model_join_sql)) {
3427
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3428
-        }
3429
-        return $query_object;
3430
-    }
3431
-
3432
-
3433
-
3434
-    /**
3435
-     * Gets the where conditions that should be imposed on the query based on the
3436
-     * context (eg reading frontend, backend, edit or delete).
3437
-     *
3438
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3439
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3440
-     * @throws \EE_Error
3441
-     */
3442
-    public function caps_where_conditions($context = self::caps_read)
3443
-    {
3444
-        EEM_Base::verify_is_valid_cap_context($context);
3445
-        $cap_where_conditions = array();
3446
-        $cap_restrictions = $this->caps_missing($context);
3447
-        /**
3448
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3449
-         */
3450
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3451
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3452
-                $restriction_if_no_cap->get_default_where_conditions());
3453
-        }
3454
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3455
-            $cap_restrictions);
3456
-    }
3457
-
3458
-
3459
-
3460
-    /**
3461
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3462
-     * otherwise throws an exception
3463
-     *
3464
-     * @param string $should_be_order_string
3465
-     * @return string either ASC, asc, DESC or desc
3466
-     * @throws EE_Error
3467
-     */
3468
-    private function _extract_order($should_be_order_string)
3469
-    {
3470
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3471
-            return $should_be_order_string;
3472
-        } else {
3473
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3474
-                "event_espresso"), get_class($this), $should_be_order_string));
3475
-        }
3476
-    }
3477
-
3478
-
3479
-
3480
-    /**
3481
-     * Looks at all the models which are included in this query, and asks each
3482
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3483
-     * so they can be merged
3484
-     *
3485
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3486
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3487
-     *                                                                  'none' means NO default where conditions will
3488
-     *                                                                  be used AT ALL during this query.
3489
-     *                                                                  'other_models_only' means default where
3490
-     *                                                                  conditions from other models will be used, but
3491
-     *                                                                  not for this primary model. 'all', the default,
3492
-     *                                                                  means default where conditions will apply as
3493
-     *                                                                  normal
3494
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3495
-     * @throws EE_Error
3496
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3497
-     */
3498
-    private function _get_default_where_conditions_for_models_in_query(
3499
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3500
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3501
-        $where_query_params = array()
3502
-    ) {
3503
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3504
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3505
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3506
-                "event_espresso"), $use_default_where_conditions,
3507
-                implode(", ", $allowed_used_default_where_conditions_values)));
3508
-        }
3509
-        $universal_query_params = array();
3510
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3511
-            $universal_query_params = $this->_get_default_where_conditions();
3512
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3513
-            $universal_query_params = $this->_get_minimum_where_conditions();
3514
-        }
3515
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3516
-            $related_model = $this->get_related_model_obj($model_name);
3517
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3518
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3519
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3520
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3521
-            } else {
3522
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3523
-                continue;
3524
-            }
3525
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3526
-                $related_model_universal_where_params,
3527
-                $where_query_params,
3528
-                $related_model,
3529
-                $model_relation_path
3530
-            );
3531
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3532
-                $universal_query_params,
3533
-                $overrides
3534
-            );
3535
-        }
3536
-        return $universal_query_params;
3537
-    }
3538
-
3539
-
3540
-
3541
-    /**
3542
-     * Determines whether or not we should use default where conditions for the model in question
3543
-     * (this model, or other related models).
3544
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3545
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3546
-     * We should use default where conditions on related models when they requested to use default where conditions
3547
-     * on all models, or specifically just on other related models
3548
-     * @param      $default_where_conditions_value
3549
-     * @param bool $for_this_model false means this is for OTHER related models
3550
-     * @return bool
3551
-     */
3552
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3553
-    {
3554
-        return (
3555
-                   $for_this_model
3556
-                   && in_array(
3557
-                       $default_where_conditions_value,
3558
-                       array(
3559
-                           EEM_Base::default_where_conditions_all,
3560
-                           EEM_Base::default_where_conditions_this_only,
3561
-                           EEM_Base::default_where_conditions_minimum_others,
3562
-                       ),
3563
-                       true
3564
-                   )
3565
-               )
3566
-               || (
3567
-                   ! $for_this_model
3568
-                   && in_array(
3569
-                       $default_where_conditions_value,
3570
-                       array(
3571
-                           EEM_Base::default_where_conditions_all,
3572
-                           EEM_Base::default_where_conditions_others_only,
3573
-                       ),
3574
-                       true
3575
-                   )
3576
-               );
3577
-    }
3578
-
3579
-    /**
3580
-     * Determines whether or not we should use default minimum conditions for the model in question
3581
-     * (this model, or other related models).
3582
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3583
-     * where conditions.
3584
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3585
-     * on this model or others
3586
-     * @param      $default_where_conditions_value
3587
-     * @param bool $for_this_model false means this is for OTHER related models
3588
-     * @return bool
3589
-     */
3590
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3591
-    {
3592
-        return (
3593
-                   $for_this_model
3594
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3595
-               )
3596
-               || (
3597
-                   ! $for_this_model
3598
-                   && in_array(
3599
-                       $default_where_conditions_value,
3600
-                       array(
3601
-                           EEM_Base::default_where_conditions_minimum_others,
3602
-                           EEM_Base::default_where_conditions_minimum_all,
3603
-                       ),
3604
-                       true
3605
-                   )
3606
-               );
3607
-    }
3608
-
3609
-
3610
-    /**
3611
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3612
-     * then we also add a special where condition which allows for that model's primary key
3613
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3614
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3615
-     *
3616
-     * @param array    $default_where_conditions
3617
-     * @param array    $provided_where_conditions
3618
-     * @param EEM_Base $model
3619
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3620
-     * @return array like EEM_Base::get_all's $query_params[0]
3621
-     * @throws \EE_Error
3622
-     */
3623
-    private function _override_defaults_or_make_null_friendly(
3624
-        $default_where_conditions,
3625
-        $provided_where_conditions,
3626
-        $model,
3627
-        $model_relation_path
3628
-    ) {
3629
-        $null_friendly_where_conditions = array();
3630
-        $none_overridden = true;
3631
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3632
-        foreach ($default_where_conditions as $key => $val) {
3633
-            if (isset($provided_where_conditions[$key])) {
3634
-                $none_overridden = false;
3635
-            } else {
3636
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3637
-            }
3638
-        }
3639
-        if ($none_overridden && $default_where_conditions) {
3640
-            if ($model->has_primary_key_field()) {
3641
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3642
-                                                                                . "."
3643
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3644
-            }/*else{
32
+	/**
33
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
34
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
35
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
36
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
37
+	 *
38
+	 * @var boolean
39
+	 */
40
+	private $_values_already_prepared_by_model_object = 0;
41
+
42
+	/**
43
+	 * when $_values_already_prepared_by_model_object equals this, we assume
44
+	 * the data is just like form input that needs to have the model fields'
45
+	 * prepare_for_set and prepare_for_use_in_db called on it
46
+	 */
47
+	const not_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we
51
+	 * assume this value is coming from a model object and doesn't need to have
52
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
53
+	 */
54
+	const prepared_by_model_object = 1;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we assume
58
+	 * the values are already to be used in the database (ie no processing is done
59
+	 * on them by the model's fields)
60
+	 */
61
+	const prepared_for_use_in_db = 2;
62
+
63
+
64
+	protected $singular_item = 'Item';
65
+
66
+	protected $plural_item   = 'Items';
67
+
68
+	/**
69
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
70
+	 */
71
+	protected $_tables;
72
+
73
+	/**
74
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
75
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
76
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
77
+	 *
78
+	 * @var \EE_Model_Field_Base[][] $_fields
79
+	 */
80
+	protected $_fields;
81
+
82
+	/**
83
+	 * array of different kinds of relations
84
+	 *
85
+	 * @var \EE_Model_Relation_Base[] $_model_relations
86
+	 */
87
+	protected $_model_relations;
88
+
89
+	/**
90
+	 * @var \EE_Index[] $_indexes
91
+	 */
92
+	protected $_indexes = array();
93
+
94
+	/**
95
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
96
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
97
+	 * by setting the same columns as used in these queries in the query yourself.
98
+	 *
99
+	 * @var EE_Default_Where_Conditions
100
+	 */
101
+	protected $_default_where_conditions_strategy;
102
+
103
+	/**
104
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
105
+	 * This is particularly useful when you want something between 'none' and 'default'
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_minimum_where_conditions_strategy;
110
+
111
+	/**
112
+	 * String describing how to find the "owner" of this model's objects.
113
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
114
+	 * But when there isn't, this indicates which related model, or transiently-related model,
115
+	 * has the foreign key to the wp_users table.
116
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
117
+	 * related to events, and events have a foreign key to wp_users.
118
+	 * On EEM_Transaction, this would be 'Transaction.Event'
119
+	 *
120
+	 * @var string
121
+	 */
122
+	protected $_model_chain_to_wp_user = '';
123
+
124
+	/**
125
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
126
+	 * don't need it (particularly CPT models)
127
+	 *
128
+	 * @var bool
129
+	 */
130
+	protected $_ignore_where_strategy = false;
131
+
132
+	/**
133
+	 * String used in caps relating to this model. Eg, if the caps relating to this
134
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
135
+	 *
136
+	 * @var string. If null it hasn't been initialized yet. If false then we
137
+	 * have indicated capabilities don't apply to this
138
+	 */
139
+	protected $_caps_slug = null;
140
+
141
+	/**
142
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
143
+	 * and next-level keys are capability names, and each's value is a
144
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
145
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
146
+	 * and then each capability in the corresponding sub-array that they're missing
147
+	 * adds the where conditions onto the query.
148
+	 *
149
+	 * @var array
150
+	 */
151
+	protected $_cap_restrictions = array(
152
+		self::caps_read       => array(),
153
+		self::caps_read_admin => array(),
154
+		self::caps_edit       => array(),
155
+		self::caps_delete     => array(),
156
+	);
157
+
158
+	/**
159
+	 * Array defining which cap restriction generators to use to create default
160
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
161
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
162
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
163
+	 * automatically set this to false (not just null).
164
+	 *
165
+	 * @var EE_Restriction_Generator_Base[]
166
+	 */
167
+	protected $_cap_restriction_generators = array();
168
+
169
+	/**
170
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
171
+	 */
172
+	const caps_read       = 'read';
173
+
174
+	const caps_read_admin = 'read_admin';
175
+
176
+	const caps_edit       = 'edit';
177
+
178
+	const caps_delete     = 'delete';
179
+
180
+	/**
181
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
182
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
183
+	 * maps to 'read' because when looking for relevant permissions we're going to use
184
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
185
+	 *
186
+	 * @var array
187
+	 */
188
+	protected $_cap_contexts_to_cap_action_map = array(
189
+		self::caps_read       => 'read',
190
+		self::caps_read_admin => 'read',
191
+		self::caps_edit       => 'edit',
192
+		self::caps_delete     => 'delete',
193
+	);
194
+
195
+	/**
196
+	 * Timezone
197
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
198
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
199
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
200
+	 * EE_Datetime_Field data type will have access to it.
201
+	 *
202
+	 * @var string
203
+	 */
204
+	protected $_timezone;
205
+
206
+
207
+	/**
208
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
209
+	 * multisite.
210
+	 *
211
+	 * @var int
212
+	 */
213
+	protected static $_model_query_blog_id;
214
+
215
+	/**
216
+	 * A copy of _fields, except the array keys are the model names pointed to by
217
+	 * the field
218
+	 *
219
+	 * @var EE_Model_Field_Base[]
220
+	 */
221
+	private $_cache_foreign_key_to_fields = array();
222
+
223
+	/**
224
+	 * Cached list of all the fields on the model, indexed by their name
225
+	 *
226
+	 * @var EE_Model_Field_Base[]
227
+	 */
228
+	private $_cached_fields = null;
229
+
230
+	/**
231
+	 * Cached list of all the fields on the model, except those that are
232
+	 * marked as only pertinent to the database
233
+	 *
234
+	 * @var EE_Model_Field_Base[]
235
+	 */
236
+	private $_cached_fields_non_db_only = null;
237
+
238
+	/**
239
+	 * A cached reference to the primary key for quick lookup
240
+	 *
241
+	 * @var EE_Model_Field_Base
242
+	 */
243
+	private $_primary_key_field = null;
244
+
245
+	/**
246
+	 * Flag indicating whether this model has a primary key or not
247
+	 *
248
+	 * @var boolean
249
+	 */
250
+	protected $_has_primary_key_field = null;
251
+
252
+	/**
253
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
254
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
255
+	 * This should be true for models that deal with data that should exist independent of EE.
256
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
257
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
258
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
259
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
260
+	 * @var boolean
261
+	 */
262
+	protected $_wp_core_model = false;
263
+
264
+	/**
265
+	 *    List of valid operators that can be used for querying.
266
+	 * The keys are all operators we'll accept, the values are the real SQL
267
+	 * operators used
268
+	 *
269
+	 * @var array
270
+	 */
271
+	protected $_valid_operators = array(
272
+		'='           => '=',
273
+		'<='          => '<=',
274
+		'<'           => '<',
275
+		'>='          => '>=',
276
+		'>'           => '>',
277
+		'!='          => '!=',
278
+		'LIKE'        => 'LIKE',
279
+		'like'        => 'LIKE',
280
+		'NOT_LIKE'    => 'NOT LIKE',
281
+		'not_like'    => 'NOT LIKE',
282
+		'NOT LIKE'    => 'NOT LIKE',
283
+		'not like'    => 'NOT LIKE',
284
+		'IN'          => 'IN',
285
+		'in'          => 'IN',
286
+		'NOT_IN'      => 'NOT IN',
287
+		'not_in'      => 'NOT IN',
288
+		'NOT IN'      => 'NOT IN',
289
+		'not in'      => 'NOT IN',
290
+		'between'     => 'BETWEEN',
291
+		'BETWEEN'     => 'BETWEEN',
292
+		'IS_NOT_NULL' => 'IS NOT NULL',
293
+		'is_not_null' => 'IS NOT NULL',
294
+		'IS NOT NULL' => 'IS NOT NULL',
295
+		'is not null' => 'IS NOT NULL',
296
+		'IS_NULL'     => 'IS NULL',
297
+		'is_null'     => 'IS NULL',
298
+		'IS NULL'     => 'IS NULL',
299
+		'is null'     => 'IS NULL',
300
+		'REGEXP'      => 'REGEXP',
301
+		'regexp'      => 'REGEXP',
302
+		'NOT_REGEXP'  => 'NOT REGEXP',
303
+		'not_regexp'  => 'NOT REGEXP',
304
+		'NOT REGEXP'  => 'NOT REGEXP',
305
+		'not regexp'  => 'NOT REGEXP',
306
+	);
307
+
308
+	/**
309
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
310
+	 *
311
+	 * @var array
312
+	 */
313
+	protected $_in_style_operators = array('IN', 'NOT IN');
314
+
315
+	/**
316
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
317
+	 * '12-31-2012'"
318
+	 *
319
+	 * @var array
320
+	 */
321
+	protected $_between_style_operators = array('BETWEEN');
322
+
323
+	/**
324
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
325
+	 * @var array
326
+	 */
327
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
328
+	/**
329
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
330
+	 * on a join table.
331
+	 *
332
+	 * @var array
333
+	 */
334
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
335
+
336
+	/**
337
+	 * Allowed values for $query_params['order'] for ordering in queries
338
+	 *
339
+	 * @var array
340
+	 */
341
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
342
+
343
+	/**
344
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
345
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
346
+	 *
347
+	 * @var array
348
+	 */
349
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
350
+
351
+	/**
352
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
353
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
354
+	 *
355
+	 * @var array
356
+	 */
357
+	private $_allowed_query_params = array(
358
+		0,
359
+		'limit',
360
+		'order_by',
361
+		'group_by',
362
+		'having',
363
+		'force_join',
364
+		'order',
365
+		'on_join_limit',
366
+		'default_where_conditions',
367
+		'caps',
368
+	);
369
+
370
+	/**
371
+	 * All the data types that can be used in $wpdb->prepare statements.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
376
+
377
+	/**
378
+	 *    EE_Registry Object
379
+	 *
380
+	 * @var    object
381
+	 * @access    protected
382
+	 */
383
+	protected $EE = null;
384
+
385
+
386
+	/**
387
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
+	 *
389
+	 * @var int
390
+	 */
391
+	protected $_show_next_x_db_queries = 0;
392
+
393
+	/**
394
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
+	 *
397
+	 * @var array
398
+	 */
399
+	protected $_custom_selections = array();
400
+
401
+	/**
402
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
+	 * caches every model object we've fetched from the DB on this request
404
+	 *
405
+	 * @var array
406
+	 */
407
+	protected $_entity_map;
408
+
409
+	/**
410
+	 * constant used to show EEM_Base has not yet verified the db on this http request
411
+	 */
412
+	const db_verified_none = 0;
413
+
414
+	/**
415
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
416
+	 * but not the addons' dbs
417
+	 */
418
+	const db_verified_core = 1;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
422
+	 * the EE core db too)
423
+	 */
424
+	const db_verified_addons = 2;
425
+
426
+	/**
427
+	 * indicates whether an EEM_Base child has already re-verified the DB
428
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
429
+	 * looking like EEM_Base::db_verified_*
430
+	 *
431
+	 * @var int - 0 = none, 1 = core, 2 = addons
432
+	 */
433
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
434
+
435
+	/**
436
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
437
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
438
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
439
+	 */
440
+	const default_where_conditions_all = 'all';
441
+
442
+	/**
443
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
444
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
445
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
446
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
447
+	 *        models which share tables with other models, this can return data for the wrong model.
448
+	 */
449
+	const default_where_conditions_this_only = 'this_model_only';
450
+
451
+	/**
452
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
453
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
454
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
455
+	 */
456
+	const default_where_conditions_others_only = 'other_models_only';
457
+
458
+	/**
459
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
460
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
461
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
462
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
463
+	 *        (regardless of whether those events and venues are trashed)
464
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
465
+	 *        events.
466
+	 */
467
+	const default_where_conditions_minimum_all = 'minimum';
468
+
469
+	/**
470
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
471
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
472
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
473
+	 *        not)
474
+	 */
475
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
476
+
477
+	/**
478
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
479
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
480
+	 *        it's possible it will return table entries for other models. You should use
481
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
482
+	 */
483
+	const default_where_conditions_none = 'none';
484
+
485
+
486
+
487
+	/**
488
+	 * About all child constructors:
489
+	 * they should define the _tables, _fields and _model_relations arrays.
490
+	 * Should ALWAYS be called after child constructor.
491
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
492
+	 * finalizes constructing all the object's attributes.
493
+	 * Generally, rather than requiring a child to code
494
+	 * $this->_tables = array(
495
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
496
+	 *        ...);
497
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
498
+	 * each EE_Table has a function to set the table's alias after the constructor, using
499
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
500
+	 * do something similar.
501
+	 *
502
+	 * @param null $timezone
503
+	 * @throws \EE_Error
504
+	 */
505
+	protected function __construct($timezone = null)
506
+	{
507
+		// check that the model has not been loaded too soon
508
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
+			throw new EE_Error (
510
+				sprintf(
511
+					__('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.',
512
+						'event_espresso'),
513
+					get_class($this)
514
+				)
515
+			);
516
+		}
517
+		/**
518
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
519
+		 */
520
+		if (empty(EEM_Base::$_model_query_blog_id)) {
521
+			EEM_Base::set_model_query_blog_id();
522
+		}
523
+		/**
524
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
525
+		 * just use EE_Register_Model_Extension
526
+		 *
527
+		 * @var EE_Table_Base[] $_tables
528
+		 */
529
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
530
+		foreach ($this->_tables as $table_alias => $table_obj) {
531
+			/** @var $table_obj EE_Table_Base */
532
+			$table_obj->_construct_finalize_with_alias($table_alias);
533
+			if ($table_obj instanceof EE_Secondary_Table) {
534
+				/** @var $table_obj EE_Secondary_Table */
535
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
536
+			}
537
+		}
538
+		/**
539
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
540
+		 * EE_Register_Model_Extension
541
+		 *
542
+		 * @param EE_Model_Field_Base[] $_fields
543
+		 */
544
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
545
+		$this->_invalidate_field_caches();
546
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
547
+			if (! array_key_exists($table_alias, $this->_tables)) {
548
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
550
+			}
551
+			foreach ($fields_for_table as $field_name => $field_obj) {
552
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
553
+				//primary key field base has a slightly different _construct_finalize
554
+				/** @var $field_obj EE_Model_Field_Base */
555
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
556
+			}
557
+		}
558
+		// everything is related to Extra_Meta
559
+		if (get_class($this) !== 'EEM_Extra_Meta') {
560
+			//make extra meta related to everything, but don't block deleting things just
561
+			//because they have related extra meta info. For now just orphan those extra meta
562
+			//in the future we should automatically delete them
563
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
564
+		}
565
+		//and change logs
566
+		if (get_class($this) !== 'EEM_Change_Log') {
567
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
568
+		}
569
+		/**
570
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
571
+		 * EE_Register_Model_Extension
572
+		 *
573
+		 * @param EE_Model_Relation_Base[] $_model_relations
574
+		 */
575
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
576
+			$this->_model_relations);
577
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
578
+			/** @var $relation_obj EE_Model_Relation_Base */
579
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
580
+		}
581
+		foreach ($this->_indexes as $index_name => $index_obj) {
582
+			/** @var $index_obj EE_Index */
583
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
584
+		}
585
+		$this->set_timezone($timezone);
586
+		//finalize default where condition strategy, or set default
587
+		if (! $this->_default_where_conditions_strategy) {
588
+			//nothing was set during child constructor, so set default
589
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590
+		}
591
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
592
+		if (! $this->_minimum_where_conditions_strategy) {
593
+			//nothing was set during child constructor, so set default
594
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595
+		}
596
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
597
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
598
+		//to indicate to NOT set it, set it to the logical default
599
+		if ($this->_caps_slug === null) {
600
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
601
+		}
602
+		//initialize the standard cap restriction generators if none were specified by the child constructor
603
+		if ($this->_cap_restriction_generators !== false) {
604
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
606
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
607
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608
+						new EE_Restriction_Generator_Protected(),
609
+						$cap_context,
610
+						$this
611
+					);
612
+				}
613
+			}
614
+		}
615
+		//if there are cap restriction generators, use them to make the default cap restrictions
616
+		if ($this->_cap_restriction_generators !== false) {
617
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
+				if (! $generator_object) {
619
+					continue;
620
+				}
621
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
622
+					throw new EE_Error(
623
+						sprintf(
624
+							__('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.',
625
+								'event_espresso'),
626
+							$context,
627
+							$this->get_this_model_name()
628
+						)
629
+					);
630
+				}
631
+				$action = $this->cap_action_for_context($context);
632
+				if (! $generator_object->construction_finalized()) {
633
+					$generator_object->_construct_finalize($this, $action);
634
+				}
635
+			}
636
+		}
637
+		do_action('AHEE__' . get_class($this) . '__construct__end');
638
+	}
639
+
640
+
641
+
642
+	/**
643
+	 * Generates the cap restrictions for the given context, or if they were
644
+	 * already generated just gets what's cached
645
+	 *
646
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
647
+	 * @return EE_Default_Where_Conditions[]
648
+	 */
649
+	protected function _generate_cap_restrictions($context)
650
+	{
651
+		if (isset($this->_cap_restriction_generators[$context])
652
+			&& $this->_cap_restriction_generators[$context]
653
+			   instanceof
654
+			   EE_Restriction_Generator_Base
655
+		) {
656
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
657
+		} else {
658
+			return array();
659
+		}
660
+	}
661
+
662
+
663
+
664
+	/**
665
+	 * Used to set the $_model_query_blog_id static property.
666
+	 *
667
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
668
+	 *                      value for get_current_blog_id() will be used.
669
+	 */
670
+	public static function set_model_query_blog_id($blog_id = 0)
671
+	{
672
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * Returns whatever is set as the internal $model_query_blog_id.
679
+	 *
680
+	 * @return int
681
+	 */
682
+	public static function get_model_query_blog_id()
683
+	{
684
+		return EEM_Base::$_model_query_blog_id;
685
+	}
686
+
687
+
688
+
689
+	/**
690
+	 *        This function is a singleton method used to instantiate the Espresso_model object
691
+	 *
692
+	 * @access public
693
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
694
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
695
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
696
+	 *                         timezone in the 'timezone_string' wp option)
697
+	 * @return static (as in the concrete child class)
698
+	 */
699
+	public static function instance($timezone = null)
700
+	{
701
+		// check if instance of Espresso_model already exists
702
+		if (! static::$_instance instanceof static) {
703
+			// instantiate Espresso_model
704
+			static::$_instance = new static($timezone);
705
+		}
706
+		//we might have a timezone set, let set_timezone decide what to do with it
707
+		static::$_instance->set_timezone($timezone);
708
+		// Espresso_model object
709
+		return static::$_instance;
710
+	}
711
+
712
+
713
+
714
+	/**
715
+	 * resets the model and returns it
716
+	 *
717
+	 * @param null | string $timezone
718
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
719
+	 * all its properties reset; if it wasn't instantiated, returns null)
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we
738
+			//were creating a new one
739
+			static::$_instance->__construct($timezone);
740
+			return self::instance();
741
+		}
742
+		return null;
743
+	}
744
+
745
+
746
+
747
+	/**
748
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
749
+	 *
750
+	 * @param  boolean $translated return localized strings or JUST the array.
751
+	 * @return array
752
+	 * @throws \EE_Error
753
+	 */
754
+	public function status_array($translated = false)
755
+	{
756
+		if (! array_key_exists('Status', $this->_model_relations)) {
757
+			return array();
758
+		}
759
+		$model_name = $this->get_this_model_name();
760
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
761
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
762
+		$status_array = array();
763
+		foreach ($stati as $status) {
764
+			$status_array[$status->ID()] = $status->get('STS_code');
765
+		}
766
+		return $translated
767
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
768
+			: $status_array;
769
+	}
770
+
771
+
772
+
773
+	/**
774
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
775
+	 *
776
+	 * @param array $query_params             {
777
+	 * @var array $0 (where) array {
778
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
779
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
780
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
781
+	 *                                        conditions based on related models (and even
782
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
783
+	 *                                        name. Eg,
784
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
785
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
786
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
787
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
788
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
789
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
790
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
791
+	 *                                        to Venues (even when each of those models actually consisted of two
792
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
793
+	 *                                        just having
794
+	 *                                        "Venue.VNU_ID", you could have
795
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
796
+	 *                                        events are related to Registrations, which are related to Attendees). You
797
+	 *                                        can take it even further with
798
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
799
+	 *                                        (from the default of '='), change the value to an numerically-indexed
800
+	 *                                        array, where the first item in the list is the operator. eg: array(
801
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
802
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
803
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
804
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
805
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
806
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
807
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
808
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
809
+	 *                                        the value is a field, simply provide a third array item (true) to the
810
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
811
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
812
+	 *                                        Note: you can also use related model field names like you would any other
813
+	 *                                        field name. eg:
814
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
815
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
816
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
817
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
818
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
819
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
820
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
821
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
822
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
823
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
824
+	 *                                        "stick" until you specify an AND. eg
825
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
826
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
827
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
828
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
829
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
830
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
831
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
832
+	 *                                        too, eg:
833
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
834
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
835
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
836
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
837
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
838
+	 *                                        the OFFSET, the 2nd is the LIMIT
839
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
840
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
841
+	 *                                        following format array('on_join_limit'
842
+	 *                                        => array( 'table_alias', array(1,2) ) ).
843
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
844
+	 *                                        values are either 'ASC' or 'DESC'.
845
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
846
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
847
+	 *                                        DESC..." respectively. Like the
848
+	 *                                        'where' conditions, these fields can be on related models. Eg
849
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
850
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
851
+	 *                                        Attendee, Price, Datetime, etc.)
852
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
853
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
854
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
855
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
856
+	 *                                        order by the primary key. Eg,
857
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
858
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
859
+	 *                                        DTT_EVT_start) or
860
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
861
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
862
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
863
+	 *                                        'group_by'=>'VNU_ID', or
864
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
865
+	 *                                        if no
866
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
867
+	 *                                        model's primary key (or combined primary keys). This avoids some
868
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
869
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
870
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
871
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
872
+	 *                                        results)
873
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
874
+	 *                                        array where values are models to be joined in the query.Eg
875
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
876
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
877
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
878
+	 *                                        related models which belongs to the current model
879
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
880
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
881
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
882
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
883
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
884
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
885
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
886
+	 *                                        this model's default where conditions added to the query, use
887
+	 *                                        'this_model_only'. If you want to use all default where conditions
888
+	 *                                        (default), set to 'all'.
889
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
890
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
891
+	 *                                        everything? Or should we only show the current user items they should be
892
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
893
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
894
+	 *                                        }
895
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
896
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
897
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
898
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
899
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
900
+	 *                                        array( array(
901
+	 *                                        'OR'=>array(
902
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
903
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
904
+	 *                                        )
905
+	 *                                        ),
906
+	 *                                        'limit'=>10,
907
+	 *                                        'group_by'=>'TXN_ID'
908
+	 *                                        ));
909
+	 *                                        get all the answers to the question titled "shirt size" for event with id
910
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
911
+	 *                                        'Question.QST_display_text'=>'shirt size',
912
+	 *                                        'Registration.Event.EVT_ID'=>12
913
+	 *                                        ),
914
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
915
+	 *                                        ));
916
+	 * @throws \EE_Error
917
+	 */
918
+	public function get_all($query_params = array())
919
+	{
920
+		if (isset($query_params['limit'])
921
+			&& ! isset($query_params['group_by'])
922
+		) {
923
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
924
+		}
925
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
926
+	}
927
+
928
+
929
+
930
+	/**
931
+	 * Modifies the query parameters so we only get back model objects
932
+	 * that "belong" to the current user
933
+	 *
934
+	 * @param array $query_params @see EEM_Base::get_all()
935
+	 * @return array like EEM_Base::get_all
936
+	 */
937
+	public function alter_query_params_to_only_include_mine($query_params = array())
938
+	{
939
+		$wp_user_field_name = $this->wp_user_field_name();
940
+		if ($wp_user_field_name) {
941
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
942
+		}
943
+		return $query_params;
944
+	}
945
+
946
+
947
+
948
+	/**
949
+	 * Returns the name of the field's name that points to the WP_User table
950
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
951
+	 * foreign key to the WP_User table)
952
+	 *
953
+	 * @return string|boolean string on success, boolean false when there is no
954
+	 * foreign key to the WP_User table
955
+	 */
956
+	public function wp_user_field_name()
957
+	{
958
+		try {
959
+			if (! empty($this->_model_chain_to_wp_user)) {
960
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
961
+				$last_model_name = end($models_to_follow_to_wp_users);
962
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
963
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
964
+			} else {
965
+				$model_with_fk_to_wp_users = $this;
966
+				$model_chain_to_wp_user = '';
967
+			}
968
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
969
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
970
+		} catch (EE_Error $e) {
971
+			return false;
972
+		}
973
+	}
974
+
975
+
976
+
977
+	/**
978
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
979
+	 * (or transiently-related model) has a foreign key to the wp_users table;
980
+	 * useful for finding if model objects of this type are 'owned' by the current user.
981
+	 * This is an empty string when the foreign key is on this model and when it isn't,
982
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
983
+	 * (or transiently-related model)
984
+	 *
985
+	 * @return string
986
+	 */
987
+	public function model_chain_to_wp_user()
988
+	{
989
+		return $this->_model_chain_to_wp_user;
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
996
+	 * like how registrations don't have a foreign key to wp_users, but the
997
+	 * events they are for are), or is unrelated to wp users.
998
+	 * generally available
999
+	 *
1000
+	 * @return boolean
1001
+	 */
1002
+	public function is_owned()
1003
+	{
1004
+		if ($this->model_chain_to_wp_user()) {
1005
+			return true;
1006
+		} else {
1007
+			try {
1008
+				$this->get_foreign_key_to('WP_User');
1009
+				return true;
1010
+			} catch (EE_Error $e) {
1011
+				return false;
1012
+			}
1013
+		}
1014
+	}
1015
+
1016
+
1017
+
1018
+	/**
1019
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1020
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1021
+	 * the model)
1022
+	 *
1023
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1024
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1025
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1026
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1027
+	 *                                  override this and set the select to "*", or a specific column name, like
1028
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1029
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1030
+	 *                                  the aliases used to refer to this selection, and values are to be
1031
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1032
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1033
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1034
+	 * @throws \EE_Error
1035
+	 */
1036
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1037
+	{
1038
+		// remember the custom selections, if any, and type cast as array
1039
+		// (unless $columns_to_select is an object, then just set as an empty array)
1040
+		// Note: (array) 'some string' === array( 'some string' )
1041
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1042
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1043
+		$select_expressions = $columns_to_select !== null
1044
+			? $this->_construct_select_from_input($columns_to_select)
1045
+			: $this->_construct_default_select_sql($model_query_info);
1046
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1047
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1048
+	}
1049
+
1050
+
1051
+
1052
+	/**
1053
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1054
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1055
+	 * take care of joins, field preparation etc.
1056
+	 *
1057
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1058
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1059
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1060
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1061
+	 *                                  override this and set the select to "*", or a specific column name, like
1062
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1063
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1064
+	 *                                  the aliases used to refer to this selection, and values are to be
1065
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1066
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1067
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1068
+	 * @throws \EE_Error
1069
+	 */
1070
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1071
+	{
1072
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1073
+	}
1074
+
1075
+
1076
+
1077
+	/**
1078
+	 * For creating a custom select statement
1079
+	 *
1080
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1081
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1082
+	 *                                 SQL, and 1=>is the datatype
1083
+	 * @throws EE_Error
1084
+	 * @return string
1085
+	 */
1086
+	private function _construct_select_from_input($columns_to_select)
1087
+	{
1088
+		if (is_array($columns_to_select)) {
1089
+			$select_sql_array = array();
1090
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1091
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1092
+					throw new EE_Error(
1093
+						sprintf(
1094
+							__(
1095
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1096
+								"event_espresso"
1097
+							),
1098
+							$selection_and_datatype,
1099
+							$alias
1100
+						)
1101
+					);
1102
+				}
1103
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1104
+					throw new EE_Error(
1105
+						sprintf(
1106
+							__(
1107
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1108
+								"event_espresso"
1109
+							),
1110
+							$selection_and_datatype[1],
1111
+							$selection_and_datatype[0],
1112
+							$alias,
1113
+							implode(",", $this->_valid_wpdb_data_types)
1114
+						)
1115
+					);
1116
+				}
1117
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1118
+			}
1119
+			$columns_to_select_string = implode(", ", $select_sql_array);
1120
+		} else {
1121
+			$columns_to_select_string = $columns_to_select;
1122
+		}
1123
+		return $columns_to_select_string;
1124
+	}
1125
+
1126
+
1127
+
1128
+	/**
1129
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1130
+	 *
1131
+	 * @return string
1132
+	 * @throws \EE_Error
1133
+	 */
1134
+	public function primary_key_name()
1135
+	{
1136
+		return $this->get_primary_key_field()->get_name();
1137
+	}
1138
+
1139
+
1140
+
1141
+	/**
1142
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1143
+	 * If there is no primary key on this model, $id is treated as primary key string
1144
+	 *
1145
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1146
+	 * @return EE_Base_Class
1147
+	 */
1148
+	public function get_one_by_ID($id)
1149
+	{
1150
+		if ($this->get_from_entity_map($id)) {
1151
+			return $this->get_from_entity_map($id);
1152
+		}
1153
+		return $this->get_one(
1154
+			$this->alter_query_params_to_restrict_by_ID(
1155
+				$id,
1156
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1157
+			)
1158
+		);
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * Alters query parameters to only get items with this ID are returned.
1165
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1166
+	 * or could just be a simple primary key ID
1167
+	 *
1168
+	 * @param int   $id
1169
+	 * @param array $query_params
1170
+	 * @return array of normal query params, @see EEM_Base::get_all
1171
+	 * @throws \EE_Error
1172
+	 */
1173
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1174
+	{
1175
+		if (! isset($query_params[0])) {
1176
+			$query_params[0] = array();
1177
+		}
1178
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1179
+		if ($conditions_from_id === null) {
1180
+			$query_params[0][$this->primary_key_name()] = $id;
1181
+		} else {
1182
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1183
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1184
+		}
1185
+		return $query_params;
1186
+	}
1187
+
1188
+
1189
+
1190
+	/**
1191
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1192
+	 * array. If no item is found, null is returned.
1193
+	 *
1194
+	 * @param array $query_params like EEM_Base's $query_params variable.
1195
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1196
+	 * @throws \EE_Error
1197
+	 */
1198
+	public function get_one($query_params = array())
1199
+	{
1200
+		if (! is_array($query_params)) {
1201
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1202
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1203
+					gettype($query_params)), '4.6.0');
1204
+			$query_params = array();
1205
+		}
1206
+		$query_params['limit'] = 1;
1207
+		$items = $this->get_all($query_params);
1208
+		if (empty($items)) {
1209
+			return null;
1210
+		} else {
1211
+			return array_shift($items);
1212
+		}
1213
+	}
1214
+
1215
+
1216
+
1217
+	/**
1218
+	 * Returns the next x number of items in sequence from the given value as
1219
+	 * found in the database matching the given query conditions.
1220
+	 *
1221
+	 * @param mixed $current_field_value    Value used for the reference point.
1222
+	 * @param null  $field_to_order_by      What field is used for the
1223
+	 *                                      reference point.
1224
+	 * @param int   $limit                  How many to return.
1225
+	 * @param array $query_params           Extra conditions on the query.
1226
+	 * @param null  $columns_to_select      If left null, then an array of
1227
+	 *                                      EE_Base_Class objects is returned,
1228
+	 *                                      otherwise you can indicate just the
1229
+	 *                                      columns you want returned.
1230
+	 * @return EE_Base_Class[]|array
1231
+	 * @throws \EE_Error
1232
+	 */
1233
+	public function next_x(
1234
+		$current_field_value,
1235
+		$field_to_order_by = null,
1236
+		$limit = 1,
1237
+		$query_params = array(),
1238
+		$columns_to_select = null
1239
+	) {
1240
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $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
+	 */
1262
+	public function previous_x(
1263
+		$current_field_value,
1264
+		$field_to_order_by = null,
1265
+		$limit = 1,
1266
+		$query_params = array(),
1267
+		$columns_to_select = null
1268
+	) {
1269
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1270
+			$columns_to_select);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next item in sequence from the given value as found in the
1277
+	 * database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param array $query_params           Extra conditions on the query.
1283
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
+	 *                                      object is returned, otherwise you
1285
+	 *                                      can indicate just the columns you
1286
+	 *                                      want and a single array indexed by
1287
+	 *                                      the columns will be returned.
1288
+	 * @return EE_Base_Class|null|array()
1289
+	 * @throws \EE_Error
1290
+	 */
1291
+	public function next(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$query_params = array(),
1295
+		$columns_to_select = null
1296
+	) {
1297
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1298
+			$columns_to_select);
1299
+		return empty($results) ? null : reset($results);
1300
+	}
1301
+
1302
+
1303
+
1304
+	/**
1305
+	 * Returns the previous item in sequence from the given value as found in
1306
+	 * the database matching the given query conditions.
1307
+	 *
1308
+	 * @param mixed $current_field_value    Value used for the reference point.
1309
+	 * @param null  $field_to_order_by      What field is used for the
1310
+	 *                                      reference point.
1311
+	 * @param array $query_params           Extra conditions on the query.
1312
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1313
+	 *                                      object is returned, otherwise you
1314
+	 *                                      can indicate just the columns you
1315
+	 *                                      want and a single array indexed by
1316
+	 *                                      the columns will be returned.
1317
+	 * @return EE_Base_Class|null|array()
1318
+	 * @throws EE_Error
1319
+	 */
1320
+	public function previous(
1321
+		$current_field_value,
1322
+		$field_to_order_by = null,
1323
+		$query_params = array(),
1324
+		$columns_to_select = null
1325
+	) {
1326
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1327
+			$columns_to_select);
1328
+		return empty($results) ? null : reset($results);
1329
+	}
1330
+
1331
+
1332
+
1333
+	/**
1334
+	 * Returns the a consecutive number of items in sequence from the given
1335
+	 * value as found in the database matching the given query conditions.
1336
+	 *
1337
+	 * @param mixed  $current_field_value   Value used for the reference point.
1338
+	 * @param string $operand               What operand is used for the sequence.
1339
+	 * @param string $field_to_order_by     What field is used for the reference point.
1340
+	 * @param int    $limit                 How many to return.
1341
+	 * @param array  $query_params          Extra conditions on the query.
1342
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1343
+	 *                                      otherwise you can indicate just the columns you want returned.
1344
+	 * @return EE_Base_Class[]|array
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	protected function _get_consecutive(
1348
+		$current_field_value,
1349
+		$operand = '>',
1350
+		$field_to_order_by = null,
1351
+		$limit = 1,
1352
+		$query_params = array(),
1353
+		$columns_to_select = null
1354
+	) {
1355
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1356
+		if (empty($field_to_order_by)) {
1357
+			if ($this->has_primary_key_field()) {
1358
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1359
+			} else {
1360
+				if (WP_DEBUG) {
1361
+					throw new EE_Error(__('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).',
1362
+						'event_espresso'));
1363
+				}
1364
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1365
+				return array();
1366
+			}
1367
+		}
1368
+		if (! is_array($query_params)) {
1369
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1370
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1371
+					gettype($query_params)), '4.6.0');
1372
+			$query_params = array();
1373
+		}
1374
+		//let's add the where query param for consecutive look up.
1375
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1376
+		$query_params['limit'] = $limit;
1377
+		//set direction
1378
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1379
+		$query_params['order_by'] = $operand === '>'
1380
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1381
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1382
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1383
+		if (empty($columns_to_select)) {
1384
+			return $this->get_all($query_params);
1385
+		} else {
1386
+			//getting just the fields
1387
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1388
+		}
1389
+	}
1390
+
1391
+
1392
+
1393
+	/**
1394
+	 * This sets the _timezone property after model object has been instantiated.
1395
+	 *
1396
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1397
+	 */
1398
+	public function set_timezone($timezone)
1399
+	{
1400
+		if ($timezone !== null) {
1401
+			$this->_timezone = $timezone;
1402
+		}
1403
+		//note we need to loop through relations and set the timezone on those objects as well.
1404
+		foreach ($this->_model_relations as $relation) {
1405
+			$relation->set_timezone($timezone);
1406
+		}
1407
+		//and finally we do the same for any datetime fields
1408
+		foreach ($this->_fields as $field) {
1409
+			if ($field instanceof EE_Datetime_Field) {
1410
+				$field->set_timezone($timezone);
1411
+			}
1412
+		}
1413
+	}
1414
+
1415
+
1416
+
1417
+	/**
1418
+	 * This just returns whatever is set for the current timezone.
1419
+	 *
1420
+	 * @access public
1421
+	 * @return string
1422
+	 */
1423
+	public function get_timezone()
1424
+	{
1425
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1426
+		if (empty($this->_timezone)) {
1427
+			foreach ($this->_fields as $field) {
1428
+				if ($field instanceof EE_Datetime_Field) {
1429
+					$this->set_timezone($field->get_timezone());
1430
+					break;
1431
+				}
1432
+			}
1433
+		}
1434
+		//if timezone STILL empty then return the default timezone for the site.
1435
+		if (empty($this->_timezone)) {
1436
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1437
+		}
1438
+		return $this->_timezone;
1439
+	}
1440
+
1441
+
1442
+
1443
+	/**
1444
+	 * This returns the date formats set for the given field name and also ensures that
1445
+	 * $this->_timezone property is set correctly.
1446
+	 *
1447
+	 * @since 4.6.x
1448
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1449
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1450
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1451
+	 * @return array formats in an array with the date format first, and the time format last.
1452
+	 */
1453
+	public function get_formats_for($field_name, $pretty = false)
1454
+	{
1455
+		$field_settings = $this->field_settings_for($field_name);
1456
+		//if not a valid EE_Datetime_Field then throw error
1457
+		if (! $field_settings instanceof EE_Datetime_Field) {
1458
+			throw new EE_Error(sprintf(__('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.',
1459
+				'event_espresso'), $field_name));
1460
+		}
1461
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1462
+		//the field.
1463
+		$this->_timezone = $field_settings->get_timezone();
1464
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1465
+	}
1466
+
1467
+
1468
+
1469
+	/**
1470
+	 * This returns the current time in a format setup for a query on this model.
1471
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1472
+	 * it will return:
1473
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1474
+	 *  NOW
1475
+	 *  - or a unix timestamp (equivalent to time())
1476
+	 *
1477
+	 * @since 4.6.x
1478
+	 * @param string $field_name       The field the current time is needed for.
1479
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1480
+	 *                                 formatted string matching the set format for the field in the set timezone will
1481
+	 *                                 be returned.
1482
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1483
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1484
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1485
+	 *                                 exception is triggered.
1486
+	 */
1487
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1488
+	{
1489
+		$formats = $this->get_formats_for($field_name);
1490
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1491
+		if ($timestamp) {
1492
+			return $DateTime->format('U');
1493
+		}
1494
+		//not returning timestamp, so return formatted string in timezone.
1495
+		switch ($what) {
1496
+			case 'time' :
1497
+				return $DateTime->format($formats[1]);
1498
+				break;
1499
+			case 'date' :
1500
+				return $DateTime->format($formats[0]);
1501
+				break;
1502
+			default :
1503
+				return $DateTime->format(implode(' ', $formats));
1504
+				break;
1505
+		}
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1512
+	 * for the model are.  Returns a DateTime object.
1513
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1514
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1515
+	 * ignored.
1516
+	 *
1517
+	 * @param string $field_name      The field being setup.
1518
+	 * @param string $timestring      The date time string being used.
1519
+	 * @param string $incoming_format The format for the time string.
1520
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1521
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1522
+	 *                                format is
1523
+	 *                                'U', this is ignored.
1524
+	 * @return DateTime
1525
+	 * @throws \EE_Error
1526
+	 */
1527
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1528
+	{
1529
+		//just using this to ensure the timezone is set correctly internally
1530
+		$this->get_formats_for($field_name);
1531
+		//load EEH_DTT_Helper
1532
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1533
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1534
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1535
+	}
1536
+
1537
+
1538
+
1539
+	/**
1540
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1541
+	 *
1542
+	 * @return EE_Table_Base[]
1543
+	 */
1544
+	public function get_tables()
1545
+	{
1546
+		return $this->_tables;
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1553
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1554
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1555
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1556
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1557
+	 * model object with EVT_ID = 1
1558
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1559
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1560
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1561
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1562
+	 * are not specified)
1563
+	 *
1564
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1565
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1566
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1567
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1568
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1569
+	 *                                         ID=34, we'd use this method as follows:
1570
+	 *                                         EEM_Transaction::instance()->update(
1571
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1572
+	 *                                         array(array('TXN_ID'=>34)));
1573
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1574
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1575
+	 *                                         consider updating Question's QST_admin_label field is of type
1576
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1577
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1578
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1579
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1580
+	 *                                         TRUE, it is assumed that you've already called
1581
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1582
+	 *                                         malicious javascript. However, if
1583
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1584
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1585
+	 *                                         and every other field, before insertion. We provide this parameter
1586
+	 *                                         because model objects perform their prepare_for_set function on all
1587
+	 *                                         their values, and so don't need to be called again (and in many cases,
1588
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1589
+	 *                                         prepare_for_set method...)
1590
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1591
+	 *                                         in this model's entity map according to $fields_n_values that match
1592
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1593
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1594
+	 *                                         could get out-of-sync with the database
1595
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1596
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1597
+	 *                                         bad)
1598
+	 * @throws \EE_Error
1599
+	 */
1600
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1601
+	{
1602
+		if (! is_array($query_params)) {
1603
+			EE_Error::doing_it_wrong('EEM_Base::update',
1604
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1605
+					gettype($query_params)), '4.6.0');
1606
+			$query_params = array();
1607
+		}
1608
+		/**
1609
+		 * Action called before a model update call has been made.
1610
+		 *
1611
+		 * @param EEM_Base $model
1612
+		 * @param array    $fields_n_values the updated fields and their new values
1613
+		 * @param array    $query_params    @see EEM_Base::get_all()
1614
+		 */
1615
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1616
+		/**
1617
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1618
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1619
+		 *
1620
+		 * @param array    $fields_n_values fields and their new values
1621
+		 * @param EEM_Base $model           the model being queried
1622
+		 * @param array    $query_params    see EEM_Base::get_all()
1623
+		 */
1624
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1625
+			$query_params);
1626
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1627
+		//to do that, for each table, verify that it's PK isn't null.
1628
+		$tables = $this->get_tables();
1629
+		//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
1630
+		//NOTE: we should make this code more efficient by NOT querying twice
1631
+		//before the real update, but that needs to first go through ALPHA testing
1632
+		//as it's dangerous. says Mike August 8 2014
1633
+		//we want to make sure the default_where strategy is ignored
1634
+		$this->_ignore_where_strategy = true;
1635
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1636
+		foreach ($wpdb_select_results as $wpdb_result) {
1637
+			// type cast stdClass as array
1638
+			$wpdb_result = (array)$wpdb_result;
1639
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1640
+			if ($this->has_primary_key_field()) {
1641
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1642
+			} else {
1643
+				//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)
1644
+				$main_table_pk_value = null;
1645
+			}
1646
+			//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
1647
+			//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
1648
+			if (count($tables) > 1) {
1649
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1650
+				//in that table, and so we'll want to insert one
1651
+				foreach ($tables as $table_obj) {
1652
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1653
+					//if there is no private key for this table on the results, it means there's no entry
1654
+					//in this table, right? so insert a row in the current table, using any fields available
1655
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1656
+						   && $wpdb_result[$this_table_pk_column])
1657
+					) {
1658
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1659
+							$main_table_pk_value);
1660
+						//if we died here, report the error
1661
+						if (! $success) {
1662
+							return false;
1663
+						}
1664
+					}
1665
+				}
1666
+			}
1667
+			//				//and now check that if we have cached any models by that ID on the model, that
1668
+			//				//they also get updated properly
1669
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1670
+			//				if( $model_object ){
1671
+			//					foreach( $fields_n_values as $field => $value ){
1672
+			//						$model_object->set($field, $value);
1673
+			//let's make sure default_where strategy is followed now
1674
+			$this->_ignore_where_strategy = false;
1675
+		}
1676
+		//if we want to keep model objects in sync, AND
1677
+		//if this wasn't called from a model object (to update itself)
1678
+		//then we want to make sure we keep all the existing
1679
+		//model objects in sync with the db
1680
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1681
+			if ($this->has_primary_key_field()) {
1682
+				$model_objs_affected_ids = $this->get_col($query_params);
1683
+			} else {
1684
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1685
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1686
+				$model_objs_affected_ids = array();
1687
+				foreach ($models_affected_key_columns as $row) {
1688
+					$combined_index_key = $this->get_index_primary_key_string($row);
1689
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1690
+				}
1691
+			}
1692
+			if (! $model_objs_affected_ids) {
1693
+				//wait wait wait- if nothing was affected let's stop here
1694
+				return 0;
1695
+			}
1696
+			foreach ($model_objs_affected_ids as $id) {
1697
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1698
+				if ($model_obj_in_entity_map) {
1699
+					foreach ($fields_n_values as $field => $new_value) {
1700
+						$model_obj_in_entity_map->set($field, $new_value);
1701
+					}
1702
+				}
1703
+			}
1704
+			//if there is a primary key on this model, we can now do a slight optimization
1705
+			if ($this->has_primary_key_field()) {
1706
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1707
+				$query_params = array(
1708
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1709
+					'limit'                    => count($model_objs_affected_ids),
1710
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1711
+				);
1712
+			}
1713
+		}
1714
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1715
+		$SQL = "UPDATE "
1716
+			   . $model_query_info->get_full_join_sql()
1717
+			   . " SET "
1718
+			   . $this->_construct_update_sql($fields_n_values)
1719
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1720
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1721
+		/**
1722
+		 * Action called after a model update call has been made.
1723
+		 *
1724
+		 * @param EEM_Base $model
1725
+		 * @param array    $fields_n_values the updated fields and their new values
1726
+		 * @param array    $query_params    @see EEM_Base::get_all()
1727
+		 * @param int      $rows_affected
1728
+		 */
1729
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1730
+		return $rows_affected;//how many supposedly got updated
1731
+	}
1732
+
1733
+
1734
+
1735
+	/**
1736
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1737
+	 * are teh values of the field specified (or by default the primary key field)
1738
+	 * that matched the query params. Note that you should pass the name of the
1739
+	 * model FIELD, not the database table's column name.
1740
+	 *
1741
+	 * @param array  $query_params @see EEM_Base::get_all()
1742
+	 * @param string $field_to_select
1743
+	 * @return array just like $wpdb->get_col()
1744
+	 * @throws \EE_Error
1745
+	 */
1746
+	public function get_col($query_params = array(), $field_to_select = null)
1747
+	{
1748
+		if ($field_to_select) {
1749
+			$field = $this->field_settings_for($field_to_select);
1750
+		} elseif ($this->has_primary_key_field()) {
1751
+			$field = $this->get_primary_key_field();
1752
+		} else {
1753
+			//no primary key, just grab the first column
1754
+			$field = reset($this->field_settings());
1755
+		}
1756
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1757
+		$select_expressions = $field->get_qualified_column();
1758
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1759
+		return $this->_do_wpdb_query('get_col', array($SQL));
1760
+	}
1761
+
1762
+
1763
+
1764
+	/**
1765
+	 * Returns a single column value for a single row from the database
1766
+	 *
1767
+	 * @param array  $query_params    @see EEM_Base::get_all()
1768
+	 * @param string $field_to_select @see EEM_Base::get_col()
1769
+	 * @return string
1770
+	 * @throws \EE_Error
1771
+	 */
1772
+	public function get_var($query_params = array(), $field_to_select = null)
1773
+	{
1774
+		$query_params['limit'] = 1;
1775
+		$col = $this->get_col($query_params, $field_to_select);
1776
+		if (! empty($col)) {
1777
+			return reset($col);
1778
+		} else {
1779
+			return null;
1780
+		}
1781
+	}
1782
+
1783
+
1784
+
1785
+	/**
1786
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1787
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1788
+	 * injection, but currently no further filtering is done
1789
+	 *
1790
+	 * @global      $wpdb
1791
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1792
+	 *                               be updated to in the DB
1793
+	 * @return string of SQL
1794
+	 * @throws \EE_Error
1795
+	 */
1796
+	public function _construct_update_sql($fields_n_values)
1797
+	{
1798
+		/** @type WPDB $wpdb */
1799
+		global $wpdb;
1800
+		$cols_n_values = array();
1801
+		foreach ($fields_n_values as $field_name => $value) {
1802
+			$field_obj = $this->field_settings_for($field_name);
1803
+			//if the value is NULL, we want to assign the value to that.
1804
+			//wpdb->prepare doesn't really handle that properly
1805
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1806
+			$value_sql = $prepared_value === null ? 'NULL'
1807
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1808
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1809
+		}
1810
+		return implode(",", $cols_n_values);
1811
+	}
1812
+
1813
+
1814
+
1815
+	/**
1816
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1817
+	 * Performs a HARD delete, meaning the database row should always be removed,
1818
+	 * not just have a flag field on it switched
1819
+	 * Wrapper for EEM_Base::delete_permanently()
1820
+	 *
1821
+	 * @param mixed $id
1822
+	 * @param boolean $allow_blocking
1823
+	 * @return int the number of rows deleted
1824
+	 * @throws \EE_Error
1825
+	 */
1826
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1827
+	{
1828
+		return $this->delete_permanently(
1829
+			array(
1830
+				array($this->get_primary_key_field()->get_name() => $id),
1831
+				'limit' => 1,
1832
+			),
1833
+			$allow_blocking
1834
+		);
1835
+	}
1836
+
1837
+
1838
+
1839
+	/**
1840
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1841
+	 * Wrapper for EEM_Base::delete()
1842
+	 *
1843
+	 * @param mixed $id
1844
+	 * @param boolean $allow_blocking
1845
+	 * @return int the number of rows deleted
1846
+	 * @throws \EE_Error
1847
+	 */
1848
+	public function delete_by_ID($id, $allow_blocking = true)
1849
+	{
1850
+		return $this->delete(
1851
+			array(
1852
+				array($this->get_primary_key_field()->get_name() => $id),
1853
+				'limit' => 1,
1854
+			),
1855
+			$allow_blocking
1856
+		);
1857
+	}
1858
+
1859
+
1860
+
1861
+	/**
1862
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1863
+	 * meaning if the model has a field that indicates its been "trashed" or
1864
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1865
+	 *
1866
+	 * @see EEM_Base::delete_permanently
1867
+	 * @param array   $query_params
1868
+	 * @param boolean $allow_blocking
1869
+	 * @return int how many rows got deleted
1870
+	 * @throws \EE_Error
1871
+	 */
1872
+	public function delete($query_params, $allow_blocking = true)
1873
+	{
1874
+		return $this->delete_permanently($query_params, $allow_blocking);
1875
+	}
1876
+
1877
+
1878
+
1879
+	/**
1880
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1881
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1882
+	 * as archived, not actually deleted
1883
+	 *
1884
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1885
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1886
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1887
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1888
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1889
+	 *                                DB
1890
+	 * @return int how many rows got deleted
1891
+	 * @throws \EE_Error
1892
+	 */
1893
+	public function delete_permanently($query_params, $allow_blocking = true)
1894
+	{
1895
+		/**
1896
+		 * Action called just before performing a real deletion query. You can use the
1897
+		 * model and its $query_params to find exactly which items will be deleted
1898
+		 *
1899
+		 * @param EEM_Base $model
1900
+		 * @param array    $query_params   @see EEM_Base::get_all()
1901
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1902
+		 *                                 to block (prevent) this deletion
1903
+		 */
1904
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1905
+		//some MySQL databases may be running safe mode, which may restrict
1906
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1907
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1908
+		//to delete them
1909
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1910
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1911
+		if ($deletion_where) {
1912
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1913
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1914
+			$table_aliases = array_keys($this->_tables);
1915
+			$SQL = "DELETE "
1916
+				   . implode(", ", $table_aliases)
1917
+				   . " FROM "
1918
+				   . $model_query_info->get_full_join_sql()
1919
+				   . " WHERE "
1920
+				   . $deletion_where;
1921
+			//		/echo "delete sql:$SQL";
1922
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1923
+		} else {
1924
+			$rows_deleted = 0;
1925
+		}
1926
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1927
+		if ($this->has_primary_key_field()) {
1928
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1929
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1930
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1931
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1932
+				}
1933
+			}
1934
+		}
1935
+		/**
1936
+		 * Action called just after performing a real deletion query. Although at this point the
1937
+		 * items should have been deleted
1938
+		 *
1939
+		 * @param EEM_Base $model
1940
+		 * @param array    $query_params @see EEM_Base::get_all()
1941
+		 * @param int      $rows_deleted
1942
+		 */
1943
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1944
+		return $rows_deleted;//how many supposedly got deleted
1945
+	}
1946
+
1947
+
1948
+
1949
+	/**
1950
+	 * Checks all the relations that throw error messages when there are blocking related objects
1951
+	 * for related model objects. If there are any related model objects on those relations,
1952
+	 * adds an EE_Error, and return true
1953
+	 *
1954
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1955
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1956
+	 *                                                 should be ignored when determining whether there are related
1957
+	 *                                                 model objects which block this model object's deletion. Useful
1958
+	 *                                                 if you know A is related to B and are considering deleting A,
1959
+	 *                                                 but want to see if A has any other objects blocking its deletion
1960
+	 *                                                 before removing the relation between A and B
1961
+	 * @return boolean
1962
+	 * @throws \EE_Error
1963
+	 */
1964
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1965
+	{
1966
+		//first, if $ignore_this_model_obj was supplied, get its model
1967
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1968
+			$ignored_model = $ignore_this_model_obj->get_model();
1969
+		} else {
1970
+			$ignored_model = null;
1971
+		}
1972
+		//now check all the relations of $this_model_obj_or_id and see if there
1973
+		//are any related model objects blocking it?
1974
+		$is_blocked = false;
1975
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1976
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1977
+				//if $ignore_this_model_obj was supplied, then for the query
1978
+				//on that model needs to be told to ignore $ignore_this_model_obj
1979
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1980
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1981
+						array(
1982
+							$ignored_model->get_primary_key_field()->get_name() => array(
1983
+								'!=',
1984
+								$ignore_this_model_obj->ID(),
1985
+							),
1986
+						),
1987
+					));
1988
+				} else {
1989
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1990
+				}
1991
+				if ($related_model_objects) {
1992
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1993
+					$is_blocked = true;
1994
+				}
1995
+			}
1996
+		}
1997
+		return $is_blocked;
1998
+	}
1999
+
2000
+
2001
+
2002
+	/**
2003
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
2004
+	 * well.
2005
+	 *
2006
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
2007
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
2008
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
2009
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
2010
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
2011
+	 *                                      easily corrupt your DB
2012
+	 * @throws EE_Error
2013
+	 * @return string    everything that comes after the WHERE statement.
2014
+	 */
2015
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
2016
+	{
2017
+		if ($this->has_primary_key_field()) {
2018
+			$primary_table = $this->_get_main_table();
2019
+			$pt_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2020
+			$other_tables = $this->_get_other_tables();
2021
+			$ot_pk_fields = array();
2022
+			$ot_fk_fields = array();
2023
+			foreach($other_tables as $other_table_alias => $other_table_obj){
2024
+				$ot_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2025
+				$ot_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2026
+			}
2027
+			$deletes = $query = array();
2028
+			foreach ($objects_for_deletion as $delete_object) {
2029
+				//before we mark this object for deletion,
2030
+				//make sure there's no related objects blocking its deletion (if we're checking)
2031
+				if (
2032
+					$allow_blocking
2033
+					&& $this->delete_is_blocked_by_related_models(
2034
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2035
+					)
2036
+				) {
2037
+					continue;
2038
+				}
2039
+				//primary table deletes
2040
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2041
+
2042
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2043
+						$delete_object[$primary_table->get_fully_qualified_pk_column()],
2044
+						$pt_pk_field
2045
+					);
2046
+				}
2047
+				//other tables
2048
+				if (! empty($other_tables)) {
2049
+					foreach ($other_tables as $ot_alias => $ot) {
2050
+						$ot_pk_field = $ot_pk_fields[$ot_alias];
2051
+						$ot_fk_field = $ot_fk_fields[$ot_alias];
2052
+						//first check if we've got the foreign key column here.
2053
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
2054
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2055
+								$delete_object[$ot->get_fully_qualified_fk_column()],
2056
+								$ot_fk_field
2057
+							);
2058
+						}
2059
+						// wait! it's entirely possible that we'll have a the primary key
2060
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2061
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
2062
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2063
+								$delete_object[$ot->get_fully_qualified_pk_column()],
2064
+								$ot_pk_field
2065
+							);
2066
+						}
2067
+						// finally, it is possible that the fk for this table is found
2068
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2069
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
2070
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2071
+								$delete_object[$ot->get_fully_qualified_pk_column()],
2072
+								$ot_pk_field
2073
+							);
2074
+						}
2075
+					}
2076
+				}
2077
+			}
2078
+			//we should have deletes now, so let's just go through and setup the where statement
2079
+			foreach ($deletes as $column => $values) {
2080
+				//make sure we have unique $values;
2081
+				$values = array_unique($values);
2082
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2083
+			}
2084
+			return ! empty($query) ? implode(' AND ', $query) : '';
2085
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2086
+			$ways_to_identify_a_row = array();
2087
+			$fields = $this->get_combined_primary_key_fields();
2088
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
2089
+			foreach ($objects_for_deletion as $delete_object) {
2090
+				$values_for_each_cpk_for_a_row = array();
2091
+				foreach ($fields as $cpk_field) {
2092
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2093
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
2094
+														   . "="
2095
+														   . $delete_object[$cpk_field->get_qualified_column()];
2096
+					}
2097
+				}
2098
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2099
+			}
2100
+			return implode(" OR ", $ways_to_identify_a_row);
2101
+		} else {
2102
+			//so there's no primary key and no combined key...
2103
+			//sorry, can't help you
2104
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2105
+				"event_espresso"), get_class($this)));
2106
+		}
2107
+	}
2108
+
2109
+
2110
+	/**
2111
+	 * Gets the model field by the fully qualified name
2112
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2113
+	 * @return EE_Model_Field_Base
2114
+	 */
2115
+	public function get_field_by_column($qualified_column_name)
2116
+	{
2117
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2118
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2119
+			   return $field_obj;
2120
+		   }
2121
+	   }
2122
+		throw new EE_Error(
2123
+			sprintf(
2124
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2125
+				$this->get_this_model_name(),
2126
+				$qualified_column_name
2127
+			)
2128
+		);
2129
+	}
2130
+
2131
+
2132
+
2133
+	/**
2134
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2135
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2136
+	 * column
2137
+	 *
2138
+	 * @param array  $query_params   like EEM_Base::get_all's
2139
+	 * @param string $field_to_count field on model to count by (not column name)
2140
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2141
+	 *                               that by the setting $distinct to TRUE;
2142
+	 * @return int
2143
+	 * @throws \EE_Error
2144
+	 */
2145
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2146
+	{
2147
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2148
+		if ($field_to_count) {
2149
+			$field_obj = $this->field_settings_for($field_to_count);
2150
+			$column_to_count = $field_obj->get_qualified_column();
2151
+		} elseif ($this->has_primary_key_field()) {
2152
+			$pk_field_obj = $this->get_primary_key_field();
2153
+			$column_to_count = $pk_field_obj->get_qualified_column();
2154
+		} else {
2155
+			//there's no primary key
2156
+			//if we're counting distinct items, and there's no primary key,
2157
+			//we need to list out the columns for distinction;
2158
+			//otherwise we can just use star
2159
+			if ($distinct) {
2160
+				$columns_to_use = array();
2161
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2162
+					$columns_to_use[] = $field_obj->get_qualified_column();
2163
+				}
2164
+				$column_to_count = implode(',', $columns_to_use);
2165
+			} else {
2166
+				$column_to_count = '*';
2167
+			}
2168
+		}
2169
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2170
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2171
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2172
+	}
2173
+
2174
+
2175
+
2176
+	/**
2177
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2178
+	 *
2179
+	 * @param array  $query_params like EEM_Base::get_all
2180
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2181
+	 * @return float
2182
+	 * @throws \EE_Error
2183
+	 */
2184
+	public function sum($query_params, $field_to_sum = null)
2185
+	{
2186
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2187
+		if ($field_to_sum) {
2188
+			$field_obj = $this->field_settings_for($field_to_sum);
2189
+		} else {
2190
+			$field_obj = $this->get_primary_key_field();
2191
+		}
2192
+		$column_to_count = $field_obj->get_qualified_column();
2193
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2194
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2195
+		$data_type = $field_obj->get_wpdb_data_type();
2196
+		if ($data_type === '%d' || $data_type === '%s') {
2197
+			return (float)$return_value;
2198
+		} else {//must be %f
2199
+			return (float)$return_value;
2200
+		}
2201
+	}
2202
+
2203
+
2204
+
2205
+	/**
2206
+	 * Just calls the specified method on $wpdb with the given arguments
2207
+	 * Consolidates a little extra error handling code
2208
+	 *
2209
+	 * @param string $wpdb_method
2210
+	 * @param array  $arguments_to_provide
2211
+	 * @throws EE_Error
2212
+	 * @global wpdb  $wpdb
2213
+	 * @return mixed
2214
+	 */
2215
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2216
+	{
2217
+		//if we're in maintenance mode level 2, DON'T run any queries
2218
+		//because level 2 indicates the database needs updating and
2219
+		//is probably out of sync with the code
2220
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2221
+			throw new EE_Error(sprintf(__("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.",
2222
+				"event_espresso")));
2223
+		}
2224
+		/** @type WPDB $wpdb */
2225
+		global $wpdb;
2226
+		if (! method_exists($wpdb, $wpdb_method)) {
2227
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2228
+				'event_espresso'), $wpdb_method));
2229
+		}
2230
+		if (WP_DEBUG) {
2231
+			$old_show_errors_value = $wpdb->show_errors;
2232
+			$wpdb->show_errors(false);
2233
+		}
2234
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2235
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2236
+		if (WP_DEBUG) {
2237
+			$wpdb->show_errors($old_show_errors_value);
2238
+			if (! empty($wpdb->last_error)) {
2239
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2240
+			} elseif ($result === false) {
2241
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2242
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2243
+			}
2244
+		} elseif ($result === false) {
2245
+			EE_Error::add_error(
2246
+				sprintf(
2247
+					__('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"',
2248
+						'event_espresso'),
2249
+					$wpdb_method,
2250
+					var_export($arguments_to_provide, true),
2251
+					$wpdb->last_error
2252
+				),
2253
+				__FILE__,
2254
+				__FUNCTION__,
2255
+				__LINE__
2256
+			);
2257
+		}
2258
+		return $result;
2259
+	}
2260
+
2261
+
2262
+
2263
+	/**
2264
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2265
+	 * and if there's an error tries to verify the DB is correct. Uses
2266
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2267
+	 * we should try to fix the EE core db, the addons, or just give up
2268
+	 *
2269
+	 * @param string $wpdb_method
2270
+	 * @param array  $arguments_to_provide
2271
+	 * @return mixed
2272
+	 */
2273
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2274
+	{
2275
+		/** @type WPDB $wpdb */
2276
+		global $wpdb;
2277
+		$wpdb->last_error = null;
2278
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2279
+		// was there an error running the query? but we don't care on new activations
2280
+		// (we're going to setup the DB anyway on new activations)
2281
+		if (($result === false || ! empty($wpdb->last_error))
2282
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2283
+		) {
2284
+			switch (EEM_Base::$_db_verification_level) {
2285
+				case EEM_Base::db_verified_none :
2286
+					// let's double-check core's DB
2287
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2288
+					break;
2289
+				case EEM_Base::db_verified_core :
2290
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2291
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2292
+					break;
2293
+				case EEM_Base::db_verified_addons :
2294
+					// ummmm... you in trouble
2295
+					return $result;
2296
+					break;
2297
+			}
2298
+			if (! empty($error_message)) {
2299
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2300
+				trigger_error($error_message);
2301
+			}
2302
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2303
+		}
2304
+		return $result;
2305
+	}
2306
+
2307
+
2308
+
2309
+	/**
2310
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2311
+	 * EEM_Base::$_db_verification_level
2312
+	 *
2313
+	 * @param string $wpdb_method
2314
+	 * @param array  $arguments_to_provide
2315
+	 * @return string
2316
+	 */
2317
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2318
+	{
2319
+		/** @type WPDB $wpdb */
2320
+		global $wpdb;
2321
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2322
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2323
+		$error_message = sprintf(
2324
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2325
+				'event_espresso'),
2326
+			$wpdb->last_error,
2327
+			$wpdb_method,
2328
+			wp_json_encode($arguments_to_provide)
2329
+		);
2330
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2331
+		return $error_message;
2332
+	}
2333
+
2334
+
2335
+
2336
+	/**
2337
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2338
+	 * EEM_Base::$_db_verification_level
2339
+	 *
2340
+	 * @param $wpdb_method
2341
+	 * @param $arguments_to_provide
2342
+	 * @return string
2343
+	 */
2344
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2345
+	{
2346
+		/** @type WPDB $wpdb */
2347
+		global $wpdb;
2348
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2349
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2350
+		$error_message = sprintf(
2351
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2352
+				'event_espresso'),
2353
+			$wpdb->last_error,
2354
+			$wpdb_method,
2355
+			wp_json_encode($arguments_to_provide)
2356
+		);
2357
+		EE_System::instance()->initialize_addons();
2358
+		return $error_message;
2359
+	}
2360
+
2361
+
2362
+
2363
+	/**
2364
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2365
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2366
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2367
+	 * ..."
2368
+	 *
2369
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2370
+	 * @return string
2371
+	 */
2372
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2373
+	{
2374
+		return " FROM " . $model_query_info->get_full_join_sql() .
2375
+			   $model_query_info->get_where_sql() .
2376
+			   $model_query_info->get_group_by_sql() .
2377
+			   $model_query_info->get_having_sql() .
2378
+			   $model_query_info->get_order_by_sql() .
2379
+			   $model_query_info->get_limit_sql();
2380
+	}
2381
+
2382
+
2383
+
2384
+	/**
2385
+	 * Set to easily debug the next X queries ran from this model.
2386
+	 *
2387
+	 * @param int $count
2388
+	 */
2389
+	public function show_next_x_db_queries($count = 1)
2390
+	{
2391
+		$this->_show_next_x_db_queries = $count;
2392
+	}
2393
+
2394
+
2395
+
2396
+	/**
2397
+	 * @param $sql_query
2398
+	 */
2399
+	public function show_db_query_if_previously_requested($sql_query)
2400
+	{
2401
+		if ($this->_show_next_x_db_queries > 0) {
2402
+			echo $sql_query;
2403
+			$this->_show_next_x_db_queries--;
2404
+		}
2405
+	}
2406
+
2407
+
2408
+
2409
+	/**
2410
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2411
+	 * There are the 3 cases:
2412
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2413
+	 * $otherModelObject has no ID, it is first saved.
2414
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2415
+	 * has no ID, it is first saved.
2416
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2417
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2418
+	 * join table
2419
+	 *
2420
+	 * @param        EE_Base_Class                     /int $thisModelObject
2421
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2422
+	 * @param string $relationName                     , key in EEM_Base::_relations
2423
+	 *                                                 an attendee to a group, you also want to specify which role they
2424
+	 *                                                 will have in that group. So you would use this parameter to
2425
+	 *                                                 specify array('role-column-name'=>'role-id')
2426
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2427
+	 *                                                 to for relation to methods that allow you to further specify
2428
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2429
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2430
+	 *                                                 because these will be inserted in any new rows created as well.
2431
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2432
+	 * @throws \EE_Error
2433
+	 */
2434
+	public function add_relationship_to(
2435
+		$id_or_obj,
2436
+		$other_model_id_or_obj,
2437
+		$relationName,
2438
+		$extra_join_model_fields_n_values = array()
2439
+	) {
2440
+		$relation_obj = $this->related_settings_for($relationName);
2441
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2442
+	}
2443
+
2444
+
2445
+
2446
+	/**
2447
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2448
+	 * There are the 3 cases:
2449
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2450
+	 * error
2451
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2452
+	 * an error
2453
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2454
+	 *
2455
+	 * @param        EE_Base_Class /int $id_or_obj
2456
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2457
+	 * @param string $relationName key in EEM_Base::_relations
2458
+	 * @return boolean of success
2459
+	 * @throws \EE_Error
2460
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2461
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2462
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2463
+	 *                             because these will be inserted in any new rows created as well.
2464
+	 */
2465
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2466
+	{
2467
+		$relation_obj = $this->related_settings_for($relationName);
2468
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2469
+	}
2470
+
2471
+
2472
+
2473
+	/**
2474
+	 * @param mixed           $id_or_obj
2475
+	 * @param string          $relationName
2476
+	 * @param array           $where_query_params
2477
+	 * @param EE_Base_Class[] objects to which relations were removed
2478
+	 * @return \EE_Base_Class[]
2479
+	 * @throws \EE_Error
2480
+	 */
2481
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2482
+	{
2483
+		$relation_obj = $this->related_settings_for($relationName);
2484
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2485
+	}
2486
+
2487
+
2488
+
2489
+	/**
2490
+	 * Gets all the related items of the specified $model_name, using $query_params.
2491
+	 * Note: by default, we remove the "default query params"
2492
+	 * because we want to get even deleted items etc.
2493
+	 *
2494
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2495
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2496
+	 * @param array  $query_params like EEM_Base::get_all
2497
+	 * @return EE_Base_Class[]
2498
+	 * @throws \EE_Error
2499
+	 */
2500
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2501
+	{
2502
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2503
+		$relation_settings = $this->related_settings_for($model_name);
2504
+		return $relation_settings->get_all_related($model_obj, $query_params);
2505
+	}
2506
+
2507
+
2508
+
2509
+	/**
2510
+	 * Deletes all the model objects across the relation indicated by $model_name
2511
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2512
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2513
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2514
+	 *
2515
+	 * @param EE_Base_Class|int|string $id_or_obj
2516
+	 * @param string                   $model_name
2517
+	 * @param array                    $query_params
2518
+	 * @return int how many deleted
2519
+	 * @throws \EE_Error
2520
+	 */
2521
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2522
+	{
2523
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2524
+		$relation_settings = $this->related_settings_for($model_name);
2525
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2526
+	}
2527
+
2528
+
2529
+
2530
+	/**
2531
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2532
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2533
+	 * the model objects can't be hard deleted because of blocking related model objects,
2534
+	 * just does a soft-delete on them instead.
2535
+	 *
2536
+	 * @param EE_Base_Class|int|string $id_or_obj
2537
+	 * @param string                   $model_name
2538
+	 * @param array                    $query_params
2539
+	 * @return int how many deleted
2540
+	 * @throws \EE_Error
2541
+	 */
2542
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2543
+	{
2544
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2545
+		$relation_settings = $this->related_settings_for($model_name);
2546
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2547
+	}
2548
+
2549
+
2550
+
2551
+	/**
2552
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2553
+	 * unless otherwise specified in the $query_params
2554
+	 *
2555
+	 * @param        int             /EE_Base_Class $id_or_obj
2556
+	 * @param string $model_name     like 'Event', or 'Registration'
2557
+	 * @param array  $query_params   like EEM_Base::get_all's
2558
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2559
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2560
+	 *                               that by the setting $distinct to TRUE;
2561
+	 * @return int
2562
+	 * @throws \EE_Error
2563
+	 */
2564
+	public function count_related(
2565
+		$id_or_obj,
2566
+		$model_name,
2567
+		$query_params = array(),
2568
+		$field_to_count = null,
2569
+		$distinct = false
2570
+	) {
2571
+		$related_model = $this->get_related_model_obj($model_name);
2572
+		//we're just going to use the query params on the related model's normal get_all query,
2573
+		//except add a condition to say to match the current mod
2574
+		if (! isset($query_params['default_where_conditions'])) {
2575
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2576
+		}
2577
+		$this_model_name = $this->get_this_model_name();
2578
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2579
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2580
+		return $related_model->count($query_params, $field_to_count, $distinct);
2581
+	}
2582
+
2583
+
2584
+
2585
+	/**
2586
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2587
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2588
+	 *
2589
+	 * @param        int           /EE_Base_Class $id_or_obj
2590
+	 * @param string $model_name   like 'Event', or 'Registration'
2591
+	 * @param array  $query_params like EEM_Base::get_all's
2592
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2593
+	 * @return float
2594
+	 * @throws \EE_Error
2595
+	 */
2596
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2597
+	{
2598
+		$related_model = $this->get_related_model_obj($model_name);
2599
+		if (! is_array($query_params)) {
2600
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2601
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2602
+					gettype($query_params)), '4.6.0');
2603
+			$query_params = array();
2604
+		}
2605
+		//we're just going to use the query params on the related model's normal get_all query,
2606
+		//except add a condition to say to match the current mod
2607
+		if (! isset($query_params['default_where_conditions'])) {
2608
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2609
+		}
2610
+		$this_model_name = $this->get_this_model_name();
2611
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2612
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2613
+		return $related_model->sum($query_params, $field_to_sum);
2614
+	}
2615
+
2616
+
2617
+
2618
+	/**
2619
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2620
+	 * $modelObject
2621
+	 *
2622
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2623
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2624
+	 * @param array               $query_params     like EEM_Base::get_all's
2625
+	 * @return EE_Base_Class
2626
+	 * @throws \EE_Error
2627
+	 */
2628
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2629
+	{
2630
+		$query_params['limit'] = 1;
2631
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2632
+		if ($results) {
2633
+			return array_shift($results);
2634
+		} else {
2635
+			return null;
2636
+		}
2637
+	}
2638
+
2639
+
2640
+
2641
+	/**
2642
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2643
+	 *
2644
+	 * @return string
2645
+	 */
2646
+	public function get_this_model_name()
2647
+	{
2648
+		return str_replace("EEM_", "", get_class($this));
2649
+	}
2650
+
2651
+
2652
+
2653
+	/**
2654
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2655
+	 *
2656
+	 * @return EE_Any_Foreign_Model_Name_Field
2657
+	 * @throws EE_Error
2658
+	 */
2659
+	public function get_field_containing_related_model_name()
2660
+	{
2661
+		foreach ($this->field_settings(true) as $field) {
2662
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2663
+				$field_with_model_name = $field;
2664
+			}
2665
+		}
2666
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2667
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2668
+				$this->get_this_model_name()));
2669
+		}
2670
+		return $field_with_model_name;
2671
+	}
2672
+
2673
+
2674
+
2675
+	/**
2676
+	 * Inserts a new entry into the database, for each table.
2677
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2678
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2679
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2680
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2681
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2682
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2683
+	 *
2684
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2685
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2686
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2687
+	 *                              of EEM_Base)
2688
+	 * @return int new primary key on main table that got inserted
2689
+	 * @throws EE_Error
2690
+	 */
2691
+	public function insert($field_n_values)
2692
+	{
2693
+		/**
2694
+		 * Filters the fields and their values before inserting an item using the models
2695
+		 *
2696
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2697
+		 * @param EEM_Base $model           the model used
2698
+		 */
2699
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2700
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2701
+			$main_table = $this->_get_main_table();
2702
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2703
+			if ($new_id !== false) {
2704
+				foreach ($this->_get_other_tables() as $other_table) {
2705
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2706
+				}
2707
+			}
2708
+			/**
2709
+			 * Done just after attempting to insert a new model object
2710
+			 *
2711
+			 * @param EEM_Base   $model           used
2712
+			 * @param array      $fields_n_values fields and their values
2713
+			 * @param int|string the              ID of the newly-inserted model object
2714
+			 */
2715
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2716
+			return $new_id;
2717
+		} else {
2718
+			return false;
2719
+		}
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Checks that the result would satisfy the unique indexes on this model
2726
+	 *
2727
+	 * @param array  $field_n_values
2728
+	 * @param string $action
2729
+	 * @return boolean
2730
+	 * @throws \EE_Error
2731
+	 */
2732
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2733
+	{
2734
+		foreach ($this->unique_indexes() as $index_name => $index) {
2735
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2736
+			if ($this->exists(array($uniqueness_where_params))) {
2737
+				EE_Error::add_error(
2738
+					sprintf(
2739
+						__(
2740
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2741
+							"event_espresso"
2742
+						),
2743
+						$action,
2744
+						$this->_get_class_name(),
2745
+						$index_name,
2746
+						implode(",", $index->field_names()),
2747
+						http_build_query($uniqueness_where_params)
2748
+					),
2749
+					__FILE__,
2750
+					__FUNCTION__,
2751
+					__LINE__
2752
+				);
2753
+				return false;
2754
+			}
2755
+		}
2756
+		return true;
2757
+	}
2758
+
2759
+
2760
+
2761
+	/**
2762
+	 * Checks the database for an item that conflicts (ie, if this item were
2763
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2764
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2765
+	 * can be either an EE_Base_Class or an array of fields n values
2766
+	 *
2767
+	 * @param EE_Base_Class|array $obj_or_fields_array
2768
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2769
+	 *                                                 when looking for conflicts
2770
+	 *                                                 (ie, if false, we ignore the model object's primary key
2771
+	 *                                                 when finding "conflicts". If true, it's also considered).
2772
+	 *                                                 Only works for INT primary key,
2773
+	 *                                                 STRING primary keys cannot be ignored
2774
+	 * @throws EE_Error
2775
+	 * @return EE_Base_Class|array
2776
+	 */
2777
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2778
+	{
2779
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2780
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2781
+		} elseif (is_array($obj_or_fields_array)) {
2782
+			$fields_n_values = $obj_or_fields_array;
2783
+		} else {
2784
+			throw new EE_Error(
2785
+				sprintf(
2786
+					__(
2787
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2788
+						"event_espresso"
2789
+					),
2790
+					get_class($this),
2791
+					$obj_or_fields_array
2792
+				)
2793
+			);
2794
+		}
2795
+		$query_params = array();
2796
+		if ($this->has_primary_key_field()
2797
+			&& ($include_primary_key
2798
+				|| $this->get_primary_key_field()
2799
+				   instanceof
2800
+				   EE_Primary_Key_String_Field)
2801
+			&& isset($fields_n_values[$this->primary_key_name()])
2802
+		) {
2803
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2804
+		}
2805
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2806
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2807
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2808
+		}
2809
+		//if there is nothing to base this search on, then we shouldn't find anything
2810
+		if (empty($query_params)) {
2811
+			return array();
2812
+		} else {
2813
+			return $this->get_one($query_params);
2814
+		}
2815
+	}
2816
+
2817
+
2818
+
2819
+	/**
2820
+	 * Like count, but is optimized and returns a boolean instead of an int
2821
+	 *
2822
+	 * @param array $query_params
2823
+	 * @return boolean
2824
+	 * @throws \EE_Error
2825
+	 */
2826
+	public function exists($query_params)
2827
+	{
2828
+		$query_params['limit'] = 1;
2829
+		return $this->count($query_params) > 0;
2830
+	}
2831
+
2832
+
2833
+
2834
+	/**
2835
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2836
+	 *
2837
+	 * @param int|string $id
2838
+	 * @return boolean
2839
+	 * @throws \EE_Error
2840
+	 */
2841
+	public function exists_by_ID($id)
2842
+	{
2843
+		return $this->exists(
2844
+			array(
2845
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2846
+				array(
2847
+					$this->primary_key_name() => $id,
2848
+				),
2849
+			)
2850
+		);
2851
+	}
2852
+
2853
+
2854
+
2855
+	/**
2856
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2857
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2858
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2859
+	 * on the main table)
2860
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2861
+	 * cases where we want to call it directly rather than via insert().
2862
+	 *
2863
+	 * @access   protected
2864
+	 * @param EE_Table_Base $table
2865
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2866
+	 *                                       float
2867
+	 * @param int           $new_id          for now we assume only int keys
2868
+	 * @throws EE_Error
2869
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2870
+	 * @return int ID of new row inserted, or FALSE on failure
2871
+	 */
2872
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2873
+	{
2874
+		global $wpdb;
2875
+		$insertion_col_n_values = array();
2876
+		$format_for_insertion = array();
2877
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2878
+		foreach ($fields_on_table as $field_name => $field_obj) {
2879
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2880
+			if ($field_obj->is_auto_increment()) {
2881
+				continue;
2882
+			}
2883
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2884
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2885
+			if ($prepared_value !== null) {
2886
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2887
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2888
+			}
2889
+		}
2890
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2891
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2892
+			//so add the fk to the main table as a column
2893
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2894
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2895
+		}
2896
+		//insert the new entry
2897
+		$result = $this->_do_wpdb_query('insert',
2898
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2899
+		if ($result === false) {
2900
+			return false;
2901
+		}
2902
+		//ok, now what do we return for the ID of the newly-inserted thing?
2903
+		if ($this->has_primary_key_field()) {
2904
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2905
+				return $wpdb->insert_id;
2906
+			} else {
2907
+				//it's not an auto-increment primary key, so
2908
+				//it must have been supplied
2909
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2910
+			}
2911
+		} else {
2912
+			//we can't return a  primary key because there is none. instead return
2913
+			//a unique string indicating this model
2914
+			return $this->get_index_primary_key_string($fields_n_values);
2915
+		}
2916
+	}
2917
+
2918
+
2919
+
2920
+	/**
2921
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2922
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2923
+	 * and there is no default, we pass it along. WPDB will take care of it)
2924
+	 *
2925
+	 * @param EE_Model_Field_Base $field_obj
2926
+	 * @param array               $fields_n_values
2927
+	 * @return mixed string|int|float depending on what the table column will be expecting
2928
+	 * @throws \EE_Error
2929
+	 */
2930
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2931
+	{
2932
+		//if this field doesn't allow nullable, don't allow it
2933
+		if (! $field_obj->is_nullable()
2934
+			&& (
2935
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2936
+		) {
2937
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2938
+		}
2939
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2940
+			: null;
2941
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2942
+	}
2943
+
2944
+
2945
+
2946
+	/**
2947
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2948
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2949
+	 * the field's prepare_for_set() method.
2950
+	 *
2951
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2952
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2953
+	 *                                   top of file)
2954
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2955
+	 *                                   $value is a custom selection
2956
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2957
+	 */
2958
+	private function _prepare_value_for_use_in_db($value, $field)
2959
+	{
2960
+		if ($field && $field instanceof EE_Model_Field_Base) {
2961
+			switch ($this->_values_already_prepared_by_model_object) {
2962
+				/** @noinspection PhpMissingBreakStatementInspection */
2963
+				case self::not_prepared_by_model_object:
2964
+					$value = $field->prepare_for_set($value);
2965
+				//purposefully left out "return"
2966
+				case self::prepared_by_model_object:
2967
+					$value = $field->prepare_for_use_in_db($value);
2968
+				case self::prepared_for_use_in_db:
2969
+					//leave the value alone
2970
+			}
2971
+			return $value;
2972
+		} else {
2973
+			return $value;
2974
+		}
2975
+	}
2976
+
2977
+
2978
+
2979
+	/**
2980
+	 * Returns the main table on this model
2981
+	 *
2982
+	 * @return EE_Primary_Table
2983
+	 * @throws EE_Error
2984
+	 */
2985
+	protected function _get_main_table()
2986
+	{
2987
+		foreach ($this->_tables as $table) {
2988
+			if ($table instanceof EE_Primary_Table) {
2989
+				return $table;
2990
+			}
2991
+		}
2992
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2993
+			'event_espresso'), get_class($this)));
2994
+	}
2995
+
2996
+
2997
+
2998
+	/**
2999
+	 * table
3000
+	 * returns EE_Primary_Table table name
3001
+	 *
3002
+	 * @return string
3003
+	 * @throws \EE_Error
3004
+	 */
3005
+	public function table()
3006
+	{
3007
+		return $this->_get_main_table()->get_table_name();
3008
+	}
3009
+
3010
+
3011
+
3012
+	/**
3013
+	 * table
3014
+	 * returns first EE_Secondary_Table table name
3015
+	 *
3016
+	 * @return string
3017
+	 */
3018
+	public function second_table()
3019
+	{
3020
+		// grab second table from tables array
3021
+		$second_table = end($this->_tables);
3022
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3023
+	}
3024
+
3025
+
3026
+
3027
+	/**
3028
+	 * get_table_obj_by_alias
3029
+	 * returns table name given it's alias
3030
+	 *
3031
+	 * @param string $table_alias
3032
+	 * @return EE_Primary_Table | EE_Secondary_Table
3033
+	 */
3034
+	public function get_table_obj_by_alias($table_alias = '')
3035
+	{
3036
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3037
+	}
3038
+
3039
+
3040
+
3041
+	/**
3042
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3043
+	 *
3044
+	 * @return EE_Secondary_Table[]
3045
+	 */
3046
+	protected function _get_other_tables()
3047
+	{
3048
+		$other_tables = array();
3049
+		foreach ($this->_tables as $table_alias => $table) {
3050
+			if ($table instanceof EE_Secondary_Table) {
3051
+				$other_tables[$table_alias] = $table;
3052
+			}
3053
+		}
3054
+		return $other_tables;
3055
+	}
3056
+
3057
+
3058
+
3059
+	/**
3060
+	 * Finds all the fields that correspond to the given table
3061
+	 *
3062
+	 * @param string $table_alias , array key in EEM_Base::_tables
3063
+	 * @return EE_Model_Field_Base[]
3064
+	 */
3065
+	public function _get_fields_for_table($table_alias)
3066
+	{
3067
+		return $this->_fields[$table_alias];
3068
+	}
3069
+
3070
+
3071
+
3072
+	/**
3073
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3074
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3075
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3076
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3077
+	 * related Registration, Transaction, and Payment models.
3078
+	 *
3079
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3080
+	 * @return EE_Model_Query_Info_Carrier
3081
+	 * @throws \EE_Error
3082
+	 */
3083
+	public function _extract_related_models_from_query($query_params)
3084
+	{
3085
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3086
+		if (array_key_exists(0, $query_params)) {
3087
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3088
+		}
3089
+		if (array_key_exists('group_by', $query_params)) {
3090
+			if (is_array($query_params['group_by'])) {
3091
+				$this->_extract_related_models_from_sub_params_array_values(
3092
+					$query_params['group_by'],
3093
+					$query_info_carrier,
3094
+					'group_by'
3095
+				);
3096
+			} elseif (! empty ($query_params['group_by'])) {
3097
+				$this->_extract_related_model_info_from_query_param(
3098
+					$query_params['group_by'],
3099
+					$query_info_carrier,
3100
+					'group_by'
3101
+				);
3102
+			}
3103
+		}
3104
+		if (array_key_exists('having', $query_params)) {
3105
+			$this->_extract_related_models_from_sub_params_array_keys(
3106
+				$query_params[0],
3107
+				$query_info_carrier,
3108
+				'having'
3109
+			);
3110
+		}
3111
+		if (array_key_exists('order_by', $query_params)) {
3112
+			if (is_array($query_params['order_by'])) {
3113
+				$this->_extract_related_models_from_sub_params_array_keys(
3114
+					$query_params['order_by'],
3115
+					$query_info_carrier,
3116
+					'order_by'
3117
+				);
3118
+			} elseif (! empty($query_params['order_by'])) {
3119
+				$this->_extract_related_model_info_from_query_param(
3120
+					$query_params['order_by'],
3121
+					$query_info_carrier,
3122
+					'order_by'
3123
+				);
3124
+			}
3125
+		}
3126
+		if (array_key_exists('force_join', $query_params)) {
3127
+			$this->_extract_related_models_from_sub_params_array_values(
3128
+				$query_params['force_join'],
3129
+				$query_info_carrier,
3130
+				'force_join'
3131
+			);
3132
+		}
3133
+		return $query_info_carrier;
3134
+	}
3135
+
3136
+
3137
+
3138
+	/**
3139
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3140
+	 *
3141
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3142
+	 *                                                      $query_params['having']
3143
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3144
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3145
+	 * @throws EE_Error
3146
+	 * @return \EE_Model_Query_Info_Carrier
3147
+	 */
3148
+	private function _extract_related_models_from_sub_params_array_keys(
3149
+		$sub_query_params,
3150
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3151
+		$query_param_type
3152
+	) {
3153
+		if (! empty($sub_query_params)) {
3154
+			$sub_query_params = (array)$sub_query_params;
3155
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3156
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3157
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3158
+					$query_param_type);
3159
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3160
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3161
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3162
+				//of array('Registration.TXN_ID'=>23)
3163
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3164
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3165
+					if (! is_array($possibly_array_of_params)) {
3166
+						throw new EE_Error(sprintf(__("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'))",
3167
+							"event_espresso"),
3168
+							$param, $possibly_array_of_params));
3169
+					} else {
3170
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3171
+							$model_query_info_carrier, $query_param_type);
3172
+					}
3173
+				} elseif ($query_param_type === 0 //ie WHERE
3174
+						  && is_array($possibly_array_of_params)
3175
+						  && isset($possibly_array_of_params[2])
3176
+						  && $possibly_array_of_params[2] == true
3177
+				) {
3178
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3179
+					//indicating that $possible_array_of_params[1] is actually a field name,
3180
+					//from which we should extract query parameters!
3181
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3182
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3183
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3184
+					}
3185
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3186
+						$model_query_info_carrier, $query_param_type);
3187
+				}
3188
+			}
3189
+		}
3190
+		return $model_query_info_carrier;
3191
+	}
3192
+
3193
+
3194
+
3195
+	/**
3196
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3197
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3198
+	 *
3199
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3200
+	 *                                                      $query_params['having']
3201
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3202
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3203
+	 * @throws EE_Error
3204
+	 * @return \EE_Model_Query_Info_Carrier
3205
+	 */
3206
+	private function _extract_related_models_from_sub_params_array_values(
3207
+		$sub_query_params,
3208
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3209
+		$query_param_type
3210
+	) {
3211
+		if (! empty($sub_query_params)) {
3212
+			if (! is_array($sub_query_params)) {
3213
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3214
+					$sub_query_params));
3215
+			}
3216
+			foreach ($sub_query_params as $param) {
3217
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3218
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3219
+					$query_param_type);
3220
+			}
3221
+		}
3222
+		return $model_query_info_carrier;
3223
+	}
3224
+
3225
+
3226
+
3227
+	/**
3228
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3229
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3230
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3231
+	 * but use them in a different order. Eg, we need to know what models we are querying
3232
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3233
+	 * other models before we can finalize the where clause SQL.
3234
+	 *
3235
+	 * @param array $query_params
3236
+	 * @throws EE_Error
3237
+	 * @return EE_Model_Query_Info_Carrier
3238
+	 */
3239
+	public function _create_model_query_info_carrier($query_params)
3240
+	{
3241
+		if (! is_array($query_params)) {
3242
+			EE_Error::doing_it_wrong(
3243
+				'EEM_Base::_create_model_query_info_carrier',
3244
+				sprintf(
3245
+					__(
3246
+						'$query_params should be an array, you passed a variable of type %s',
3247
+						'event_espresso'
3248
+					),
3249
+					gettype($query_params)
3250
+				),
3251
+				'4.6.0'
3252
+			);
3253
+			$query_params = array();
3254
+		}
3255
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3256
+		//first check if we should alter the query to account for caps or not
3257
+		//because the caps might require us to do extra joins
3258
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3259
+			$query_params[0] = $where_query_params = array_replace_recursive(
3260
+				$where_query_params,
3261
+				$this->caps_where_conditions(
3262
+					$query_params['caps']
3263
+				)
3264
+			);
3265
+		}
3266
+		$query_object = $this->_extract_related_models_from_query($query_params);
3267
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3268
+		foreach ($where_query_params as $key => $value) {
3269
+			if (is_int($key)) {
3270
+				throw new EE_Error(
3271
+					sprintf(
3272
+						__(
3273
+							"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.",
3274
+							"event_espresso"
3275
+						),
3276
+						$key,
3277
+						var_export($value, true),
3278
+						var_export($query_params, true),
3279
+						get_class($this)
3280
+					)
3281
+				);
3282
+			}
3283
+		}
3284
+		if (
3285
+			array_key_exists('default_where_conditions', $query_params)
3286
+			&& ! empty($query_params['default_where_conditions'])
3287
+		) {
3288
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3289
+		} else {
3290
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3291
+		}
3292
+		$where_query_params = array_merge(
3293
+			$this->_get_default_where_conditions_for_models_in_query(
3294
+				$query_object,
3295
+				$use_default_where_conditions,
3296
+				$where_query_params
3297
+			),
3298
+			$where_query_params
3299
+		);
3300
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3301
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3302
+		// So we need to setup a subquery and use that for the main join.
3303
+		// Note for now this only works on the primary table for the model.
3304
+		// So for instance, you could set the limit array like this:
3305
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3306
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3307
+			$query_object->set_main_model_join_sql(
3308
+				$this->_construct_limit_join_select(
3309
+					$query_params['on_join_limit'][0],
3310
+					$query_params['on_join_limit'][1]
3311
+				)
3312
+			);
3313
+		}
3314
+		//set limit
3315
+		if (array_key_exists('limit', $query_params)) {
3316
+			if (is_array($query_params['limit'])) {
3317
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3318
+					$e = sprintf(
3319
+						__(
3320
+							"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)",
3321
+							"event_espresso"
3322
+						),
3323
+						http_build_query($query_params['limit'])
3324
+					);
3325
+					throw new EE_Error($e . "|" . $e);
3326
+				}
3327
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3328
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3329
+			} elseif (! empty ($query_params['limit'])) {
3330
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3331
+			}
3332
+		}
3333
+		//set order by
3334
+		if (array_key_exists('order_by', $query_params)) {
3335
+			if (is_array($query_params['order_by'])) {
3336
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3337
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3338
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3339
+				if (array_key_exists('order', $query_params)) {
3340
+					throw new EE_Error(
3341
+						sprintf(
3342
+							__(
3343
+								"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 ",
3344
+								"event_espresso"
3345
+							),
3346
+							get_class($this),
3347
+							implode(", ", array_keys($query_params['order_by'])),
3348
+							implode(", ", $query_params['order_by']),
3349
+							$query_params['order']
3350
+						)
3351
+					);
3352
+				}
3353
+				$this->_extract_related_models_from_sub_params_array_keys(
3354
+					$query_params['order_by'],
3355
+					$query_object,
3356
+					'order_by'
3357
+				);
3358
+				//assume it's an array of fields to order by
3359
+				$order_array = array();
3360
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3361
+					$order = $this->_extract_order($order);
3362
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3363
+				}
3364
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3365
+			} elseif (! empty ($query_params['order_by'])) {
3366
+				$this->_extract_related_model_info_from_query_param(
3367
+					$query_params['order_by'],
3368
+					$query_object,
3369
+					'order',
3370
+					$query_params['order_by']
3371
+				);
3372
+				$order = isset($query_params['order'])
3373
+					? $this->_extract_order($query_params['order'])
3374
+					: 'DESC';
3375
+				$query_object->set_order_by_sql(
3376
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3377
+				);
3378
+			}
3379
+		}
3380
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3381
+		if (! array_key_exists('order_by', $query_params)
3382
+			&& array_key_exists('order', $query_params)
3383
+			&& ! empty($query_params['order'])
3384
+		) {
3385
+			$pk_field = $this->get_primary_key_field();
3386
+			$order = $this->_extract_order($query_params['order']);
3387
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3388
+		}
3389
+		//set group by
3390
+		if (array_key_exists('group_by', $query_params)) {
3391
+			if (is_array($query_params['group_by'])) {
3392
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3393
+				$group_by_array = array();
3394
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3395
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3396
+				}
3397
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3398
+			} elseif (! empty ($query_params['group_by'])) {
3399
+				$query_object->set_group_by_sql(
3400
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3401
+				);
3402
+			}
3403
+		}
3404
+		//set having
3405
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3406
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3407
+		}
3408
+		//now, just verify they didn't pass anything wack
3409
+		foreach ($query_params as $query_key => $query_value) {
3410
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3411
+				throw new EE_Error(
3412
+					sprintf(
3413
+						__(
3414
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3415
+							'event_espresso'
3416
+						),
3417
+						$query_key,
3418
+						get_class($this),
3419
+						//						print_r( $this->_allowed_query_params, TRUE )
3420
+						implode(',', $this->_allowed_query_params)
3421
+					)
3422
+				);
3423
+			}
3424
+		}
3425
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3426
+		if (empty($main_model_join_sql)) {
3427
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3428
+		}
3429
+		return $query_object;
3430
+	}
3431
+
3432
+
3433
+
3434
+	/**
3435
+	 * Gets the where conditions that should be imposed on the query based on the
3436
+	 * context (eg reading frontend, backend, edit or delete).
3437
+	 *
3438
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3439
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3440
+	 * @throws \EE_Error
3441
+	 */
3442
+	public function caps_where_conditions($context = self::caps_read)
3443
+	{
3444
+		EEM_Base::verify_is_valid_cap_context($context);
3445
+		$cap_where_conditions = array();
3446
+		$cap_restrictions = $this->caps_missing($context);
3447
+		/**
3448
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3449
+		 */
3450
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3451
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3452
+				$restriction_if_no_cap->get_default_where_conditions());
3453
+		}
3454
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3455
+			$cap_restrictions);
3456
+	}
3457
+
3458
+
3459
+
3460
+	/**
3461
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3462
+	 * otherwise throws an exception
3463
+	 *
3464
+	 * @param string $should_be_order_string
3465
+	 * @return string either ASC, asc, DESC or desc
3466
+	 * @throws EE_Error
3467
+	 */
3468
+	private function _extract_order($should_be_order_string)
3469
+	{
3470
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3471
+			return $should_be_order_string;
3472
+		} else {
3473
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3474
+				"event_espresso"), get_class($this), $should_be_order_string));
3475
+		}
3476
+	}
3477
+
3478
+
3479
+
3480
+	/**
3481
+	 * Looks at all the models which are included in this query, and asks each
3482
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3483
+	 * so they can be merged
3484
+	 *
3485
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3486
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3487
+	 *                                                                  'none' means NO default where conditions will
3488
+	 *                                                                  be used AT ALL during this query.
3489
+	 *                                                                  'other_models_only' means default where
3490
+	 *                                                                  conditions from other models will be used, but
3491
+	 *                                                                  not for this primary model. 'all', the default,
3492
+	 *                                                                  means default where conditions will apply as
3493
+	 *                                                                  normal
3494
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3495
+	 * @throws EE_Error
3496
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3497
+	 */
3498
+	private function _get_default_where_conditions_for_models_in_query(
3499
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3500
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3501
+		$where_query_params = array()
3502
+	) {
3503
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3504
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3505
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3506
+				"event_espresso"), $use_default_where_conditions,
3507
+				implode(", ", $allowed_used_default_where_conditions_values)));
3508
+		}
3509
+		$universal_query_params = array();
3510
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3511
+			$universal_query_params = $this->_get_default_where_conditions();
3512
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3513
+			$universal_query_params = $this->_get_minimum_where_conditions();
3514
+		}
3515
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3516
+			$related_model = $this->get_related_model_obj($model_name);
3517
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3518
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3519
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3520
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3521
+			} else {
3522
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3523
+				continue;
3524
+			}
3525
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3526
+				$related_model_universal_where_params,
3527
+				$where_query_params,
3528
+				$related_model,
3529
+				$model_relation_path
3530
+			);
3531
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3532
+				$universal_query_params,
3533
+				$overrides
3534
+			);
3535
+		}
3536
+		return $universal_query_params;
3537
+	}
3538
+
3539
+
3540
+
3541
+	/**
3542
+	 * Determines whether or not we should use default where conditions for the model in question
3543
+	 * (this model, or other related models).
3544
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3545
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3546
+	 * We should use default where conditions on related models when they requested to use default where conditions
3547
+	 * on all models, or specifically just on other related models
3548
+	 * @param      $default_where_conditions_value
3549
+	 * @param bool $for_this_model false means this is for OTHER related models
3550
+	 * @return bool
3551
+	 */
3552
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3553
+	{
3554
+		return (
3555
+				   $for_this_model
3556
+				   && in_array(
3557
+					   $default_where_conditions_value,
3558
+					   array(
3559
+						   EEM_Base::default_where_conditions_all,
3560
+						   EEM_Base::default_where_conditions_this_only,
3561
+						   EEM_Base::default_where_conditions_minimum_others,
3562
+					   ),
3563
+					   true
3564
+				   )
3565
+			   )
3566
+			   || (
3567
+				   ! $for_this_model
3568
+				   && in_array(
3569
+					   $default_where_conditions_value,
3570
+					   array(
3571
+						   EEM_Base::default_where_conditions_all,
3572
+						   EEM_Base::default_where_conditions_others_only,
3573
+					   ),
3574
+					   true
3575
+				   )
3576
+			   );
3577
+	}
3578
+
3579
+	/**
3580
+	 * Determines whether or not we should use default minimum conditions for the model in question
3581
+	 * (this model, or other related models).
3582
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3583
+	 * where conditions.
3584
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3585
+	 * on this model or others
3586
+	 * @param      $default_where_conditions_value
3587
+	 * @param bool $for_this_model false means this is for OTHER related models
3588
+	 * @return bool
3589
+	 */
3590
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3591
+	{
3592
+		return (
3593
+				   $for_this_model
3594
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3595
+			   )
3596
+			   || (
3597
+				   ! $for_this_model
3598
+				   && in_array(
3599
+					   $default_where_conditions_value,
3600
+					   array(
3601
+						   EEM_Base::default_where_conditions_minimum_others,
3602
+						   EEM_Base::default_where_conditions_minimum_all,
3603
+					   ),
3604
+					   true
3605
+				   )
3606
+			   );
3607
+	}
3608
+
3609
+
3610
+	/**
3611
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3612
+	 * then we also add a special where condition which allows for that model's primary key
3613
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3614
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3615
+	 *
3616
+	 * @param array    $default_where_conditions
3617
+	 * @param array    $provided_where_conditions
3618
+	 * @param EEM_Base $model
3619
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3620
+	 * @return array like EEM_Base::get_all's $query_params[0]
3621
+	 * @throws \EE_Error
3622
+	 */
3623
+	private function _override_defaults_or_make_null_friendly(
3624
+		$default_where_conditions,
3625
+		$provided_where_conditions,
3626
+		$model,
3627
+		$model_relation_path
3628
+	) {
3629
+		$null_friendly_where_conditions = array();
3630
+		$none_overridden = true;
3631
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3632
+		foreach ($default_where_conditions as $key => $val) {
3633
+			if (isset($provided_where_conditions[$key])) {
3634
+				$none_overridden = false;
3635
+			} else {
3636
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3637
+			}
3638
+		}
3639
+		if ($none_overridden && $default_where_conditions) {
3640
+			if ($model->has_primary_key_field()) {
3641
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3642
+																				. "."
3643
+																				. $model->primary_key_name()] = array('IS NULL');
3644
+			}/*else{
3645 3645
 				//@todo NO PK, use other defaults
3646 3646
 			}*/
3647
-        }
3648
-        return $null_friendly_where_conditions;
3649
-    }
3650
-
3651
-
3652
-
3653
-    /**
3654
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3655
-     * default where conditions on all get_all, update, and delete queries done by this model.
3656
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3657
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3658
-     *
3659
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3660
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3661
-     */
3662
-    private function _get_default_where_conditions($model_relation_path = null)
3663
-    {
3664
-        if ($this->_ignore_where_strategy) {
3665
-            return array();
3666
-        }
3667
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3668
-    }
3669
-
3670
-
3671
-
3672
-    /**
3673
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3674
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3675
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3676
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3677
-     * Similar to _get_default_where_conditions
3678
-     *
3679
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3680
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3681
-     */
3682
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3683
-    {
3684
-        if ($this->_ignore_where_strategy) {
3685
-            return array();
3686
-        }
3687
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3688
-    }
3689
-
3690
-
3691
-
3692
-    /**
3693
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3694
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3695
-     *
3696
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3697
-     * @return string
3698
-     * @throws \EE_Error
3699
-     */
3700
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3701
-    {
3702
-        $selects = $this->_get_columns_to_select_for_this_model();
3703
-        foreach (
3704
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3705
-            $name_of_other_model_included
3706
-        ) {
3707
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3708
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3709
-            foreach ($other_model_selects as $key => $value) {
3710
-                $selects[] = $value;
3711
-            }
3712
-        }
3713
-        return implode(", ", $selects);
3714
-    }
3715
-
3716
-
3717
-
3718
-    /**
3719
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3720
-     * So that's going to be the columns for all the fields on the model
3721
-     *
3722
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3723
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3724
-     */
3725
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3726
-    {
3727
-        $fields = $this->field_settings();
3728
-        $selects = array();
3729
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3730
-            $this->get_this_model_name());
3731
-        foreach ($fields as $field_obj) {
3732
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3733
-                         . $field_obj->get_table_alias()
3734
-                         . "."
3735
-                         . $field_obj->get_table_column()
3736
-                         . " AS '"
3737
-                         . $table_alias_with_model_relation_chain_prefix
3738
-                         . $field_obj->get_table_alias()
3739
-                         . "."
3740
-                         . $field_obj->get_table_column()
3741
-                         . "'";
3742
-        }
3743
-        //make sure we are also getting the PKs of each table
3744
-        $tables = $this->get_tables();
3745
-        if (count($tables) > 1) {
3746
-            foreach ($tables as $table_obj) {
3747
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3748
-                                       . $table_obj->get_fully_qualified_pk_column();
3749
-                if (! in_array($qualified_pk_column, $selects)) {
3750
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3751
-                }
3752
-            }
3753
-        }
3754
-        return $selects;
3755
-    }
3756
-
3757
-
3758
-
3759
-    /**
3760
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3761
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3762
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3763
-     * SQL for joining, and the data types
3764
-     *
3765
-     * @param null|string                 $original_query_param
3766
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3767
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3768
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3769
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3770
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3771
-     *                                                          or 'Registration's
3772
-     * @param string                      $original_query_param what it originally was (eg
3773
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3774
-     *                                                          matches $query_param
3775
-     * @throws EE_Error
3776
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3777
-     */
3778
-    private function _extract_related_model_info_from_query_param(
3779
-        $query_param,
3780
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3781
-        $query_param_type,
3782
-        $original_query_param = null
3783
-    ) {
3784
-        if ($original_query_param === null) {
3785
-            $original_query_param = $query_param;
3786
-        }
3787
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3788
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3789
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3790
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3791
-        //check to see if we have a field on this model
3792
-        $this_model_fields = $this->field_settings(true);
3793
-        if (array_key_exists($query_param, $this_model_fields)) {
3794
-            if ($allow_fields) {
3795
-                return;
3796
-            } else {
3797
-                throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3798
-                    "event_espresso"),
3799
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3800
-            }
3801
-        } //check if this is a special logic query param
3802
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3803
-            if ($allow_logic_query_params) {
3804
-                return;
3805
-            } else {
3806
-                throw new EE_Error(
3807
-                    sprintf(
3808
-                        __('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',
3809
-                            'event_espresso'),
3810
-                        implode('", "', $this->_logic_query_param_keys),
3811
-                        $query_param,
3812
-                        get_class($this),
3813
-                        '<br />',
3814
-                        "\t"
3815
-                        . ' $passed_in_query_info = <pre>'
3816
-                        . print_r($passed_in_query_info, true)
3817
-                        . '</pre>'
3818
-                        . "\n\t"
3819
-                        . ' $query_param_type = '
3820
-                        . $query_param_type
3821
-                        . "\n\t"
3822
-                        . ' $original_query_param = '
3823
-                        . $original_query_param
3824
-                    )
3825
-                );
3826
-            }
3827
-        } //check if it's a custom selection
3828
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3829
-            return;
3830
-        }
3831
-        //check if has a model name at the beginning
3832
-        //and
3833
-        //check if it's a field on a related model
3834
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3835
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3836
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3837
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3838
-                if ($query_param === '') {
3839
-                    //nothing left to $query_param
3840
-                    //we should actually end in a field name, not a model like this!
3841
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3842
-                        "event_espresso"),
3843
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3844
-                } else {
3845
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3846
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3847
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3848
-                    return;
3849
-                }
3850
-            } elseif ($query_param === $valid_related_model_name) {
3851
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3852
-                return;
3853
-            }
3854
-        }
3855
-        //ok so $query_param didn't start with a model name
3856
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3857
-        //it's wack, that's what it is
3858
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3859
-            "event_espresso"),
3860
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3861
-    }
3862
-
3863
-
3864
-
3865
-    /**
3866
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3867
-     * and store it on $passed_in_query_info
3868
-     *
3869
-     * @param string                      $model_name
3870
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3871
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3872
-     *                                                          model and $model_name. Eg, if we are querying Event,
3873
-     *                                                          and are adding a join to 'Payment' with the original
3874
-     *                                                          query param key
3875
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3876
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3877
-     *                                                          Payment wants to add default query params so that it
3878
-     *                                                          will know what models to prepend onto its default query
3879
-     *                                                          params or in case it wants to rename tables (in case
3880
-     *                                                          there are multiple joins to the same table)
3881
-     * @return void
3882
-     * @throws \EE_Error
3883
-     */
3884
-    private function _add_join_to_model(
3885
-        $model_name,
3886
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3887
-        $original_query_param
3888
-    ) {
3889
-        $relation_obj = $this->related_settings_for($model_name);
3890
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3891
-        //check if the relation is HABTM, because then we're essentially doing two joins
3892
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3893
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3894
-            $join_model_obj = $relation_obj->get_join_model();
3895
-            //replace the model specified with the join model for this relation chain, whi
3896
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3897
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3898
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3899
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3900
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3901
-            $passed_in_query_info->merge($new_query_info);
3902
-        }
3903
-        //now just join to the other table pointed to by the relation object, and add its data types
3904
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3905
-            array($model_relation_chain => $model_name),
3906
-            $relation_obj->get_join_statement($model_relation_chain));
3907
-        $passed_in_query_info->merge($new_query_info);
3908
-    }
3909
-
3910
-
3911
-
3912
-    /**
3913
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3914
-     *
3915
-     * @param array $where_params like EEM_Base::get_all
3916
-     * @return string of SQL
3917
-     * @throws \EE_Error
3918
-     */
3919
-    private function _construct_where_clause($where_params)
3920
-    {
3921
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3922
-        if ($SQL) {
3923
-            return " WHERE " . $SQL;
3924
-        } else {
3925
-            return '';
3926
-        }
3927
-    }
3928
-
3929
-
3930
-
3931
-    /**
3932
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3933
-     * and should be passed HAVING parameters, not WHERE parameters
3934
-     *
3935
-     * @param array $having_params
3936
-     * @return string
3937
-     * @throws \EE_Error
3938
-     */
3939
-    private function _construct_having_clause($having_params)
3940
-    {
3941
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3942
-        if ($SQL) {
3943
-            return " HAVING " . $SQL;
3944
-        } else {
3945
-            return '';
3946
-        }
3947
-    }
3948
-
3949
-
3950
-    /**
3951
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3952
-     * Event_Meta.meta_value = 'foo'))"
3953
-     *
3954
-     * @param array  $where_params see EEM_Base::get_all for documentation
3955
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3956
-     * @throws EE_Error
3957
-     * @return string of SQL
3958
-     */
3959
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3960
-    {
3961
-        $where_clauses = array();
3962
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3963
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3964
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3965
-                switch ($query_param) {
3966
-                    case 'not':
3967
-                    case 'NOT':
3968
-                        $where_clauses[] = "! ("
3969
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3970
-                                $glue)
3971
-                                           . ")";
3972
-                        break;
3973
-                    case 'and':
3974
-                    case 'AND':
3975
-                        $where_clauses[] = " ("
3976
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3977
-                                ' AND ')
3978
-                                           . ")";
3979
-                        break;
3980
-                    case 'or':
3981
-                    case 'OR':
3982
-                        $where_clauses[] = " ("
3983
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3984
-                                ' OR ')
3985
-                                           . ")";
3986
-                        break;
3987
-                }
3988
-            } else {
3989
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3990
-                //if it's not a normal field, maybe it's a custom selection?
3991
-                if (! $field_obj) {
3992
-                    if (isset($this->_custom_selections[$query_param][1])) {
3993
-                        $field_obj = $this->_custom_selections[$query_param][1];
3994
-                    } else {
3995
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3996
-                            "event_espresso"), $query_param));
3997
-                    }
3998
-                }
3999
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4000
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4001
-            }
4002
-        }
4003
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4004
-    }
4005
-
4006
-
4007
-
4008
-    /**
4009
-     * Takes the input parameter and extract the table name (alias) and column name
4010
-     *
4011
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4012
-     * @throws EE_Error
4013
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4014
-     */
4015
-    private function _deduce_column_name_from_query_param($query_param)
4016
-    {
4017
-        $field = $this->_deduce_field_from_query_param($query_param);
4018
-        if ($field) {
4019
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4020
-                $query_param);
4021
-            return $table_alias_prefix . $field->get_qualified_column();
4022
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4023
-            //maybe it's custom selection item?
4024
-            //if so, just use it as the "column name"
4025
-            return $query_param;
4026
-        } else {
4027
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4028
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4029
-        }
4030
-    }
4031
-
4032
-
4033
-
4034
-    /**
4035
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4036
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4037
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4038
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4039
-     *
4040
-     * @param string $condition_query_param_key
4041
-     * @return string
4042
-     */
4043
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4044
-    {
4045
-        $pos_of_star = strpos($condition_query_param_key, '*');
4046
-        if ($pos_of_star === false) {
4047
-            return $condition_query_param_key;
4048
-        } else {
4049
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4050
-            return $condition_query_param_sans_star;
4051
-        }
4052
-    }
4053
-
4054
-
4055
-
4056
-    /**
4057
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4058
-     *
4059
-     * @param                            mixed      array | string    $op_and_value
4060
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4061
-     * @throws EE_Error
4062
-     * @return string
4063
-     */
4064
-    private function _construct_op_and_value($op_and_value, $field_obj)
4065
-    {
4066
-        if (is_array($op_and_value)) {
4067
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4068
-            if (! $operator) {
4069
-                $php_array_like_string = array();
4070
-                foreach ($op_and_value as $key => $value) {
4071
-                    $php_array_like_string[] = "$key=>$value";
4072
-                }
4073
-                throw new EE_Error(
4074
-                    sprintf(
4075
-                        __(
4076
-                            "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))",
4077
-                            "event_espresso"
4078
-                        ),
4079
-                        implode(",", $php_array_like_string)
4080
-                    )
4081
-                );
4082
-            }
4083
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4084
-        } else {
4085
-            $operator = '=';
4086
-            $value = $op_and_value;
4087
-        }
4088
-        //check to see if the value is actually another field
4089
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4090
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4091
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4092
-            //in this case, the value should be an array, or at least a comma-separated list
4093
-            //it will need to handle a little differently
4094
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4095
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4096
-            return $operator . SP . $cleaned_value;
4097
-        } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4098
-            //the value should be an array with count of two.
4099
-            if (count($value) !== 2) {
4100
-                throw new EE_Error(
4101
-                    sprintf(
4102
-                        __(
4103
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4104
-                            'event_espresso'
4105
-                        ),
4106
-                        "BETWEEN"
4107
-                    )
4108
-                );
4109
-            }
4110
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4111
-            return $operator . SP . $cleaned_value;
4112
-        } elseif (in_array($operator, $this->valid_null_style_operators())) {
4113
-            if ($value !== null) {
4114
-                throw new EE_Error(
4115
-                    sprintf(
4116
-                        __(
4117
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4118
-                            "event_espresso"
4119
-                        ),
4120
-                        $value,
4121
-                        $operator
4122
-                    )
4123
-                );
4124
-            }
4125
-            return $operator;
4126
-        } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4127
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4128
-            //remove other junk. So just treat it as a string.
4129
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4130
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4132
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4133
-            throw new EE_Error(
4134
-                sprintf(
4135
-                    __(
4136
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4137
-                        'event_espresso'
4138
-                    ),
4139
-                    $operator,
4140
-                    $operator
4141
-                )
4142
-            );
4143
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4144
-            throw new EE_Error(
4145
-                sprintf(
4146
-                    __(
4147
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4148
-                        'event_espresso'
4149
-                    ),
4150
-                    $operator,
4151
-                    $operator
4152
-                )
4153
-            );
4154
-        } else {
4155
-            throw new EE_Error(
4156
-                sprintf(
4157
-                    __(
4158
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4159
-                        "event_espresso"
4160
-                    ),
4161
-                    http_build_query($op_and_value)
4162
-                )
4163
-            );
4164
-        }
4165
-    }
4166
-
4167
-
4168
-
4169
-    /**
4170
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4171
-     *
4172
-     * @param array                      $values
4173
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4174
-     *                                              '%s'
4175
-     * @return string
4176
-     * @throws \EE_Error
4177
-     */
4178
-    public function _construct_between_value($values, $field_obj)
4179
-    {
4180
-        $cleaned_values = array();
4181
-        foreach ($values as $value) {
4182
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4183
-        }
4184
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4185
-    }
4186
-
4187
-
4188
-
4189
-    /**
4190
-     * Takes an array or a comma-separated list of $values and cleans them
4191
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4192
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4193
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4194
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4195
-     *
4196
-     * @param mixed                      $values    array or comma-separated string
4197
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4198
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4199
-     * @throws \EE_Error
4200
-     */
4201
-    public function _construct_in_value($values, $field_obj)
4202
-    {
4203
-        //check if the value is a CSV list
4204
-        if (is_string($values)) {
4205
-            //in which case, turn it into an array
4206
-            $values = explode(",", $values);
4207
-        }
4208
-        $cleaned_values = array();
4209
-        foreach ($values as $value) {
4210
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4211
-        }
4212
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4213
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4214
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4215
-        if (empty($cleaned_values)) {
4216
-            $all_fields = $this->field_settings();
4217
-            $a_field = array_shift($all_fields);
4218
-            $main_table = $this->_get_main_table();
4219
-            $cleaned_values[] = "SELECT "
4220
-                                . $a_field->get_table_column()
4221
-                                . " FROM "
4222
-                                . $main_table->get_table_name()
4223
-                                . " WHERE FALSE";
4224
-        }
4225
-        return "(" . implode(",", $cleaned_values) . ")";
4226
-    }
4227
-
4228
-
4229
-
4230
-    /**
4231
-     * @param mixed                      $value
4232
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4233
-     * @throws EE_Error
4234
-     * @return false|null|string
4235
-     */
4236
-    private function _wpdb_prepare_using_field($value, $field_obj)
4237
-    {
4238
-        /** @type WPDB $wpdb */
4239
-        global $wpdb;
4240
-        if ($field_obj instanceof EE_Model_Field_Base) {
4241
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4242
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4243
-        } else {//$field_obj should really just be a data type
4244
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4245
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4246
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4247
-            }
4248
-            return $wpdb->prepare($field_obj, $value);
4249
-        }
4250
-    }
4251
-
4252
-
4253
-
4254
-    /**
4255
-     * Takes the input parameter and finds the model field that it indicates.
4256
-     *
4257
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4258
-     * @throws EE_Error
4259
-     * @return EE_Model_Field_Base
4260
-     */
4261
-    protected function _deduce_field_from_query_param($query_param_name)
4262
-    {
4263
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4264
-        //which will help us find the database table and column
4265
-        $query_param_parts = explode(".", $query_param_name);
4266
-        if (empty($query_param_parts)) {
4267
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4268
-                'event_espresso'), $query_param_name));
4269
-        }
4270
-        $number_of_parts = count($query_param_parts);
4271
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4272
-        if ($number_of_parts === 1) {
4273
-            $field_name = $last_query_param_part;
4274
-            $model_obj = $this;
4275
-        } else {// $number_of_parts >= 2
4276
-            //the last part is the column name, and there are only 2parts. therefore...
4277
-            $field_name = $last_query_param_part;
4278
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4279
-        }
4280
-        try {
4281
-            return $model_obj->field_settings_for($field_name);
4282
-        } catch (EE_Error $e) {
4283
-            return null;
4284
-        }
4285
-    }
4286
-
4287
-
4288
-
4289
-    /**
4290
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4291
-     * alias and column which corresponds to it
4292
-     *
4293
-     * @param string $field_name
4294
-     * @throws EE_Error
4295
-     * @return string
4296
-     */
4297
-    public function _get_qualified_column_for_field($field_name)
4298
-    {
4299
-        $all_fields = $this->field_settings();
4300
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4301
-        if ($field) {
4302
-            return $field->get_qualified_column();
4303
-        } else {
4304
-            throw new EE_Error(sprintf(__("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.",
4305
-                'event_espresso'), $field_name, get_class($this)));
4306
-        }
4307
-    }
4308
-
4309
-
4310
-
4311
-    /**
4312
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4313
-     * Example usage:
4314
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4315
-     *      array(),
4316
-     *      ARRAY_A,
4317
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4318
-     *  );
4319
-     * is equivalent to
4320
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4321
-     * and
4322
-     *  EEM_Event::instance()->get_all_wpdb_results(
4323
-     *      array(
4324
-     *          array(
4325
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4326
-     *          ),
4327
-     *          ARRAY_A,
4328
-     *          implode(
4329
-     *              ', ',
4330
-     *              array_merge(
4331
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4332
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4333
-     *              )
4334
-     *          )
4335
-     *      )
4336
-     *  );
4337
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4338
-     *
4339
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4340
-     *                                            and the one whose fields you are selecting for example: when querying
4341
-     *                                            tickets model and selecting fields from the tickets model you would
4342
-     *                                            leave this parameter empty, because no models are needed to join
4343
-     *                                            between the queried model and the selected one. Likewise when
4344
-     *                                            querying the datetime model and selecting fields from the tickets
4345
-     *                                            model, it would also be left empty, because there is a direct
4346
-     *                                            relation from datetimes to tickets, so no model is needed to join
4347
-     *                                            them together. However, when querying from the event model and
4348
-     *                                            selecting fields from the ticket model, you should provide the string
4349
-     *                                            'Datetime', indicating that the event model must first join to the
4350
-     *                                            datetime model in order to find its relation to ticket model.
4351
-     *                                            Also, when querying from the venue model and selecting fields from
4352
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4353
-     *                                            indicating you need to join the venue model to the event model,
4354
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4355
-     *                                            This string is used to deduce the prefix that gets added onto the
4356
-     *                                            models' tables qualified columns
4357
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4358
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4359
-     *                                            qualified column names
4360
-     * @return array|string
4361
-     */
4362
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4363
-    {
4364
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4365
-        $qualified_columns = array();
4366
-        foreach ($this->field_settings() as $field_name => $field) {
4367
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4368
-        }
4369
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4370
-    }
4371
-
4372
-
4373
-
4374
-    /**
4375
-     * constructs the select use on special limit joins
4376
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4377
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4378
-     * (as that is typically where the limits would be set).
4379
-     *
4380
-     * @param  string       $table_alias The table the select is being built for
4381
-     * @param  mixed|string $limit       The limit for this select
4382
-     * @return string                The final select join element for the query.
4383
-     */
4384
-    public function _construct_limit_join_select($table_alias, $limit)
4385
-    {
4386
-        $SQL = '';
4387
-        foreach ($this->_tables as $table_obj) {
4388
-            if ($table_obj instanceof EE_Primary_Table) {
4389
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4390
-                    ? $table_obj->get_select_join_limit($limit)
4391
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4392
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4393
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4394
-                    ? $table_obj->get_select_join_limit_join($limit)
4395
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4396
-            }
4397
-        }
4398
-        return $SQL;
4399
-    }
4400
-
4401
-
4402
-
4403
-    /**
4404
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4405
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4406
-     *
4407
-     * @return string SQL
4408
-     * @throws \EE_Error
4409
-     */
4410
-    public function _construct_internal_join()
4411
-    {
4412
-        $SQL = $this->_get_main_table()->get_table_sql();
4413
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4414
-        return $SQL;
4415
-    }
4416
-
4417
-
4418
-
4419
-    /**
4420
-     * Constructs the SQL for joining all the tables on this model.
4421
-     * Normally $alias should be the primary table's alias, but in cases where
4422
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4423
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4424
-     * alias, this will construct SQL like:
4425
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4426
-     * With $alias being a secondary table's alias, this will construct SQL like:
4427
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4428
-     *
4429
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4430
-     * @return string
4431
-     */
4432
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4433
-    {
4434
-        $SQL = '';
4435
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4436
-        foreach ($this->_tables as $table_obj) {
4437
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4438
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4439
-                    //so we're joining to this table, meaning the table is already in
4440
-                    //the FROM statement, BUT the primary table isn't. So we want
4441
-                    //to add the inverse join sql
4442
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4443
-                } else {
4444
-                    //just add a regular JOIN to this table from the primary table
4445
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4446
-                }
4447
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4448
-        }
4449
-        return $SQL;
4450
-    }
4451
-
4452
-
4453
-
4454
-    /**
4455
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4456
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4457
-     * their data type (eg, '%s', '%d', etc)
4458
-     *
4459
-     * @return array
4460
-     */
4461
-    public function _get_data_types()
4462
-    {
4463
-        $data_types = array();
4464
-        foreach ($this->field_settings() as $field_obj) {
4465
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4466
-            /** @var $field_obj EE_Model_Field_Base */
4467
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4468
-        }
4469
-        return $data_types;
4470
-    }
4471
-
4472
-
4473
-
4474
-    /**
4475
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4476
-     *
4477
-     * @param string $model_name
4478
-     * @throws EE_Error
4479
-     * @return EEM_Base
4480
-     */
4481
-    public function get_related_model_obj($model_name)
4482
-    {
4483
-        $model_classname = "EEM_" . $model_name;
4484
-        if (! class_exists($model_classname)) {
4485
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4486
-                'event_espresso'), $model_name, $model_classname));
4487
-        }
4488
-        return call_user_func($model_classname . "::instance");
4489
-    }
4490
-
4491
-
4492
-
4493
-    /**
4494
-     * Returns the array of EE_ModelRelations for this model.
4495
-     *
4496
-     * @return EE_Model_Relation_Base[]
4497
-     */
4498
-    public function relation_settings()
4499
-    {
4500
-        return $this->_model_relations;
4501
-    }
4502
-
4503
-
4504
-
4505
-    /**
4506
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4507
-     * because without THOSE models, this model probably doesn't have much purpose.
4508
-     * (Eg, without an event, datetimes have little purpose.)
4509
-     *
4510
-     * @return EE_Belongs_To_Relation[]
4511
-     */
4512
-    public function belongs_to_relations()
4513
-    {
4514
-        $belongs_to_relations = array();
4515
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4516
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4517
-                $belongs_to_relations[$model_name] = $relation_obj;
4518
-            }
4519
-        }
4520
-        return $belongs_to_relations;
4521
-    }
4522
-
4523
-
4524
-
4525
-    /**
4526
-     * Returns the specified EE_Model_Relation, or throws an exception
4527
-     *
4528
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4529
-     * @throws EE_Error
4530
-     * @return EE_Model_Relation_Base
4531
-     */
4532
-    public function related_settings_for($relation_name)
4533
-    {
4534
-        $relatedModels = $this->relation_settings();
4535
-        if (! array_key_exists($relation_name, $relatedModels)) {
4536
-            throw new EE_Error(
4537
-                sprintf(
4538
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4539
-                        'event_espresso'),
4540
-                    $relation_name,
4541
-                    $this->_get_class_name(),
4542
-                    implode(', ', array_keys($relatedModels))
4543
-                )
4544
-            );
4545
-        }
4546
-        return $relatedModels[$relation_name];
4547
-    }
4548
-
4549
-
4550
-
4551
-    /**
4552
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4553
-     * fields
4554
-     *
4555
-     * @param string $fieldName
4556
-     * @param boolean $include_db_only_fields
4557
-     * @throws EE_Error
4558
-     * @return EE_Model_Field_Base
4559
-     */
4560
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4561
-    {
4562
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4563
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4564
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4565
-                get_class($this)));
4566
-        }
4567
-        return $fieldSettings[$fieldName];
4568
-    }
4569
-
4570
-
4571
-
4572
-    /**
4573
-     * Checks if this field exists on this model
4574
-     *
4575
-     * @param string $fieldName a key in the model's _field_settings array
4576
-     * @return boolean
4577
-     */
4578
-    public function has_field($fieldName)
4579
-    {
4580
-        $fieldSettings = $this->field_settings(true);
4581
-        if (isset($fieldSettings[$fieldName])) {
4582
-            return true;
4583
-        } else {
4584
-            return false;
4585
-        }
4586
-    }
4587
-
4588
-
4589
-
4590
-    /**
4591
-     * Returns whether or not this model has a relation to the specified model
4592
-     *
4593
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4594
-     * @return boolean
4595
-     */
4596
-    public function has_relation($relation_name)
4597
-    {
4598
-        $relations = $this->relation_settings();
4599
-        if (isset($relations[$relation_name])) {
4600
-            return true;
4601
-        } else {
4602
-            return false;
4603
-        }
4604
-    }
4605
-
4606
-
4607
-
4608
-    /**
4609
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4610
-     * Eg, on EE_Answer that would be ANS_ID field object
4611
-     *
4612
-     * @param $field_obj
4613
-     * @return boolean
4614
-     */
4615
-    public function is_primary_key_field($field_obj)
4616
-    {
4617
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4618
-    }
4619
-
4620
-
4621
-
4622
-    /**
4623
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4624
-     * Eg, on EE_Answer that would be ANS_ID field object
4625
-     *
4626
-     * @return EE_Model_Field_Base
4627
-     * @throws EE_Error
4628
-     */
4629
-    public function get_primary_key_field()
4630
-    {
4631
-        if ($this->_primary_key_field === null) {
4632
-            foreach ($this->field_settings(true) as $field_obj) {
4633
-                if ($this->is_primary_key_field($field_obj)) {
4634
-                    $this->_primary_key_field = $field_obj;
4635
-                    break;
4636
-                }
4637
-            }
4638
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4639
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4640
-                    get_class($this)));
4641
-            }
4642
-        }
4643
-        return $this->_primary_key_field;
4644
-    }
4645
-
4646
-
4647
-
4648
-    /**
4649
-     * Returns whether or not not there is a primary key on this model.
4650
-     * Internally does some caching.
4651
-     *
4652
-     * @return boolean
4653
-     */
4654
-    public function has_primary_key_field()
4655
-    {
4656
-        if ($this->_has_primary_key_field === null) {
4657
-            try {
4658
-                $this->get_primary_key_field();
4659
-                $this->_has_primary_key_field = true;
4660
-            } catch (EE_Error $e) {
4661
-                $this->_has_primary_key_field = false;
4662
-            }
4663
-        }
4664
-        return $this->_has_primary_key_field;
4665
-    }
4666
-
4667
-
4668
-
4669
-    /**
4670
-     * Finds the first field of type $field_class_name.
4671
-     *
4672
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4673
-     *                                 EE_Foreign_Key_Field, etc
4674
-     * @return EE_Model_Field_Base or null if none is found
4675
-     */
4676
-    public function get_a_field_of_type($field_class_name)
4677
-    {
4678
-        foreach ($this->field_settings() as $field) {
4679
-            if ($field instanceof $field_class_name) {
4680
-                return $field;
4681
-            }
4682
-        }
4683
-        return null;
4684
-    }
4685
-
4686
-
4687
-
4688
-    /**
4689
-     * Gets a foreign key field pointing to model.
4690
-     *
4691
-     * @param string $model_name eg Event, Registration, not EEM_Event
4692
-     * @return EE_Foreign_Key_Field_Base
4693
-     * @throws EE_Error
4694
-     */
4695
-    public function get_foreign_key_to($model_name)
4696
-    {
4697
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698
-            foreach ($this->field_settings() as $field) {
4699
-                if (
4700
-                    $field instanceof EE_Foreign_Key_Field_Base
4701
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4702
-                ) {
4703
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4704
-                    break;
4705
-                }
4706
-            }
4707
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4708
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4709
-                    'event_espresso'), $model_name, get_class($this)));
4710
-            }
4711
-        }
4712
-        return $this->_cache_foreign_key_to_fields[$model_name];
4713
-    }
4714
-
4715
-
4716
-
4717
-    /**
4718
-     * Gets the actual table for the table alias
4719
-     *
4720
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4721
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4722
-     *                            Either one works
4723
-     * @return EE_Table_Base
4724
-     */
4725
-    public function get_table_for_alias($table_alias)
4726
-    {
4727
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4728
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4729
-    }
4730
-
4731
-
4732
-
4733
-    /**
4734
-     * Returns a flat array of all field son this model, instead of organizing them
4735
-     * by table_alias as they are in the constructor.
4736
-     *
4737
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4738
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4739
-     */
4740
-    public function field_settings($include_db_only_fields = false)
4741
-    {
4742
-        if ($include_db_only_fields) {
4743
-            if ($this->_cached_fields === null) {
4744
-                $this->_cached_fields = array();
4745
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4746
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4747
-                        $this->_cached_fields[$field_name] = $field_obj;
4748
-                    }
4749
-                }
4750
-            }
4751
-            return $this->_cached_fields;
4752
-        } else {
4753
-            if ($this->_cached_fields_non_db_only === null) {
4754
-                $this->_cached_fields_non_db_only = array();
4755
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4756
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4757
-                        /** @var $field_obj EE_Model_Field_Base */
4758
-                        if (! $field_obj->is_db_only_field()) {
4759
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4760
-                        }
4761
-                    }
4762
-                }
4763
-            }
4764
-            return $this->_cached_fields_non_db_only;
4765
-        }
4766
-    }
4767
-
4768
-
4769
-
4770
-    /**
4771
-     *        cycle though array of attendees and create objects out of each item
4772
-     *
4773
-     * @access        private
4774
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4775
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4776
-     *                           numerically indexed)
4777
-     * @throws \EE_Error
4778
-     */
4779
-    protected function _create_objects($rows = array())
4780
-    {
4781
-        $array_of_objects = array();
4782
-        if (empty($rows)) {
4783
-            return array();
4784
-        }
4785
-        $count_if_model_has_no_primary_key = 0;
4786
-        $has_primary_key = $this->has_primary_key_field();
4787
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4788
-        foreach ((array)$rows as $row) {
4789
-            if (empty($row)) {
4790
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4791
-                return array();
4792
-            }
4793
-            //check if we've already set this object in the results array,
4794
-            //in which case there's no need to process it further (again)
4795
-            if ($has_primary_key) {
4796
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4797
-                    $row,
4798
-                    $primary_key_field->get_qualified_column(),
4799
-                    $primary_key_field->get_table_column()
4800
-                );
4801
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4802
-                    continue;
4803
-                }
4804
-            }
4805
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4806
-            if (! $classInstance) {
4807
-                throw new EE_Error(
4808
-                    sprintf(
4809
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4810
-                        $this->get_this_model_name(),
4811
-                        http_build_query($row)
4812
-                    )
4813
-                );
4814
-            }
4815
-            //set the timezone on the instantiated objects
4816
-            $classInstance->set_timezone($this->_timezone);
4817
-            //make sure if there is any timezone setting present that we set the timezone for the object
4818
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4819
-            $array_of_objects[$key] = $classInstance;
4820
-            //also, for all the relations of type BelongsTo, see if we can cache
4821
-            //those related models
4822
-            //(we could do this for other relations too, but if there are conditions
4823
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4824
-            //so it requires a little more thought than just caching them immediately...)
4825
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4826
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4827
-                    //check if this model's INFO is present. If so, cache it on the model
4828
-                    $other_model = $relation_obj->get_other_model();
4829
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4830
-                    //if we managed to make a model object from the results, cache it on the main model object
4831
-                    if ($other_model_obj_maybe) {
4832
-                        //set timezone on these other model objects if they are present
4833
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4834
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4835
-                    }
4836
-                }
4837
-            }
4838
-        }
4839
-        return $array_of_objects;
4840
-    }
4841
-
4842
-
4843
-
4844
-    /**
4845
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4846
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4847
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4848
-     * object (as set in the model_field!).
4849
-     *
4850
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4851
-     */
4852
-    public function create_default_object()
4853
-    {
4854
-        $this_model_fields_and_values = array();
4855
-        //setup the row using default values;
4856
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4857
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4858
-        }
4859
-        $className = $this->_get_class_name();
4860
-        $classInstance = EE_Registry::instance()
4861
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4862
-        return $classInstance;
4863
-    }
4864
-
4865
-
4866
-
4867
-    /**
4868
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4869
-     *                             or an stdClass where each property is the name of a column,
4870
-     * @return EE_Base_Class
4871
-     * @throws \EE_Error
4872
-     */
4873
-    public function instantiate_class_from_array_or_object($cols_n_values)
4874
-    {
4875
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4876
-            $cols_n_values = get_object_vars($cols_n_values);
4877
-        }
4878
-        $primary_key = null;
4879
-        //make sure the array only has keys that are fields/columns on this model
4880
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4881
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4882
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4883
-        }
4884
-        $className = $this->_get_class_name();
4885
-        //check we actually found results that we can use to build our model object
4886
-        //if not, return null
4887
-        if ($this->has_primary_key_field()) {
4888
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4889
-                return null;
4890
-            }
4891
-        } else if ($this->unique_indexes()) {
4892
-            $first_column = reset($this_model_fields_n_values);
4893
-            if (empty($first_column)) {
4894
-                return null;
4895
-            }
4896
-        }
4897
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4898
-        if ($primary_key) {
4899
-            $classInstance = $this->get_from_entity_map($primary_key);
4900
-            if (! $classInstance) {
4901
-                $classInstance = EE_Registry::instance()
4902
-                                            ->load_class($className,
4903
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4904
-                // add this new object to the entity map
4905
-                $classInstance = $this->add_to_entity_map($classInstance);
4906
-            }
4907
-        } else {
4908
-            $classInstance = EE_Registry::instance()
4909
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4910
-                                            true, false);
4911
-        }
4912
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4913
-        $this->set_timezone($classInstance->get_timezone());
4914
-        return $classInstance;
4915
-    }
4916
-
4917
-
4918
-
4919
-    /**
4920
-     * Gets the model object from the  entity map if it exists
4921
-     *
4922
-     * @param int|string $id the ID of the model object
4923
-     * @return EE_Base_Class
4924
-     */
4925
-    public function get_from_entity_map($id)
4926
-    {
4927
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4928
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4929
-    }
4930
-
4931
-
4932
-
4933
-    /**
4934
-     * add_to_entity_map
4935
-     * Adds the object to the model's entity mappings
4936
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4937
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4938
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4939
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4940
-     *        then this method should be called immediately after the update query
4941
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4942
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4943
-     *
4944
-     * @param    EE_Base_Class $object
4945
-     * @throws EE_Error
4946
-     * @return \EE_Base_Class
4947
-     */
4948
-    public function add_to_entity_map(EE_Base_Class $object)
4949
-    {
4950
-        $className = $this->_get_class_name();
4951
-        if (! $object instanceof $className) {
4952
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4953
-                is_object($object) ? get_class($object) : $object, $className));
4954
-        }
4955
-        /** @var $object EE_Base_Class */
4956
-        if (! $object->ID()) {
4957
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4958
-                "event_espresso"), get_class($this)));
4959
-        }
4960
-        // double check it's not already there
4961
-        $classInstance = $this->get_from_entity_map($object->ID());
4962
-        if ($classInstance) {
4963
-            return $classInstance;
4964
-        } else {
4965
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4966
-            return $object;
4967
-        }
4968
-    }
4969
-
4970
-
4971
-
4972
-    /**
4973
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4974
-     * if no identifier is provided, then the entire entity map is emptied
4975
-     *
4976
-     * @param int|string $id the ID of the model object
4977
-     * @return boolean
4978
-     */
4979
-    public function clear_entity_map($id = null)
4980
-    {
4981
-        if (empty($id)) {
4982
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4983
-            return true;
4984
-        }
4985
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4986
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4987
-            return true;
4988
-        }
4989
-        return false;
4990
-    }
4991
-
4992
-
4993
-
4994
-    /**
4995
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4996
-     * Given an array where keys are column (or column alias) names and values,
4997
-     * returns an array of their corresponding field names and database values
4998
-     *
4999
-     * @param array $cols_n_values
5000
-     * @return array
5001
-     */
5002
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5003
-    {
5004
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5005
-    }
5006
-
5007
-
5008
-
5009
-    /**
5010
-     * _deduce_fields_n_values_from_cols_n_values
5011
-     * Given an array where keys are column (or column alias) names and values,
5012
-     * returns an array of their corresponding field names and database values
5013
-     *
5014
-     * @param string $cols_n_values
5015
-     * @return array
5016
-     */
5017
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5018
-    {
5019
-        $this_model_fields_n_values = array();
5020
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5021
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5022
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5023
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5024
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5025
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5026
-                    if (! $field_obj->is_db_only_field()) {
5027
-                        //prepare field as if its coming from db
5028
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5029
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5030
-                    }
5031
-                }
5032
-            } else {
5033
-                //the table's rows existed. Use their values
5034
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5035
-                    if (! $field_obj->is_db_only_field()) {
5036
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5037
-                            $cols_n_values, $field_obj->get_qualified_column(),
5038
-                            $field_obj->get_table_column()
5039
-                        );
5040
-                    }
5041
-                }
5042
-            }
5043
-        }
5044
-        return $this_model_fields_n_values;
5045
-    }
5046
-
5047
-
5048
-
5049
-    /**
5050
-     * @param $cols_n_values
5051
-     * @param $qualified_column
5052
-     * @param $regular_column
5053
-     * @return null
5054
-     */
5055
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5056
-    {
5057
-        $value = null;
5058
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5059
-        //does the field on the model relate to this column retrieved from the db?
5060
-        //or is it a db-only field? (not relating to the model)
5061
-        if (isset($cols_n_values[$qualified_column])) {
5062
-            $value = $cols_n_values[$qualified_column];
5063
-        } elseif (isset($cols_n_values[$regular_column])) {
5064
-            $value = $cols_n_values[$regular_column];
5065
-        }
5066
-        return $value;
5067
-    }
5068
-
5069
-
5070
-
5071
-    /**
5072
-     * refresh_entity_map_from_db
5073
-     * Makes sure the model object in the entity map at $id assumes the values
5074
-     * of the database (opposite of EE_base_Class::save())
5075
-     *
5076
-     * @param int|string $id
5077
-     * @return EE_Base_Class
5078
-     * @throws \EE_Error
5079
-     */
5080
-    public function refresh_entity_map_from_db($id)
5081
-    {
5082
-        $obj_in_map = $this->get_from_entity_map($id);
5083
-        if ($obj_in_map) {
5084
-            $wpdb_results = $this->_get_all_wpdb_results(
5085
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5086
-            );
5087
-            if ($wpdb_results && is_array($wpdb_results)) {
5088
-                $one_row = reset($wpdb_results);
5089
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5090
-                    $obj_in_map->set_from_db($field_name, $db_value);
5091
-                }
5092
-                //clear the cache of related model objects
5093
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5094
-                    $obj_in_map->clear_cache($relation_name, null, true);
5095
-                }
5096
-            }
5097
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5098
-            return $obj_in_map;
5099
-        } else {
5100
-            return $this->get_one_by_ID($id);
5101
-        }
5102
-    }
5103
-
5104
-
5105
-
5106
-    /**
5107
-     * refresh_entity_map_with
5108
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5109
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5110
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5111
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5112
-     *
5113
-     * @param int|string    $id
5114
-     * @param EE_Base_Class $replacing_model_obj
5115
-     * @return \EE_Base_Class
5116
-     * @throws \EE_Error
5117
-     */
5118
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5119
-    {
5120
-        $obj_in_map = $this->get_from_entity_map($id);
5121
-        if ($obj_in_map) {
5122
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5123
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5124
-                    $obj_in_map->set($field_name, $value);
5125
-                }
5126
-                //make the model object in the entity map's cache match the $replacing_model_obj
5127
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5128
-                    $obj_in_map->clear_cache($relation_name, null, true);
5129
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5130
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5131
-                    }
5132
-                }
5133
-            }
5134
-            return $obj_in_map;
5135
-        } else {
5136
-            $this->add_to_entity_map($replacing_model_obj);
5137
-            return $replacing_model_obj;
5138
-        }
5139
-    }
5140
-
5141
-
5142
-
5143
-    /**
5144
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5145
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5146
-     * require_once($this->_getClassName().".class.php");
5147
-     *
5148
-     * @return string
5149
-     */
5150
-    private function _get_class_name()
5151
-    {
5152
-        return "EE_" . $this->get_this_model_name();
5153
-    }
5154
-
5155
-
5156
-
5157
-    /**
5158
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5159
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5160
-     * it would be 'Events'.
5161
-     *
5162
-     * @param int $quantity
5163
-     * @return string
5164
-     */
5165
-    public function item_name($quantity = 1)
5166
-    {
5167
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5168
-    }
5169
-
5170
-
5171
-
5172
-    /**
5173
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5174
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5175
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5176
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5177
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5178
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5179
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5180
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5181
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5182
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5183
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5184
-     *        return $previousReturnValue.$returnString;
5185
-     * }
5186
-     * require('EEM_Answer.model.php');
5187
-     * $answer=EEM_Answer::instance();
5188
-     * echo $answer->my_callback('monkeys',100);
5189
-     * //will output "you called my_callback! and passed args:monkeys,100"
5190
-     *
5191
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5192
-     * @param array  $args       array of original arguments passed to the function
5193
-     * @throws EE_Error
5194
-     * @return mixed whatever the plugin which calls add_filter decides
5195
-     */
5196
-    public function __call($methodName, $args)
5197
-    {
5198
-        $className = get_class($this);
5199
-        $tagName = "FHEE__{$className}__{$methodName}";
5200
-        if (! has_filter($tagName)) {
5201
-            throw new EE_Error(
5202
-                sprintf(
5203
-                    __('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 );',
5204
-                        'event_espresso'),
5205
-                    $methodName,
5206
-                    $className,
5207
-                    $tagName,
5208
-                    '<br />'
5209
-                )
5210
-            );
5211
-        }
5212
-        return apply_filters($tagName, null, $this, $args);
5213
-    }
5214
-
5215
-
5216
-
5217
-    /**
5218
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5219
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5220
-     *
5221
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5222
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5223
-     *                                                       the object's class name
5224
-     *                                                       or object's ID
5225
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5226
-     *                                                       exists in the database. If it does not, we add it
5227
-     * @throws EE_Error
5228
-     * @return EE_Base_Class
5229
-     */
5230
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5231
-    {
5232
-        $className = $this->_get_class_name();
5233
-        if ($base_class_obj_or_id instanceof $className) {
5234
-            $model_object = $base_class_obj_or_id;
5235
-        } else {
5236
-            $primary_key_field = $this->get_primary_key_field();
5237
-            if (
5238
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5239
-                && (
5240
-                    is_int($base_class_obj_or_id)
5241
-                    || is_string($base_class_obj_or_id)
5242
-                )
5243
-            ) {
5244
-                // assume it's an ID.
5245
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5246
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5247
-            } else if (
5248
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5249
-                && is_string($base_class_obj_or_id)
5250
-            ) {
5251
-                // assume its a string representation of the object
5252
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5253
-            } else {
5254
-                throw new EE_Error(
5255
-                    sprintf(
5256
-                        __(
5257
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5258
-                            'event_espresso'
5259
-                        ),
5260
-                        $base_class_obj_or_id,
5261
-                        $this->_get_class_name(),
5262
-                        print_r($base_class_obj_or_id, true)
5263
-                    )
5264
-                );
5265
-            }
5266
-        }
5267
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5268
-            $model_object->save();
5269
-        }
5270
-        return $model_object;
5271
-    }
5272
-
5273
-
5274
-
5275
-    /**
5276
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5277
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5278
-     * returns it ID.
5279
-     *
5280
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5281
-     * @return int|string depending on the type of this model object's ID
5282
-     * @throws EE_Error
5283
-     */
5284
-    public function ensure_is_ID($base_class_obj_or_id)
5285
-    {
5286
-        $className = $this->_get_class_name();
5287
-        if ($base_class_obj_or_id instanceof $className) {
5288
-            /** @var $base_class_obj_or_id EE_Base_Class */
5289
-            $id = $base_class_obj_or_id->ID();
5290
-        } elseif (is_int($base_class_obj_or_id)) {
5291
-            //assume it's an ID
5292
-            $id = $base_class_obj_or_id;
5293
-        } elseif (is_string($base_class_obj_or_id)) {
5294
-            //assume its a string representation of the object
5295
-            $id = $base_class_obj_or_id;
5296
-        } else {
5297
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5298
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5299
-                print_r($base_class_obj_or_id, true)));
5300
-        }
5301
-        return $id;
5302
-    }
5303
-
5304
-
5305
-
5306
-    /**
5307
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5308
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5309
-     * been sanitized and converted into the appropriate domain.
5310
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5311
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5312
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5313
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5314
-     * $EVT = EEM_Event::instance(); $old_setting =
5315
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5316
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5317
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5318
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5319
-     *
5320
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5321
-     * @return void
5322
-     */
5323
-    public function assume_values_already_prepared_by_model_object(
5324
-        $values_already_prepared = self::not_prepared_by_model_object
5325
-    ) {
5326
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5327
-    }
5328
-
5329
-
5330
-
5331
-    /**
5332
-     * Read comments for assume_values_already_prepared_by_model_object()
5333
-     *
5334
-     * @return int
5335
-     */
5336
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5337
-    {
5338
-        return $this->_values_already_prepared_by_model_object;
5339
-    }
5340
-
5341
-
5342
-
5343
-    /**
5344
-     * Gets all the indexes on this model
5345
-     *
5346
-     * @return EE_Index[]
5347
-     */
5348
-    public function indexes()
5349
-    {
5350
-        return $this->_indexes;
5351
-    }
5352
-
5353
-
5354
-
5355
-    /**
5356
-     * Gets all the Unique Indexes on this model
5357
-     *
5358
-     * @return EE_Unique_Index[]
5359
-     */
5360
-    public function unique_indexes()
5361
-    {
5362
-        $unique_indexes = array();
5363
-        foreach ($this->_indexes as $name => $index) {
5364
-            if ($index instanceof EE_Unique_Index) {
5365
-                $unique_indexes [$name] = $index;
5366
-            }
5367
-        }
5368
-        return $unique_indexes;
5369
-    }
5370
-
5371
-
5372
-
5373
-    /**
5374
-     * Gets all the fields which, when combined, make the primary key.
5375
-     * This is usually just an array with 1 element (the primary key), but in cases
5376
-     * where there is no primary key, it's a combination of fields as defined
5377
-     * on a primary index
5378
-     *
5379
-     * @return EE_Model_Field_Base[] indexed by the field's name
5380
-     * @throws \EE_Error
5381
-     */
5382
-    public function get_combined_primary_key_fields()
5383
-    {
5384
-        foreach ($this->indexes() as $index) {
5385
-            if ($index instanceof EE_Primary_Key_Index) {
5386
-                return $index->fields();
5387
-            }
5388
-        }
5389
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5390
-    }
5391
-
5392
-
5393
-
5394
-    /**
5395
-     * Used to build a primary key string (when the model has no primary key),
5396
-     * which can be used a unique string to identify this model object.
5397
-     *
5398
-     * @param array $cols_n_values keys are field names, values are their values
5399
-     * @return string
5400
-     * @throws \EE_Error
5401
-     */
5402
-    public function get_index_primary_key_string($cols_n_values)
5403
-    {
5404
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5405
-            $this->get_combined_primary_key_fields());
5406
-        return http_build_query($cols_n_values_for_primary_key_index);
5407
-    }
5408
-
5409
-
5410
-
5411
-    /**
5412
-     * Gets the field values from the primary key string
5413
-     *
5414
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5415
-     * @param string $index_primary_key_string
5416
-     * @return null|array
5417
-     * @throws \EE_Error
5418
-     */
5419
-    public function parse_index_primary_key_string($index_primary_key_string)
5420
-    {
5421
-        $key_fields = $this->get_combined_primary_key_fields();
5422
-        //check all of them are in the $id
5423
-        $key_vals_in_combined_pk = array();
5424
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5425
-        foreach ($key_fields as $key_field_name => $field_obj) {
5426
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5427
-                return null;
5428
-            }
5429
-        }
5430
-        return $key_vals_in_combined_pk;
5431
-    }
5432
-
5433
-
5434
-
5435
-    /**
5436
-     * verifies that an array of key-value pairs for model fields has a key
5437
-     * for each field comprising the primary key index
5438
-     *
5439
-     * @param array $key_vals
5440
-     * @return boolean
5441
-     * @throws \EE_Error
5442
-     */
5443
-    public function has_all_combined_primary_key_fields($key_vals)
5444
-    {
5445
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5446
-        foreach ($keys_it_should_have as $key) {
5447
-            if (! isset($key_vals[$key])) {
5448
-                return false;
5449
-            }
5450
-        }
5451
-        return true;
5452
-    }
5453
-
5454
-
5455
-
5456
-    /**
5457
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5458
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5459
-     *
5460
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5461
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5462
-     * @throws EE_Error
5463
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5464
-     *                                                              indexed)
5465
-     */
5466
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5467
-    {
5468
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5469
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5470
-        } elseif (is_array($model_object_or_attributes_array)) {
5471
-            $attributes_array = $model_object_or_attributes_array;
5472
-        } else {
5473
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5474
-                "event_espresso"), $model_object_or_attributes_array));
5475
-        }
5476
-        //even copies obviously won't have the same ID, so remove the primary key
5477
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5478
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5479
-            unset($attributes_array[$this->primary_key_name()]);
5480
-        }
5481
-        if (isset($query_params[0])) {
5482
-            $query_params[0] = array_merge($attributes_array, $query_params);
5483
-        } else {
5484
-            $query_params[0] = $attributes_array;
5485
-        }
5486
-        return $this->get_all($query_params);
5487
-    }
5488
-
5489
-
5490
-
5491
-    /**
5492
-     * Gets the first copy we find. See get_all_copies for more details
5493
-     *
5494
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5495
-     * @param array $query_params
5496
-     * @return EE_Base_Class
5497
-     * @throws \EE_Error
5498
-     */
5499
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5500
-    {
5501
-        if (! is_array($query_params)) {
5502
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5503
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5504
-                    gettype($query_params)), '4.6.0');
5505
-            $query_params = array();
5506
-        }
5507
-        $query_params['limit'] = 1;
5508
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5509
-        if (is_array($copies)) {
5510
-            return array_shift($copies);
5511
-        } else {
5512
-            return null;
5513
-        }
5514
-    }
5515
-
5516
-
5517
-
5518
-    /**
5519
-     * Updates the item with the specified id. Ignores default query parameters because
5520
-     * we have specified the ID, and its assumed we KNOW what we're doing
5521
-     *
5522
-     * @param array      $fields_n_values keys are field names, values are their new values
5523
-     * @param int|string $id              the value of the primary key to update
5524
-     * @return int number of rows updated
5525
-     * @throws \EE_Error
5526
-     */
5527
-    public function update_by_ID($fields_n_values, $id)
5528
-    {
5529
-        $query_params = array(
5530
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5531
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5532
-        );
5533
-        return $this->update($fields_n_values, $query_params);
5534
-    }
5535
-
5536
-
5537
-
5538
-    /**
5539
-     * Changes an operator which was supplied to the models into one usable in SQL
5540
-     *
5541
-     * @param string $operator_supplied
5542
-     * @return string an operator which can be used in SQL
5543
-     * @throws EE_Error
5544
-     */
5545
-    private function _prepare_operator_for_sql($operator_supplied)
5546
-    {
5547
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5548
-            : null;
5549
-        if ($sql_operator) {
5550
-            return $sql_operator;
5551
-        } else {
5552
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5553
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5554
-        }
5555
-    }
5556
-
5557
-
5558
-
5559
-    /**
5560
-     * Gets the valid operators
5561
-     * @return array keys are accepted strings, values are the SQL they are converted to
5562
-     */
5563
-    public function valid_operators(){
5564
-        return $this->_valid_operators;
5565
-    }
5566
-
5567
-
5568
-
5569
-    /**
5570
-     * Gets the between-style operators (take 2 arguments).
5571
-     * @return array keys are accepted strings, values are the SQL they are converted to
5572
-     */
5573
-    public function valid_between_style_operators()
5574
-    {
5575
-        return array_intersect(
5576
-            $this->valid_operators(),
5577
-            $this->_between_style_operators
5578
-        );
5579
-    }
5580
-
5581
-    /**
5582
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5583
-     * @return array keys are accepted strings, values are the SQL they are converted to
5584
-     */
5585
-    public function valid_like_style_operators()
5586
-    {
5587
-        return array_intersect(
5588
-            $this->valid_operators(),
5589
-            $this->_like_style_operators
5590
-        );
5591
-    }
5592
-
5593
-    /**
5594
-     * Gets the "in"-style operators
5595
-     * @return array keys are accepted strings, values are the SQL they are converted to
5596
-     */
5597
-    public function valid_in_style_operators()
5598
-    {
5599
-        return array_intersect(
5600
-            $this->valid_operators(),
5601
-            $this->_in_style_operators
5602
-        );
5603
-    }
5604
-
5605
-    /**
5606
-     * Gets the "null"-style operators (accept no arguments)
5607
-     * @return array keys are accepted strings, values are the SQL they are converted to
5608
-     */
5609
-    public function valid_null_style_operators()
5610
-    {
5611
-        return array_intersect(
5612
-            $this->valid_operators(),
5613
-            $this->_null_style_operators
5614
-        );
5615
-    }
5616
-
5617
-    /**
5618
-     * Gets an array where keys are the primary keys and values are their 'names'
5619
-     * (as determined by the model object's name() function, which is often overridden)
5620
-     *
5621
-     * @param array $query_params like get_all's
5622
-     * @return string[]
5623
-     * @throws \EE_Error
5624
-     */
5625
-    public function get_all_names($query_params = array())
5626
-    {
5627
-        $objs = $this->get_all($query_params);
5628
-        $names = array();
5629
-        foreach ($objs as $obj) {
5630
-            $names[$obj->ID()] = $obj->name();
5631
-        }
5632
-        return $names;
5633
-    }
5634
-
5635
-
5636
-
5637
-    /**
5638
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5639
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5640
-     * this is duplicated effort and reduces efficiency) you would be better to use
5641
-     * array_keys() on $model_objects.
5642
-     *
5643
-     * @param \EE_Base_Class[] $model_objects
5644
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5645
-     *                                               in the returned array
5646
-     * @return array
5647
-     * @throws \EE_Error
5648
-     */
5649
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5650
-    {
5651
-        if (! $this->has_primary_key_field()) {
5652
-            if (WP_DEBUG) {
5653
-                EE_Error::add_error(
5654
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5655
-                    __FILE__,
5656
-                    __FUNCTION__,
5657
-                    __LINE__
5658
-                );
5659
-            }
5660
-        }
5661
-        $IDs = array();
5662
-        foreach ($model_objects as $model_object) {
5663
-            $id = $model_object->ID();
5664
-            if (! $id) {
5665
-                if ($filter_out_empty_ids) {
5666
-                    continue;
5667
-                }
5668
-                if (WP_DEBUG) {
5669
-                    EE_Error::add_error(
5670
-                        __(
5671
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5672
-                            'event_espresso'
5673
-                        ),
5674
-                        __FILE__,
5675
-                        __FUNCTION__,
5676
-                        __LINE__
5677
-                    );
5678
-                }
5679
-            }
5680
-            $IDs[] = $id;
5681
-        }
5682
-        return $IDs;
5683
-    }
5684
-
5685
-
5686
-
5687
-    /**
5688
-     * Returns the string used in capabilities relating to this model. If there
5689
-     * are no capabilities that relate to this model returns false
5690
-     *
5691
-     * @return string|false
5692
-     */
5693
-    public function cap_slug()
5694
-    {
5695
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5696
-    }
5697
-
5698
-
5699
-
5700
-    /**
5701
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5702
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5703
-     * only returns the cap restrictions array in that context (ie, the array
5704
-     * at that key)
5705
-     *
5706
-     * @param string $context
5707
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5708
-     * @throws \EE_Error
5709
-     */
5710
-    public function cap_restrictions($context = EEM_Base::caps_read)
5711
-    {
5712
-        EEM_Base::verify_is_valid_cap_context($context);
5713
-        //check if we ought to run the restriction generator first
5714
-        if (
5715
-            isset($this->_cap_restriction_generators[$context])
5716
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5717
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5718
-        ) {
5719
-            $this->_cap_restrictions[$context] = array_merge(
5720
-                $this->_cap_restrictions[$context],
5721
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5722
-            );
5723
-        }
5724
-        //and make sure we've finalized the construction of each restriction
5725
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5726
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5727
-                $where_conditions_obj->_finalize_construct($this);
5728
-            }
5729
-        }
5730
-        return $this->_cap_restrictions[$context];
5731
-    }
5732
-
5733
-
5734
-
5735
-    /**
5736
-     * Indicating whether or not this model thinks its a wp core model
5737
-     *
5738
-     * @return boolean
5739
-     */
5740
-    public function is_wp_core_model()
5741
-    {
5742
-        return $this->_wp_core_model;
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Gets all the caps that are missing which impose a restriction on
5749
-     * queries made in this context
5750
-     *
5751
-     * @param string $context one of EEM_Base::caps_ constants
5752
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5753
-     * @throws \EE_Error
5754
-     */
5755
-    public function caps_missing($context = EEM_Base::caps_read)
5756
-    {
5757
-        $missing_caps = array();
5758
-        $cap_restrictions = $this->cap_restrictions($context);
5759
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5760
-            if (! EE_Capabilities::instance()
5761
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5762
-            ) {
5763
-                $missing_caps[$cap] = $restriction_if_no_cap;
5764
-            }
5765
-        }
5766
-        return $missing_caps;
5767
-    }
5768
-
5769
-
5770
-
5771
-    /**
5772
-     * Gets the mapping from capability contexts to action strings used in capability names
5773
-     *
5774
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5775
-     * one of 'read', 'edit', or 'delete'
5776
-     */
5777
-    public function cap_contexts_to_cap_action_map()
5778
-    {
5779
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5780
-            $this);
5781
-    }
5782
-
5783
-
5784
-
5785
-    /**
5786
-     * Gets the action string for the specified capability context
5787
-     *
5788
-     * @param string $context
5789
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5790
-     * @throws \EE_Error
5791
-     */
5792
-    public function cap_action_for_context($context)
5793
-    {
5794
-        $mapping = $this->cap_contexts_to_cap_action_map();
5795
-        if (isset($mapping[$context])) {
5796
-            return $mapping[$context];
5797
-        }
5798
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5799
-            return $action;
5800
-        }
5801
-        throw new EE_Error(
5802
-            sprintf(
5803
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5804
-                $context,
5805
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5806
-            )
5807
-        );
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Returns all the capability contexts which are valid when querying models
5814
-     *
5815
-     * @return array
5816
-     */
5817
-    public static function valid_cap_contexts()
5818
-    {
5819
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5820
-            self::caps_read,
5821
-            self::caps_read_admin,
5822
-            self::caps_edit,
5823
-            self::caps_delete,
5824
-        ));
5825
-    }
5826
-
5827
-
5828
-
5829
-    /**
5830
-     * Returns all valid options for 'default_where_conditions'
5831
-     *
5832
-     * @return array
5833
-     */
5834
-    public static function valid_default_where_conditions()
5835
-    {
5836
-        return array(
5837
-            EEM_Base::default_where_conditions_all,
5838
-            EEM_Base::default_where_conditions_this_only,
5839
-            EEM_Base::default_where_conditions_others_only,
5840
-            EEM_Base::default_where_conditions_minimum_all,
5841
-            EEM_Base::default_where_conditions_minimum_others,
5842
-            EEM_Base::default_where_conditions_none
5843
-        );
5844
-    }
5845
-
5846
-    // public static function default_where_conditions_full
5847
-    /**
5848
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5849
-     *
5850
-     * @param string $context
5851
-     * @return bool
5852
-     * @throws \EE_Error
5853
-     */
5854
-    static public function verify_is_valid_cap_context($context)
5855
-    {
5856
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5857
-        if (in_array($context, $valid_cap_contexts)) {
5858
-            return true;
5859
-        } else {
5860
-            throw new EE_Error(
5861
-                sprintf(
5862
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5863
-                        'event_espresso'),
5864
-                    $context,
5865
-                    'EEM_Base',
5866
-                    implode(',', $valid_cap_contexts)
5867
-                )
5868
-            );
5869
-        }
5870
-    }
5871
-
5872
-
5873
-
5874
-    /**
5875
-     * Clears all the models field caches. This is only useful when a sub-class
5876
-     * might have added a field or something and these caches might be invalidated
5877
-     */
5878
-    protected function _invalidate_field_caches()
5879
-    {
5880
-        $this->_cache_foreign_key_to_fields = array();
5881
-        $this->_cached_fields = null;
5882
-        $this->_cached_fields_non_db_only = null;
5883
-    }
5884
-
5885
-
5886
-
5887
-    /**
5888
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5889
-     * (eg "and", "or", "not").
5890
-     *
5891
-     * @return array
5892
-     */
5893
-    public function logic_query_param_keys()
5894
-    {
5895
-        return $this->_logic_query_param_keys;
5896
-    }
5897
-
5898
-
5899
-
5900
-    /**
5901
-     * Determines whether or not the where query param array key is for a logic query param.
5902
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5903
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5904
-     *
5905
-     * @param $query_param_key
5906
-     * @return bool
5907
-     */
5908
-    public function is_logic_query_param_key($query_param_key)
5909
-    {
5910
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5911
-            if ($query_param_key === $logic_query_param_key
5912
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5913
-            ) {
5914
-                return true;
5915
-            }
5916
-        }
5917
-        return false;
5918
-    }
3647
+		}
3648
+		return $null_friendly_where_conditions;
3649
+	}
3650
+
3651
+
3652
+
3653
+	/**
3654
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3655
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3656
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3657
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3658
+	 *
3659
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3660
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3661
+	 */
3662
+	private function _get_default_where_conditions($model_relation_path = null)
3663
+	{
3664
+		if ($this->_ignore_where_strategy) {
3665
+			return array();
3666
+		}
3667
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3668
+	}
3669
+
3670
+
3671
+
3672
+	/**
3673
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3674
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3675
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3676
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3677
+	 * Similar to _get_default_where_conditions
3678
+	 *
3679
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3680
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3681
+	 */
3682
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3683
+	{
3684
+		if ($this->_ignore_where_strategy) {
3685
+			return array();
3686
+		}
3687
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3688
+	}
3689
+
3690
+
3691
+
3692
+	/**
3693
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3694
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3695
+	 *
3696
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3697
+	 * @return string
3698
+	 * @throws \EE_Error
3699
+	 */
3700
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3701
+	{
3702
+		$selects = $this->_get_columns_to_select_for_this_model();
3703
+		foreach (
3704
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3705
+			$name_of_other_model_included
3706
+		) {
3707
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3708
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3709
+			foreach ($other_model_selects as $key => $value) {
3710
+				$selects[] = $value;
3711
+			}
3712
+		}
3713
+		return implode(", ", $selects);
3714
+	}
3715
+
3716
+
3717
+
3718
+	/**
3719
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3720
+	 * So that's going to be the columns for all the fields on the model
3721
+	 *
3722
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3723
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3724
+	 */
3725
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3726
+	{
3727
+		$fields = $this->field_settings();
3728
+		$selects = array();
3729
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3730
+			$this->get_this_model_name());
3731
+		foreach ($fields as $field_obj) {
3732
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3733
+						 . $field_obj->get_table_alias()
3734
+						 . "."
3735
+						 . $field_obj->get_table_column()
3736
+						 . " AS '"
3737
+						 . $table_alias_with_model_relation_chain_prefix
3738
+						 . $field_obj->get_table_alias()
3739
+						 . "."
3740
+						 . $field_obj->get_table_column()
3741
+						 . "'";
3742
+		}
3743
+		//make sure we are also getting the PKs of each table
3744
+		$tables = $this->get_tables();
3745
+		if (count($tables) > 1) {
3746
+			foreach ($tables as $table_obj) {
3747
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3748
+									   . $table_obj->get_fully_qualified_pk_column();
3749
+				if (! in_array($qualified_pk_column, $selects)) {
3750
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3751
+				}
3752
+			}
3753
+		}
3754
+		return $selects;
3755
+	}
3756
+
3757
+
3758
+
3759
+	/**
3760
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3761
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3762
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3763
+	 * SQL for joining, and the data types
3764
+	 *
3765
+	 * @param null|string                 $original_query_param
3766
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3767
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3768
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3769
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3770
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3771
+	 *                                                          or 'Registration's
3772
+	 * @param string                      $original_query_param what it originally was (eg
3773
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3774
+	 *                                                          matches $query_param
3775
+	 * @throws EE_Error
3776
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3777
+	 */
3778
+	private function _extract_related_model_info_from_query_param(
3779
+		$query_param,
3780
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3781
+		$query_param_type,
3782
+		$original_query_param = null
3783
+	) {
3784
+		if ($original_query_param === null) {
3785
+			$original_query_param = $query_param;
3786
+		}
3787
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3788
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3789
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3790
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3791
+		//check to see if we have a field on this model
3792
+		$this_model_fields = $this->field_settings(true);
3793
+		if (array_key_exists($query_param, $this_model_fields)) {
3794
+			if ($allow_fields) {
3795
+				return;
3796
+			} else {
3797
+				throw new EE_Error(sprintf(__("Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3798
+					"event_espresso"),
3799
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3800
+			}
3801
+		} //check if this is a special logic query param
3802
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3803
+			if ($allow_logic_query_params) {
3804
+				return;
3805
+			} else {
3806
+				throw new EE_Error(
3807
+					sprintf(
3808
+						__('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',
3809
+							'event_espresso'),
3810
+						implode('", "', $this->_logic_query_param_keys),
3811
+						$query_param,
3812
+						get_class($this),
3813
+						'<br />',
3814
+						"\t"
3815
+						. ' $passed_in_query_info = <pre>'
3816
+						. print_r($passed_in_query_info, true)
3817
+						. '</pre>'
3818
+						. "\n\t"
3819
+						. ' $query_param_type = '
3820
+						. $query_param_type
3821
+						. "\n\t"
3822
+						. ' $original_query_param = '
3823
+						. $original_query_param
3824
+					)
3825
+				);
3826
+			}
3827
+		} //check if it's a custom selection
3828
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3829
+			return;
3830
+		}
3831
+		//check if has a model name at the beginning
3832
+		//and
3833
+		//check if it's a field on a related model
3834
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3835
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3836
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3837
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3838
+				if ($query_param === '') {
3839
+					//nothing left to $query_param
3840
+					//we should actually end in a field name, not a model like this!
3841
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3842
+						"event_espresso"),
3843
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3844
+				} else {
3845
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3846
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3847
+						$passed_in_query_info, $query_param_type, $original_query_param);
3848
+					return;
3849
+				}
3850
+			} elseif ($query_param === $valid_related_model_name) {
3851
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3852
+				return;
3853
+			}
3854
+		}
3855
+		//ok so $query_param didn't start with a model name
3856
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3857
+		//it's wack, that's what it is
3858
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3859
+			"event_espresso"),
3860
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3861
+	}
3862
+
3863
+
3864
+
3865
+	/**
3866
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3867
+	 * and store it on $passed_in_query_info
3868
+	 *
3869
+	 * @param string                      $model_name
3870
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3871
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3872
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3873
+	 *                                                          and are adding a join to 'Payment' with the original
3874
+	 *                                                          query param key
3875
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3876
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3877
+	 *                                                          Payment wants to add default query params so that it
3878
+	 *                                                          will know what models to prepend onto its default query
3879
+	 *                                                          params or in case it wants to rename tables (in case
3880
+	 *                                                          there are multiple joins to the same table)
3881
+	 * @return void
3882
+	 * @throws \EE_Error
3883
+	 */
3884
+	private function _add_join_to_model(
3885
+		$model_name,
3886
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3887
+		$original_query_param
3888
+	) {
3889
+		$relation_obj = $this->related_settings_for($model_name);
3890
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3891
+		//check if the relation is HABTM, because then we're essentially doing two joins
3892
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3893
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3894
+			$join_model_obj = $relation_obj->get_join_model();
3895
+			//replace the model specified with the join model for this relation chain, whi
3896
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3897
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3898
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3899
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3900
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3901
+			$passed_in_query_info->merge($new_query_info);
3902
+		}
3903
+		//now just join to the other table pointed to by the relation object, and add its data types
3904
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3905
+			array($model_relation_chain => $model_name),
3906
+			$relation_obj->get_join_statement($model_relation_chain));
3907
+		$passed_in_query_info->merge($new_query_info);
3908
+	}
3909
+
3910
+
3911
+
3912
+	/**
3913
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3914
+	 *
3915
+	 * @param array $where_params like EEM_Base::get_all
3916
+	 * @return string of SQL
3917
+	 * @throws \EE_Error
3918
+	 */
3919
+	private function _construct_where_clause($where_params)
3920
+	{
3921
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3922
+		if ($SQL) {
3923
+			return " WHERE " . $SQL;
3924
+		} else {
3925
+			return '';
3926
+		}
3927
+	}
3928
+
3929
+
3930
+
3931
+	/**
3932
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3933
+	 * and should be passed HAVING parameters, not WHERE parameters
3934
+	 *
3935
+	 * @param array $having_params
3936
+	 * @return string
3937
+	 * @throws \EE_Error
3938
+	 */
3939
+	private function _construct_having_clause($having_params)
3940
+	{
3941
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3942
+		if ($SQL) {
3943
+			return " HAVING " . $SQL;
3944
+		} else {
3945
+			return '';
3946
+		}
3947
+	}
3948
+
3949
+
3950
+	/**
3951
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3952
+	 * Event_Meta.meta_value = 'foo'))"
3953
+	 *
3954
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3955
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3956
+	 * @throws EE_Error
3957
+	 * @return string of SQL
3958
+	 */
3959
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3960
+	{
3961
+		$where_clauses = array();
3962
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3963
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3964
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3965
+				switch ($query_param) {
3966
+					case 'not':
3967
+					case 'NOT':
3968
+						$where_clauses[] = "! ("
3969
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3970
+								$glue)
3971
+										   . ")";
3972
+						break;
3973
+					case 'and':
3974
+					case 'AND':
3975
+						$where_clauses[] = " ("
3976
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3977
+								' AND ')
3978
+										   . ")";
3979
+						break;
3980
+					case 'or':
3981
+					case 'OR':
3982
+						$where_clauses[] = " ("
3983
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3984
+								' OR ')
3985
+										   . ")";
3986
+						break;
3987
+				}
3988
+			} else {
3989
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3990
+				//if it's not a normal field, maybe it's a custom selection?
3991
+				if (! $field_obj) {
3992
+					if (isset($this->_custom_selections[$query_param][1])) {
3993
+						$field_obj = $this->_custom_selections[$query_param][1];
3994
+					} else {
3995
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3996
+							"event_espresso"), $query_param));
3997
+					}
3998
+				}
3999
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4000
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4001
+			}
4002
+		}
4003
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4004
+	}
4005
+
4006
+
4007
+
4008
+	/**
4009
+	 * Takes the input parameter and extract the table name (alias) and column name
4010
+	 *
4011
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4012
+	 * @throws EE_Error
4013
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4014
+	 */
4015
+	private function _deduce_column_name_from_query_param($query_param)
4016
+	{
4017
+		$field = $this->_deduce_field_from_query_param($query_param);
4018
+		if ($field) {
4019
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4020
+				$query_param);
4021
+			return $table_alias_prefix . $field->get_qualified_column();
4022
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4023
+			//maybe it's custom selection item?
4024
+			//if so, just use it as the "column name"
4025
+			return $query_param;
4026
+		} else {
4027
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4028
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4029
+		}
4030
+	}
4031
+
4032
+
4033
+
4034
+	/**
4035
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4036
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4037
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4038
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4039
+	 *
4040
+	 * @param string $condition_query_param_key
4041
+	 * @return string
4042
+	 */
4043
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4044
+	{
4045
+		$pos_of_star = strpos($condition_query_param_key, '*');
4046
+		if ($pos_of_star === false) {
4047
+			return $condition_query_param_key;
4048
+		} else {
4049
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4050
+			return $condition_query_param_sans_star;
4051
+		}
4052
+	}
4053
+
4054
+
4055
+
4056
+	/**
4057
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4058
+	 *
4059
+	 * @param                            mixed      array | string    $op_and_value
4060
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4061
+	 * @throws EE_Error
4062
+	 * @return string
4063
+	 */
4064
+	private function _construct_op_and_value($op_and_value, $field_obj)
4065
+	{
4066
+		if (is_array($op_and_value)) {
4067
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4068
+			if (! $operator) {
4069
+				$php_array_like_string = array();
4070
+				foreach ($op_and_value as $key => $value) {
4071
+					$php_array_like_string[] = "$key=>$value";
4072
+				}
4073
+				throw new EE_Error(
4074
+					sprintf(
4075
+						__(
4076
+							"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))",
4077
+							"event_espresso"
4078
+						),
4079
+						implode(",", $php_array_like_string)
4080
+					)
4081
+				);
4082
+			}
4083
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4084
+		} else {
4085
+			$operator = '=';
4086
+			$value = $op_and_value;
4087
+		}
4088
+		//check to see if the value is actually another field
4089
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4090
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4091
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4092
+			//in this case, the value should be an array, or at least a comma-separated list
4093
+			//it will need to handle a little differently
4094
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4095
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4096
+			return $operator . SP . $cleaned_value;
4097
+		} elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4098
+			//the value should be an array with count of two.
4099
+			if (count($value) !== 2) {
4100
+				throw new EE_Error(
4101
+					sprintf(
4102
+						__(
4103
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4104
+							'event_espresso'
4105
+						),
4106
+						"BETWEEN"
4107
+					)
4108
+				);
4109
+			}
4110
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4111
+			return $operator . SP . $cleaned_value;
4112
+		} elseif (in_array($operator, $this->valid_null_style_operators())) {
4113
+			if ($value !== null) {
4114
+				throw new EE_Error(
4115
+					sprintf(
4116
+						__(
4117
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4118
+							"event_espresso"
4119
+						),
4120
+						$value,
4121
+						$operator
4122
+					)
4123
+				);
4124
+			}
4125
+			return $operator;
4126
+		} elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4127
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4128
+			//remove other junk. So just treat it as a string.
4129
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4130
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4132
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4133
+			throw new EE_Error(
4134
+				sprintf(
4135
+					__(
4136
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4137
+						'event_espresso'
4138
+					),
4139
+					$operator,
4140
+					$operator
4141
+				)
4142
+			);
4143
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4144
+			throw new EE_Error(
4145
+				sprintf(
4146
+					__(
4147
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4148
+						'event_espresso'
4149
+					),
4150
+					$operator,
4151
+					$operator
4152
+				)
4153
+			);
4154
+		} else {
4155
+			throw new EE_Error(
4156
+				sprintf(
4157
+					__(
4158
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4159
+						"event_espresso"
4160
+					),
4161
+					http_build_query($op_and_value)
4162
+				)
4163
+			);
4164
+		}
4165
+	}
4166
+
4167
+
4168
+
4169
+	/**
4170
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4171
+	 *
4172
+	 * @param array                      $values
4173
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4174
+	 *                                              '%s'
4175
+	 * @return string
4176
+	 * @throws \EE_Error
4177
+	 */
4178
+	public function _construct_between_value($values, $field_obj)
4179
+	{
4180
+		$cleaned_values = array();
4181
+		foreach ($values as $value) {
4182
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4183
+		}
4184
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4185
+	}
4186
+
4187
+
4188
+
4189
+	/**
4190
+	 * Takes an array or a comma-separated list of $values and cleans them
4191
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4192
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4193
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4194
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4195
+	 *
4196
+	 * @param mixed                      $values    array or comma-separated string
4197
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4198
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4199
+	 * @throws \EE_Error
4200
+	 */
4201
+	public function _construct_in_value($values, $field_obj)
4202
+	{
4203
+		//check if the value is a CSV list
4204
+		if (is_string($values)) {
4205
+			//in which case, turn it into an array
4206
+			$values = explode(",", $values);
4207
+		}
4208
+		$cleaned_values = array();
4209
+		foreach ($values as $value) {
4210
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4211
+		}
4212
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4213
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4214
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4215
+		if (empty($cleaned_values)) {
4216
+			$all_fields = $this->field_settings();
4217
+			$a_field = array_shift($all_fields);
4218
+			$main_table = $this->_get_main_table();
4219
+			$cleaned_values[] = "SELECT "
4220
+								. $a_field->get_table_column()
4221
+								. " FROM "
4222
+								. $main_table->get_table_name()
4223
+								. " WHERE FALSE";
4224
+		}
4225
+		return "(" . implode(",", $cleaned_values) . ")";
4226
+	}
4227
+
4228
+
4229
+
4230
+	/**
4231
+	 * @param mixed                      $value
4232
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4233
+	 * @throws EE_Error
4234
+	 * @return false|null|string
4235
+	 */
4236
+	private function _wpdb_prepare_using_field($value, $field_obj)
4237
+	{
4238
+		/** @type WPDB $wpdb */
4239
+		global $wpdb;
4240
+		if ($field_obj instanceof EE_Model_Field_Base) {
4241
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4242
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4243
+		} else {//$field_obj should really just be a data type
4244
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4245
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4246
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4247
+			}
4248
+			return $wpdb->prepare($field_obj, $value);
4249
+		}
4250
+	}
4251
+
4252
+
4253
+
4254
+	/**
4255
+	 * Takes the input parameter and finds the model field that it indicates.
4256
+	 *
4257
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4258
+	 * @throws EE_Error
4259
+	 * @return EE_Model_Field_Base
4260
+	 */
4261
+	protected function _deduce_field_from_query_param($query_param_name)
4262
+	{
4263
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4264
+		//which will help us find the database table and column
4265
+		$query_param_parts = explode(".", $query_param_name);
4266
+		if (empty($query_param_parts)) {
4267
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4268
+				'event_espresso'), $query_param_name));
4269
+		}
4270
+		$number_of_parts = count($query_param_parts);
4271
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4272
+		if ($number_of_parts === 1) {
4273
+			$field_name = $last_query_param_part;
4274
+			$model_obj = $this;
4275
+		} else {// $number_of_parts >= 2
4276
+			//the last part is the column name, and there are only 2parts. therefore...
4277
+			$field_name = $last_query_param_part;
4278
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4279
+		}
4280
+		try {
4281
+			return $model_obj->field_settings_for($field_name);
4282
+		} catch (EE_Error $e) {
4283
+			return null;
4284
+		}
4285
+	}
4286
+
4287
+
4288
+
4289
+	/**
4290
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4291
+	 * alias and column which corresponds to it
4292
+	 *
4293
+	 * @param string $field_name
4294
+	 * @throws EE_Error
4295
+	 * @return string
4296
+	 */
4297
+	public function _get_qualified_column_for_field($field_name)
4298
+	{
4299
+		$all_fields = $this->field_settings();
4300
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4301
+		if ($field) {
4302
+			return $field->get_qualified_column();
4303
+		} else {
4304
+			throw new EE_Error(sprintf(__("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.",
4305
+				'event_espresso'), $field_name, get_class($this)));
4306
+		}
4307
+	}
4308
+
4309
+
4310
+
4311
+	/**
4312
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4313
+	 * Example usage:
4314
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4315
+	 *      array(),
4316
+	 *      ARRAY_A,
4317
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4318
+	 *  );
4319
+	 * is equivalent to
4320
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4321
+	 * and
4322
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4323
+	 *      array(
4324
+	 *          array(
4325
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4326
+	 *          ),
4327
+	 *          ARRAY_A,
4328
+	 *          implode(
4329
+	 *              ', ',
4330
+	 *              array_merge(
4331
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4332
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4333
+	 *              )
4334
+	 *          )
4335
+	 *      )
4336
+	 *  );
4337
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4338
+	 *
4339
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4340
+	 *                                            and the one whose fields you are selecting for example: when querying
4341
+	 *                                            tickets model and selecting fields from the tickets model you would
4342
+	 *                                            leave this parameter empty, because no models are needed to join
4343
+	 *                                            between the queried model and the selected one. Likewise when
4344
+	 *                                            querying the datetime model and selecting fields from the tickets
4345
+	 *                                            model, it would also be left empty, because there is a direct
4346
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4347
+	 *                                            them together. However, when querying from the event model and
4348
+	 *                                            selecting fields from the ticket model, you should provide the string
4349
+	 *                                            'Datetime', indicating that the event model must first join to the
4350
+	 *                                            datetime model in order to find its relation to ticket model.
4351
+	 *                                            Also, when querying from the venue model and selecting fields from
4352
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4353
+	 *                                            indicating you need to join the venue model to the event model,
4354
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4355
+	 *                                            This string is used to deduce the prefix that gets added onto the
4356
+	 *                                            models' tables qualified columns
4357
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4358
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4359
+	 *                                            qualified column names
4360
+	 * @return array|string
4361
+	 */
4362
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4363
+	{
4364
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4365
+		$qualified_columns = array();
4366
+		foreach ($this->field_settings() as $field_name => $field) {
4367
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4368
+		}
4369
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4370
+	}
4371
+
4372
+
4373
+
4374
+	/**
4375
+	 * constructs the select use on special limit joins
4376
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4377
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4378
+	 * (as that is typically where the limits would be set).
4379
+	 *
4380
+	 * @param  string       $table_alias The table the select is being built for
4381
+	 * @param  mixed|string $limit       The limit for this select
4382
+	 * @return string                The final select join element for the query.
4383
+	 */
4384
+	public function _construct_limit_join_select($table_alias, $limit)
4385
+	{
4386
+		$SQL = '';
4387
+		foreach ($this->_tables as $table_obj) {
4388
+			if ($table_obj instanceof EE_Primary_Table) {
4389
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4390
+					? $table_obj->get_select_join_limit($limit)
4391
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4392
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4393
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4394
+					? $table_obj->get_select_join_limit_join($limit)
4395
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4396
+			}
4397
+		}
4398
+		return $SQL;
4399
+	}
4400
+
4401
+
4402
+
4403
+	/**
4404
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4405
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4406
+	 *
4407
+	 * @return string SQL
4408
+	 * @throws \EE_Error
4409
+	 */
4410
+	public function _construct_internal_join()
4411
+	{
4412
+		$SQL = $this->_get_main_table()->get_table_sql();
4413
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4414
+		return $SQL;
4415
+	}
4416
+
4417
+
4418
+
4419
+	/**
4420
+	 * Constructs the SQL for joining all the tables on this model.
4421
+	 * Normally $alias should be the primary table's alias, but in cases where
4422
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4423
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4424
+	 * alias, this will construct SQL like:
4425
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4426
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4427
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4428
+	 *
4429
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4430
+	 * @return string
4431
+	 */
4432
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4433
+	{
4434
+		$SQL = '';
4435
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4436
+		foreach ($this->_tables as $table_obj) {
4437
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4438
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4439
+					//so we're joining to this table, meaning the table is already in
4440
+					//the FROM statement, BUT the primary table isn't. So we want
4441
+					//to add the inverse join sql
4442
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4443
+				} else {
4444
+					//just add a regular JOIN to this table from the primary table
4445
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4446
+				}
4447
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4448
+		}
4449
+		return $SQL;
4450
+	}
4451
+
4452
+
4453
+
4454
+	/**
4455
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4456
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4457
+	 * their data type (eg, '%s', '%d', etc)
4458
+	 *
4459
+	 * @return array
4460
+	 */
4461
+	public function _get_data_types()
4462
+	{
4463
+		$data_types = array();
4464
+		foreach ($this->field_settings() as $field_obj) {
4465
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4466
+			/** @var $field_obj EE_Model_Field_Base */
4467
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4468
+		}
4469
+		return $data_types;
4470
+	}
4471
+
4472
+
4473
+
4474
+	/**
4475
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4476
+	 *
4477
+	 * @param string $model_name
4478
+	 * @throws EE_Error
4479
+	 * @return EEM_Base
4480
+	 */
4481
+	public function get_related_model_obj($model_name)
4482
+	{
4483
+		$model_classname = "EEM_" . $model_name;
4484
+		if (! class_exists($model_classname)) {
4485
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4486
+				'event_espresso'), $model_name, $model_classname));
4487
+		}
4488
+		return call_user_func($model_classname . "::instance");
4489
+	}
4490
+
4491
+
4492
+
4493
+	/**
4494
+	 * Returns the array of EE_ModelRelations for this model.
4495
+	 *
4496
+	 * @return EE_Model_Relation_Base[]
4497
+	 */
4498
+	public function relation_settings()
4499
+	{
4500
+		return $this->_model_relations;
4501
+	}
4502
+
4503
+
4504
+
4505
+	/**
4506
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4507
+	 * because without THOSE models, this model probably doesn't have much purpose.
4508
+	 * (Eg, without an event, datetimes have little purpose.)
4509
+	 *
4510
+	 * @return EE_Belongs_To_Relation[]
4511
+	 */
4512
+	public function belongs_to_relations()
4513
+	{
4514
+		$belongs_to_relations = array();
4515
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4516
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4517
+				$belongs_to_relations[$model_name] = $relation_obj;
4518
+			}
4519
+		}
4520
+		return $belongs_to_relations;
4521
+	}
4522
+
4523
+
4524
+
4525
+	/**
4526
+	 * Returns the specified EE_Model_Relation, or throws an exception
4527
+	 *
4528
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4529
+	 * @throws EE_Error
4530
+	 * @return EE_Model_Relation_Base
4531
+	 */
4532
+	public function related_settings_for($relation_name)
4533
+	{
4534
+		$relatedModels = $this->relation_settings();
4535
+		if (! array_key_exists($relation_name, $relatedModels)) {
4536
+			throw new EE_Error(
4537
+				sprintf(
4538
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4539
+						'event_espresso'),
4540
+					$relation_name,
4541
+					$this->_get_class_name(),
4542
+					implode(', ', array_keys($relatedModels))
4543
+				)
4544
+			);
4545
+		}
4546
+		return $relatedModels[$relation_name];
4547
+	}
4548
+
4549
+
4550
+
4551
+	/**
4552
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4553
+	 * fields
4554
+	 *
4555
+	 * @param string $fieldName
4556
+	 * @param boolean $include_db_only_fields
4557
+	 * @throws EE_Error
4558
+	 * @return EE_Model_Field_Base
4559
+	 */
4560
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4561
+	{
4562
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4563
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4564
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4565
+				get_class($this)));
4566
+		}
4567
+		return $fieldSettings[$fieldName];
4568
+	}
4569
+
4570
+
4571
+
4572
+	/**
4573
+	 * Checks if this field exists on this model
4574
+	 *
4575
+	 * @param string $fieldName a key in the model's _field_settings array
4576
+	 * @return boolean
4577
+	 */
4578
+	public function has_field($fieldName)
4579
+	{
4580
+		$fieldSettings = $this->field_settings(true);
4581
+		if (isset($fieldSettings[$fieldName])) {
4582
+			return true;
4583
+		} else {
4584
+			return false;
4585
+		}
4586
+	}
4587
+
4588
+
4589
+
4590
+	/**
4591
+	 * Returns whether or not this model has a relation to the specified model
4592
+	 *
4593
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4594
+	 * @return boolean
4595
+	 */
4596
+	public function has_relation($relation_name)
4597
+	{
4598
+		$relations = $this->relation_settings();
4599
+		if (isset($relations[$relation_name])) {
4600
+			return true;
4601
+		} else {
4602
+			return false;
4603
+		}
4604
+	}
4605
+
4606
+
4607
+
4608
+	/**
4609
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4610
+	 * Eg, on EE_Answer that would be ANS_ID field object
4611
+	 *
4612
+	 * @param $field_obj
4613
+	 * @return boolean
4614
+	 */
4615
+	public function is_primary_key_field($field_obj)
4616
+	{
4617
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4618
+	}
4619
+
4620
+
4621
+
4622
+	/**
4623
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4624
+	 * Eg, on EE_Answer that would be ANS_ID field object
4625
+	 *
4626
+	 * @return EE_Model_Field_Base
4627
+	 * @throws EE_Error
4628
+	 */
4629
+	public function get_primary_key_field()
4630
+	{
4631
+		if ($this->_primary_key_field === null) {
4632
+			foreach ($this->field_settings(true) as $field_obj) {
4633
+				if ($this->is_primary_key_field($field_obj)) {
4634
+					$this->_primary_key_field = $field_obj;
4635
+					break;
4636
+				}
4637
+			}
4638
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4639
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4640
+					get_class($this)));
4641
+			}
4642
+		}
4643
+		return $this->_primary_key_field;
4644
+	}
4645
+
4646
+
4647
+
4648
+	/**
4649
+	 * Returns whether or not not there is a primary key on this model.
4650
+	 * Internally does some caching.
4651
+	 *
4652
+	 * @return boolean
4653
+	 */
4654
+	public function has_primary_key_field()
4655
+	{
4656
+		if ($this->_has_primary_key_field === null) {
4657
+			try {
4658
+				$this->get_primary_key_field();
4659
+				$this->_has_primary_key_field = true;
4660
+			} catch (EE_Error $e) {
4661
+				$this->_has_primary_key_field = false;
4662
+			}
4663
+		}
4664
+		return $this->_has_primary_key_field;
4665
+	}
4666
+
4667
+
4668
+
4669
+	/**
4670
+	 * Finds the first field of type $field_class_name.
4671
+	 *
4672
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4673
+	 *                                 EE_Foreign_Key_Field, etc
4674
+	 * @return EE_Model_Field_Base or null if none is found
4675
+	 */
4676
+	public function get_a_field_of_type($field_class_name)
4677
+	{
4678
+		foreach ($this->field_settings() as $field) {
4679
+			if ($field instanceof $field_class_name) {
4680
+				return $field;
4681
+			}
4682
+		}
4683
+		return null;
4684
+	}
4685
+
4686
+
4687
+
4688
+	/**
4689
+	 * Gets a foreign key field pointing to model.
4690
+	 *
4691
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4692
+	 * @return EE_Foreign_Key_Field_Base
4693
+	 * @throws EE_Error
4694
+	 */
4695
+	public function get_foreign_key_to($model_name)
4696
+	{
4697
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698
+			foreach ($this->field_settings() as $field) {
4699
+				if (
4700
+					$field instanceof EE_Foreign_Key_Field_Base
4701
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4702
+				) {
4703
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4704
+					break;
4705
+				}
4706
+			}
4707
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4708
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4709
+					'event_espresso'), $model_name, get_class($this)));
4710
+			}
4711
+		}
4712
+		return $this->_cache_foreign_key_to_fields[$model_name];
4713
+	}
4714
+
4715
+
4716
+
4717
+	/**
4718
+	 * Gets the actual table for the table alias
4719
+	 *
4720
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4721
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4722
+	 *                            Either one works
4723
+	 * @return EE_Table_Base
4724
+	 */
4725
+	public function get_table_for_alias($table_alias)
4726
+	{
4727
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4728
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4729
+	}
4730
+
4731
+
4732
+
4733
+	/**
4734
+	 * Returns a flat array of all field son this model, instead of organizing them
4735
+	 * by table_alias as they are in the constructor.
4736
+	 *
4737
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4738
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4739
+	 */
4740
+	public function field_settings($include_db_only_fields = false)
4741
+	{
4742
+		if ($include_db_only_fields) {
4743
+			if ($this->_cached_fields === null) {
4744
+				$this->_cached_fields = array();
4745
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4746
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4747
+						$this->_cached_fields[$field_name] = $field_obj;
4748
+					}
4749
+				}
4750
+			}
4751
+			return $this->_cached_fields;
4752
+		} else {
4753
+			if ($this->_cached_fields_non_db_only === null) {
4754
+				$this->_cached_fields_non_db_only = array();
4755
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4756
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4757
+						/** @var $field_obj EE_Model_Field_Base */
4758
+						if (! $field_obj->is_db_only_field()) {
4759
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4760
+						}
4761
+					}
4762
+				}
4763
+			}
4764
+			return $this->_cached_fields_non_db_only;
4765
+		}
4766
+	}
4767
+
4768
+
4769
+
4770
+	/**
4771
+	 *        cycle though array of attendees and create objects out of each item
4772
+	 *
4773
+	 * @access        private
4774
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4775
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4776
+	 *                           numerically indexed)
4777
+	 * @throws \EE_Error
4778
+	 */
4779
+	protected function _create_objects($rows = array())
4780
+	{
4781
+		$array_of_objects = array();
4782
+		if (empty($rows)) {
4783
+			return array();
4784
+		}
4785
+		$count_if_model_has_no_primary_key = 0;
4786
+		$has_primary_key = $this->has_primary_key_field();
4787
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4788
+		foreach ((array)$rows as $row) {
4789
+			if (empty($row)) {
4790
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4791
+				return array();
4792
+			}
4793
+			//check if we've already set this object in the results array,
4794
+			//in which case there's no need to process it further (again)
4795
+			if ($has_primary_key) {
4796
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4797
+					$row,
4798
+					$primary_key_field->get_qualified_column(),
4799
+					$primary_key_field->get_table_column()
4800
+				);
4801
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4802
+					continue;
4803
+				}
4804
+			}
4805
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4806
+			if (! $classInstance) {
4807
+				throw new EE_Error(
4808
+					sprintf(
4809
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4810
+						$this->get_this_model_name(),
4811
+						http_build_query($row)
4812
+					)
4813
+				);
4814
+			}
4815
+			//set the timezone on the instantiated objects
4816
+			$classInstance->set_timezone($this->_timezone);
4817
+			//make sure if there is any timezone setting present that we set the timezone for the object
4818
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4819
+			$array_of_objects[$key] = $classInstance;
4820
+			//also, for all the relations of type BelongsTo, see if we can cache
4821
+			//those related models
4822
+			//(we could do this for other relations too, but if there are conditions
4823
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4824
+			//so it requires a little more thought than just caching them immediately...)
4825
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4826
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4827
+					//check if this model's INFO is present. If so, cache it on the model
4828
+					$other_model = $relation_obj->get_other_model();
4829
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4830
+					//if we managed to make a model object from the results, cache it on the main model object
4831
+					if ($other_model_obj_maybe) {
4832
+						//set timezone on these other model objects if they are present
4833
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4834
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4835
+					}
4836
+				}
4837
+			}
4838
+		}
4839
+		return $array_of_objects;
4840
+	}
4841
+
4842
+
4843
+
4844
+	/**
4845
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4846
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4847
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4848
+	 * object (as set in the model_field!).
4849
+	 *
4850
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4851
+	 */
4852
+	public function create_default_object()
4853
+	{
4854
+		$this_model_fields_and_values = array();
4855
+		//setup the row using default values;
4856
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4857
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4858
+		}
4859
+		$className = $this->_get_class_name();
4860
+		$classInstance = EE_Registry::instance()
4861
+									->load_class($className, array($this_model_fields_and_values), false, false);
4862
+		return $classInstance;
4863
+	}
4864
+
4865
+
4866
+
4867
+	/**
4868
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4869
+	 *                             or an stdClass where each property is the name of a column,
4870
+	 * @return EE_Base_Class
4871
+	 * @throws \EE_Error
4872
+	 */
4873
+	public function instantiate_class_from_array_or_object($cols_n_values)
4874
+	{
4875
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4876
+			$cols_n_values = get_object_vars($cols_n_values);
4877
+		}
4878
+		$primary_key = null;
4879
+		//make sure the array only has keys that are fields/columns on this model
4880
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4881
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4882
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4883
+		}
4884
+		$className = $this->_get_class_name();
4885
+		//check we actually found results that we can use to build our model object
4886
+		//if not, return null
4887
+		if ($this->has_primary_key_field()) {
4888
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4889
+				return null;
4890
+			}
4891
+		} else if ($this->unique_indexes()) {
4892
+			$first_column = reset($this_model_fields_n_values);
4893
+			if (empty($first_column)) {
4894
+				return null;
4895
+			}
4896
+		}
4897
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4898
+		if ($primary_key) {
4899
+			$classInstance = $this->get_from_entity_map($primary_key);
4900
+			if (! $classInstance) {
4901
+				$classInstance = EE_Registry::instance()
4902
+											->load_class($className,
4903
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4904
+				// add this new object to the entity map
4905
+				$classInstance = $this->add_to_entity_map($classInstance);
4906
+			}
4907
+		} else {
4908
+			$classInstance = EE_Registry::instance()
4909
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4910
+											true, false);
4911
+		}
4912
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
4913
+		$this->set_timezone($classInstance->get_timezone());
4914
+		return $classInstance;
4915
+	}
4916
+
4917
+
4918
+
4919
+	/**
4920
+	 * Gets the model object from the  entity map if it exists
4921
+	 *
4922
+	 * @param int|string $id the ID of the model object
4923
+	 * @return EE_Base_Class
4924
+	 */
4925
+	public function get_from_entity_map($id)
4926
+	{
4927
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4928
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4929
+	}
4930
+
4931
+
4932
+
4933
+	/**
4934
+	 * add_to_entity_map
4935
+	 * Adds the object to the model's entity mappings
4936
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4937
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4938
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4939
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4940
+	 *        then this method should be called immediately after the update query
4941
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4942
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4943
+	 *
4944
+	 * @param    EE_Base_Class $object
4945
+	 * @throws EE_Error
4946
+	 * @return \EE_Base_Class
4947
+	 */
4948
+	public function add_to_entity_map(EE_Base_Class $object)
4949
+	{
4950
+		$className = $this->_get_class_name();
4951
+		if (! $object instanceof $className) {
4952
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4953
+				is_object($object) ? get_class($object) : $object, $className));
4954
+		}
4955
+		/** @var $object EE_Base_Class */
4956
+		if (! $object->ID()) {
4957
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4958
+				"event_espresso"), get_class($this)));
4959
+		}
4960
+		// double check it's not already there
4961
+		$classInstance = $this->get_from_entity_map($object->ID());
4962
+		if ($classInstance) {
4963
+			return $classInstance;
4964
+		} else {
4965
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4966
+			return $object;
4967
+		}
4968
+	}
4969
+
4970
+
4971
+
4972
+	/**
4973
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4974
+	 * if no identifier is provided, then the entire entity map is emptied
4975
+	 *
4976
+	 * @param int|string $id the ID of the model object
4977
+	 * @return boolean
4978
+	 */
4979
+	public function clear_entity_map($id = null)
4980
+	{
4981
+		if (empty($id)) {
4982
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4983
+			return true;
4984
+		}
4985
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4986
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4987
+			return true;
4988
+		}
4989
+		return false;
4990
+	}
4991
+
4992
+
4993
+
4994
+	/**
4995
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4996
+	 * Given an array where keys are column (or column alias) names and values,
4997
+	 * returns an array of their corresponding field names and database values
4998
+	 *
4999
+	 * @param array $cols_n_values
5000
+	 * @return array
5001
+	 */
5002
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5003
+	{
5004
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5005
+	}
5006
+
5007
+
5008
+
5009
+	/**
5010
+	 * _deduce_fields_n_values_from_cols_n_values
5011
+	 * Given an array where keys are column (or column alias) names and values,
5012
+	 * returns an array of their corresponding field names and database values
5013
+	 *
5014
+	 * @param string $cols_n_values
5015
+	 * @return array
5016
+	 */
5017
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5018
+	{
5019
+		$this_model_fields_n_values = array();
5020
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5021
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5022
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5023
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5024
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5025
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5026
+					if (! $field_obj->is_db_only_field()) {
5027
+						//prepare field as if its coming from db
5028
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5029
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5030
+					}
5031
+				}
5032
+			} else {
5033
+				//the table's rows existed. Use their values
5034
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5035
+					if (! $field_obj->is_db_only_field()) {
5036
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5037
+							$cols_n_values, $field_obj->get_qualified_column(),
5038
+							$field_obj->get_table_column()
5039
+						);
5040
+					}
5041
+				}
5042
+			}
5043
+		}
5044
+		return $this_model_fields_n_values;
5045
+	}
5046
+
5047
+
5048
+
5049
+	/**
5050
+	 * @param $cols_n_values
5051
+	 * @param $qualified_column
5052
+	 * @param $regular_column
5053
+	 * @return null
5054
+	 */
5055
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5056
+	{
5057
+		$value = null;
5058
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5059
+		//does the field on the model relate to this column retrieved from the db?
5060
+		//or is it a db-only field? (not relating to the model)
5061
+		if (isset($cols_n_values[$qualified_column])) {
5062
+			$value = $cols_n_values[$qualified_column];
5063
+		} elseif (isset($cols_n_values[$regular_column])) {
5064
+			$value = $cols_n_values[$regular_column];
5065
+		}
5066
+		return $value;
5067
+	}
5068
+
5069
+
5070
+
5071
+	/**
5072
+	 * refresh_entity_map_from_db
5073
+	 * Makes sure the model object in the entity map at $id assumes the values
5074
+	 * of the database (opposite of EE_base_Class::save())
5075
+	 *
5076
+	 * @param int|string $id
5077
+	 * @return EE_Base_Class
5078
+	 * @throws \EE_Error
5079
+	 */
5080
+	public function refresh_entity_map_from_db($id)
5081
+	{
5082
+		$obj_in_map = $this->get_from_entity_map($id);
5083
+		if ($obj_in_map) {
5084
+			$wpdb_results = $this->_get_all_wpdb_results(
5085
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5086
+			);
5087
+			if ($wpdb_results && is_array($wpdb_results)) {
5088
+				$one_row = reset($wpdb_results);
5089
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5090
+					$obj_in_map->set_from_db($field_name, $db_value);
5091
+				}
5092
+				//clear the cache of related model objects
5093
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5094
+					$obj_in_map->clear_cache($relation_name, null, true);
5095
+				}
5096
+			}
5097
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5098
+			return $obj_in_map;
5099
+		} else {
5100
+			return $this->get_one_by_ID($id);
5101
+		}
5102
+	}
5103
+
5104
+
5105
+
5106
+	/**
5107
+	 * refresh_entity_map_with
5108
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5109
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5110
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5111
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5112
+	 *
5113
+	 * @param int|string    $id
5114
+	 * @param EE_Base_Class $replacing_model_obj
5115
+	 * @return \EE_Base_Class
5116
+	 * @throws \EE_Error
5117
+	 */
5118
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5119
+	{
5120
+		$obj_in_map = $this->get_from_entity_map($id);
5121
+		if ($obj_in_map) {
5122
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5123
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5124
+					$obj_in_map->set($field_name, $value);
5125
+				}
5126
+				//make the model object in the entity map's cache match the $replacing_model_obj
5127
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5128
+					$obj_in_map->clear_cache($relation_name, null, true);
5129
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5130
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5131
+					}
5132
+				}
5133
+			}
5134
+			return $obj_in_map;
5135
+		} else {
5136
+			$this->add_to_entity_map($replacing_model_obj);
5137
+			return $replacing_model_obj;
5138
+		}
5139
+	}
5140
+
5141
+
5142
+
5143
+	/**
5144
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5145
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5146
+	 * require_once($this->_getClassName().".class.php");
5147
+	 *
5148
+	 * @return string
5149
+	 */
5150
+	private function _get_class_name()
5151
+	{
5152
+		return "EE_" . $this->get_this_model_name();
5153
+	}
5154
+
5155
+
5156
+
5157
+	/**
5158
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5159
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5160
+	 * it would be 'Events'.
5161
+	 *
5162
+	 * @param int $quantity
5163
+	 * @return string
5164
+	 */
5165
+	public function item_name($quantity = 1)
5166
+	{
5167
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5168
+	}
5169
+
5170
+
5171
+
5172
+	/**
5173
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5174
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5175
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5176
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5177
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5178
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5179
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5180
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5181
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5182
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5183
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5184
+	 *        return $previousReturnValue.$returnString;
5185
+	 * }
5186
+	 * require('EEM_Answer.model.php');
5187
+	 * $answer=EEM_Answer::instance();
5188
+	 * echo $answer->my_callback('monkeys',100);
5189
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5190
+	 *
5191
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5192
+	 * @param array  $args       array of original arguments passed to the function
5193
+	 * @throws EE_Error
5194
+	 * @return mixed whatever the plugin which calls add_filter decides
5195
+	 */
5196
+	public function __call($methodName, $args)
5197
+	{
5198
+		$className = get_class($this);
5199
+		$tagName = "FHEE__{$className}__{$methodName}";
5200
+		if (! has_filter($tagName)) {
5201
+			throw new EE_Error(
5202
+				sprintf(
5203
+					__('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 );',
5204
+						'event_espresso'),
5205
+					$methodName,
5206
+					$className,
5207
+					$tagName,
5208
+					'<br />'
5209
+				)
5210
+			);
5211
+		}
5212
+		return apply_filters($tagName, null, $this, $args);
5213
+	}
5214
+
5215
+
5216
+
5217
+	/**
5218
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5219
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5220
+	 *
5221
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5222
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5223
+	 *                                                       the object's class name
5224
+	 *                                                       or object's ID
5225
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5226
+	 *                                                       exists in the database. If it does not, we add it
5227
+	 * @throws EE_Error
5228
+	 * @return EE_Base_Class
5229
+	 */
5230
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5231
+	{
5232
+		$className = $this->_get_class_name();
5233
+		if ($base_class_obj_or_id instanceof $className) {
5234
+			$model_object = $base_class_obj_or_id;
5235
+		} else {
5236
+			$primary_key_field = $this->get_primary_key_field();
5237
+			if (
5238
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5239
+				&& (
5240
+					is_int($base_class_obj_or_id)
5241
+					|| is_string($base_class_obj_or_id)
5242
+				)
5243
+			) {
5244
+				// assume it's an ID.
5245
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5246
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5247
+			} else if (
5248
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5249
+				&& is_string($base_class_obj_or_id)
5250
+			) {
5251
+				// assume its a string representation of the object
5252
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5253
+			} else {
5254
+				throw new EE_Error(
5255
+					sprintf(
5256
+						__(
5257
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5258
+							'event_espresso'
5259
+						),
5260
+						$base_class_obj_or_id,
5261
+						$this->_get_class_name(),
5262
+						print_r($base_class_obj_or_id, true)
5263
+					)
5264
+				);
5265
+			}
5266
+		}
5267
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5268
+			$model_object->save();
5269
+		}
5270
+		return $model_object;
5271
+	}
5272
+
5273
+
5274
+
5275
+	/**
5276
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5277
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5278
+	 * returns it ID.
5279
+	 *
5280
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5281
+	 * @return int|string depending on the type of this model object's ID
5282
+	 * @throws EE_Error
5283
+	 */
5284
+	public function ensure_is_ID($base_class_obj_or_id)
5285
+	{
5286
+		$className = $this->_get_class_name();
5287
+		if ($base_class_obj_or_id instanceof $className) {
5288
+			/** @var $base_class_obj_or_id EE_Base_Class */
5289
+			$id = $base_class_obj_or_id->ID();
5290
+		} elseif (is_int($base_class_obj_or_id)) {
5291
+			//assume it's an ID
5292
+			$id = $base_class_obj_or_id;
5293
+		} elseif (is_string($base_class_obj_or_id)) {
5294
+			//assume its a string representation of the object
5295
+			$id = $base_class_obj_or_id;
5296
+		} else {
5297
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5298
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5299
+				print_r($base_class_obj_or_id, true)));
5300
+		}
5301
+		return $id;
5302
+	}
5303
+
5304
+
5305
+
5306
+	/**
5307
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5308
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5309
+	 * been sanitized and converted into the appropriate domain.
5310
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5311
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5312
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5313
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5314
+	 * $EVT = EEM_Event::instance(); $old_setting =
5315
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5316
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5317
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5318
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5319
+	 *
5320
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5321
+	 * @return void
5322
+	 */
5323
+	public function assume_values_already_prepared_by_model_object(
5324
+		$values_already_prepared = self::not_prepared_by_model_object
5325
+	) {
5326
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5327
+	}
5328
+
5329
+
5330
+
5331
+	/**
5332
+	 * Read comments for assume_values_already_prepared_by_model_object()
5333
+	 *
5334
+	 * @return int
5335
+	 */
5336
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5337
+	{
5338
+		return $this->_values_already_prepared_by_model_object;
5339
+	}
5340
+
5341
+
5342
+
5343
+	/**
5344
+	 * Gets all the indexes on this model
5345
+	 *
5346
+	 * @return EE_Index[]
5347
+	 */
5348
+	public function indexes()
5349
+	{
5350
+		return $this->_indexes;
5351
+	}
5352
+
5353
+
5354
+
5355
+	/**
5356
+	 * Gets all the Unique Indexes on this model
5357
+	 *
5358
+	 * @return EE_Unique_Index[]
5359
+	 */
5360
+	public function unique_indexes()
5361
+	{
5362
+		$unique_indexes = array();
5363
+		foreach ($this->_indexes as $name => $index) {
5364
+			if ($index instanceof EE_Unique_Index) {
5365
+				$unique_indexes [$name] = $index;
5366
+			}
5367
+		}
5368
+		return $unique_indexes;
5369
+	}
5370
+
5371
+
5372
+
5373
+	/**
5374
+	 * Gets all the fields which, when combined, make the primary key.
5375
+	 * This is usually just an array with 1 element (the primary key), but in cases
5376
+	 * where there is no primary key, it's a combination of fields as defined
5377
+	 * on a primary index
5378
+	 *
5379
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5380
+	 * @throws \EE_Error
5381
+	 */
5382
+	public function get_combined_primary_key_fields()
5383
+	{
5384
+		foreach ($this->indexes() as $index) {
5385
+			if ($index instanceof EE_Primary_Key_Index) {
5386
+				return $index->fields();
5387
+			}
5388
+		}
5389
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5390
+	}
5391
+
5392
+
5393
+
5394
+	/**
5395
+	 * Used to build a primary key string (when the model has no primary key),
5396
+	 * which can be used a unique string to identify this model object.
5397
+	 *
5398
+	 * @param array $cols_n_values keys are field names, values are their values
5399
+	 * @return string
5400
+	 * @throws \EE_Error
5401
+	 */
5402
+	public function get_index_primary_key_string($cols_n_values)
5403
+	{
5404
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5405
+			$this->get_combined_primary_key_fields());
5406
+		return http_build_query($cols_n_values_for_primary_key_index);
5407
+	}
5408
+
5409
+
5410
+
5411
+	/**
5412
+	 * Gets the field values from the primary key string
5413
+	 *
5414
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5415
+	 * @param string $index_primary_key_string
5416
+	 * @return null|array
5417
+	 * @throws \EE_Error
5418
+	 */
5419
+	public function parse_index_primary_key_string($index_primary_key_string)
5420
+	{
5421
+		$key_fields = $this->get_combined_primary_key_fields();
5422
+		//check all of them are in the $id
5423
+		$key_vals_in_combined_pk = array();
5424
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5425
+		foreach ($key_fields as $key_field_name => $field_obj) {
5426
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5427
+				return null;
5428
+			}
5429
+		}
5430
+		return $key_vals_in_combined_pk;
5431
+	}
5432
+
5433
+
5434
+
5435
+	/**
5436
+	 * verifies that an array of key-value pairs for model fields has a key
5437
+	 * for each field comprising the primary key index
5438
+	 *
5439
+	 * @param array $key_vals
5440
+	 * @return boolean
5441
+	 * @throws \EE_Error
5442
+	 */
5443
+	public function has_all_combined_primary_key_fields($key_vals)
5444
+	{
5445
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5446
+		foreach ($keys_it_should_have as $key) {
5447
+			if (! isset($key_vals[$key])) {
5448
+				return false;
5449
+			}
5450
+		}
5451
+		return true;
5452
+	}
5453
+
5454
+
5455
+
5456
+	/**
5457
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5458
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5459
+	 *
5460
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5461
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5462
+	 * @throws EE_Error
5463
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5464
+	 *                                                              indexed)
5465
+	 */
5466
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5467
+	{
5468
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5469
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5470
+		} elseif (is_array($model_object_or_attributes_array)) {
5471
+			$attributes_array = $model_object_or_attributes_array;
5472
+		} else {
5473
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5474
+				"event_espresso"), $model_object_or_attributes_array));
5475
+		}
5476
+		//even copies obviously won't have the same ID, so remove the primary key
5477
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5478
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5479
+			unset($attributes_array[$this->primary_key_name()]);
5480
+		}
5481
+		if (isset($query_params[0])) {
5482
+			$query_params[0] = array_merge($attributes_array, $query_params);
5483
+		} else {
5484
+			$query_params[0] = $attributes_array;
5485
+		}
5486
+		return $this->get_all($query_params);
5487
+	}
5488
+
5489
+
5490
+
5491
+	/**
5492
+	 * Gets the first copy we find. See get_all_copies for more details
5493
+	 *
5494
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5495
+	 * @param array $query_params
5496
+	 * @return EE_Base_Class
5497
+	 * @throws \EE_Error
5498
+	 */
5499
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5500
+	{
5501
+		if (! is_array($query_params)) {
5502
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5503
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5504
+					gettype($query_params)), '4.6.0');
5505
+			$query_params = array();
5506
+		}
5507
+		$query_params['limit'] = 1;
5508
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5509
+		if (is_array($copies)) {
5510
+			return array_shift($copies);
5511
+		} else {
5512
+			return null;
5513
+		}
5514
+	}
5515
+
5516
+
5517
+
5518
+	/**
5519
+	 * Updates the item with the specified id. Ignores default query parameters because
5520
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5521
+	 *
5522
+	 * @param array      $fields_n_values keys are field names, values are their new values
5523
+	 * @param int|string $id              the value of the primary key to update
5524
+	 * @return int number of rows updated
5525
+	 * @throws \EE_Error
5526
+	 */
5527
+	public function update_by_ID($fields_n_values, $id)
5528
+	{
5529
+		$query_params = array(
5530
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5531
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5532
+		);
5533
+		return $this->update($fields_n_values, $query_params);
5534
+	}
5535
+
5536
+
5537
+
5538
+	/**
5539
+	 * Changes an operator which was supplied to the models into one usable in SQL
5540
+	 *
5541
+	 * @param string $operator_supplied
5542
+	 * @return string an operator which can be used in SQL
5543
+	 * @throws EE_Error
5544
+	 */
5545
+	private function _prepare_operator_for_sql($operator_supplied)
5546
+	{
5547
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5548
+			: null;
5549
+		if ($sql_operator) {
5550
+			return $sql_operator;
5551
+		} else {
5552
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5553
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5554
+		}
5555
+	}
5556
+
5557
+
5558
+
5559
+	/**
5560
+	 * Gets the valid operators
5561
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5562
+	 */
5563
+	public function valid_operators(){
5564
+		return $this->_valid_operators;
5565
+	}
5566
+
5567
+
5568
+
5569
+	/**
5570
+	 * Gets the between-style operators (take 2 arguments).
5571
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5572
+	 */
5573
+	public function valid_between_style_operators()
5574
+	{
5575
+		return array_intersect(
5576
+			$this->valid_operators(),
5577
+			$this->_between_style_operators
5578
+		);
5579
+	}
5580
+
5581
+	/**
5582
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5583
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5584
+	 */
5585
+	public function valid_like_style_operators()
5586
+	{
5587
+		return array_intersect(
5588
+			$this->valid_operators(),
5589
+			$this->_like_style_operators
5590
+		);
5591
+	}
5592
+
5593
+	/**
5594
+	 * Gets the "in"-style operators
5595
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5596
+	 */
5597
+	public function valid_in_style_operators()
5598
+	{
5599
+		return array_intersect(
5600
+			$this->valid_operators(),
5601
+			$this->_in_style_operators
5602
+		);
5603
+	}
5604
+
5605
+	/**
5606
+	 * Gets the "null"-style operators (accept no arguments)
5607
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5608
+	 */
5609
+	public function valid_null_style_operators()
5610
+	{
5611
+		return array_intersect(
5612
+			$this->valid_operators(),
5613
+			$this->_null_style_operators
5614
+		);
5615
+	}
5616
+
5617
+	/**
5618
+	 * Gets an array where keys are the primary keys and values are their 'names'
5619
+	 * (as determined by the model object's name() function, which is often overridden)
5620
+	 *
5621
+	 * @param array $query_params like get_all's
5622
+	 * @return string[]
5623
+	 * @throws \EE_Error
5624
+	 */
5625
+	public function get_all_names($query_params = array())
5626
+	{
5627
+		$objs = $this->get_all($query_params);
5628
+		$names = array();
5629
+		foreach ($objs as $obj) {
5630
+			$names[$obj->ID()] = $obj->name();
5631
+		}
5632
+		return $names;
5633
+	}
5634
+
5635
+
5636
+
5637
+	/**
5638
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5639
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5640
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5641
+	 * array_keys() on $model_objects.
5642
+	 *
5643
+	 * @param \EE_Base_Class[] $model_objects
5644
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5645
+	 *                                               in the returned array
5646
+	 * @return array
5647
+	 * @throws \EE_Error
5648
+	 */
5649
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5650
+	{
5651
+		if (! $this->has_primary_key_field()) {
5652
+			if (WP_DEBUG) {
5653
+				EE_Error::add_error(
5654
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5655
+					__FILE__,
5656
+					__FUNCTION__,
5657
+					__LINE__
5658
+				);
5659
+			}
5660
+		}
5661
+		$IDs = array();
5662
+		foreach ($model_objects as $model_object) {
5663
+			$id = $model_object->ID();
5664
+			if (! $id) {
5665
+				if ($filter_out_empty_ids) {
5666
+					continue;
5667
+				}
5668
+				if (WP_DEBUG) {
5669
+					EE_Error::add_error(
5670
+						__(
5671
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5672
+							'event_espresso'
5673
+						),
5674
+						__FILE__,
5675
+						__FUNCTION__,
5676
+						__LINE__
5677
+					);
5678
+				}
5679
+			}
5680
+			$IDs[] = $id;
5681
+		}
5682
+		return $IDs;
5683
+	}
5684
+
5685
+
5686
+
5687
+	/**
5688
+	 * Returns the string used in capabilities relating to this model. If there
5689
+	 * are no capabilities that relate to this model returns false
5690
+	 *
5691
+	 * @return string|false
5692
+	 */
5693
+	public function cap_slug()
5694
+	{
5695
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5696
+	}
5697
+
5698
+
5699
+
5700
+	/**
5701
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5702
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5703
+	 * only returns the cap restrictions array in that context (ie, the array
5704
+	 * at that key)
5705
+	 *
5706
+	 * @param string $context
5707
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5708
+	 * @throws \EE_Error
5709
+	 */
5710
+	public function cap_restrictions($context = EEM_Base::caps_read)
5711
+	{
5712
+		EEM_Base::verify_is_valid_cap_context($context);
5713
+		//check if we ought to run the restriction generator first
5714
+		if (
5715
+			isset($this->_cap_restriction_generators[$context])
5716
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5717
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5718
+		) {
5719
+			$this->_cap_restrictions[$context] = array_merge(
5720
+				$this->_cap_restrictions[$context],
5721
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5722
+			);
5723
+		}
5724
+		//and make sure we've finalized the construction of each restriction
5725
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5726
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5727
+				$where_conditions_obj->_finalize_construct($this);
5728
+			}
5729
+		}
5730
+		return $this->_cap_restrictions[$context];
5731
+	}
5732
+
5733
+
5734
+
5735
+	/**
5736
+	 * Indicating whether or not this model thinks its a wp core model
5737
+	 *
5738
+	 * @return boolean
5739
+	 */
5740
+	public function is_wp_core_model()
5741
+	{
5742
+		return $this->_wp_core_model;
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Gets all the caps that are missing which impose a restriction on
5749
+	 * queries made in this context
5750
+	 *
5751
+	 * @param string $context one of EEM_Base::caps_ constants
5752
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5753
+	 * @throws \EE_Error
5754
+	 */
5755
+	public function caps_missing($context = EEM_Base::caps_read)
5756
+	{
5757
+		$missing_caps = array();
5758
+		$cap_restrictions = $this->cap_restrictions($context);
5759
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5760
+			if (! EE_Capabilities::instance()
5761
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5762
+			) {
5763
+				$missing_caps[$cap] = $restriction_if_no_cap;
5764
+			}
5765
+		}
5766
+		return $missing_caps;
5767
+	}
5768
+
5769
+
5770
+
5771
+	/**
5772
+	 * Gets the mapping from capability contexts to action strings used in capability names
5773
+	 *
5774
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5775
+	 * one of 'read', 'edit', or 'delete'
5776
+	 */
5777
+	public function cap_contexts_to_cap_action_map()
5778
+	{
5779
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5780
+			$this);
5781
+	}
5782
+
5783
+
5784
+
5785
+	/**
5786
+	 * Gets the action string for the specified capability context
5787
+	 *
5788
+	 * @param string $context
5789
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5790
+	 * @throws \EE_Error
5791
+	 */
5792
+	public function cap_action_for_context($context)
5793
+	{
5794
+		$mapping = $this->cap_contexts_to_cap_action_map();
5795
+		if (isset($mapping[$context])) {
5796
+			return $mapping[$context];
5797
+		}
5798
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5799
+			return $action;
5800
+		}
5801
+		throw new EE_Error(
5802
+			sprintf(
5803
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5804
+				$context,
5805
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5806
+			)
5807
+		);
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Returns all the capability contexts which are valid when querying models
5814
+	 *
5815
+	 * @return array
5816
+	 */
5817
+	public static function valid_cap_contexts()
5818
+	{
5819
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5820
+			self::caps_read,
5821
+			self::caps_read_admin,
5822
+			self::caps_edit,
5823
+			self::caps_delete,
5824
+		));
5825
+	}
5826
+
5827
+
5828
+
5829
+	/**
5830
+	 * Returns all valid options for 'default_where_conditions'
5831
+	 *
5832
+	 * @return array
5833
+	 */
5834
+	public static function valid_default_where_conditions()
5835
+	{
5836
+		return array(
5837
+			EEM_Base::default_where_conditions_all,
5838
+			EEM_Base::default_where_conditions_this_only,
5839
+			EEM_Base::default_where_conditions_others_only,
5840
+			EEM_Base::default_where_conditions_minimum_all,
5841
+			EEM_Base::default_where_conditions_minimum_others,
5842
+			EEM_Base::default_where_conditions_none
5843
+		);
5844
+	}
5845
+
5846
+	// public static function default_where_conditions_full
5847
+	/**
5848
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5849
+	 *
5850
+	 * @param string $context
5851
+	 * @return bool
5852
+	 * @throws \EE_Error
5853
+	 */
5854
+	static public function verify_is_valid_cap_context($context)
5855
+	{
5856
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5857
+		if (in_array($context, $valid_cap_contexts)) {
5858
+			return true;
5859
+		} else {
5860
+			throw new EE_Error(
5861
+				sprintf(
5862
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5863
+						'event_espresso'),
5864
+					$context,
5865
+					'EEM_Base',
5866
+					implode(',', $valid_cap_contexts)
5867
+				)
5868
+			);
5869
+		}
5870
+	}
5871
+
5872
+
5873
+
5874
+	/**
5875
+	 * Clears all the models field caches. This is only useful when a sub-class
5876
+	 * might have added a field or something and these caches might be invalidated
5877
+	 */
5878
+	protected function _invalidate_field_caches()
5879
+	{
5880
+		$this->_cache_foreign_key_to_fields = array();
5881
+		$this->_cached_fields = null;
5882
+		$this->_cached_fields_non_db_only = null;
5883
+	}
5884
+
5885
+
5886
+
5887
+	/**
5888
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5889
+	 * (eg "and", "or", "not").
5890
+	 *
5891
+	 * @return array
5892
+	 */
5893
+	public function logic_query_param_keys()
5894
+	{
5895
+		return $this->_logic_query_param_keys;
5896
+	}
5897
+
5898
+
5899
+
5900
+	/**
5901
+	 * Determines whether or not the where query param array key is for a logic query param.
5902
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5903
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5904
+	 *
5905
+	 * @param $query_param_key
5906
+	 * @return bool
5907
+	 */
5908
+	public function is_logic_query_param_key($query_param_key)
5909
+	{
5910
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5911
+			if ($query_param_key === $logic_query_param_key
5912
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5913
+			) {
5914
+				return true;
5915
+			}
5916
+		}
5917
+		return false;
5918
+	}
5919 5919
 
5920 5920
 
5921 5921
 
Please login to merge, or discard this patch.
Spacing   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -505,8 +505,8 @@  discard block
 block discarded – undo
505 505
     protected function __construct($timezone = null)
506 506
     {
507 507
         // check that the model has not been loaded too soon
508
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
-            throw new EE_Error (
508
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
509
+            throw new EE_Error(
510 510
                 sprintf(
511 511
                     __('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.',
512 512
                         'event_espresso'),
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
          *
527 527
          * @var EE_Table_Base[] $_tables
528 528
          */
529
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
529
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
530 530
         foreach ($this->_tables as $table_alias => $table_obj) {
531 531
             /** @var $table_obj EE_Table_Base */
532 532
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -541,10 +541,10 @@  discard block
 block discarded – undo
541 541
          *
542 542
          * @param EE_Model_Field_Base[] $_fields
543 543
          */
544
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
544
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
545 545
         $this->_invalidate_field_caches();
546 546
         foreach ($this->_fields as $table_alias => $fields_for_table) {
547
-            if (! array_key_exists($table_alias, $this->_tables)) {
547
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
548 548
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549 549
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
550 550
             }
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
          *
573 573
          * @param EE_Model_Relation_Base[] $_model_relations
574 574
          */
575
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
575
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
576 576
             $this->_model_relations);
577 577
         foreach ($this->_model_relations as $model_name => $relation_obj) {
578 578
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -584,12 +584,12 @@  discard block
 block discarded – undo
584 584
         }
585 585
         $this->set_timezone($timezone);
586 586
         //finalize default where condition strategy, or set default
587
-        if (! $this->_default_where_conditions_strategy) {
587
+        if ( ! $this->_default_where_conditions_strategy) {
588 588
             //nothing was set during child constructor, so set default
589 589
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590 590
         }
591 591
         $this->_default_where_conditions_strategy->_finalize_construct($this);
592
-        if (! $this->_minimum_where_conditions_strategy) {
592
+        if ( ! $this->_minimum_where_conditions_strategy) {
593 593
             //nothing was set during child constructor, so set default
594 594
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595 595
         }
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
         //initialize the standard cap restriction generators if none were specified by the child constructor
603 603
         if ($this->_cap_restriction_generators !== false) {
604 604
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
605
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
606 606
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
607 607
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608 608
                         new EE_Restriction_Generator_Protected(),
@@ -615,10 +615,10 @@  discard block
 block discarded – undo
615 615
         //if there are cap restriction generators, use them to make the default cap restrictions
616 616
         if ($this->_cap_restriction_generators !== false) {
617 617
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
-                if (! $generator_object) {
618
+                if ( ! $generator_object) {
619 619
                     continue;
620 620
                 }
621
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
621
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
622 622
                     throw new EE_Error(
623 623
                         sprintf(
624 624
                             __('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.',
@@ -629,12 +629,12 @@  discard block
 block discarded – undo
629 629
                     );
630 630
                 }
631 631
                 $action = $this->cap_action_for_context($context);
632
-                if (! $generator_object->construction_finalized()) {
632
+                if ( ! $generator_object->construction_finalized()) {
633 633
                     $generator_object->_construct_finalize($this, $action);
634 634
                 }
635 635
             }
636 636
         }
637
-        do_action('AHEE__' . get_class($this) . '__construct__end');
637
+        do_action('AHEE__'.get_class($this).'__construct__end');
638 638
     }
639 639
 
640 640
 
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
      */
670 670
     public static function set_model_query_blog_id($blog_id = 0)
671 671
     {
672
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
672
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
673 673
     }
674 674
 
675 675
 
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
     public static function instance($timezone = null)
700 700
     {
701 701
         // check if instance of Espresso_model already exists
702
-        if (! static::$_instance instanceof static) {
702
+        if ( ! static::$_instance instanceof static) {
703 703
             // instantiate Espresso_model
704 704
             static::$_instance = new static($timezone);
705 705
         }
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -753,7 +753,7 @@  discard block
 block discarded – undo
753 753
      */
754 754
     public function status_array($translated = false)
755 755
     {
756
-        if (! array_key_exists('Status', $this->_model_relations)) {
756
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
757 757
             return array();
758 758
         }
759 759
         $model_name = $this->get_this_model_name();
@@ -956,17 +956,17 @@  discard block
 block discarded – undo
956 956
     public function wp_user_field_name()
957 957
     {
958 958
         try {
959
-            if (! empty($this->_model_chain_to_wp_user)) {
959
+            if ( ! empty($this->_model_chain_to_wp_user)) {
960 960
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
961 961
                 $last_model_name = end($models_to_follow_to_wp_users);
962 962
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
963
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
963
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
964 964
             } else {
965 965
                 $model_with_fk_to_wp_users = $this;
966 966
                 $model_chain_to_wp_user = '';
967 967
             }
968 968
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
969
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
969
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
970 970
         } catch (EE_Error $e) {
971 971
             return false;
972 972
         }
@@ -1038,12 +1038,12 @@  discard block
 block discarded – undo
1038 1038
         // remember the custom selections, if any, and type cast as array
1039 1039
         // (unless $columns_to_select is an object, then just set as an empty array)
1040 1040
         // Note: (array) 'some string' === array( 'some string' )
1041
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1041
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1042 1042
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1043 1043
         $select_expressions = $columns_to_select !== null
1044 1044
             ? $this->_construct_select_from_input($columns_to_select)
1045 1045
             : $this->_construct_default_select_sql($model_query_info);
1046
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1046
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1047 1047
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1048 1048
     }
1049 1049
 
@@ -1088,7 +1088,7 @@  discard block
 block discarded – undo
1088 1088
         if (is_array($columns_to_select)) {
1089 1089
             $select_sql_array = array();
1090 1090
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1091
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1091
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1092 1092
                     throw new EE_Error(
1093 1093
                         sprintf(
1094 1094
                             __(
@@ -1100,7 +1100,7 @@  discard block
 block discarded – undo
1100 1100
                         )
1101 1101
                     );
1102 1102
                 }
1103
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1103
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1104 1104
                     throw new EE_Error(
1105 1105
                         sprintf(
1106 1106
                             __(
@@ -1172,7 +1172,7 @@  discard block
 block discarded – undo
1172 1172
      */
1173 1173
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1174 1174
     {
1175
-        if (! isset($query_params[0])) {
1175
+        if ( ! isset($query_params[0])) {
1176 1176
             $query_params[0] = array();
1177 1177
         }
1178 1178
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1197,7 +1197,7 @@  discard block
 block discarded – undo
1197 1197
      */
1198 1198
     public function get_one($query_params = array())
1199 1199
     {
1200
-        if (! is_array($query_params)) {
1200
+        if ( ! is_array($query_params)) {
1201 1201
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1202 1202
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1203 1203
                     gettype($query_params)), '4.6.0');
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
                 return array();
1366 1366
             }
1367 1367
         }
1368
-        if (! is_array($query_params)) {
1368
+        if ( ! is_array($query_params)) {
1369 1369
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1370 1370
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1371 1371
                     gettype($query_params)), '4.6.0');
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1376 1376
         $query_params['limit'] = $limit;
1377 1377
         //set direction
1378
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1378
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1379 1379
         $query_params['order_by'] = $operand === '>'
1380 1380
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1381 1381
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1454,7 +1454,7 @@  discard block
 block discarded – undo
1454 1454
     {
1455 1455
         $field_settings = $this->field_settings_for($field_name);
1456 1456
         //if not a valid EE_Datetime_Field then throw error
1457
-        if (! $field_settings instanceof EE_Datetime_Field) {
1457
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1458 1458
             throw new EE_Error(sprintf(__('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.',
1459 1459
                 'event_espresso'), $field_name));
1460 1460
         }
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
         //load EEH_DTT_Helper
1532 1532
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1533 1533
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1534
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1534
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1535 1535
     }
1536 1536
 
1537 1537
 
@@ -1599,7 +1599,7 @@  discard block
 block discarded – undo
1599 1599
      */
1600 1600
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1601 1601
     {
1602
-        if (! is_array($query_params)) {
1602
+        if ( ! is_array($query_params)) {
1603 1603
             EE_Error::doing_it_wrong('EEM_Base::update',
1604 1604
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1605 1605
                     gettype($query_params)), '4.6.0');
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
          * @param EEM_Base $model           the model being queried
1622 1622
          * @param array    $query_params    see EEM_Base::get_all()
1623 1623
          */
1624
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1624
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1625 1625
             $query_params);
1626 1626
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1627 1627
         //to do that, for each table, verify that it's PK isn't null.
@@ -1635,7 +1635,7 @@  discard block
 block discarded – undo
1635 1635
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1636 1636
         foreach ($wpdb_select_results as $wpdb_result) {
1637 1637
             // type cast stdClass as array
1638
-            $wpdb_result = (array)$wpdb_result;
1638
+            $wpdb_result = (array) $wpdb_result;
1639 1639
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1640 1640
             if ($this->has_primary_key_field()) {
1641 1641
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1652,13 +1652,13 @@  discard block
 block discarded – undo
1652 1652
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1653 1653
                     //if there is no private key for this table on the results, it means there's no entry
1654 1654
                     //in this table, right? so insert a row in the current table, using any fields available
1655
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1655
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1656 1656
                            && $wpdb_result[$this_table_pk_column])
1657 1657
                     ) {
1658 1658
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1659 1659
                             $main_table_pk_value);
1660 1660
                         //if we died here, report the error
1661
-                        if (! $success) {
1661
+                        if ( ! $success) {
1662 1662
                             return false;
1663 1663
                         }
1664 1664
                     }
@@ -1689,7 +1689,7 @@  discard block
 block discarded – undo
1689 1689
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1690 1690
                 }
1691 1691
             }
1692
-            if (! $model_objs_affected_ids) {
1692
+            if ( ! $model_objs_affected_ids) {
1693 1693
                 //wait wait wait- if nothing was affected let's stop here
1694 1694
                 return 0;
1695 1695
             }
@@ -1716,7 +1716,7 @@  discard block
 block discarded – undo
1716 1716
                . $model_query_info->get_full_join_sql()
1717 1717
                . " SET "
1718 1718
                . $this->_construct_update_sql($fields_n_values)
1719
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1719
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1720 1720
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1721 1721
         /**
1722 1722
          * Action called after a model update call has been made.
@@ -1727,7 +1727,7 @@  discard block
 block discarded – undo
1727 1727
          * @param int      $rows_affected
1728 1728
          */
1729 1729
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1730
-        return $rows_affected;//how many supposedly got updated
1730
+        return $rows_affected; //how many supposedly got updated
1731 1731
     }
1732 1732
 
1733 1733
 
@@ -1755,7 +1755,7 @@  discard block
 block discarded – undo
1755 1755
         }
1756 1756
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1757 1757
         $select_expressions = $field->get_qualified_column();
1758
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1758
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1759 1759
         return $this->_do_wpdb_query('get_col', array($SQL));
1760 1760
     }
1761 1761
 
@@ -1773,7 +1773,7 @@  discard block
 block discarded – undo
1773 1773
     {
1774 1774
         $query_params['limit'] = 1;
1775 1775
         $col = $this->get_col($query_params, $field_to_select);
1776
-        if (! empty($col)) {
1776
+        if ( ! empty($col)) {
1777 1777
             return reset($col);
1778 1778
         } else {
1779 1779
             return null;
@@ -1805,7 +1805,7 @@  discard block
 block discarded – undo
1805 1805
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1806 1806
             $value_sql = $prepared_value === null ? 'NULL'
1807 1807
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1808
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1808
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1809 1809
         }
1810 1810
         return implode(",", $cols_n_values);
1811 1811
     }
@@ -1941,7 +1941,7 @@  discard block
 block discarded – undo
1941 1941
          * @param int      $rows_deleted
1942 1942
          */
1943 1943
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1944
-        return $rows_deleted;//how many supposedly got deleted
1944
+        return $rows_deleted; //how many supposedly got deleted
1945 1945
     }
1946 1946
 
1947 1947
 
@@ -2020,7 +2020,7 @@  discard block
 block discarded – undo
2020 2020
             $other_tables = $this->_get_other_tables();
2021 2021
             $ot_pk_fields = array();
2022 2022
             $ot_fk_fields = array();
2023
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2023
+            foreach ($other_tables as $other_table_alias => $other_table_obj) {
2024 2024
                 $ot_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2025 2025
                 $ot_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2026 2026
             }
@@ -2045,7 +2045,7 @@  discard block
 block discarded – undo
2045 2045
                     );
2046 2046
                 }
2047 2047
                 //other tables
2048
-                if (! empty($other_tables)) {
2048
+                if ( ! empty($other_tables)) {
2049 2049
                     foreach ($other_tables as $ot_alias => $ot) {
2050 2050
                         $ot_pk_field = $ot_pk_fields[$ot_alias];
2051 2051
                         $ot_fk_field = $ot_fk_fields[$ot_alias];
@@ -2079,7 +2079,7 @@  discard block
 block discarded – undo
2079 2079
             foreach ($deletes as $column => $values) {
2080 2080
                 //make sure we have unique $values;
2081 2081
                 $values = array_unique($values);
2082
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2082
+                $query[] = $column.' IN('.implode(",", $values).')';
2083 2083
             }
2084 2084
             return ! empty($query) ? implode(' AND ', $query) : '';
2085 2085
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2095,7 +2095,7 @@  discard block
 block discarded – undo
2095 2095
                                                            . $delete_object[$cpk_field->get_qualified_column()];
2096 2096
                     }
2097 2097
                 }
2098
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
2098
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $values_for_each_cpk_for_a_row).")";
2099 2099
             }
2100 2100
             return implode(" OR ", $ways_to_identify_a_row);
2101 2101
         } else {
@@ -2114,8 +2114,8 @@  discard block
 block discarded – undo
2114 2114
      */
2115 2115
     public function get_field_by_column($qualified_column_name)
2116 2116
     {
2117
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2118
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2117
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2118
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2119 2119
                return $field_obj;
2120 2120
            }
2121 2121
        }
@@ -2166,9 +2166,9 @@  discard block
 block discarded – undo
2166 2166
                 $column_to_count = '*';
2167 2167
             }
2168 2168
         }
2169
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2170
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2171
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2169
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2170
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2171
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2172 2172
     }
2173 2173
 
2174 2174
 
@@ -2190,13 +2190,13 @@  discard block
 block discarded – undo
2190 2190
             $field_obj = $this->get_primary_key_field();
2191 2191
         }
2192 2192
         $column_to_count = $field_obj->get_qualified_column();
2193
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2193
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2194 2194
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2195 2195
         $data_type = $field_obj->get_wpdb_data_type();
2196 2196
         if ($data_type === '%d' || $data_type === '%s') {
2197
-            return (float)$return_value;
2197
+            return (float) $return_value;
2198 2198
         } else {//must be %f
2199
-            return (float)$return_value;
2199
+            return (float) $return_value;
2200 2200
         }
2201 2201
     }
2202 2202
 
@@ -2217,13 +2217,13 @@  discard block
 block discarded – undo
2217 2217
         //if we're in maintenance mode level 2, DON'T run any queries
2218 2218
         //because level 2 indicates the database needs updating and
2219 2219
         //is probably out of sync with the code
2220
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2220
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2221 2221
             throw new EE_Error(sprintf(__("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.",
2222 2222
                 "event_espresso")));
2223 2223
         }
2224 2224
         /** @type WPDB $wpdb */
2225 2225
         global $wpdb;
2226
-        if (! method_exists($wpdb, $wpdb_method)) {
2226
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2227 2227
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2228 2228
                 'event_espresso'), $wpdb_method));
2229 2229
         }
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2236 2236
         if (WP_DEBUG) {
2237 2237
             $wpdb->show_errors($old_show_errors_value);
2238
-            if (! empty($wpdb->last_error)) {
2238
+            if ( ! empty($wpdb->last_error)) {
2239 2239
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2240 2240
             } elseif ($result === false) {
2241 2241
                 throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
@@ -2295,7 +2295,7 @@  discard block
 block discarded – undo
2295 2295
                     return $result;
2296 2296
                     break;
2297 2297
             }
2298
-            if (! empty($error_message)) {
2298
+            if ( ! empty($error_message)) {
2299 2299
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2300 2300
                 trigger_error($error_message);
2301 2301
             }
@@ -2371,11 +2371,11 @@  discard block
 block discarded – undo
2371 2371
      */
2372 2372
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2373 2373
     {
2374
-        return " FROM " . $model_query_info->get_full_join_sql() .
2375
-               $model_query_info->get_where_sql() .
2376
-               $model_query_info->get_group_by_sql() .
2377
-               $model_query_info->get_having_sql() .
2378
-               $model_query_info->get_order_by_sql() .
2374
+        return " FROM ".$model_query_info->get_full_join_sql().
2375
+               $model_query_info->get_where_sql().
2376
+               $model_query_info->get_group_by_sql().
2377
+               $model_query_info->get_having_sql().
2378
+               $model_query_info->get_order_by_sql().
2379 2379
                $model_query_info->get_limit_sql();
2380 2380
     }
2381 2381
 
@@ -2571,12 +2571,12 @@  discard block
 block discarded – undo
2571 2571
         $related_model = $this->get_related_model_obj($model_name);
2572 2572
         //we're just going to use the query params on the related model's normal get_all query,
2573 2573
         //except add a condition to say to match the current mod
2574
-        if (! isset($query_params['default_where_conditions'])) {
2574
+        if ( ! isset($query_params['default_where_conditions'])) {
2575 2575
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2576 2576
         }
2577 2577
         $this_model_name = $this->get_this_model_name();
2578 2578
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2579
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2579
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2580 2580
         return $related_model->count($query_params, $field_to_count, $distinct);
2581 2581
     }
2582 2582
 
@@ -2596,7 +2596,7 @@  discard block
 block discarded – undo
2596 2596
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2597 2597
     {
2598 2598
         $related_model = $this->get_related_model_obj($model_name);
2599
-        if (! is_array($query_params)) {
2599
+        if ( ! is_array($query_params)) {
2600 2600
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2601 2601
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2602 2602
                     gettype($query_params)), '4.6.0');
@@ -2604,12 +2604,12 @@  discard block
 block discarded – undo
2604 2604
         }
2605 2605
         //we're just going to use the query params on the related model's normal get_all query,
2606 2606
         //except add a condition to say to match the current mod
2607
-        if (! isset($query_params['default_where_conditions'])) {
2607
+        if ( ! isset($query_params['default_where_conditions'])) {
2608 2608
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2609 2609
         }
2610 2610
         $this_model_name = $this->get_this_model_name();
2611 2611
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2612
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2612
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2613 2613
         return $related_model->sum($query_params, $field_to_sum);
2614 2614
     }
2615 2615
 
@@ -2663,7 +2663,7 @@  discard block
 block discarded – undo
2663 2663
                 $field_with_model_name = $field;
2664 2664
             }
2665 2665
         }
2666
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2666
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2667 2667
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2668 2668
                 $this->get_this_model_name()));
2669 2669
         }
@@ -2696,7 +2696,7 @@  discard block
 block discarded – undo
2696 2696
          * @param array    $fields_n_values keys are the fields and values are their new values
2697 2697
          * @param EEM_Base $model           the model used
2698 2698
          */
2699
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2699
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2700 2700
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2701 2701
             $main_table = $this->_get_main_table();
2702 2702
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2804,7 +2804,7 @@  discard block
 block discarded – undo
2804 2804
         }
2805 2805
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2806 2806
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2807
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2807
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2808 2808
         }
2809 2809
         //if there is nothing to base this search on, then we shouldn't find anything
2810 2810
         if (empty($query_params)) {
@@ -2891,7 +2891,7 @@  discard block
 block discarded – undo
2891 2891
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2892 2892
             //so add the fk to the main table as a column
2893 2893
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2894
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2894
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2895 2895
         }
2896 2896
         //insert the new entry
2897 2897
         $result = $this->_do_wpdb_query('insert',
@@ -2930,7 +2930,7 @@  discard block
 block discarded – undo
2930 2930
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2931 2931
     {
2932 2932
         //if this field doesn't allow nullable, don't allow it
2933
-        if (! $field_obj->is_nullable()
2933
+        if ( ! $field_obj->is_nullable()
2934 2934
             && (
2935 2935
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2936 2936
         ) {
@@ -3093,7 +3093,7 @@  discard block
 block discarded – undo
3093 3093
                     $query_info_carrier,
3094 3094
                     'group_by'
3095 3095
                 );
3096
-            } elseif (! empty ($query_params['group_by'])) {
3096
+            } elseif ( ! empty ($query_params['group_by'])) {
3097 3097
                 $this->_extract_related_model_info_from_query_param(
3098 3098
                     $query_params['group_by'],
3099 3099
                     $query_info_carrier,
@@ -3115,7 +3115,7 @@  discard block
 block discarded – undo
3115 3115
                     $query_info_carrier,
3116 3116
                     'order_by'
3117 3117
                 );
3118
-            } elseif (! empty($query_params['order_by'])) {
3118
+            } elseif ( ! empty($query_params['order_by'])) {
3119 3119
                 $this->_extract_related_model_info_from_query_param(
3120 3120
                     $query_params['order_by'],
3121 3121
                     $query_info_carrier,
@@ -3150,8 +3150,8 @@  discard block
 block discarded – undo
3150 3150
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3151 3151
         $query_param_type
3152 3152
     ) {
3153
-        if (! empty($sub_query_params)) {
3154
-            $sub_query_params = (array)$sub_query_params;
3153
+        if ( ! empty($sub_query_params)) {
3154
+            $sub_query_params = (array) $sub_query_params;
3155 3155
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3156 3156
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3157 3157
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3162,7 +3162,7 @@  discard block
 block discarded – undo
3162 3162
                 //of array('Registration.TXN_ID'=>23)
3163 3163
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3164 3164
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3165
-                    if (! is_array($possibly_array_of_params)) {
3165
+                    if ( ! is_array($possibly_array_of_params)) {
3166 3166
                         throw new EE_Error(sprintf(__("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'))",
3167 3167
                             "event_espresso"),
3168 3168
                             $param, $possibly_array_of_params));
@@ -3178,7 +3178,7 @@  discard block
 block discarded – undo
3178 3178
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3179 3179
                     //indicating that $possible_array_of_params[1] is actually a field name,
3180 3180
                     //from which we should extract query parameters!
3181
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3181
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3182 3182
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3183 3183
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3184 3184
                     }
@@ -3208,8 +3208,8 @@  discard block
 block discarded – undo
3208 3208
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3209 3209
         $query_param_type
3210 3210
     ) {
3211
-        if (! empty($sub_query_params)) {
3212
-            if (! is_array($sub_query_params)) {
3211
+        if ( ! empty($sub_query_params)) {
3212
+            if ( ! is_array($sub_query_params)) {
3213 3213
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3214 3214
                     $sub_query_params));
3215 3215
             }
@@ -3238,7 +3238,7 @@  discard block
 block discarded – undo
3238 3238
      */
3239 3239
     public function _create_model_query_info_carrier($query_params)
3240 3240
     {
3241
-        if (! is_array($query_params)) {
3241
+        if ( ! is_array($query_params)) {
3242 3242
             EE_Error::doing_it_wrong(
3243 3243
                 'EEM_Base::_create_model_query_info_carrier',
3244 3244
                 sprintf(
@@ -3314,7 +3314,7 @@  discard block
 block discarded – undo
3314 3314
         //set limit
3315 3315
         if (array_key_exists('limit', $query_params)) {
3316 3316
             if (is_array($query_params['limit'])) {
3317
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3317
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3318 3318
                     $e = sprintf(
3319 3319
                         __(
3320 3320
                             "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)",
@@ -3322,12 +3322,12 @@  discard block
 block discarded – undo
3322 3322
                         ),
3323 3323
                         http_build_query($query_params['limit'])
3324 3324
                     );
3325
-                    throw new EE_Error($e . "|" . $e);
3325
+                    throw new EE_Error($e."|".$e);
3326 3326
                 }
3327 3327
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3328
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3329
-            } elseif (! empty ($query_params['limit'])) {
3330
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3328
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3329
+            } elseif ( ! empty ($query_params['limit'])) {
3330
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3331 3331
             }
3332 3332
         }
3333 3333
         //set order by
@@ -3359,10 +3359,10 @@  discard block
 block discarded – undo
3359 3359
                 $order_array = array();
3360 3360
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3361 3361
                     $order = $this->_extract_order($order);
3362
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3362
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3363 3363
                 }
3364
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3365
-            } elseif (! empty ($query_params['order_by'])) {
3364
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3365
+            } elseif ( ! empty ($query_params['order_by'])) {
3366 3366
                 $this->_extract_related_model_info_from_query_param(
3367 3367
                     $query_params['order_by'],
3368 3368
                     $query_object,
@@ -3373,18 +3373,18 @@  discard block
 block discarded – undo
3373 3373
                     ? $this->_extract_order($query_params['order'])
3374 3374
                     : 'DESC';
3375 3375
                 $query_object->set_order_by_sql(
3376
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3376
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3377 3377
                 );
3378 3378
             }
3379 3379
         }
3380 3380
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3381
-        if (! array_key_exists('order_by', $query_params)
3381
+        if ( ! array_key_exists('order_by', $query_params)
3382 3382
             && array_key_exists('order', $query_params)
3383 3383
             && ! empty($query_params['order'])
3384 3384
         ) {
3385 3385
             $pk_field = $this->get_primary_key_field();
3386 3386
             $order = $this->_extract_order($query_params['order']);
3387
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3387
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3388 3388
         }
3389 3389
         //set group by
3390 3390
         if (array_key_exists('group_by', $query_params)) {
@@ -3394,10 +3394,10 @@  discard block
 block discarded – undo
3394 3394
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3395 3395
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3396 3396
                 }
3397
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3398
-            } elseif (! empty ($query_params['group_by'])) {
3397
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3398
+            } elseif ( ! empty ($query_params['group_by'])) {
3399 3399
                 $query_object->set_group_by_sql(
3400
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3400
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3401 3401
                 );
3402 3402
             }
3403 3403
         }
@@ -3407,7 +3407,7 @@  discard block
 block discarded – undo
3407 3407
         }
3408 3408
         //now, just verify they didn't pass anything wack
3409 3409
         foreach ($query_params as $query_key => $query_value) {
3410
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3410
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3411 3411
                 throw new EE_Error(
3412 3412
                     sprintf(
3413 3413
                         __(
@@ -3501,22 +3501,22 @@  discard block
 block discarded – undo
3501 3501
         $where_query_params = array()
3502 3502
     ) {
3503 3503
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3504
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3504
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3505 3505
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3506 3506
                 "event_espresso"), $use_default_where_conditions,
3507 3507
                 implode(", ", $allowed_used_default_where_conditions_values)));
3508 3508
         }
3509 3509
         $universal_query_params = array();
3510
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3510
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3511 3511
             $universal_query_params = $this->_get_default_where_conditions();
3512
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3512
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3513 3513
             $universal_query_params = $this->_get_minimum_where_conditions();
3514 3514
         }
3515 3515
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3516 3516
             $related_model = $this->get_related_model_obj($model_name);
3517
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3517
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3518 3518
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3519
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3519
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3520 3520
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3521 3521
             } else {
3522 3522
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3549,7 +3549,7 @@  discard block
 block discarded – undo
3549 3549
      * @param bool $for_this_model false means this is for OTHER related models
3550 3550
      * @return bool
3551 3551
      */
3552
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3552
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3553 3553
     {
3554 3554
         return (
3555 3555
                    $for_this_model
@@ -3628,7 +3628,7 @@  discard block
 block discarded – undo
3628 3628
     ) {
3629 3629
         $null_friendly_where_conditions = array();
3630 3630
         $none_overridden = true;
3631
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3631
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3632 3632
         foreach ($default_where_conditions as $key => $val) {
3633 3633
             if (isset($provided_where_conditions[$key])) {
3634 3634
                 $none_overridden = false;
@@ -3746,7 +3746,7 @@  discard block
 block discarded – undo
3746 3746
             foreach ($tables as $table_obj) {
3747 3747
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3748 3748
                                        . $table_obj->get_fully_qualified_pk_column();
3749
-                if (! in_array($qualified_pk_column, $selects)) {
3749
+                if ( ! in_array($qualified_pk_column, $selects)) {
3750 3750
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3751 3751
                 }
3752 3752
             }
@@ -3832,9 +3832,9 @@  discard block
 block discarded – undo
3832 3832
         //and
3833 3833
         //check if it's a field on a related model
3834 3834
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3835
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3835
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3836 3836
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3837
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3837
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3838 3838
                 if ($query_param === '') {
3839 3839
                     //nothing left to $query_param
3840 3840
                     //we should actually end in a field name, not a model like this!
@@ -3920,7 +3920,7 @@  discard block
 block discarded – undo
3920 3920
     {
3921 3921
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3922 3922
         if ($SQL) {
3923
-            return " WHERE " . $SQL;
3923
+            return " WHERE ".$SQL;
3924 3924
         } else {
3925 3925
             return '';
3926 3926
         }
@@ -3940,7 +3940,7 @@  discard block
 block discarded – undo
3940 3940
     {
3941 3941
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3942 3942
         if ($SQL) {
3943
-            return " HAVING " . $SQL;
3943
+            return " HAVING ".$SQL;
3944 3944
         } else {
3945 3945
             return '';
3946 3946
         }
@@ -3960,7 +3960,7 @@  discard block
 block discarded – undo
3960 3960
     {
3961 3961
         $where_clauses = array();
3962 3962
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3963
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3963
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3964 3964
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3965 3965
                 switch ($query_param) {
3966 3966
                     case 'not':
@@ -3988,7 +3988,7 @@  discard block
 block discarded – undo
3988 3988
             } else {
3989 3989
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3990 3990
                 //if it's not a normal field, maybe it's a custom selection?
3991
-                if (! $field_obj) {
3991
+                if ( ! $field_obj) {
3992 3992
                     if (isset($this->_custom_selections[$query_param][1])) {
3993 3993
                         $field_obj = $this->_custom_selections[$query_param][1];
3994 3994
                     } else {
@@ -3997,7 +3997,7 @@  discard block
 block discarded – undo
3997 3997
                     }
3998 3998
                 }
3999 3999
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4000
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4000
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4001 4001
             }
4002 4002
         }
4003 4003
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4018,7 +4018,7 @@  discard block
 block discarded – undo
4018 4018
         if ($field) {
4019 4019
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4020 4020
                 $query_param);
4021
-            return $table_alias_prefix . $field->get_qualified_column();
4021
+            return $table_alias_prefix.$field->get_qualified_column();
4022 4022
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4023 4023
             //maybe it's custom selection item?
4024 4024
             //if so, just use it as the "column name"
@@ -4065,7 +4065,7 @@  discard block
 block discarded – undo
4065 4065
     {
4066 4066
         if (is_array($op_and_value)) {
4067 4067
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4068
-            if (! $operator) {
4068
+            if ( ! $operator) {
4069 4069
                 $php_array_like_string = array();
4070 4070
                 foreach ($op_and_value as $key => $value) {
4071 4071
                     $php_array_like_string[] = "$key=>$value";
@@ -4087,13 +4087,13 @@  discard block
 block discarded – undo
4087 4087
         }
4088 4088
         //check to see if the value is actually another field
4089 4089
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4090
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4090
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4091 4091
         } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4092 4092
             //in this case, the value should be an array, or at least a comma-separated list
4093 4093
             //it will need to handle a little differently
4094 4094
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4095 4095
             //note: $cleaned_value has already been run through $wpdb->prepare()
4096
-            return $operator . SP . $cleaned_value;
4096
+            return $operator.SP.$cleaned_value;
4097 4097
         } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4098 4098
             //the value should be an array with count of two.
4099 4099
             if (count($value) !== 2) {
@@ -4108,7 +4108,7 @@  discard block
 block discarded – undo
4108 4108
                 );
4109 4109
             }
4110 4110
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4111
-            return $operator . SP . $cleaned_value;
4111
+            return $operator.SP.$cleaned_value;
4112 4112
         } elseif (in_array($operator, $this->valid_null_style_operators())) {
4113 4113
             if ($value !== null) {
4114 4114
                 throw new EE_Error(
@@ -4126,9 +4126,9 @@  discard block
 block discarded – undo
4126 4126
         } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4127 4127
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4128 4128
             //remove other junk. So just treat it as a string.
4129
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4130
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4129
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4130
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4131
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4132 4132
         } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4133 4133
             throw new EE_Error(
4134 4134
                 sprintf(
@@ -4140,7 +4140,7 @@  discard block
 block discarded – undo
4140 4140
                     $operator
4141 4141
                 )
4142 4142
             );
4143
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4143
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4144 4144
             throw new EE_Error(
4145 4145
                 sprintf(
4146 4146
                     __(
@@ -4181,7 +4181,7 @@  discard block
 block discarded – undo
4181 4181
         foreach ($values as $value) {
4182 4182
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4183 4183
         }
4184
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4184
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4185 4185
     }
4186 4186
 
4187 4187
 
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
                                 . $main_table->get_table_name()
4223 4223
                                 . " WHERE FALSE";
4224 4224
         }
4225
-        return "(" . implode(",", $cleaned_values) . ")";
4225
+        return "(".implode(",", $cleaned_values).")";
4226 4226
     }
4227 4227
 
4228 4228
 
@@ -4241,7 +4241,7 @@  discard block
 block discarded – undo
4241 4241
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4242 4242
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4243 4243
         } else {//$field_obj should really just be a data type
4244
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4244
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4245 4245
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4246 4246
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4247 4247
             }
@@ -4361,10 +4361,10 @@  discard block
 block discarded – undo
4361 4361
      */
4362 4362
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4363 4363
     {
4364
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4364
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4365 4365
         $qualified_columns = array();
4366 4366
         foreach ($this->field_settings() as $field_name => $field) {
4367
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4367
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4368 4368
         }
4369 4369
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4370 4370
     }
@@ -4388,11 +4388,11 @@  discard block
 block discarded – undo
4388 4388
             if ($table_obj instanceof EE_Primary_Table) {
4389 4389
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4390 4390
                     ? $table_obj->get_select_join_limit($limit)
4391
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4391
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4392 4392
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4393 4393
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4394 4394
                     ? $table_obj->get_select_join_limit_join($limit)
4395
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4395
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4396 4396
             }
4397 4397
         }
4398 4398
         return $SQL;
@@ -4480,12 +4480,12 @@  discard block
 block discarded – undo
4480 4480
      */
4481 4481
     public function get_related_model_obj($model_name)
4482 4482
     {
4483
-        $model_classname = "EEM_" . $model_name;
4484
-        if (! class_exists($model_classname)) {
4483
+        $model_classname = "EEM_".$model_name;
4484
+        if ( ! class_exists($model_classname)) {
4485 4485
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4486 4486
                 'event_espresso'), $model_name, $model_classname));
4487 4487
         }
4488
-        return call_user_func($model_classname . "::instance");
4488
+        return call_user_func($model_classname."::instance");
4489 4489
     }
4490 4490
 
4491 4491
 
@@ -4532,7 +4532,7 @@  discard block
 block discarded – undo
4532 4532
     public function related_settings_for($relation_name)
4533 4533
     {
4534 4534
         $relatedModels = $this->relation_settings();
4535
-        if (! array_key_exists($relation_name, $relatedModels)) {
4535
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4536 4536
             throw new EE_Error(
4537 4537
                 sprintf(
4538 4538
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4560,7 +4560,7 @@  discard block
 block discarded – undo
4560 4560
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4561 4561
     {
4562 4562
         $fieldSettings = $this->field_settings($include_db_only_fields);
4563
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4563
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4564 4564
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4565 4565
                 get_class($this)));
4566 4566
         }
@@ -4635,7 +4635,7 @@  discard block
 block discarded – undo
4635 4635
                     break;
4636 4636
                 }
4637 4637
             }
4638
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4638
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4639 4639
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4640 4640
                     get_class($this)));
4641 4641
             }
@@ -4694,7 +4694,7 @@  discard block
 block discarded – undo
4694 4694
      */
4695 4695
     public function get_foreign_key_to($model_name)
4696 4696
     {
4697
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4697
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4698 4698
             foreach ($this->field_settings() as $field) {
4699 4699
                 if (
4700 4700
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4704,7 +4704,7 @@  discard block
 block discarded – undo
4704 4704
                     break;
4705 4705
                 }
4706 4706
             }
4707
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4707
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4708 4708
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4709 4709
                     'event_espresso'), $model_name, get_class($this)));
4710 4710
             }
@@ -4755,7 +4755,7 @@  discard block
 block discarded – undo
4755 4755
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4756 4756
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4757 4757
                         /** @var $field_obj EE_Model_Field_Base */
4758
-                        if (! $field_obj->is_db_only_field()) {
4758
+                        if ( ! $field_obj->is_db_only_field()) {
4759 4759
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4760 4760
                         }
4761 4761
                     }
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
         $count_if_model_has_no_primary_key = 0;
4786 4786
         $has_primary_key = $this->has_primary_key_field();
4787 4787
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4788
-        foreach ((array)$rows as $row) {
4788
+        foreach ((array) $rows as $row) {
4789 4789
             if (empty($row)) {
4790 4790
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4791 4791
                 return array();
@@ -4803,7 +4803,7 @@  discard block
 block discarded – undo
4803 4803
                 }
4804 4804
             }
4805 4805
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4806
-            if (! $classInstance) {
4806
+            if ( ! $classInstance) {
4807 4807
                 throw new EE_Error(
4808 4808
                     sprintf(
4809 4809
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4872,7 +4872,7 @@  discard block
 block discarded – undo
4872 4872
      */
4873 4873
     public function instantiate_class_from_array_or_object($cols_n_values)
4874 4874
     {
4875
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4875
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4876 4876
             $cols_n_values = get_object_vars($cols_n_values);
4877 4877
         }
4878 4878
         $primary_key = null;
@@ -4897,7 +4897,7 @@  discard block
 block discarded – undo
4897 4897
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4898 4898
         if ($primary_key) {
4899 4899
             $classInstance = $this->get_from_entity_map($primary_key);
4900
-            if (! $classInstance) {
4900
+            if ( ! $classInstance) {
4901 4901
                 $classInstance = EE_Registry::instance()
4902 4902
                                             ->load_class($className,
4903 4903
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4948,12 +4948,12 @@  discard block
 block discarded – undo
4948 4948
     public function add_to_entity_map(EE_Base_Class $object)
4949 4949
     {
4950 4950
         $className = $this->_get_class_name();
4951
-        if (! $object instanceof $className) {
4951
+        if ( ! $object instanceof $className) {
4952 4952
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4953 4953
                 is_object($object) ? get_class($object) : $object, $className));
4954 4954
         }
4955 4955
         /** @var $object EE_Base_Class */
4956
-        if (! $object->ID()) {
4956
+        if ( ! $object->ID()) {
4957 4957
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4958 4958
                 "event_espresso"), get_class($this)));
4959 4959
         }
@@ -5023,7 +5023,7 @@  discard block
 block discarded – undo
5023 5023
             //there is a primary key on this table and its not set. Use defaults for all its columns
5024 5024
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5025 5025
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5026
-                    if (! $field_obj->is_db_only_field()) {
5026
+                    if ( ! $field_obj->is_db_only_field()) {
5027 5027
                         //prepare field as if its coming from db
5028 5028
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5029 5029
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5032,7 +5032,7 @@  discard block
 block discarded – undo
5032 5032
             } else {
5033 5033
                 //the table's rows existed. Use their values
5034 5034
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5035
-                    if (! $field_obj->is_db_only_field()) {
5035
+                    if ( ! $field_obj->is_db_only_field()) {
5036 5036
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5037 5037
                             $cols_n_values, $field_obj->get_qualified_column(),
5038 5038
                             $field_obj->get_table_column()
@@ -5149,7 +5149,7 @@  discard block
 block discarded – undo
5149 5149
      */
5150 5150
     private function _get_class_name()
5151 5151
     {
5152
-        return "EE_" . $this->get_this_model_name();
5152
+        return "EE_".$this->get_this_model_name();
5153 5153
     }
5154 5154
 
5155 5155
 
@@ -5164,7 +5164,7 @@  discard block
 block discarded – undo
5164 5164
      */
5165 5165
     public function item_name($quantity = 1)
5166 5166
     {
5167
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5167
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5168 5168
     }
5169 5169
 
5170 5170
 
@@ -5197,7 +5197,7 @@  discard block
 block discarded – undo
5197 5197
     {
5198 5198
         $className = get_class($this);
5199 5199
         $tagName = "FHEE__{$className}__{$methodName}";
5200
-        if (! has_filter($tagName)) {
5200
+        if ( ! has_filter($tagName)) {
5201 5201
             throw new EE_Error(
5202 5202
                 sprintf(
5203 5203
                     __('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 );',
@@ -5423,7 +5423,7 @@  discard block
 block discarded – undo
5423 5423
         $key_vals_in_combined_pk = array();
5424 5424
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5425 5425
         foreach ($key_fields as $key_field_name => $field_obj) {
5426
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5426
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5427 5427
                 return null;
5428 5428
             }
5429 5429
         }
@@ -5444,7 +5444,7 @@  discard block
 block discarded – undo
5444 5444
     {
5445 5445
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5446 5446
         foreach ($keys_it_should_have as $key) {
5447
-            if (! isset($key_vals[$key])) {
5447
+            if ( ! isset($key_vals[$key])) {
5448 5448
                 return false;
5449 5449
             }
5450 5450
         }
@@ -5498,7 +5498,7 @@  discard block
 block discarded – undo
5498 5498
      */
5499 5499
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5500 5500
     {
5501
-        if (! is_array($query_params)) {
5501
+        if ( ! is_array($query_params)) {
5502 5502
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5503 5503
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5504 5504
                     gettype($query_params)), '4.6.0');
@@ -5560,7 +5560,7 @@  discard block
 block discarded – undo
5560 5560
      * Gets the valid operators
5561 5561
      * @return array keys are accepted strings, values are the SQL they are converted to
5562 5562
      */
5563
-    public function valid_operators(){
5563
+    public function valid_operators() {
5564 5564
         return $this->_valid_operators;
5565 5565
     }
5566 5566
 
@@ -5648,7 +5648,7 @@  discard block
 block discarded – undo
5648 5648
      */
5649 5649
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5650 5650
     {
5651
-        if (! $this->has_primary_key_field()) {
5651
+        if ( ! $this->has_primary_key_field()) {
5652 5652
             if (WP_DEBUG) {
5653 5653
                 EE_Error::add_error(
5654 5654
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5661,7 +5661,7 @@  discard block
 block discarded – undo
5661 5661
         $IDs = array();
5662 5662
         foreach ($model_objects as $model_object) {
5663 5663
             $id = $model_object->ID();
5664
-            if (! $id) {
5664
+            if ( ! $id) {
5665 5665
                 if ($filter_out_empty_ids) {
5666 5666
                     continue;
5667 5667
                 }
@@ -5757,8 +5757,8 @@  discard block
 block discarded – undo
5757 5757
         $missing_caps = array();
5758 5758
         $cap_restrictions = $this->cap_restrictions($context);
5759 5759
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5760
-            if (! EE_Capabilities::instance()
5761
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5760
+            if ( ! EE_Capabilities::instance()
5761
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5762 5762
             ) {
5763 5763
                 $missing_caps[$cap] = $restriction_if_no_cap;
5764 5764
             }
@@ -5909,7 +5909,7 @@  discard block
 block discarded – undo
5909 5909
     {
5910 5910
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5911 5911
             if ($query_param_key === $logic_query_param_key
5912
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5912
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5913 5913
             ) {
5914 5914
                 return true;
5915 5915
             }
Please login to merge, or discard this patch.
core/db_models/strategies/EE_Restriction_Generator_Reg_Form.strategy.php 2 patches
Indentation   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -49,16 +49,16 @@
 block discarded – undo
49 49
 			EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() ) => new EE_Return_None_Where_Conditions(),
50 50
 		);
51 51
 		if( $this->action() !== EEM_Base::caps_delete ){
52
-            $restrictions[EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
53
-                array(
54
-                    'OR*no_' . EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system' ) => array(
55
-                        $this->_system_field_name       => array( 'IN', array( '', 0 ) ),
56
-                        $this->_system_field_name . '*' => array( 'IS_NULL' )
57
-                    )
58
-                )
59
-            );
60
-        }
61
-        return $restrictions;
52
+			$restrictions[EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
53
+				array(
54
+					'OR*no_' . EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system' ) => array(
55
+						$this->_system_field_name       => array( 'IN', array( '', 0 ) ),
56
+						$this->_system_field_name . '*' => array( 'IS_NULL' )
57
+					)
58
+				)
59
+			);
60
+		}
61
+		return $restrictions;
62 62
 	}
63 63
 }
64 64
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
3
-	exit( 'No direct script access allowed' );
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3
+	exit('No direct script access allowed');
4 4
 }
5 5
 
6 6
 /**
@@ -15,7 +15,7 @@  discard block
 block discarded – undo
15 15
  * @author				Mike Nelson
16 16
  *
17 17
  */
18
-class EE_Restriction_Generator_Reg_Form extends EE_Restriction_Generator_Base{
18
+class EE_Restriction_Generator_Reg_Form extends EE_Restriction_Generator_Base {
19 19
 
20 20
 	/**
21 21
 	 *
@@ -27,7 +27,7 @@  discard block
 block discarded – undo
27 27
 	 * Accepts the name of the field that indicates whether or not an object is a "system" one or not
28 28
 	 * @param string $system_field_name
29 29
 	 */
30
-	public function __construct( $system_field_name ) {
30
+	public function __construct($system_field_name) {
31 31
 		$this->_system_field_name = $system_field_name;
32 32
 	}
33 33
 
@@ -40,20 +40,20 @@  discard block
 block discarded – undo
40 40
 	protected function _generate_restrictions() {
41 41
 		//if there are no standard caps for this model, then for now all we know
42 42
 		//if they need the default cap to access this
43
-		if( ! $this->model()->cap_slug() ) {
43
+		if ( ! $this->model()->cap_slug()) {
44 44
 			return array(
45 45
 				EE_Restriction_Generator_Base::get_default_restrictions_cap() => new EE_Return_None_Where_Conditions()
46 46
 			);
47 47
 		}
48 48
 		$restrictions = array(
49
-			EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() ) => new EE_Return_None_Where_Conditions(),
49
+			EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action()) => new EE_Return_None_Where_Conditions(),
50 50
 		);
51
-		if( $this->action() !== EEM_Base::caps_delete ){
52
-            $restrictions[EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system')] = new EE_Default_Where_Conditions(
51
+		if ($this->action() !== EEM_Base::caps_delete) {
52
+            $restrictions[EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action().'_system')] = new EE_Default_Where_Conditions(
53 53
                 array(
54
-                    'OR*no_' . EE_Restriction_Generator_Base::get_cap_name( $this->model(), $this->action() . '_system' ) => array(
55
-                        $this->_system_field_name       => array( 'IN', array( '', 0 ) ),
56
-                        $this->_system_field_name . '*' => array( 'IS_NULL' )
54
+                    'OR*no_'.EE_Restriction_Generator_Base::get_cap_name($this->model(), $this->action().'_system') => array(
55
+                        $this->_system_field_name       => array('IN', array('', 0)),
56
+                        $this->_system_field_name.'*' => array('IS_NULL')
57 57
                     )
58 58
                 )
59 59
             );
Please login to merge, or discard this patch.