Completed
Branch FET-10429-simplify-delete-perm... (93f55d)
by
unknown
66:50 queued 55:48
created
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5858 added lines, -5858 removed lines patch added patch discarded remove patch
@@ -28,5870 +28,5870 @@
 block discarded – undo
28 28
 abstract class EEM_Base extends EE_Base implements EventEspresso\core\interfaces\ResettableInterface
29 29
 {
30 30
 
31
-    //admin posty
32
-    //basic -> grants access to mine -> if they don't have it, select none
33
-    //*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
-    //*_published -> grants access to published -> if they dont have it, select non-published
36
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
38
-    //frontend posty
39
-    //by default has access to published
40
-    //basic -> grants access to mine that aren't published, and all published
41
-    //*_others ->grants access to others that aren't private, all mine
42
-    //*_private -> grants full access
43
-    //frontend non-posty
44
-    //like admin posty
45
-    //category-y
46
-    //assign -> grants access to join-table
47
-    //(delete, edit)
48
-    //payment-method-y
49
-    //for each registered payment method,
50
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
-    /**
52
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
-     * They almost always WILL NOT, but it's not necessarily a requirement.
55
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
-     *
57
-     * @var boolean
58
-     */
59
-    private $_values_already_prepared_by_model_object = 0;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the data is just like form input that needs to have the model fields'
64
-     * prepare_for_set and prepare_for_use_in_db called on it
65
-     */
66
-    const not_prepared_by_model_object = 0;
67
-
68
-    /**
69
-     * when $_values_already_prepared_by_model_object equals this, we
70
-     * assume this value is coming from a model object and doesn't need to have
71
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
72
-     */
73
-    const prepared_by_model_object = 1;
74
-
75
-    /**
76
-     * when $_values_already_prepared_by_model_object equals this, we assume
77
-     * the values are already to be used in the database (ie no processing is done
78
-     * on them by the model's fields)
79
-     */
80
-    const prepared_for_use_in_db = 2;
81
-
82
-
83
-    protected $singular_item = 'Item';
84
-
85
-    protected $plural_item   = 'Items';
86
-
87
-    /**
88
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
-     */
90
-    protected $_tables;
91
-
92
-    /**
93
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
-     *
97
-     * @var \EE_Model_Field_Base[] $_fields
98
-     */
99
-    protected $_fields;
100
-
101
-    /**
102
-     * array of different kinds of relations
103
-     *
104
-     * @var \EE_Model_Relation_Base[] $_model_relations
105
-     */
106
-    protected $_model_relations;
107
-
108
-    /**
109
-     * @var \EE_Index[] $_indexes
110
-     */
111
-    protected $_indexes = array();
112
-
113
-    /**
114
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
115
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
-     * by setting the same columns as used in these queries in the query yourself.
117
-     *
118
-     * @var EE_Default_Where_Conditions
119
-     */
120
-    protected $_default_where_conditions_strategy;
121
-
122
-    /**
123
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
-     * This is particularly useful when you want something between 'none' and 'default'
125
-     *
126
-     * @var EE_Default_Where_Conditions
127
-     */
128
-    protected $_minimum_where_conditions_strategy;
129
-
130
-    /**
131
-     * String describing how to find the "owner" of this model's objects.
132
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
-     * But when there isn't, this indicates which related model, or transiently-related model,
134
-     * has the foreign key to the wp_users table.
135
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
-     * related to events, and events have a foreign key to wp_users.
137
-     * On EEM_Transaction, this would be 'Transaction.Event'
138
-     *
139
-     * @var string
140
-     */
141
-    protected $_model_chain_to_wp_user = '';
142
-
143
-    /**
144
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
-     * don't need it (particularly CPT models)
146
-     *
147
-     * @var bool
148
-     */
149
-    protected $_ignore_where_strategy = false;
150
-
151
-    /**
152
-     * String used in caps relating to this model. Eg, if the caps relating to this
153
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
-     *
155
-     * @var string. If null it hasn't been initialized yet. If false then we
156
-     * have indicated capabilities don't apply to this
157
-     */
158
-    protected $_caps_slug = null;
159
-
160
-    /**
161
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
-     * and next-level keys are capability names, and each's value is a
163
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
-     * they specify which context to use (ie, frontend, backend, edit or delete)
165
-     * and then each capability in the corresponding sub-array that they're missing
166
-     * adds the where conditions onto the query.
167
-     *
168
-     * @var array
169
-     */
170
-    protected $_cap_restrictions = array(
171
-        self::caps_read       => array(),
172
-        self::caps_read_admin => array(),
173
-        self::caps_edit       => array(),
174
-        self::caps_delete     => array(),
175
-    );
176
-
177
-    /**
178
-     * Array defining which cap restriction generators to use to create default
179
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
180
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
-     * automatically set this to false (not just null).
183
-     *
184
-     * @var EE_Restriction_Generator_Base[]
185
-     */
186
-    protected $_cap_restriction_generators = array();
187
-
188
-    /**
189
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
-     */
191
-    const caps_read       = 'read';
192
-
193
-    const caps_read_admin = 'read_admin';
194
-
195
-    const caps_edit       = 'edit';
196
-
197
-    const caps_delete     = 'delete';
198
-
199
-    /**
200
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
-     * maps to 'read' because when looking for relevant permissions we're going to use
203
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
204
-     *
205
-     * @var array
206
-     */
207
-    protected $_cap_contexts_to_cap_action_map = array(
208
-        self::caps_read       => 'read',
209
-        self::caps_read_admin => 'read',
210
-        self::caps_edit       => 'edit',
211
-        self::caps_delete     => 'delete',
212
-    );
213
-
214
-    /**
215
-     * Timezone
216
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
-     * EE_Datetime_Field data type will have access to it.
220
-     *
221
-     * @var string
222
-     */
223
-    protected $_timezone;
224
-
225
-
226
-    /**
227
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
-     * multisite.
229
-     *
230
-     * @var int
231
-     */
232
-    protected static $_model_query_blog_id;
233
-
234
-    /**
235
-     * A copy of _fields, except the array keys are the model names pointed to by
236
-     * the field
237
-     *
238
-     * @var EE_Model_Field_Base[]
239
-     */
240
-    private $_cache_foreign_key_to_fields = array();
241
-
242
-    /**
243
-     * Cached list of all the fields on the model, indexed by their name
244
-     *
245
-     * @var EE_Model_Field_Base[]
246
-     */
247
-    private $_cached_fields = null;
248
-
249
-    /**
250
-     * Cached list of all the fields on the model, except those that are
251
-     * marked as only pertinent to the database
252
-     *
253
-     * @var EE_Model_Field_Base[]
254
-     */
255
-    private $_cached_fields_non_db_only = null;
256
-
257
-    /**
258
-     * A cached reference to the primary key for quick lookup
259
-     *
260
-     * @var EE_Model_Field_Base
261
-     */
262
-    private $_primary_key_field = null;
263
-
264
-    /**
265
-     * Flag indicating whether this model has a primary key or not
266
-     *
267
-     * @var boolean
268
-     */
269
-    protected $_has_primary_key_field = null;
270
-
271
-    /**
272
-     * Whether or not this model is based off a table in WP core only (CPTs should set
273
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
-     *
275
-     * @var boolean
276
-     */
277
-    protected $_wp_core_model = false;
278
-
279
-    /**
280
-     *    List of valid operators that can be used for querying.
281
-     * The keys are all operators we'll accept, the values are the real SQL
282
-     * operators used
283
-     *
284
-     * @var array
285
-     */
286
-    protected $_valid_operators = array(
287
-        '='           => '=',
288
-        '<='          => '<=',
289
-        '<'           => '<',
290
-        '>='          => '>=',
291
-        '>'           => '>',
292
-        '!='          => '!=',
293
-        'LIKE'        => 'LIKE',
294
-        'like'        => 'LIKE',
295
-        'NOT_LIKE'    => 'NOT LIKE',
296
-        'not_like'    => 'NOT LIKE',
297
-        'NOT LIKE'    => 'NOT LIKE',
298
-        'not like'    => 'NOT LIKE',
299
-        'IN'          => 'IN',
300
-        'in'          => 'IN',
301
-        'NOT_IN'      => 'NOT IN',
302
-        'not_in'      => 'NOT IN',
303
-        'NOT IN'      => 'NOT IN',
304
-        'not in'      => 'NOT IN',
305
-        'between'     => 'BETWEEN',
306
-        'BETWEEN'     => 'BETWEEN',
307
-        'IS_NOT_NULL' => 'IS NOT NULL',
308
-        'is_not_null' => 'IS NOT NULL',
309
-        'IS NOT NULL' => 'IS NOT NULL',
310
-        'is not null' => 'IS NOT NULL',
311
-        'IS_NULL'     => 'IS NULL',
312
-        'is_null'     => 'IS NULL',
313
-        'IS NULL'     => 'IS NULL',
314
-        'is null'     => 'IS NULL',
315
-        'REGEXP'      => 'REGEXP',
316
-        'regexp'      => 'REGEXP',
317
-        'NOT_REGEXP'  => 'NOT REGEXP',
318
-        'not_regexp'  => 'NOT REGEXP',
319
-        'NOT REGEXP'  => 'NOT REGEXP',
320
-        'not regexp'  => 'NOT REGEXP',
321
-    );
322
-
323
-    /**
324
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
-     *
326
-     * @var array
327
-     */
328
-    protected $_in_style_operators = array('IN', 'NOT IN');
329
-
330
-    /**
331
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
-     * '12-31-2012'"
333
-     *
334
-     * @var array
335
-     */
336
-    protected $_between_style_operators = array('BETWEEN');
337
-
338
-    /**
339
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
-     * on a join table.
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
-
346
-    /**
347
-     * Allowed values for $query_params['order'] for ordering in queries
348
-     *
349
-     * @var array
350
-     */
351
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
-
353
-    /**
354
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
356
-     *
357
-     * @var array
358
-     */
359
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
-
361
-    /**
362
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
364
-     *
365
-     * @var array
366
-     */
367
-    private $_allowed_query_params = array(
368
-        0,
369
-        'limit',
370
-        'order_by',
371
-        'group_by',
372
-        'having',
373
-        'force_join',
374
-        'order',
375
-        'on_join_limit',
376
-        'default_where_conditions',
377
-        'caps',
378
-    );
379
-
380
-    /**
381
-     * All the data types that can be used in $wpdb->prepare statements.
382
-     *
383
-     * @var array
384
-     */
385
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
-
387
-    /**
388
-     *    EE_Registry Object
389
-     *
390
-     * @var    object
391
-     * @access    protected
392
-     */
393
-    protected $EE = null;
394
-
395
-
396
-    /**
397
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
-     *
399
-     * @var int
400
-     */
401
-    protected $_show_next_x_db_queries = 0;
402
-
403
-    /**
404
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
-     *
407
-     * @var array
408
-     */
409
-    protected $_custom_selections = array();
410
-
411
-    /**
412
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
-     * caches every model object we've fetched from the DB on this request
414
-     *
415
-     * @var array
416
-     */
417
-    protected $_entity_map;
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws \EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('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.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('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.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Generates the cap restrictions for the given context, or if they were
654
-     * already generated just gets what's cached
655
-     *
656
-     * @param string $context one of EEM_Base::valid_cap_contexts()
657
-     * @return EE_Default_Where_Conditions[]
658
-     */
659
-    protected function _generate_cap_restrictions($context)
660
-    {
661
-        if (isset($this->_cap_restriction_generators[$context])
662
-            && $this->_cap_restriction_generators[$context]
663
-               instanceof
664
-               EE_Restriction_Generator_Base
665
-        ) {
666
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
-        } else {
668
-            return array();
669
-        }
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Used to set the $_model_query_blog_id static property.
676
-     *
677
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
-     *                      value for get_current_blog_id() will be used.
679
-     */
680
-    public static function set_model_query_blog_id($blog_id = 0)
681
-    {
682
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
-    }
684
-
685
-
686
-
687
-    /**
688
-     * Returns whatever is set as the internal $model_query_blog_id.
689
-     *
690
-     * @return int
691
-     */
692
-    public static function get_model_query_blog_id()
693
-    {
694
-        return EEM_Base::$_model_query_blog_id;
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     *        This function is a singleton method used to instantiate the Espresso_model object
701
-     *
702
-     * @access public
703
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
-     *                         timezone in the 'timezone_string' wp option)
707
-     * @return static (as in the concrete child class)
708
-     */
709
-    public static function instance($timezone = null)
710
-    {
711
-        // check if instance of Espresso_model already exists
712
-        if (! static::$_instance instanceof static) {
713
-            // instantiate Espresso_model
714
-            static::$_instance = new static($timezone);
715
-        }
716
-        //we might have a timezone set, let set_timezone decide what to do with it
717
-        static::$_instance->set_timezone($timezone);
718
-        // Espresso_model object
719
-        return static::$_instance;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * resets the model and returns it
726
-     *
727
-     * @param null | string $timezone
728
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
-     * all its properties reset; if it wasn't instantiated, returns null)
730
-     */
731
-    public static function reset($timezone = null)
732
-    {
733
-        if (static::$_instance instanceof EEM_Base) {
734
-            //let's try to NOT swap out the current instance for a new one
735
-            //because if someone has a reference to it, we can't remove their reference
736
-            //so it's best to keep using the same reference, but change the original object
737
-            //reset all its properties to their original values as defined in the class
738
-            $r = new ReflectionClass(get_class(static::$_instance));
739
-            $static_properties = $r->getStaticProperties();
740
-            foreach ($r->getDefaultProperties() as $property => $value) {
741
-                //don't set instance to null like it was originally,
742
-                //but it's static anyways, and we're ignoring static properties (for now at least)
743
-                if (! isset($static_properties[$property])) {
744
-                    static::$_instance->{$property} = $value;
745
-                }
746
-            }
747
-            //and then directly call its constructor again, like we would if we
748
-            //were creating a new one
749
-            static::$_instance->__construct($timezone);
750
-            return self::instance();
751
-        }
752
-        return null;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
-     *
760
-     * @param  boolean $translated return localized strings or JUST the array.
761
-     * @return array
762
-     * @throws \EE_Error
763
-     */
764
-    public function status_array($translated = false)
765
-    {
766
-        if (! array_key_exists('Status', $this->_model_relations)) {
767
-            return array();
768
-        }
769
-        $model_name = $this->get_this_model_name();
770
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
-        $status_array = array();
773
-        foreach ($stati as $status) {
774
-            $status_array[$status->ID()] = $status->get('STS_code');
775
-        }
776
-        return $translated
777
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
-            : $status_array;
779
-    }
780
-
781
-
782
-
783
-    /**
784
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
-     *
786
-     * @param array $query_params             {
787
-     * @var array $0 (where) array {
788
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
-     *                                        conditions based on related models (and even
792
-     *                                        models-related-to-related-models) prepend the model's name onto the field
793
-     *                                        name. Eg,
794
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
-     *                                        to Venues (even when each of those models actually consisted of two
802
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
803
-     *                                        just having
804
-     *                                        "Venue.VNU_ID", you could have
805
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
-     *                                        events are related to Registrations, which are related to Attendees). You
807
-     *                                        can take it even further with
808
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
-     *                                        (from the default of '='), change the value to an numerically-indexed
810
-     *                                        array, where the first item in the list is the operator. eg: array(
811
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
819
-     *                                        the value is a field, simply provide a third array item (true) to the
820
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
-     *                                        Note: you can also use related model field names like you would any other
823
-     *                                        field name. eg:
824
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
-     *                                        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__>' =>
826
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
833
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
-     *                                        "stick" until you specify an AND. eg
835
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
-     *                                        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 >>
840
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
-     *                                        too, eg:
843
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
848
-     *                                        the OFFSET, the 2nd is the LIMIT
849
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
-     *                                        following format array('on_join_limit'
852
-     *                                        => array( 'table_alias', array(1,2) ) ).
853
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
-     *                                        values are either 'ASC' or 'DESC'.
855
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
-     *                                        DESC..." respectively. Like the
858
-     *                                        'where' conditions, these fields can be on related models. Eg
859
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
861
-     *                                        Attendee, Price, Datetime, etc.)
862
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
864
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
-     *                                        order by the primary key. Eg,
867
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
-     *                                        //(will join with the Datetime model's table(s) and order by its field
869
-     *                                        DTT_EVT_start) or
870
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
-     *                                        'group_by'=>'VNU_ID', or
874
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
-     *                                        if no
876
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
877
-     *                                        model's primary key (or combined primary keys). This avoids some
878
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
879
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
-     *                                        results)
883
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
-     *                                        array where values are models to be joined in the query.Eg
885
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
887
-     *                                        probably only want to do this in hopes of increasing efficiency, as
888
-     *                                        related models which belongs to the current model
889
-     *                                        (ie, the current model has a foreign key to them, like how Registration
890
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
891
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
894
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
-     *                                        default where conditions set it to 'other_models_only'. If you only want
896
-     *                                        this model's default where conditions added to the query, use
897
-     *                                        'this_model_only'. If you want to use all default where conditions
898
-     *                                        (default), set to 'all'.
899
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
-     *                                        everything? Or should we only show the current user items they should be
902
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
-     *                                        }
905
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
-     *                                        array( array(
911
-     *                                        'OR'=>array(
912
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
-     *                                        )
915
-     *                                        ),
916
-     *                                        'limit'=>10,
917
-     *                                        'group_by'=>'TXN_ID'
918
-     *                                        ));
919
-     *                                        get all the answers to the question titled "shirt size" for event with id
920
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
-     *                                        'Question.QST_display_text'=>'shirt size',
922
-     *                                        'Registration.Event.EVT_ID'=>12
923
-     *                                        ),
924
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
925
-     *                                        ));
926
-     * @throws \EE_Error
927
-     */
928
-    public function get_all($query_params = array())
929
-    {
930
-        if (isset($query_params['limit'])
931
-            && ! isset($query_params['group_by'])
932
-        ) {
933
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
-        }
935
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
-    }
937
-
938
-
939
-
940
-    /**
941
-     * Modifies the query parameters so we only get back model objects
942
-     * that "belong" to the current user
943
-     *
944
-     * @param array $query_params @see EEM_Base::get_all()
945
-     * @return array like EEM_Base::get_all
946
-     */
947
-    public function alter_query_params_to_only_include_mine($query_params = array())
948
-    {
949
-        $wp_user_field_name = $this->wp_user_field_name();
950
-        if ($wp_user_field_name) {
951
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
952
-        }
953
-        return $query_params;
954
-    }
955
-
956
-
957
-
958
-    /**
959
-     * Returns the name of the field's name that points to the WP_User table
960
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
-     * foreign key to the WP_User table)
962
-     *
963
-     * @return string|boolean string on success, boolean false when there is no
964
-     * foreign key to the WP_User table
965
-     */
966
-    public function wp_user_field_name()
967
-    {
968
-        try {
969
-            if (! empty($this->_model_chain_to_wp_user)) {
970
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
-                $last_model_name = end($models_to_follow_to_wp_users);
972
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
-            } else {
975
-                $model_with_fk_to_wp_users = $this;
976
-                $model_chain_to_wp_user = '';
977
-            }
978
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
980
-        } catch (EE_Error $e) {
981
-            return false;
982
-        }
983
-    }
984
-
985
-
986
-
987
-    /**
988
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
989
-     * (or transiently-related model) has a foreign key to the wp_users table;
990
-     * useful for finding if model objects of this type are 'owned' by the current user.
991
-     * This is an empty string when the foreign key is on this model and when it isn't,
992
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
993
-     * (or transiently-related model)
994
-     *
995
-     * @return string
996
-     */
997
-    public function model_chain_to_wp_user()
998
-    {
999
-        return $this->_model_chain_to_wp_user;
1000
-    }
1001
-
1002
-
1003
-
1004
-    /**
1005
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
-     * like how registrations don't have a foreign key to wp_users, but the
1007
-     * events they are for are), or is unrelated to wp users.
1008
-     * generally available
1009
-     *
1010
-     * @return boolean
1011
-     */
1012
-    public function is_owned()
1013
-    {
1014
-        if ($this->model_chain_to_wp_user()) {
1015
-            return true;
1016
-        } else {
1017
-            try {
1018
-                $this->get_foreign_key_to('WP_User');
1019
-                return true;
1020
-            } catch (EE_Error $e) {
1021
-                return false;
1022
-            }
1023
-        }
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
-     * the model)
1032
-     *
1033
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws \EE_Error
1045
-     */
1046
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        // remember the custom selections, if any, and type cast as array
1049
-        // (unless $columns_to_select is an object, then just set as an empty array)
1050
-        // Note: (array) 'some string' === array( 'some string' )
1051
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
-        $select_expressions = $columns_to_select !== null
1054
-            ? $this->_construct_select_from_input($columns_to_select)
1055
-            : $this->_construct_default_select_sql($model_query_info);
1056
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
-    }
1059
-
1060
-
1061
-
1062
-    /**
1063
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1064
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
-     * take care of joins, field preparation etc.
1066
-     *
1067
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1071
-     *                                  override this and set the select to "*", or a specific column name, like
1072
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
-     *                                  the aliases used to refer to this selection, and values are to be
1075
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
-     * @throws \EE_Error
1079
-     */
1080
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
-    {
1082
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
-    }
1084
-
1085
-
1086
-
1087
-    /**
1088
-     * For creating a custom select statement
1089
-     *
1090
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
-     *                                 SQL, and 1=>is the datatype
1093
-     * @throws EE_Error
1094
-     * @return string
1095
-     */
1096
-    private function _construct_select_from_input($columns_to_select)
1097
-    {
1098
-        if (is_array($columns_to_select)) {
1099
-            $select_sql_array = array();
1100
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
-                    throw new EE_Error(
1103
-                        sprintf(
1104
-                            __(
1105
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
-                                "event_espresso"
1107
-                            ),
1108
-                            $selection_and_datatype,
1109
-                            $alias
1110
-                        )
1111
-                    );
1112
-                }
1113
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
-                    throw new EE_Error(
1115
-                        sprintf(
1116
-                            __(
1117
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
-                                "event_espresso"
1119
-                            ),
1120
-                            $selection_and_datatype[1],
1121
-                            $selection_and_datatype[0],
1122
-                            $alias,
1123
-                            implode(",", $this->_valid_wpdb_data_types)
1124
-                        )
1125
-                    );
1126
-                }
1127
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
-            }
1129
-            $columns_to_select_string = implode(", ", $select_sql_array);
1130
-        } else {
1131
-            $columns_to_select_string = $columns_to_select;
1132
-        }
1133
-        return $columns_to_select_string;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
-     *
1141
-     * @return string
1142
-     * @throws \EE_Error
1143
-     */
1144
-    public function primary_key_name()
1145
-    {
1146
-        return $this->get_primary_key_field()->get_name();
1147
-    }
1148
-
1149
-
1150
-
1151
-    /**
1152
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
-     * If there is no primary key on this model, $id is treated as primary key string
1154
-     *
1155
-     * @param mixed $id int or string, depending on the type of the model's primary key
1156
-     * @return EE_Base_Class
1157
-     */
1158
-    public function get_one_by_ID($id)
1159
-    {
1160
-        if ($this->get_from_entity_map($id)) {
1161
-            return $this->get_from_entity_map($id);
1162
-        }
1163
-        return $this->get_one(
1164
-            $this->alter_query_params_to_restrict_by_ID(
1165
-                $id,
1166
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
-            )
1168
-        );
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Alters query parameters to only get items with this ID are returned.
1175
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
-     * or could just be a simple primary key ID
1177
-     *
1178
-     * @param int   $id
1179
-     * @param array $query_params
1180
-     * @return array of normal query params, @see EEM_Base::get_all
1181
-     * @throws \EE_Error
1182
-     */
1183
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
-    {
1185
-        if (! isset($query_params[0])) {
1186
-            $query_params[0] = array();
1187
-        }
1188
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1189
-        if ($conditions_from_id === null) {
1190
-            $query_params[0][$this->primary_key_name()] = $id;
1191
-        } else {
1192
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1193
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
-        }
1195
-        return $query_params;
1196
-    }
1197
-
1198
-
1199
-
1200
-    /**
1201
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
-     * array. If no item is found, null is returned.
1203
-     *
1204
-     * @param array $query_params like EEM_Base's $query_params variable.
1205
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
-     * @throws \EE_Error
1207
-     */
1208
-    public function get_one($query_params = array())
1209
-    {
1210
-        if (! is_array($query_params)) {
1211
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
-                    gettype($query_params)), '4.6.0');
1214
-            $query_params = array();
1215
-        }
1216
-        $query_params['limit'] = 1;
1217
-        $items = $this->get_all($query_params);
1218
-        if (empty($items)) {
1219
-            return null;
1220
-        } else {
1221
-            return array_shift($items);
1222
-        }
1223
-    }
1224
-
1225
-
1226
-
1227
-    /**
1228
-     * Returns the next x number of items in sequence from the given value as
1229
-     * found in the database matching the given query conditions.
1230
-     *
1231
-     * @param mixed $current_field_value    Value used for the reference point.
1232
-     * @param null  $field_to_order_by      What field is used for the
1233
-     *                                      reference point.
1234
-     * @param int   $limit                  How many to return.
1235
-     * @param array $query_params           Extra conditions on the query.
1236
-     * @param null  $columns_to_select      If left null, then an array of
1237
-     *                                      EE_Base_Class objects is returned,
1238
-     *                                      otherwise you can indicate just the
1239
-     *                                      columns you want returned.
1240
-     * @return EE_Base_Class[]|array
1241
-     * @throws \EE_Error
1242
-     */
1243
-    public function next_x(
1244
-        $current_field_value,
1245
-        $field_to_order_by = null,
1246
-        $limit = 1,
1247
-        $query_params = array(),
1248
-        $columns_to_select = null
1249
-    ) {
1250
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
-            $columns_to_select);
1252
-    }
1253
-
1254
-
1255
-
1256
-    /**
1257
-     * Returns the previous x number of items in sequence from the given value
1258
-     * as found in the database matching the given query conditions.
1259
-     *
1260
-     * @param mixed $current_field_value    Value used for the reference point.
1261
-     * @param null  $field_to_order_by      What field is used for the
1262
-     *                                      reference point.
1263
-     * @param int   $limit                  How many to return.
1264
-     * @param array $query_params           Extra conditions on the query.
1265
-     * @param null  $columns_to_select      If left null, then an array of
1266
-     *                                      EE_Base_Class objects is returned,
1267
-     *                                      otherwise you can indicate just the
1268
-     *                                      columns you want returned.
1269
-     * @return EE_Base_Class[]|array
1270
-     * @throws \EE_Error
1271
-     */
1272
-    public function previous_x(
1273
-        $current_field_value,
1274
-        $field_to_order_by = null,
1275
-        $limit = 1,
1276
-        $query_params = array(),
1277
-        $columns_to_select = null
1278
-    ) {
1279
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
-            $columns_to_select);
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * Returns the next item in sequence from the given value as found in the
1287
-     * database matching the given query conditions.
1288
-     *
1289
-     * @param mixed $current_field_value    Value used for the reference point.
1290
-     * @param null  $field_to_order_by      What field is used for the
1291
-     *                                      reference point.
1292
-     * @param array $query_params           Extra conditions on the query.
1293
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
-     *                                      object is returned, otherwise you
1295
-     *                                      can indicate just the columns you
1296
-     *                                      want and a single array indexed by
1297
-     *                                      the columns will be returned.
1298
-     * @return EE_Base_Class|null|array()
1299
-     * @throws \EE_Error
1300
-     */
1301
-    public function next(
1302
-        $current_field_value,
1303
-        $field_to_order_by = null,
1304
-        $query_params = array(),
1305
-        $columns_to_select = null
1306
-    ) {
1307
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
-            $columns_to_select);
1309
-        return empty($results) ? null : reset($results);
1310
-    }
1311
-
1312
-
1313
-
1314
-    /**
1315
-     * Returns the previous item in sequence from the given value as found in
1316
-     * the database matching the given query conditions.
1317
-     *
1318
-     * @param mixed $current_field_value    Value used for the reference point.
1319
-     * @param null  $field_to_order_by      What field is used for the
1320
-     *                                      reference point.
1321
-     * @param array $query_params           Extra conditions on the query.
1322
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
-     *                                      object is returned, otherwise you
1324
-     *                                      can indicate just the columns you
1325
-     *                                      want and a single array indexed by
1326
-     *                                      the columns will be returned.
1327
-     * @return EE_Base_Class|null|array()
1328
-     * @throws EE_Error
1329
-     */
1330
-    public function previous(
1331
-        $current_field_value,
1332
-        $field_to_order_by = null,
1333
-        $query_params = array(),
1334
-        $columns_to_select = null
1335
-    ) {
1336
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
-            $columns_to_select);
1338
-        return empty($results) ? null : reset($results);
1339
-    }
1340
-
1341
-
1342
-
1343
-    /**
1344
-     * Returns the a consecutive number of items in sequence from the given
1345
-     * value as found in the database matching the given query conditions.
1346
-     *
1347
-     * @param mixed  $current_field_value   Value used for the reference point.
1348
-     * @param string $operand               What operand is used for the sequence.
1349
-     * @param string $field_to_order_by     What field is used for the reference point.
1350
-     * @param int    $limit                 How many to return.
1351
-     * @param array  $query_params          Extra conditions on the query.
1352
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
-     *                                      otherwise you can indicate just the columns you want returned.
1354
-     * @return EE_Base_Class[]|array
1355
-     * @throws EE_Error
1356
-     */
1357
-    protected function _get_consecutive(
1358
-        $current_field_value,
1359
-        $operand = '>',
1360
-        $field_to_order_by = null,
1361
-        $limit = 1,
1362
-        $query_params = array(),
1363
-        $columns_to_select = null
1364
-    ) {
1365
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
-        if (empty($field_to_order_by)) {
1367
-            if ($this->has_primary_key_field()) {
1368
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1369
-            } else {
1370
-                if (WP_DEBUG) {
1371
-                    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).',
1372
-                        'event_espresso'));
1373
-                }
1374
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
-                return array();
1376
-            }
1377
-        }
1378
-        if (! is_array($query_params)) {
1379
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
-                    gettype($query_params)), '4.6.0');
1382
-            $query_params = array();
1383
-        }
1384
-        //let's add the where query param for consecutive look up.
1385
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
-        $query_params['limit'] = $limit;
1387
-        //set direction
1388
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
-        $query_params['order_by'] = $operand === '>'
1390
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
-        if (empty($columns_to_select)) {
1394
-            return $this->get_all($query_params);
1395
-        } else {
1396
-            //getting just the fields
1397
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
-        }
1399
-    }
1400
-
1401
-
1402
-
1403
-    /**
1404
-     * This sets the _timezone property after model object has been instantiated.
1405
-     *
1406
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
-     */
1408
-    public function set_timezone($timezone)
1409
-    {
1410
-        if ($timezone !== null) {
1411
-            $this->_timezone = $timezone;
1412
-        }
1413
-        //note we need to loop through relations and set the timezone on those objects as well.
1414
-        foreach ($this->_model_relations as $relation) {
1415
-            $relation->set_timezone($timezone);
1416
-        }
1417
-        //and finally we do the same for any datetime fields
1418
-        foreach ($this->_fields as $field) {
1419
-            if ($field instanceof EE_Datetime_Field) {
1420
-                $field->set_timezone($timezone);
1421
-            }
1422
-        }
1423
-    }
1424
-
1425
-
1426
-
1427
-    /**
1428
-     * This just returns whatever is set for the current timezone.
1429
-     *
1430
-     * @access public
1431
-     * @return string
1432
-     */
1433
-    public function get_timezone()
1434
-    {
1435
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
-        if (empty($this->_timezone)) {
1437
-            foreach ($this->_fields as $field) {
1438
-                if ($field instanceof EE_Datetime_Field) {
1439
-                    $this->set_timezone($field->get_timezone());
1440
-                    break;
1441
-                }
1442
-            }
1443
-        }
1444
-        //if timezone STILL empty then return the default timezone for the site.
1445
-        if (empty($this->_timezone)) {
1446
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
-        }
1448
-        return $this->_timezone;
1449
-    }
1450
-
1451
-
1452
-
1453
-    /**
1454
-     * This returns the date formats set for the given field name and also ensures that
1455
-     * $this->_timezone property is set correctly.
1456
-     *
1457
-     * @since 4.6.x
1458
-     * @param string $field_name The name of the field the formats are being retrieved for.
1459
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
-     * @return array formats in an array with the date format first, and the time format last.
1462
-     */
1463
-    public function get_formats_for($field_name, $pretty = false)
1464
-    {
1465
-        $field_settings = $this->field_settings_for($field_name);
1466
-        //if not a valid EE_Datetime_Field then throw error
1467
-        if (! $field_settings instanceof EE_Datetime_Field) {
1468
-            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.',
1469
-                'event_espresso'), $field_name));
1470
-        }
1471
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
-        //the field.
1473
-        $this->_timezone = $field_settings->get_timezone();
1474
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
-    }
1476
-
1477
-
1478
-
1479
-    /**
1480
-     * This returns the current time in a format setup for a query on this model.
1481
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
-     * it will return:
1483
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
-     *  NOW
1485
-     *  - or a unix timestamp (equivalent to time())
1486
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
-     * @since 4.6.x
1490
-     * @param string $field_name       The field the current time is needed for.
1491
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
-     *                                 formatted string matching the set format for the field in the set timezone will
1493
-     *                                 be returned.
1494
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
-     *                                 exception is triggered.
1498
-     */
1499
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
-    {
1501
-        $formats = $this->get_formats_for($field_name);
1502
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
-        if ($timestamp) {
1504
-            return $DateTime->format('U');
1505
-        }
1506
-        //not returning timestamp, so return formatted string in timezone.
1507
-        switch ($what) {
1508
-            case 'time' :
1509
-                return $DateTime->format($formats[1]);
1510
-                break;
1511
-            case 'date' :
1512
-                return $DateTime->format($formats[0]);
1513
-                break;
1514
-            default :
1515
-                return $DateTime->format(implode(' ', $formats));
1516
-                break;
1517
-        }
1518
-    }
1519
-
1520
-
1521
-
1522
-    /**
1523
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
-     * for the model are.  Returns a DateTime object.
1525
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
-     * ignored.
1528
-     *
1529
-     * @param string $field_name      The field being setup.
1530
-     * @param string $timestring      The date time string being used.
1531
-     * @param string $incoming_format The format for the time string.
1532
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
-     *                                format is
1535
-     *                                'U', this is ignored.
1536
-     * @return DateTime
1537
-     * @throws \EE_Error
1538
-     */
1539
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
-    {
1541
-        //just using this to ensure the timezone is set correctly internally
1542
-        $this->get_formats_for($field_name);
1543
-        //load EEH_DTT_Helper
1544
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
-     *
1554
-     * @return EE_Table_Base[]
1555
-     */
1556
-    public function get_tables()
1557
-    {
1558
-        return $this->_tables;
1559
-    }
1560
-
1561
-
1562
-
1563
-    /**
1564
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
-     * model object with EVT_ID = 1
1570
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
-     * are not specified)
1575
-     *
1576
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1581
-     *                                         ID=34, we'd use this method as follows:
1582
-     *                                         EEM_Transaction::instance()->update(
1583
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
-     *                                         array(array('TXN_ID'=>34)));
1585
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
-     *                                         in client code into what's expected to be stored on each field. Eg,
1587
-     *                                         consider updating Question's QST_admin_label field is of type
1588
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
-     *                                         TRUE, it is assumed that you've already called
1593
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
-     *                                         malicious javascript. However, if
1595
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
-     *                                         and every other field, before insertion. We provide this parameter
1598
-     *                                         because model objects perform their prepare_for_set function on all
1599
-     *                                         their values, and so don't need to be called again (and in many cases,
1600
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
-     *                                         prepare_for_set method...)
1602
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
-     *                                         in this model's entity map according to $fields_n_values that match
1604
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1605
-     *                                         by setting this to FALSE, but be aware that model objects being used
1606
-     *                                         could get out-of-sync with the database
1607
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
-     *                                         bad)
1610
-     * @throws \EE_Error
1611
-     */
1612
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
-    {
1614
-        if (! is_array($query_params)) {
1615
-            EE_Error::doing_it_wrong('EEM_Base::update',
1616
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
-                    gettype($query_params)), '4.6.0');
1618
-            $query_params = array();
1619
-        }
1620
-        /**
1621
-         * Action called before a model update call has been made.
1622
-         *
1623
-         * @param EEM_Base $model
1624
-         * @param array    $fields_n_values the updated fields and their new values
1625
-         * @param array    $query_params    @see EEM_Base::get_all()
1626
-         */
1627
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
-        /**
1629
-         * Filters the fields about to be updated given the query parameters. You can provide the
1630
-         * $query_params to $this->get_all() to find exactly which records will be updated
1631
-         *
1632
-         * @param array    $fields_n_values fields and their new values
1633
-         * @param EEM_Base $model           the model being queried
1634
-         * @param array    $query_params    see EEM_Base::get_all()
1635
-         */
1636
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
-            $query_params);
1638
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
-        //to do that, for each table, verify that it's PK isn't null.
1640
-        $tables = $this->get_tables();
1641
-        //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
1642
-        //NOTE: we should make this code more efficient by NOT querying twice
1643
-        //before the real update, but that needs to first go through ALPHA testing
1644
-        //as it's dangerous. says Mike August 8 2014
1645
-        //we want to make sure the default_where strategy is ignored
1646
-        $this->_ignore_where_strategy = true;
1647
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
-        foreach ($wpdb_select_results as $wpdb_result) {
1649
-            // type cast stdClass as array
1650
-            $wpdb_result = (array)$wpdb_result;
1651
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
-            if ($this->has_primary_key_field()) {
1653
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
-            } else {
1655
-                //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)
1656
-                $main_table_pk_value = null;
1657
-            }
1658
-            //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
1659
-            //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
1660
-            if (count($tables) > 1) {
1661
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
-                //in that table, and so we'll want to insert one
1663
-                foreach ($tables as $table_obj) {
1664
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
-                    //if there is no private key for this table on the results, it means there's no entry
1666
-                    //in this table, right? so insert a row in the current table, using any fields available
1667
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
-                           && $wpdb_result[$this_table_pk_column])
1669
-                    ) {
1670
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
-                            $main_table_pk_value);
1672
-                        //if we died here, report the error
1673
-                        if (! $success) {
1674
-                            return false;
1675
-                        }
1676
-                    }
1677
-                }
1678
-            }
1679
-            //				//and now check that if we have cached any models by that ID on the model, that
1680
-            //				//they also get updated properly
1681
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
-            //				if( $model_object ){
1683
-            //					foreach( $fields_n_values as $field => $value ){
1684
-            //						$model_object->set($field, $value);
1685
-            //let's make sure default_where strategy is followed now
1686
-            $this->_ignore_where_strategy = false;
1687
-        }
1688
-        //if we want to keep model objects in sync, AND
1689
-        //if this wasn't called from a model object (to update itself)
1690
-        //then we want to make sure we keep all the existing
1691
-        //model objects in sync with the db
1692
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
-            if ($this->has_primary_key_field()) {
1694
-                $model_objs_affected_ids = $this->get_col($query_params);
1695
-            } else {
1696
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
-                $model_objs_affected_ids = array();
1699
-                foreach ($models_affected_key_columns as $row) {
1700
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1701
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
-                }
1703
-            }
1704
-            if (! $model_objs_affected_ids) {
1705
-                //wait wait wait- if nothing was affected let's stop here
1706
-                return 0;
1707
-            }
1708
-            foreach ($model_objs_affected_ids as $id) {
1709
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
-                if ($model_obj_in_entity_map) {
1711
-                    foreach ($fields_n_values as $field => $new_value) {
1712
-                        $model_obj_in_entity_map->set($field, $new_value);
1713
-                    }
1714
-                }
1715
-            }
1716
-            //if there is a primary key on this model, we can now do a slight optimization
1717
-            if ($this->has_primary_key_field()) {
1718
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
-                $query_params = array(
1720
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
-                    'limit'                    => count($model_objs_affected_ids),
1722
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
-                );
1724
-            }
1725
-        }
1726
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
-        $SQL = "UPDATE "
1728
-               . $model_query_info->get_full_join_sql()
1729
-               . " SET "
1730
-               . $this->_construct_update_sql($fields_n_values)
1731
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
-        /**
1734
-         * Action called after a model update call has been made.
1735
-         *
1736
-         * @param EEM_Base $model
1737
-         * @param array    $fields_n_values the updated fields and their new values
1738
-         * @param array    $query_params    @see EEM_Base::get_all()
1739
-         * @param int      $rows_affected
1740
-         */
1741
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
-        return $rows_affected;//how many supposedly got updated
1743
-    }
1744
-
1745
-
1746
-
1747
-    /**
1748
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
-     * are teh values of the field specified (or by default the primary key field)
1750
-     * that matched the query params. Note that you should pass the name of the
1751
-     * model FIELD, not the database table's column name.
1752
-     *
1753
-     * @param array  $query_params @see EEM_Base::get_all()
1754
-     * @param string $field_to_select
1755
-     * @return array just like $wpdb->get_col()
1756
-     * @throws \EE_Error
1757
-     */
1758
-    public function get_col($query_params = array(), $field_to_select = null)
1759
-    {
1760
-        if ($field_to_select) {
1761
-            $field = $this->field_settings_for($field_to_select);
1762
-        } elseif ($this->has_primary_key_field()) {
1763
-            $field = $this->get_primary_key_field();
1764
-        } else {
1765
-            //no primary key, just grab the first column
1766
-            $field = reset($this->field_settings());
1767
-        }
1768
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
-        $select_expressions = $field->get_qualified_column();
1770
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
-        return $this->_do_wpdb_query('get_col', array($SQL));
1772
-    }
1773
-
1774
-
1775
-
1776
-    /**
1777
-     * Returns a single column value for a single row from the database
1778
-     *
1779
-     * @param array  $query_params    @see EEM_Base::get_all()
1780
-     * @param string $field_to_select @see EEM_Base::get_col()
1781
-     * @return string
1782
-     * @throws \EE_Error
1783
-     */
1784
-    public function get_var($query_params = array(), $field_to_select = null)
1785
-    {
1786
-        $query_params['limit'] = 1;
1787
-        $col = $this->get_col($query_params, $field_to_select);
1788
-        if (! empty($col)) {
1789
-            return reset($col);
1790
-        } else {
1791
-            return null;
1792
-        }
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
-     * injection, but currently no further filtering is done
1801
-     *
1802
-     * @global      $wpdb
1803
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
-     *                               be updated to in the DB
1805
-     * @return string of SQL
1806
-     * @throws \EE_Error
1807
-     */
1808
-    public function _construct_update_sql($fields_n_values)
1809
-    {
1810
-        /** @type WPDB $wpdb */
1811
-        global $wpdb;
1812
-        $cols_n_values = array();
1813
-        foreach ($fields_n_values as $field_name => $value) {
1814
-            $field_obj = $this->field_settings_for($field_name);
1815
-            //if the value is NULL, we want to assign the value to that.
1816
-            //wpdb->prepare doesn't really handle that properly
1817
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
-            $value_sql = $prepared_value === null ? 'NULL'
1819
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
-        }
1822
-        return implode(",", $cols_n_values);
1823
-    }
1824
-
1825
-
1826
-
1827
-    /**
1828
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
-     * Performs a HARD delete, meaning the database row should always be removed,
1830
-     * not just have a flag field on it switched
1831
-     * Wrapper for EEM_Base::delete_permanently()
1832
-     *
1833
-     * @param mixed $id
1834
-     * @return boolean whether the row got deleted or not
1835
-     * @throws \EE_Error
1836
-     */
1837
-    public function delete_permanently_by_ID($id)
1838
-    {
1839
-        return $this->delete_permanently(
1840
-            array(
1841
-                array($this->get_primary_key_field()->get_name() => $id),
1842
-                'limit' => 1,
1843
-            )
1844
-        );
1845
-    }
1846
-
1847
-
1848
-
1849
-    /**
1850
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
-     * Wrapper for EEM_Base::delete()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @return boolean whether the row got deleted or not
1855
-     * @throws \EE_Error
1856
-     */
1857
-    public function delete_by_ID($id)
1858
-    {
1859
-        return $this->delete(
1860
-            array(
1861
-                array($this->get_primary_key_field()->get_name() => $id),
1862
-                'limit' => 1,
1863
-            )
1864
-        );
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1871
-     * meaning if the model has a field that indicates its been "trashed" or
1872
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1873
-     *
1874
-     * @see EEM_Base::delete_permanently
1875
-     * @param array   $query_params
1876
-     * @param boolean $allow_blocking
1877
-     * @return int how many rows got deleted
1878
-     * @throws \EE_Error
1879
-     */
1880
-    public function delete($query_params, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete_permanently($query_params, $allow_blocking);
1883
-    }
1884
-
1885
-
1886
-
1887
-    /**
1888
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1889
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
-     * as archived, not actually deleted
1891
-     *
1892
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
-     *                                deletes regardless of other objects which may depend on it. Its generally
1896
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
-     *                                DB
1898
-     * @return int how many rows got deleted
1899
-     * @throws \EE_Error
1900
-     */
1901
-    public function delete_permanently($query_params, $allow_blocking = true)
1902
-    {
1903
-        /**
1904
-         * Action called just before performing a real deletion query. You can use the
1905
-         * model and its $query_params to find exactly which items will be deleted
1906
-         *
1907
-         * @param EEM_Base $model
1908
-         * @param array    $query_params   @see EEM_Base::get_all()
1909
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1910
-         *                                 to block (prevent) this deletion
1911
-         */
1912
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
-        //some MySQL databases may be running safe mode, which may restrict
1914
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
-        //to delete them
1917
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
-            $columns_and_ids_for_deleting
1921
-        );
1922
-        /**
1923
-         * Allows client code to act on the items being deleted before the query is actually executed.
1924
-         *
1925
-         * @param EEM_Base $this  The model instance being acted on.
1926
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
-         *                                                  derived from the incoming query parameters.
1930
-         *                                                  @see details on the structure of this array in the phpdocs
1931
-         *                                                  for the `_get_ids_for_delete_method`
1932
-         *
1933
-         */
1934
-        do_action('AHEE__EEM_Base__delete__before_query',
1935
-            $this,
1936
-            $query_params,
1937
-            $allow_blocking,
1938
-            $columns_and_ids_for_deleting
1939
-        );
1940
-        if ($deletion_where_query_part) {
1941
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
-            $table_aliases = array_keys($this->_tables);
1943
-            $SQL = "DELETE "
1944
-                   . implode(", ", $table_aliases)
1945
-                   . " FROM "
1946
-                   . $model_query_info->get_full_join_sql()
1947
-                   . " WHERE "
1948
-                   . $deletion_where_query_part;
1949
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
-        } else {
1951
-            $rows_deleted = 0;
1952
-        }
1953
-
1954
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
-        //there was no error with the delete query.
1956
-        if ($this->has_primary_key_field() && $rows_deleted !== false) {
1957
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1958
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1959
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1960
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1961
-                }
1962
-            }
1963
-        }
1964
-        /**
1965
-         * Action called just after performing a real deletion query. Although at this point the
1966
-         * items should have been deleted
1967
-         *
1968
-         * @param EEM_Base $model
1969
-         * @param array    $query_params @see EEM_Base::get_all()
1970
-         * @param int      $rows_deleted
1971
-         */
1972
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1973
-        return $rows_deleted;//how many supposedly got deleted
1974
-    }
1975
-
1976
-
1977
-
1978
-    /**
1979
-     * Checks all the relations that throw error messages when there are blocking related objects
1980
-     * for related model objects. If there are any related model objects on those relations,
1981
-     * adds an EE_Error, and return true
1982
-     *
1983
-     * @param EE_Base_Class|int $this_model_obj_or_id
1984
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1985
-     *                                                 should be ignored when determining whether there are related
1986
-     *                                                 model objects which block this model object's deletion. Useful
1987
-     *                                                 if you know A is related to B and are considering deleting A,
1988
-     *                                                 but want to see if A has any other objects blocking its deletion
1989
-     *                                                 before removing the relation between A and B
1990
-     * @return boolean
1991
-     * @throws \EE_Error
1992
-     */
1993
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1994
-    {
1995
-        //first, if $ignore_this_model_obj was supplied, get its model
1996
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1997
-            $ignored_model = $ignore_this_model_obj->get_model();
1998
-        } else {
1999
-            $ignored_model = null;
2000
-        }
2001
-        //now check all the relations of $this_model_obj_or_id and see if there
2002
-        //are any related model objects blocking it?
2003
-        $is_blocked = false;
2004
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2005
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2006
-                //if $ignore_this_model_obj was supplied, then for the query
2007
-                //on that model needs to be told to ignore $ignore_this_model_obj
2008
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2009
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2010
-                        array(
2011
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2012
-                                '!=',
2013
-                                $ignore_this_model_obj->ID(),
2014
-                            ),
2015
-                        ),
2016
-                    ));
2017
-                } else {
2018
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2019
-                }
2020
-                if ($related_model_objects) {
2021
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2022
-                    $is_blocked = true;
2023
-                }
2024
-            }
2025
-        }
2026
-        return $is_blocked;
2027
-    }
2028
-
2029
-
2030
-    /**
2031
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2032
-     * @param array $row_results_for_deleting
2033
-     * @param bool  $allow_blocking
2034
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2035
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2036
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2037
-     *                 deleted. Example:
2038
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2039
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2040
-     *                 where each element is a group of columns and values that get deleted. Example:
2041
-     *                      array(
2042
-     *                          0 => array(
2043
-     *                              'Term_Relationship.object_id' => 1
2044
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2045
-     *                          ),
2046
-     *                          1 => array(
2047
-     *                              'Term_Relationship.object_id' => 1
2048
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2049
-     *                          )
2050
-     *                      )
2051
-     * @throws EE_Error
2052
-     */
2053
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2054
-    {
2055
-        $ids_to_delete_indexed_by_column = array();
2056
-        if ($this->has_primary_key_field()) {
2057
-            $primary_table = $this->_get_main_table();
2058
-            $other_tables = $this->_get_other_tables();
2059
-            $ids_to_delete_indexed_by_column = $query = array();
2060
-            foreach ($row_results_for_deleting as $item_to_delete) {
2061
-                //before we mark this item for deletion,
2062
-                //make sure there's no related entities blocking its deletion (if we're checking)
2063
-                if (
2064
-                    $allow_blocking
2065
-                    && $this->delete_is_blocked_by_related_models(
2066
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2067
-                    )
2068
-                ) {
2069
-                    continue;
2070
-                }
2071
-                //primary table deletes
2072
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2073
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2074
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2075
-                }
2076
-            }
2077
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2078
-            $fields = $this->get_combined_primary_key_fields();
2079
-            foreach ($row_results_for_deleting as $item_to_delete) {
2080
-                $ids_to_delete_indexed_by_column_for_row = array();
2081
-                foreach ($fields as $cpk_field) {
2082
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2083
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2084
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2085
-                    }
2086
-                }
2087
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2088
-            }
2089
-        } else {
2090
-            //so there's no primary key and no combined key...
2091
-            //sorry, can't help you
2092
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2093
-                "event_espresso"), get_class($this)));
2094
-        }
2095
-        return $ids_to_delete_indexed_by_column;
2096
-    }
2097
-
2098
-
2099
-    /**
2100
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2101
-     * the corresponding query_part for the query performing the delete.
2102
-     *
2103
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2104
-     * @return string
2105
-     * @throws EE_Error
2106
-     */
2107
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2108
-        $query_part = '';
2109
-        if (empty($ids_to_delete_indexed_by_column)) {
2110
-            return $query_part;
2111
-        } elseif ($this->has_primary_key_field()) {
2112
-            $query = array();
2113
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2114
-                //make sure we have unique $ids
2115
-                $ids = array_unique($ids);
2116
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2117
-            }
2118
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2119
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2120
-            $ways_to_identify_a_row = array();
2121
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2122
-                $values_for_each_combined_primary_key_for_a_row = array();
2123
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2124
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2125
-                }
2126
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2127
-            }
2128
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2129
-        }
2130
-        return $query_part;
2131
-    }
31
+	//admin posty
32
+	//basic -> grants access to mine -> if they don't have it, select none
33
+	//*_others -> grants access to others that aren't private, and all mine -> if they don't have it, select mine
34
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
35
+	//*_published -> grants access to published -> if they dont have it, select non-published
36
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
37
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
38
+	//frontend posty
39
+	//by default has access to published
40
+	//basic -> grants access to mine that aren't published, and all published
41
+	//*_others ->grants access to others that aren't private, all mine
42
+	//*_private -> grants full access
43
+	//frontend non-posty
44
+	//like admin posty
45
+	//category-y
46
+	//assign -> grants access to join-table
47
+	//(delete, edit)
48
+	//payment-method-y
49
+	//for each registered payment method,
50
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
51
+	/**
52
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
53
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
54
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
55
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
56
+	 *
57
+	 * @var boolean
58
+	 */
59
+	private $_values_already_prepared_by_model_object = 0;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the data is just like form input that needs to have the model fields'
64
+	 * prepare_for_set and prepare_for_use_in_db called on it
65
+	 */
66
+	const not_prepared_by_model_object = 0;
67
+
68
+	/**
69
+	 * when $_values_already_prepared_by_model_object equals this, we
70
+	 * assume this value is coming from a model object and doesn't need to have
71
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
72
+	 */
73
+	const prepared_by_model_object = 1;
74
+
75
+	/**
76
+	 * when $_values_already_prepared_by_model_object equals this, we assume
77
+	 * the values are already to be used in the database (ie no processing is done
78
+	 * on them by the model's fields)
79
+	 */
80
+	const prepared_for_use_in_db = 2;
81
+
82
+
83
+	protected $singular_item = 'Item';
84
+
85
+	protected $plural_item   = 'Items';
86
+
87
+	/**
88
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
89
+	 */
90
+	protected $_tables;
91
+
92
+	/**
93
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
94
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
95
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
96
+	 *
97
+	 * @var \EE_Model_Field_Base[] $_fields
98
+	 */
99
+	protected $_fields;
100
+
101
+	/**
102
+	 * array of different kinds of relations
103
+	 *
104
+	 * @var \EE_Model_Relation_Base[] $_model_relations
105
+	 */
106
+	protected $_model_relations;
107
+
108
+	/**
109
+	 * @var \EE_Index[] $_indexes
110
+	 */
111
+	protected $_indexes = array();
112
+
113
+	/**
114
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
115
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
116
+	 * by setting the same columns as used in these queries in the query yourself.
117
+	 *
118
+	 * @var EE_Default_Where_Conditions
119
+	 */
120
+	protected $_default_where_conditions_strategy;
121
+
122
+	/**
123
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
124
+	 * This is particularly useful when you want something between 'none' and 'default'
125
+	 *
126
+	 * @var EE_Default_Where_Conditions
127
+	 */
128
+	protected $_minimum_where_conditions_strategy;
129
+
130
+	/**
131
+	 * String describing how to find the "owner" of this model's objects.
132
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
133
+	 * But when there isn't, this indicates which related model, or transiently-related model,
134
+	 * has the foreign key to the wp_users table.
135
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
136
+	 * related to events, and events have a foreign key to wp_users.
137
+	 * On EEM_Transaction, this would be 'Transaction.Event'
138
+	 *
139
+	 * @var string
140
+	 */
141
+	protected $_model_chain_to_wp_user = '';
142
+
143
+	/**
144
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
145
+	 * don't need it (particularly CPT models)
146
+	 *
147
+	 * @var bool
148
+	 */
149
+	protected $_ignore_where_strategy = false;
150
+
151
+	/**
152
+	 * String used in caps relating to this model. Eg, if the caps relating to this
153
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
154
+	 *
155
+	 * @var string. If null it hasn't been initialized yet. If false then we
156
+	 * have indicated capabilities don't apply to this
157
+	 */
158
+	protected $_caps_slug = null;
159
+
160
+	/**
161
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
162
+	 * and next-level keys are capability names, and each's value is a
163
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
164
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
165
+	 * and then each capability in the corresponding sub-array that they're missing
166
+	 * adds the where conditions onto the query.
167
+	 *
168
+	 * @var array
169
+	 */
170
+	protected $_cap_restrictions = array(
171
+		self::caps_read       => array(),
172
+		self::caps_read_admin => array(),
173
+		self::caps_edit       => array(),
174
+		self::caps_delete     => array(),
175
+	);
176
+
177
+	/**
178
+	 * Array defining which cap restriction generators to use to create default
179
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
180
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
181
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
182
+	 * automatically set this to false (not just null).
183
+	 *
184
+	 * @var EE_Restriction_Generator_Base[]
185
+	 */
186
+	protected $_cap_restriction_generators = array();
187
+
188
+	/**
189
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
190
+	 */
191
+	const caps_read       = 'read';
192
+
193
+	const caps_read_admin = 'read_admin';
194
+
195
+	const caps_edit       = 'edit';
196
+
197
+	const caps_delete     = 'delete';
198
+
199
+	/**
200
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
201
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
202
+	 * maps to 'read' because when looking for relevant permissions we're going to use
203
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
204
+	 *
205
+	 * @var array
206
+	 */
207
+	protected $_cap_contexts_to_cap_action_map = array(
208
+		self::caps_read       => 'read',
209
+		self::caps_read_admin => 'read',
210
+		self::caps_edit       => 'edit',
211
+		self::caps_delete     => 'delete',
212
+	);
213
+
214
+	/**
215
+	 * Timezone
216
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
217
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
218
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
219
+	 * EE_Datetime_Field data type will have access to it.
220
+	 *
221
+	 * @var string
222
+	 */
223
+	protected $_timezone;
224
+
225
+
226
+	/**
227
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
228
+	 * multisite.
229
+	 *
230
+	 * @var int
231
+	 */
232
+	protected static $_model_query_blog_id;
233
+
234
+	/**
235
+	 * A copy of _fields, except the array keys are the model names pointed to by
236
+	 * the field
237
+	 *
238
+	 * @var EE_Model_Field_Base[]
239
+	 */
240
+	private $_cache_foreign_key_to_fields = array();
241
+
242
+	/**
243
+	 * Cached list of all the fields on the model, indexed by their name
244
+	 *
245
+	 * @var EE_Model_Field_Base[]
246
+	 */
247
+	private $_cached_fields = null;
248
+
249
+	/**
250
+	 * Cached list of all the fields on the model, except those that are
251
+	 * marked as only pertinent to the database
252
+	 *
253
+	 * @var EE_Model_Field_Base[]
254
+	 */
255
+	private $_cached_fields_non_db_only = null;
256
+
257
+	/**
258
+	 * A cached reference to the primary key for quick lookup
259
+	 *
260
+	 * @var EE_Model_Field_Base
261
+	 */
262
+	private $_primary_key_field = null;
263
+
264
+	/**
265
+	 * Flag indicating whether this model has a primary key or not
266
+	 *
267
+	 * @var boolean
268
+	 */
269
+	protected $_has_primary_key_field = null;
270
+
271
+	/**
272
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
273
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
274
+	 *
275
+	 * @var boolean
276
+	 */
277
+	protected $_wp_core_model = false;
278
+
279
+	/**
280
+	 *    List of valid operators that can be used for querying.
281
+	 * The keys are all operators we'll accept, the values are the real SQL
282
+	 * operators used
283
+	 *
284
+	 * @var array
285
+	 */
286
+	protected $_valid_operators = array(
287
+		'='           => '=',
288
+		'<='          => '<=',
289
+		'<'           => '<',
290
+		'>='          => '>=',
291
+		'>'           => '>',
292
+		'!='          => '!=',
293
+		'LIKE'        => 'LIKE',
294
+		'like'        => 'LIKE',
295
+		'NOT_LIKE'    => 'NOT LIKE',
296
+		'not_like'    => 'NOT LIKE',
297
+		'NOT LIKE'    => 'NOT LIKE',
298
+		'not like'    => 'NOT LIKE',
299
+		'IN'          => 'IN',
300
+		'in'          => 'IN',
301
+		'NOT_IN'      => 'NOT IN',
302
+		'not_in'      => 'NOT IN',
303
+		'NOT IN'      => 'NOT IN',
304
+		'not in'      => 'NOT IN',
305
+		'between'     => 'BETWEEN',
306
+		'BETWEEN'     => 'BETWEEN',
307
+		'IS_NOT_NULL' => 'IS NOT NULL',
308
+		'is_not_null' => 'IS NOT NULL',
309
+		'IS NOT NULL' => 'IS NOT NULL',
310
+		'is not null' => 'IS NOT NULL',
311
+		'IS_NULL'     => 'IS NULL',
312
+		'is_null'     => 'IS NULL',
313
+		'IS NULL'     => 'IS NULL',
314
+		'is null'     => 'IS NULL',
315
+		'REGEXP'      => 'REGEXP',
316
+		'regexp'      => 'REGEXP',
317
+		'NOT_REGEXP'  => 'NOT REGEXP',
318
+		'not_regexp'  => 'NOT REGEXP',
319
+		'NOT REGEXP'  => 'NOT REGEXP',
320
+		'not regexp'  => 'NOT REGEXP',
321
+	);
322
+
323
+	/**
324
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
325
+	 *
326
+	 * @var array
327
+	 */
328
+	protected $_in_style_operators = array('IN', 'NOT IN');
329
+
330
+	/**
331
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
332
+	 * '12-31-2012'"
333
+	 *
334
+	 * @var array
335
+	 */
336
+	protected $_between_style_operators = array('BETWEEN');
337
+
338
+	/**
339
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
340
+	 * on a join table.
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
345
+
346
+	/**
347
+	 * Allowed values for $query_params['order'] for ordering in queries
348
+	 *
349
+	 * @var array
350
+	 */
351
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
352
+
353
+	/**
354
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
355
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
356
+	 *
357
+	 * @var array
358
+	 */
359
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
360
+
361
+	/**
362
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
363
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
364
+	 *
365
+	 * @var array
366
+	 */
367
+	private $_allowed_query_params = array(
368
+		0,
369
+		'limit',
370
+		'order_by',
371
+		'group_by',
372
+		'having',
373
+		'force_join',
374
+		'order',
375
+		'on_join_limit',
376
+		'default_where_conditions',
377
+		'caps',
378
+	);
379
+
380
+	/**
381
+	 * All the data types that can be used in $wpdb->prepare statements.
382
+	 *
383
+	 * @var array
384
+	 */
385
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
386
+
387
+	/**
388
+	 *    EE_Registry Object
389
+	 *
390
+	 * @var    object
391
+	 * @access    protected
392
+	 */
393
+	protected $EE = null;
394
+
395
+
396
+	/**
397
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
398
+	 *
399
+	 * @var int
400
+	 */
401
+	protected $_show_next_x_db_queries = 0;
402
+
403
+	/**
404
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
405
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
406
+	 *
407
+	 * @var array
408
+	 */
409
+	protected $_custom_selections = array();
410
+
411
+	/**
412
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
413
+	 * caches every model object we've fetched from the DB on this request
414
+	 *
415
+	 * @var array
416
+	 */
417
+	protected $_entity_map;
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws \EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('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.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('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.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Generates the cap restrictions for the given context, or if they were
654
+	 * already generated just gets what's cached
655
+	 *
656
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
657
+	 * @return EE_Default_Where_Conditions[]
658
+	 */
659
+	protected function _generate_cap_restrictions($context)
660
+	{
661
+		if (isset($this->_cap_restriction_generators[$context])
662
+			&& $this->_cap_restriction_generators[$context]
663
+			   instanceof
664
+			   EE_Restriction_Generator_Base
665
+		) {
666
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
667
+		} else {
668
+			return array();
669
+		}
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Used to set the $_model_query_blog_id static property.
676
+	 *
677
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
678
+	 *                      value for get_current_blog_id() will be used.
679
+	 */
680
+	public static function set_model_query_blog_id($blog_id = 0)
681
+	{
682
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
683
+	}
684
+
685
+
686
+
687
+	/**
688
+	 * Returns whatever is set as the internal $model_query_blog_id.
689
+	 *
690
+	 * @return int
691
+	 */
692
+	public static function get_model_query_blog_id()
693
+	{
694
+		return EEM_Base::$_model_query_blog_id;
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 *        This function is a singleton method used to instantiate the Espresso_model object
701
+	 *
702
+	 * @access public
703
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
704
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
705
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
706
+	 *                         timezone in the 'timezone_string' wp option)
707
+	 * @return static (as in the concrete child class)
708
+	 */
709
+	public static function instance($timezone = null)
710
+	{
711
+		// check if instance of Espresso_model already exists
712
+		if (! static::$_instance instanceof static) {
713
+			// instantiate Espresso_model
714
+			static::$_instance = new static($timezone);
715
+		}
716
+		//we might have a timezone set, let set_timezone decide what to do with it
717
+		static::$_instance->set_timezone($timezone);
718
+		// Espresso_model object
719
+		return static::$_instance;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * resets the model and returns it
726
+	 *
727
+	 * @param null | string $timezone
728
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
729
+	 * all its properties reset; if it wasn't instantiated, returns null)
730
+	 */
731
+	public static function reset($timezone = null)
732
+	{
733
+		if (static::$_instance instanceof EEM_Base) {
734
+			//let's try to NOT swap out the current instance for a new one
735
+			//because if someone has a reference to it, we can't remove their reference
736
+			//so it's best to keep using the same reference, but change the original object
737
+			//reset all its properties to their original values as defined in the class
738
+			$r = new ReflectionClass(get_class(static::$_instance));
739
+			$static_properties = $r->getStaticProperties();
740
+			foreach ($r->getDefaultProperties() as $property => $value) {
741
+				//don't set instance to null like it was originally,
742
+				//but it's static anyways, and we're ignoring static properties (for now at least)
743
+				if (! isset($static_properties[$property])) {
744
+					static::$_instance->{$property} = $value;
745
+				}
746
+			}
747
+			//and then directly call its constructor again, like we would if we
748
+			//were creating a new one
749
+			static::$_instance->__construct($timezone);
750
+			return self::instance();
751
+		}
752
+		return null;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
759
+	 *
760
+	 * @param  boolean $translated return localized strings or JUST the array.
761
+	 * @return array
762
+	 * @throws \EE_Error
763
+	 */
764
+	public function status_array($translated = false)
765
+	{
766
+		if (! array_key_exists('Status', $this->_model_relations)) {
767
+			return array();
768
+		}
769
+		$model_name = $this->get_this_model_name();
770
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
771
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
772
+		$status_array = array();
773
+		foreach ($stati as $status) {
774
+			$status_array[$status->ID()] = $status->get('STS_code');
775
+		}
776
+		return $translated
777
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
778
+			: $status_array;
779
+	}
780
+
781
+
782
+
783
+	/**
784
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
785
+	 *
786
+	 * @param array $query_params             {
787
+	 * @var array $0 (where) array {
788
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
789
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
790
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
791
+	 *                                        conditions based on related models (and even
792
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
793
+	 *                                        name. Eg,
794
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
795
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
796
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
797
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
798
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
799
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
800
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
801
+	 *                                        to Venues (even when each of those models actually consisted of two
802
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
803
+	 *                                        just having
804
+	 *                                        "Venue.VNU_ID", you could have
805
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
806
+	 *                                        events are related to Registrations, which are related to Attendees). You
807
+	 *                                        can take it even further with
808
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
809
+	 *                                        (from the default of '='), change the value to an numerically-indexed
810
+	 *                                        array, where the first item in the list is the operator. eg: array(
811
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
812
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
813
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
814
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
815
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
816
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
817
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
818
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
819
+	 *                                        the value is a field, simply provide a third array item (true) to the
820
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
821
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
822
+	 *                                        Note: you can also use related model field names like you would any other
823
+	 *                                        field name. eg:
824
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
825
+	 *                                        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__>' =>
826
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
827
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
828
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
829
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
830
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
831
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
832
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
833
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
834
+	 *                                        "stick" until you specify an AND. eg
835
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
836
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
837
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
838
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
839
+	 *                                        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 >>
840
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
841
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
842
+	 *                                        too, eg:
843
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
844
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
845
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
846
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
847
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
848
+	 *                                        the OFFSET, the 2nd is the LIMIT
849
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
850
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
851
+	 *                                        following format array('on_join_limit'
852
+	 *                                        => array( 'table_alias', array(1,2) ) ).
853
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
854
+	 *                                        values are either 'ASC' or 'DESC'.
855
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
856
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
857
+	 *                                        DESC..." respectively. Like the
858
+	 *                                        'where' conditions, these fields can be on related models. Eg
859
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
860
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
861
+	 *                                        Attendee, Price, Datetime, etc.)
862
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
863
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
864
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
865
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
866
+	 *                                        order by the primary key. Eg,
867
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
868
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
869
+	 *                                        DTT_EVT_start) or
870
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
871
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
872
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
873
+	 *                                        'group_by'=>'VNU_ID', or
874
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
875
+	 *                                        if no
876
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
877
+	 *                                        model's primary key (or combined primary keys). This avoids some
878
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
879
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
880
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
881
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
882
+	 *                                        results)
883
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
884
+	 *                                        array where values are models to be joined in the query.Eg
885
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
886
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
887
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
888
+	 *                                        related models which belongs to the current model
889
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
890
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
891
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
892
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
893
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
894
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
895
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
896
+	 *                                        this model's default where conditions added to the query, use
897
+	 *                                        'this_model_only'. If you want to use all default where conditions
898
+	 *                                        (default), set to 'all'.
899
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
900
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
901
+	 *                                        everything? Or should we only show the current user items they should be
902
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
903
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
904
+	 *                                        }
905
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
906
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
907
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
908
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
909
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
910
+	 *                                        array( array(
911
+	 *                                        'OR'=>array(
912
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
913
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
914
+	 *                                        )
915
+	 *                                        ),
916
+	 *                                        'limit'=>10,
917
+	 *                                        'group_by'=>'TXN_ID'
918
+	 *                                        ));
919
+	 *                                        get all the answers to the question titled "shirt size" for event with id
920
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
921
+	 *                                        'Question.QST_display_text'=>'shirt size',
922
+	 *                                        'Registration.Event.EVT_ID'=>12
923
+	 *                                        ),
924
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
925
+	 *                                        ));
926
+	 * @throws \EE_Error
927
+	 */
928
+	public function get_all($query_params = array())
929
+	{
930
+		if (isset($query_params['limit'])
931
+			&& ! isset($query_params['group_by'])
932
+		) {
933
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
934
+		}
935
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
936
+	}
937
+
938
+
939
+
940
+	/**
941
+	 * Modifies the query parameters so we only get back model objects
942
+	 * that "belong" to the current user
943
+	 *
944
+	 * @param array $query_params @see EEM_Base::get_all()
945
+	 * @return array like EEM_Base::get_all
946
+	 */
947
+	public function alter_query_params_to_only_include_mine($query_params = array())
948
+	{
949
+		$wp_user_field_name = $this->wp_user_field_name();
950
+		if ($wp_user_field_name) {
951
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
952
+		}
953
+		return $query_params;
954
+	}
955
+
956
+
957
+
958
+	/**
959
+	 * Returns the name of the field's name that points to the WP_User table
960
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
961
+	 * foreign key to the WP_User table)
962
+	 *
963
+	 * @return string|boolean string on success, boolean false when there is no
964
+	 * foreign key to the WP_User table
965
+	 */
966
+	public function wp_user_field_name()
967
+	{
968
+		try {
969
+			if (! empty($this->_model_chain_to_wp_user)) {
970
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
971
+				$last_model_name = end($models_to_follow_to_wp_users);
972
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
973
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
974
+			} else {
975
+				$model_with_fk_to_wp_users = $this;
976
+				$model_chain_to_wp_user = '';
977
+			}
978
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
979
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
980
+		} catch (EE_Error $e) {
981
+			return false;
982
+		}
983
+	}
984
+
985
+
986
+
987
+	/**
988
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
989
+	 * (or transiently-related model) has a foreign key to the wp_users table;
990
+	 * useful for finding if model objects of this type are 'owned' by the current user.
991
+	 * This is an empty string when the foreign key is on this model and when it isn't,
992
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
993
+	 * (or transiently-related model)
994
+	 *
995
+	 * @return string
996
+	 */
997
+	public function model_chain_to_wp_user()
998
+	{
999
+		return $this->_model_chain_to_wp_user;
1000
+	}
1001
+
1002
+
1003
+
1004
+	/**
1005
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1006
+	 * like how registrations don't have a foreign key to wp_users, but the
1007
+	 * events they are for are), or is unrelated to wp users.
1008
+	 * generally available
1009
+	 *
1010
+	 * @return boolean
1011
+	 */
1012
+	public function is_owned()
1013
+	{
1014
+		if ($this->model_chain_to_wp_user()) {
1015
+			return true;
1016
+		} else {
1017
+			try {
1018
+				$this->get_foreign_key_to('WP_User');
1019
+				return true;
1020
+			} catch (EE_Error $e) {
1021
+				return false;
1022
+			}
1023
+		}
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1030
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1031
+	 * the model)
1032
+	 *
1033
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws \EE_Error
1045
+	 */
1046
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		// remember the custom selections, if any, and type cast as array
1049
+		// (unless $columns_to_select is an object, then just set as an empty array)
1050
+		// Note: (array) 'some string' === array( 'some string' )
1051
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1052
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1053
+		$select_expressions = $columns_to_select !== null
1054
+			? $this->_construct_select_from_input($columns_to_select)
1055
+			: $this->_construct_default_select_sql($model_query_info);
1056
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1057
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1058
+	}
1059
+
1060
+
1061
+
1062
+	/**
1063
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1064
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1065
+	 * take care of joins, field preparation etc.
1066
+	 *
1067
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1068
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1069
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1070
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1071
+	 *                                  override this and set the select to "*", or a specific column name, like
1072
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1073
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1074
+	 *                                  the aliases used to refer to this selection, and values are to be
1075
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1076
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1077
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1078
+	 * @throws \EE_Error
1079
+	 */
1080
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1081
+	{
1082
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1083
+	}
1084
+
1085
+
1086
+
1087
+	/**
1088
+	 * For creating a custom select statement
1089
+	 *
1090
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1091
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1092
+	 *                                 SQL, and 1=>is the datatype
1093
+	 * @throws EE_Error
1094
+	 * @return string
1095
+	 */
1096
+	private function _construct_select_from_input($columns_to_select)
1097
+	{
1098
+		if (is_array($columns_to_select)) {
1099
+			$select_sql_array = array();
1100
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1101
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1102
+					throw new EE_Error(
1103
+						sprintf(
1104
+							__(
1105
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1106
+								"event_espresso"
1107
+							),
1108
+							$selection_and_datatype,
1109
+							$alias
1110
+						)
1111
+					);
1112
+				}
1113
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1114
+					throw new EE_Error(
1115
+						sprintf(
1116
+							__(
1117
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1118
+								"event_espresso"
1119
+							),
1120
+							$selection_and_datatype[1],
1121
+							$selection_and_datatype[0],
1122
+							$alias,
1123
+							implode(",", $this->_valid_wpdb_data_types)
1124
+						)
1125
+					);
1126
+				}
1127
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1128
+			}
1129
+			$columns_to_select_string = implode(", ", $select_sql_array);
1130
+		} else {
1131
+			$columns_to_select_string = $columns_to_select;
1132
+		}
1133
+		return $columns_to_select_string;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1140
+	 *
1141
+	 * @return string
1142
+	 * @throws \EE_Error
1143
+	 */
1144
+	public function primary_key_name()
1145
+	{
1146
+		return $this->get_primary_key_field()->get_name();
1147
+	}
1148
+
1149
+
1150
+
1151
+	/**
1152
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1153
+	 * If there is no primary key on this model, $id is treated as primary key string
1154
+	 *
1155
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1156
+	 * @return EE_Base_Class
1157
+	 */
1158
+	public function get_one_by_ID($id)
1159
+	{
1160
+		if ($this->get_from_entity_map($id)) {
1161
+			return $this->get_from_entity_map($id);
1162
+		}
1163
+		return $this->get_one(
1164
+			$this->alter_query_params_to_restrict_by_ID(
1165
+				$id,
1166
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1167
+			)
1168
+		);
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Alters query parameters to only get items with this ID are returned.
1175
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1176
+	 * or could just be a simple primary key ID
1177
+	 *
1178
+	 * @param int   $id
1179
+	 * @param array $query_params
1180
+	 * @return array of normal query params, @see EEM_Base::get_all
1181
+	 * @throws \EE_Error
1182
+	 */
1183
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1184
+	{
1185
+		if (! isset($query_params[0])) {
1186
+			$query_params[0] = array();
1187
+		}
1188
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1189
+		if ($conditions_from_id === null) {
1190
+			$query_params[0][$this->primary_key_name()] = $id;
1191
+		} else {
1192
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1193
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1194
+		}
1195
+		return $query_params;
1196
+	}
1197
+
1198
+
1199
+
1200
+	/**
1201
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1202
+	 * array. If no item is found, null is returned.
1203
+	 *
1204
+	 * @param array $query_params like EEM_Base's $query_params variable.
1205
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1206
+	 * @throws \EE_Error
1207
+	 */
1208
+	public function get_one($query_params = array())
1209
+	{
1210
+		if (! is_array($query_params)) {
1211
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1212
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1213
+					gettype($query_params)), '4.6.0');
1214
+			$query_params = array();
1215
+		}
1216
+		$query_params['limit'] = 1;
1217
+		$items = $this->get_all($query_params);
1218
+		if (empty($items)) {
1219
+			return null;
1220
+		} else {
1221
+			return array_shift($items);
1222
+		}
1223
+	}
1224
+
1225
+
1226
+
1227
+	/**
1228
+	 * Returns the next x number of items in sequence from the given value as
1229
+	 * found in the database matching the given query conditions.
1230
+	 *
1231
+	 * @param mixed $current_field_value    Value used for the reference point.
1232
+	 * @param null  $field_to_order_by      What field is used for the
1233
+	 *                                      reference point.
1234
+	 * @param int   $limit                  How many to return.
1235
+	 * @param array $query_params           Extra conditions on the query.
1236
+	 * @param null  $columns_to_select      If left null, then an array of
1237
+	 *                                      EE_Base_Class objects is returned,
1238
+	 *                                      otherwise you can indicate just the
1239
+	 *                                      columns you want returned.
1240
+	 * @return EE_Base_Class[]|array
1241
+	 * @throws \EE_Error
1242
+	 */
1243
+	public function next_x(
1244
+		$current_field_value,
1245
+		$field_to_order_by = null,
1246
+		$limit = 1,
1247
+		$query_params = array(),
1248
+		$columns_to_select = null
1249
+	) {
1250
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1251
+			$columns_to_select);
1252
+	}
1253
+
1254
+
1255
+
1256
+	/**
1257
+	 * Returns the previous x number of items in sequence from the given value
1258
+	 * as found in the database matching the given query conditions.
1259
+	 *
1260
+	 * @param mixed $current_field_value    Value used for the reference point.
1261
+	 * @param null  $field_to_order_by      What field is used for the
1262
+	 *                                      reference point.
1263
+	 * @param int   $limit                  How many to return.
1264
+	 * @param array $query_params           Extra conditions on the query.
1265
+	 * @param null  $columns_to_select      If left null, then an array of
1266
+	 *                                      EE_Base_Class objects is returned,
1267
+	 *                                      otherwise you can indicate just the
1268
+	 *                                      columns you want returned.
1269
+	 * @return EE_Base_Class[]|array
1270
+	 * @throws \EE_Error
1271
+	 */
1272
+	public function previous_x(
1273
+		$current_field_value,
1274
+		$field_to_order_by = null,
1275
+		$limit = 1,
1276
+		$query_params = array(),
1277
+		$columns_to_select = null
1278
+	) {
1279
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1280
+			$columns_to_select);
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * Returns the next item in sequence from the given value as found in the
1287
+	 * database matching the given query conditions.
1288
+	 *
1289
+	 * @param mixed $current_field_value    Value used for the reference point.
1290
+	 * @param null  $field_to_order_by      What field is used for the
1291
+	 *                                      reference point.
1292
+	 * @param array $query_params           Extra conditions on the query.
1293
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1294
+	 *                                      object is returned, otherwise you
1295
+	 *                                      can indicate just the columns you
1296
+	 *                                      want and a single array indexed by
1297
+	 *                                      the columns will be returned.
1298
+	 * @return EE_Base_Class|null|array()
1299
+	 * @throws \EE_Error
1300
+	 */
1301
+	public function next(
1302
+		$current_field_value,
1303
+		$field_to_order_by = null,
1304
+		$query_params = array(),
1305
+		$columns_to_select = null
1306
+	) {
1307
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1308
+			$columns_to_select);
1309
+		return empty($results) ? null : reset($results);
1310
+	}
1311
+
1312
+
1313
+
1314
+	/**
1315
+	 * Returns the previous item in sequence from the given value as found in
1316
+	 * the database matching the given query conditions.
1317
+	 *
1318
+	 * @param mixed $current_field_value    Value used for the reference point.
1319
+	 * @param null  $field_to_order_by      What field is used for the
1320
+	 *                                      reference point.
1321
+	 * @param array $query_params           Extra conditions on the query.
1322
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1323
+	 *                                      object is returned, otherwise you
1324
+	 *                                      can indicate just the columns you
1325
+	 *                                      want and a single array indexed by
1326
+	 *                                      the columns will be returned.
1327
+	 * @return EE_Base_Class|null|array()
1328
+	 * @throws EE_Error
1329
+	 */
1330
+	public function previous(
1331
+		$current_field_value,
1332
+		$field_to_order_by = null,
1333
+		$query_params = array(),
1334
+		$columns_to_select = null
1335
+	) {
1336
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1337
+			$columns_to_select);
1338
+		return empty($results) ? null : reset($results);
1339
+	}
1340
+
1341
+
1342
+
1343
+	/**
1344
+	 * Returns the a consecutive number of items in sequence from the given
1345
+	 * value as found in the database matching the given query conditions.
1346
+	 *
1347
+	 * @param mixed  $current_field_value   Value used for the reference point.
1348
+	 * @param string $operand               What operand is used for the sequence.
1349
+	 * @param string $field_to_order_by     What field is used for the reference point.
1350
+	 * @param int    $limit                 How many to return.
1351
+	 * @param array  $query_params          Extra conditions on the query.
1352
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1353
+	 *                                      otherwise you can indicate just the columns you want returned.
1354
+	 * @return EE_Base_Class[]|array
1355
+	 * @throws EE_Error
1356
+	 */
1357
+	protected function _get_consecutive(
1358
+		$current_field_value,
1359
+		$operand = '>',
1360
+		$field_to_order_by = null,
1361
+		$limit = 1,
1362
+		$query_params = array(),
1363
+		$columns_to_select = null
1364
+	) {
1365
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1366
+		if (empty($field_to_order_by)) {
1367
+			if ($this->has_primary_key_field()) {
1368
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1369
+			} else {
1370
+				if (WP_DEBUG) {
1371
+					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).',
1372
+						'event_espresso'));
1373
+				}
1374
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1375
+				return array();
1376
+			}
1377
+		}
1378
+		if (! is_array($query_params)) {
1379
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1380
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1381
+					gettype($query_params)), '4.6.0');
1382
+			$query_params = array();
1383
+		}
1384
+		//let's add the where query param for consecutive look up.
1385
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1386
+		$query_params['limit'] = $limit;
1387
+		//set direction
1388
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1389
+		$query_params['order_by'] = $operand === '>'
1390
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1391
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1392
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1393
+		if (empty($columns_to_select)) {
1394
+			return $this->get_all($query_params);
1395
+		} else {
1396
+			//getting just the fields
1397
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1398
+		}
1399
+	}
1400
+
1401
+
1402
+
1403
+	/**
1404
+	 * This sets the _timezone property after model object has been instantiated.
1405
+	 *
1406
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1407
+	 */
1408
+	public function set_timezone($timezone)
1409
+	{
1410
+		if ($timezone !== null) {
1411
+			$this->_timezone = $timezone;
1412
+		}
1413
+		//note we need to loop through relations and set the timezone on those objects as well.
1414
+		foreach ($this->_model_relations as $relation) {
1415
+			$relation->set_timezone($timezone);
1416
+		}
1417
+		//and finally we do the same for any datetime fields
1418
+		foreach ($this->_fields as $field) {
1419
+			if ($field instanceof EE_Datetime_Field) {
1420
+				$field->set_timezone($timezone);
1421
+			}
1422
+		}
1423
+	}
1424
+
1425
+
1426
+
1427
+	/**
1428
+	 * This just returns whatever is set for the current timezone.
1429
+	 *
1430
+	 * @access public
1431
+	 * @return string
1432
+	 */
1433
+	public function get_timezone()
1434
+	{
1435
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1436
+		if (empty($this->_timezone)) {
1437
+			foreach ($this->_fields as $field) {
1438
+				if ($field instanceof EE_Datetime_Field) {
1439
+					$this->set_timezone($field->get_timezone());
1440
+					break;
1441
+				}
1442
+			}
1443
+		}
1444
+		//if timezone STILL empty then return the default timezone for the site.
1445
+		if (empty($this->_timezone)) {
1446
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1447
+		}
1448
+		return $this->_timezone;
1449
+	}
1450
+
1451
+
1452
+
1453
+	/**
1454
+	 * This returns the date formats set for the given field name and also ensures that
1455
+	 * $this->_timezone property is set correctly.
1456
+	 *
1457
+	 * @since 4.6.x
1458
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1459
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1460
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1461
+	 * @return array formats in an array with the date format first, and the time format last.
1462
+	 */
1463
+	public function get_formats_for($field_name, $pretty = false)
1464
+	{
1465
+		$field_settings = $this->field_settings_for($field_name);
1466
+		//if not a valid EE_Datetime_Field then throw error
1467
+		if (! $field_settings instanceof EE_Datetime_Field) {
1468
+			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.',
1469
+				'event_espresso'), $field_name));
1470
+		}
1471
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1472
+		//the field.
1473
+		$this->_timezone = $field_settings->get_timezone();
1474
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1475
+	}
1476
+
1477
+
1478
+
1479
+	/**
1480
+	 * This returns the current time in a format setup for a query on this model.
1481
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1482
+	 * it will return:
1483
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1484
+	 *  NOW
1485
+	 *  - or a unix timestamp (equivalent to time())
1486
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1487
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1488
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1489
+	 * @since 4.6.x
1490
+	 * @param string $field_name       The field the current time is needed for.
1491
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1492
+	 *                                 formatted string matching the set format for the field in the set timezone will
1493
+	 *                                 be returned.
1494
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1495
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1496
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1497
+	 *                                 exception is triggered.
1498
+	 */
1499
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1500
+	{
1501
+		$formats = $this->get_formats_for($field_name);
1502
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1503
+		if ($timestamp) {
1504
+			return $DateTime->format('U');
1505
+		}
1506
+		//not returning timestamp, so return formatted string in timezone.
1507
+		switch ($what) {
1508
+			case 'time' :
1509
+				return $DateTime->format($formats[1]);
1510
+				break;
1511
+			case 'date' :
1512
+				return $DateTime->format($formats[0]);
1513
+				break;
1514
+			default :
1515
+				return $DateTime->format(implode(' ', $formats));
1516
+				break;
1517
+		}
1518
+	}
1519
+
1520
+
1521
+
1522
+	/**
1523
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1524
+	 * for the model are.  Returns a DateTime object.
1525
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1526
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1527
+	 * ignored.
1528
+	 *
1529
+	 * @param string $field_name      The field being setup.
1530
+	 * @param string $timestring      The date time string being used.
1531
+	 * @param string $incoming_format The format for the time string.
1532
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1533
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1534
+	 *                                format is
1535
+	 *                                'U', this is ignored.
1536
+	 * @return DateTime
1537
+	 * @throws \EE_Error
1538
+	 */
1539
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1540
+	{
1541
+		//just using this to ensure the timezone is set correctly internally
1542
+		$this->get_formats_for($field_name);
1543
+		//load EEH_DTT_Helper
1544
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1545
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1546
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1553
+	 *
1554
+	 * @return EE_Table_Base[]
1555
+	 */
1556
+	public function get_tables()
1557
+	{
1558
+		return $this->_tables;
1559
+	}
1560
+
1561
+
1562
+
1563
+	/**
1564
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1565
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1566
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1567
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1568
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1569
+	 * model object with EVT_ID = 1
1570
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1571
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1572
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1573
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1574
+	 * are not specified)
1575
+	 *
1576
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1577
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1578
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1579
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1580
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1581
+	 *                                         ID=34, we'd use this method as follows:
1582
+	 *                                         EEM_Transaction::instance()->update(
1583
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1584
+	 *                                         array(array('TXN_ID'=>34)));
1585
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1586
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1587
+	 *                                         consider updating Question's QST_admin_label field is of type
1588
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1589
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1590
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1591
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1592
+	 *                                         TRUE, it is assumed that you've already called
1593
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1594
+	 *                                         malicious javascript. However, if
1595
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1596
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1597
+	 *                                         and every other field, before insertion. We provide this parameter
1598
+	 *                                         because model objects perform their prepare_for_set function on all
1599
+	 *                                         their values, and so don't need to be called again (and in many cases,
1600
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1601
+	 *                                         prepare_for_set method...)
1602
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1603
+	 *                                         in this model's entity map according to $fields_n_values that match
1604
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1605
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1606
+	 *                                         could get out-of-sync with the database
1607
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1608
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1609
+	 *                                         bad)
1610
+	 * @throws \EE_Error
1611
+	 */
1612
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1613
+	{
1614
+		if (! is_array($query_params)) {
1615
+			EE_Error::doing_it_wrong('EEM_Base::update',
1616
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1617
+					gettype($query_params)), '4.6.0');
1618
+			$query_params = array();
1619
+		}
1620
+		/**
1621
+		 * Action called before a model update call has been made.
1622
+		 *
1623
+		 * @param EEM_Base $model
1624
+		 * @param array    $fields_n_values the updated fields and their new values
1625
+		 * @param array    $query_params    @see EEM_Base::get_all()
1626
+		 */
1627
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1628
+		/**
1629
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1630
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1631
+		 *
1632
+		 * @param array    $fields_n_values fields and their new values
1633
+		 * @param EEM_Base $model           the model being queried
1634
+		 * @param array    $query_params    see EEM_Base::get_all()
1635
+		 */
1636
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1637
+			$query_params);
1638
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1639
+		//to do that, for each table, verify that it's PK isn't null.
1640
+		$tables = $this->get_tables();
1641
+		//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
1642
+		//NOTE: we should make this code more efficient by NOT querying twice
1643
+		//before the real update, but that needs to first go through ALPHA testing
1644
+		//as it's dangerous. says Mike August 8 2014
1645
+		//we want to make sure the default_where strategy is ignored
1646
+		$this->_ignore_where_strategy = true;
1647
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1648
+		foreach ($wpdb_select_results as $wpdb_result) {
1649
+			// type cast stdClass as array
1650
+			$wpdb_result = (array)$wpdb_result;
1651
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1652
+			if ($this->has_primary_key_field()) {
1653
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1654
+			} else {
1655
+				//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)
1656
+				$main_table_pk_value = null;
1657
+			}
1658
+			//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
1659
+			//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
1660
+			if (count($tables) > 1) {
1661
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1662
+				//in that table, and so we'll want to insert one
1663
+				foreach ($tables as $table_obj) {
1664
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1665
+					//if there is no private key for this table on the results, it means there's no entry
1666
+					//in this table, right? so insert a row in the current table, using any fields available
1667
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1668
+						   && $wpdb_result[$this_table_pk_column])
1669
+					) {
1670
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1671
+							$main_table_pk_value);
1672
+						//if we died here, report the error
1673
+						if (! $success) {
1674
+							return false;
1675
+						}
1676
+					}
1677
+				}
1678
+			}
1679
+			//				//and now check that if we have cached any models by that ID on the model, that
1680
+			//				//they also get updated properly
1681
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1682
+			//				if( $model_object ){
1683
+			//					foreach( $fields_n_values as $field => $value ){
1684
+			//						$model_object->set($field, $value);
1685
+			//let's make sure default_where strategy is followed now
1686
+			$this->_ignore_where_strategy = false;
1687
+		}
1688
+		//if we want to keep model objects in sync, AND
1689
+		//if this wasn't called from a model object (to update itself)
1690
+		//then we want to make sure we keep all the existing
1691
+		//model objects in sync with the db
1692
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1693
+			if ($this->has_primary_key_field()) {
1694
+				$model_objs_affected_ids = $this->get_col($query_params);
1695
+			} else {
1696
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1697
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1698
+				$model_objs_affected_ids = array();
1699
+				foreach ($models_affected_key_columns as $row) {
1700
+					$combined_index_key = $this->get_index_primary_key_string($row);
1701
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1702
+				}
1703
+			}
1704
+			if (! $model_objs_affected_ids) {
1705
+				//wait wait wait- if nothing was affected let's stop here
1706
+				return 0;
1707
+			}
1708
+			foreach ($model_objs_affected_ids as $id) {
1709
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1710
+				if ($model_obj_in_entity_map) {
1711
+					foreach ($fields_n_values as $field => $new_value) {
1712
+						$model_obj_in_entity_map->set($field, $new_value);
1713
+					}
1714
+				}
1715
+			}
1716
+			//if there is a primary key on this model, we can now do a slight optimization
1717
+			if ($this->has_primary_key_field()) {
1718
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1719
+				$query_params = array(
1720
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1721
+					'limit'                    => count($model_objs_affected_ids),
1722
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1723
+				);
1724
+			}
1725
+		}
1726
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1727
+		$SQL = "UPDATE "
1728
+			   . $model_query_info->get_full_join_sql()
1729
+			   . " SET "
1730
+			   . $this->_construct_update_sql($fields_n_values)
1731
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1732
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1733
+		/**
1734
+		 * Action called after a model update call has been made.
1735
+		 *
1736
+		 * @param EEM_Base $model
1737
+		 * @param array    $fields_n_values the updated fields and their new values
1738
+		 * @param array    $query_params    @see EEM_Base::get_all()
1739
+		 * @param int      $rows_affected
1740
+		 */
1741
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1742
+		return $rows_affected;//how many supposedly got updated
1743
+	}
1744
+
1745
+
1746
+
1747
+	/**
1748
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1749
+	 * are teh values of the field specified (or by default the primary key field)
1750
+	 * that matched the query params. Note that you should pass the name of the
1751
+	 * model FIELD, not the database table's column name.
1752
+	 *
1753
+	 * @param array  $query_params @see EEM_Base::get_all()
1754
+	 * @param string $field_to_select
1755
+	 * @return array just like $wpdb->get_col()
1756
+	 * @throws \EE_Error
1757
+	 */
1758
+	public function get_col($query_params = array(), $field_to_select = null)
1759
+	{
1760
+		if ($field_to_select) {
1761
+			$field = $this->field_settings_for($field_to_select);
1762
+		} elseif ($this->has_primary_key_field()) {
1763
+			$field = $this->get_primary_key_field();
1764
+		} else {
1765
+			//no primary key, just grab the first column
1766
+			$field = reset($this->field_settings());
1767
+		}
1768
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1769
+		$select_expressions = $field->get_qualified_column();
1770
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1771
+		return $this->_do_wpdb_query('get_col', array($SQL));
1772
+	}
1773
+
1774
+
1775
+
1776
+	/**
1777
+	 * Returns a single column value for a single row from the database
1778
+	 *
1779
+	 * @param array  $query_params    @see EEM_Base::get_all()
1780
+	 * @param string $field_to_select @see EEM_Base::get_col()
1781
+	 * @return string
1782
+	 * @throws \EE_Error
1783
+	 */
1784
+	public function get_var($query_params = array(), $field_to_select = null)
1785
+	{
1786
+		$query_params['limit'] = 1;
1787
+		$col = $this->get_col($query_params, $field_to_select);
1788
+		if (! empty($col)) {
1789
+			return reset($col);
1790
+		} else {
1791
+			return null;
1792
+		}
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1799
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1800
+	 * injection, but currently no further filtering is done
1801
+	 *
1802
+	 * @global      $wpdb
1803
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1804
+	 *                               be updated to in the DB
1805
+	 * @return string of SQL
1806
+	 * @throws \EE_Error
1807
+	 */
1808
+	public function _construct_update_sql($fields_n_values)
1809
+	{
1810
+		/** @type WPDB $wpdb */
1811
+		global $wpdb;
1812
+		$cols_n_values = array();
1813
+		foreach ($fields_n_values as $field_name => $value) {
1814
+			$field_obj = $this->field_settings_for($field_name);
1815
+			//if the value is NULL, we want to assign the value to that.
1816
+			//wpdb->prepare doesn't really handle that properly
1817
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1818
+			$value_sql = $prepared_value === null ? 'NULL'
1819
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1820
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1821
+		}
1822
+		return implode(",", $cols_n_values);
1823
+	}
1824
+
1825
+
1826
+
1827
+	/**
1828
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1829
+	 * Performs a HARD delete, meaning the database row should always be removed,
1830
+	 * not just have a flag field on it switched
1831
+	 * Wrapper for EEM_Base::delete_permanently()
1832
+	 *
1833
+	 * @param mixed $id
1834
+	 * @return boolean whether the row got deleted or not
1835
+	 * @throws \EE_Error
1836
+	 */
1837
+	public function delete_permanently_by_ID($id)
1838
+	{
1839
+		return $this->delete_permanently(
1840
+			array(
1841
+				array($this->get_primary_key_field()->get_name() => $id),
1842
+				'limit' => 1,
1843
+			)
1844
+		);
1845
+	}
1846
+
1847
+
1848
+
1849
+	/**
1850
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1851
+	 * Wrapper for EEM_Base::delete()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @return boolean whether the row got deleted or not
1855
+	 * @throws \EE_Error
1856
+	 */
1857
+	public function delete_by_ID($id)
1858
+	{
1859
+		return $this->delete(
1860
+			array(
1861
+				array($this->get_primary_key_field()->get_name() => $id),
1862
+				'limit' => 1,
1863
+			)
1864
+		);
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1871
+	 * meaning if the model has a field that indicates its been "trashed" or
1872
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1873
+	 *
1874
+	 * @see EEM_Base::delete_permanently
1875
+	 * @param array   $query_params
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int how many rows got deleted
1878
+	 * @throws \EE_Error
1879
+	 */
1880
+	public function delete($query_params, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete_permanently($query_params, $allow_blocking);
1883
+	}
1884
+
1885
+
1886
+
1887
+	/**
1888
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1889
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1890
+	 * as archived, not actually deleted
1891
+	 *
1892
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1893
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1894
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1895
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1896
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1897
+	 *                                DB
1898
+	 * @return int how many rows got deleted
1899
+	 * @throws \EE_Error
1900
+	 */
1901
+	public function delete_permanently($query_params, $allow_blocking = true)
1902
+	{
1903
+		/**
1904
+		 * Action called just before performing a real deletion query. You can use the
1905
+		 * model and its $query_params to find exactly which items will be deleted
1906
+		 *
1907
+		 * @param EEM_Base $model
1908
+		 * @param array    $query_params   @see EEM_Base::get_all()
1909
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1910
+		 *                                 to block (prevent) this deletion
1911
+		 */
1912
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1913
+		//some MySQL databases may be running safe mode, which may restrict
1914
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1915
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1916
+		//to delete them
1917
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1918
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1919
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1920
+			$columns_and_ids_for_deleting
1921
+		);
1922
+		/**
1923
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1924
+		 *
1925
+		 * @param EEM_Base $this  The model instance being acted on.
1926
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1927
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1928
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1929
+		 *                                                  derived from the incoming query parameters.
1930
+		 *                                                  @see details on the structure of this array in the phpdocs
1931
+		 *                                                  for the `_get_ids_for_delete_method`
1932
+		 *
1933
+		 */
1934
+		do_action('AHEE__EEM_Base__delete__before_query',
1935
+			$this,
1936
+			$query_params,
1937
+			$allow_blocking,
1938
+			$columns_and_ids_for_deleting
1939
+		);
1940
+		if ($deletion_where_query_part) {
1941
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1942
+			$table_aliases = array_keys($this->_tables);
1943
+			$SQL = "DELETE "
1944
+				   . implode(", ", $table_aliases)
1945
+				   . " FROM "
1946
+				   . $model_query_info->get_full_join_sql()
1947
+				   . " WHERE "
1948
+				   . $deletion_where_query_part;
1949
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1950
+		} else {
1951
+			$rows_deleted = 0;
1952
+		}
1953
+
1954
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all; and if
1955
+		//there was no error with the delete query.
1956
+		if ($this->has_primary_key_field() && $rows_deleted !== false) {
1957
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1958
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1959
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1960
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1961
+				}
1962
+			}
1963
+		}
1964
+		/**
1965
+		 * Action called just after performing a real deletion query. Although at this point the
1966
+		 * items should have been deleted
1967
+		 *
1968
+		 * @param EEM_Base $model
1969
+		 * @param array    $query_params @see EEM_Base::get_all()
1970
+		 * @param int      $rows_deleted
1971
+		 */
1972
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
1973
+		return $rows_deleted;//how many supposedly got deleted
1974
+	}
1975
+
1976
+
1977
+
1978
+	/**
1979
+	 * Checks all the relations that throw error messages when there are blocking related objects
1980
+	 * for related model objects. If there are any related model objects on those relations,
1981
+	 * adds an EE_Error, and return true
1982
+	 *
1983
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1984
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1985
+	 *                                                 should be ignored when determining whether there are related
1986
+	 *                                                 model objects which block this model object's deletion. Useful
1987
+	 *                                                 if you know A is related to B and are considering deleting A,
1988
+	 *                                                 but want to see if A has any other objects blocking its deletion
1989
+	 *                                                 before removing the relation between A and B
1990
+	 * @return boolean
1991
+	 * @throws \EE_Error
1992
+	 */
1993
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1994
+	{
1995
+		//first, if $ignore_this_model_obj was supplied, get its model
1996
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1997
+			$ignored_model = $ignore_this_model_obj->get_model();
1998
+		} else {
1999
+			$ignored_model = null;
2000
+		}
2001
+		//now check all the relations of $this_model_obj_or_id and see if there
2002
+		//are any related model objects blocking it?
2003
+		$is_blocked = false;
2004
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2005
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2006
+				//if $ignore_this_model_obj was supplied, then for the query
2007
+				//on that model needs to be told to ignore $ignore_this_model_obj
2008
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2009
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2010
+						array(
2011
+							$ignored_model->get_primary_key_field()->get_name() => array(
2012
+								'!=',
2013
+								$ignore_this_model_obj->ID(),
2014
+							),
2015
+						),
2016
+					));
2017
+				} else {
2018
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2019
+				}
2020
+				if ($related_model_objects) {
2021
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2022
+					$is_blocked = true;
2023
+				}
2024
+			}
2025
+		}
2026
+		return $is_blocked;
2027
+	}
2028
+
2029
+
2030
+	/**
2031
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2032
+	 * @param array $row_results_for_deleting
2033
+	 * @param bool  $allow_blocking
2034
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2035
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2036
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2037
+	 *                 deleted. Example:
2038
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2039
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2040
+	 *                 where each element is a group of columns and values that get deleted. Example:
2041
+	 *                      array(
2042
+	 *                          0 => array(
2043
+	 *                              'Term_Relationship.object_id' => 1
2044
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2045
+	 *                          ),
2046
+	 *                          1 => array(
2047
+	 *                              'Term_Relationship.object_id' => 1
2048
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2049
+	 *                          )
2050
+	 *                      )
2051
+	 * @throws EE_Error
2052
+	 */
2053
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2054
+	{
2055
+		$ids_to_delete_indexed_by_column = array();
2056
+		if ($this->has_primary_key_field()) {
2057
+			$primary_table = $this->_get_main_table();
2058
+			$other_tables = $this->_get_other_tables();
2059
+			$ids_to_delete_indexed_by_column = $query = array();
2060
+			foreach ($row_results_for_deleting as $item_to_delete) {
2061
+				//before we mark this item for deletion,
2062
+				//make sure there's no related entities blocking its deletion (if we're checking)
2063
+				if (
2064
+					$allow_blocking
2065
+					&& $this->delete_is_blocked_by_related_models(
2066
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2067
+					)
2068
+				) {
2069
+					continue;
2070
+				}
2071
+				//primary table deletes
2072
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2073
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2074
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2075
+				}
2076
+			}
2077
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2078
+			$fields = $this->get_combined_primary_key_fields();
2079
+			foreach ($row_results_for_deleting as $item_to_delete) {
2080
+				$ids_to_delete_indexed_by_column_for_row = array();
2081
+				foreach ($fields as $cpk_field) {
2082
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2083
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2084
+							$item_to_delete[$cpk_field->get_qualified_column()];
2085
+					}
2086
+				}
2087
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2088
+			}
2089
+		} else {
2090
+			//so there's no primary key and no combined key...
2091
+			//sorry, can't help you
2092
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2093
+				"event_espresso"), get_class($this)));
2094
+		}
2095
+		return $ids_to_delete_indexed_by_column;
2096
+	}
2097
+
2098
+
2099
+	/**
2100
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2101
+	 * the corresponding query_part for the query performing the delete.
2102
+	 *
2103
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2104
+	 * @return string
2105
+	 * @throws EE_Error
2106
+	 */
2107
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2108
+		$query_part = '';
2109
+		if (empty($ids_to_delete_indexed_by_column)) {
2110
+			return $query_part;
2111
+		} elseif ($this->has_primary_key_field()) {
2112
+			$query = array();
2113
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2114
+				//make sure we have unique $ids
2115
+				$ids = array_unique($ids);
2116
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2117
+			}
2118
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2119
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2120
+			$ways_to_identify_a_row = array();
2121
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2122
+				$values_for_each_combined_primary_key_for_a_row = array();
2123
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2124
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2125
+				}
2126
+				$ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2127
+			}
2128
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2129
+		}
2130
+		return $query_part;
2131
+	}
2132 2132
     
2133 2133
 
2134 2134
 
2135 2135
 
2136
-    /**
2137
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2138
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2139
-     * column
2140
-     *
2141
-     * @param array  $query_params   like EEM_Base::get_all's
2142
-     * @param string $field_to_count field on model to count by (not column name)
2143
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2144
-     *                               that by the setting $distinct to TRUE;
2145
-     * @return int
2146
-     * @throws \EE_Error
2147
-     */
2148
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2149
-    {
2150
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
-        if ($field_to_count) {
2152
-            $field_obj = $this->field_settings_for($field_to_count);
2153
-            $column_to_count = $field_obj->get_qualified_column();
2154
-        } elseif ($this->has_primary_key_field()) {
2155
-            $pk_field_obj = $this->get_primary_key_field();
2156
-            $column_to_count = $pk_field_obj->get_qualified_column();
2157
-        } else {
2158
-            //there's no primary key
2159
-            //if we're counting distinct items, and there's no primary key,
2160
-            //we need to list out the columns for distinction;
2161
-            //otherwise we can just use star
2162
-            if ($distinct) {
2163
-                $columns_to_use = array();
2164
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2165
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2166
-                }
2167
-                $column_to_count = implode(',', $columns_to_use);
2168
-            } else {
2169
-                $column_to_count = '*';
2170
-            }
2171
-        }
2172
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2173
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2174
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2175
-    }
2176
-
2177
-
2178
-
2179
-    /**
2180
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2181
-     *
2182
-     * @param array  $query_params like EEM_Base::get_all
2183
-     * @param string $field_to_sum name of field (array key in $_fields array)
2184
-     * @return float
2185
-     * @throws \EE_Error
2186
-     */
2187
-    public function sum($query_params, $field_to_sum = null)
2188
-    {
2189
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2190
-        if ($field_to_sum) {
2191
-            $field_obj = $this->field_settings_for($field_to_sum);
2192
-        } else {
2193
-            $field_obj = $this->get_primary_key_field();
2194
-        }
2195
-        $column_to_count = $field_obj->get_qualified_column();
2196
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2197
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2198
-        $data_type = $field_obj->get_wpdb_data_type();
2199
-        if ($data_type === '%d' || $data_type === '%s') {
2200
-            return (float)$return_value;
2201
-        } else {//must be %f
2202
-            return (float)$return_value;
2203
-        }
2204
-    }
2205
-
2206
-
2207
-
2208
-    /**
2209
-     * Just calls the specified method on $wpdb with the given arguments
2210
-     * Consolidates a little extra error handling code
2211
-     *
2212
-     * @param string $wpdb_method
2213
-     * @param array  $arguments_to_provide
2214
-     * @throws EE_Error
2215
-     * @global wpdb  $wpdb
2216
-     * @return mixed
2217
-     */
2218
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2219
-    {
2220
-        //if we're in maintenance mode level 2, DON'T run any queries
2221
-        //because level 2 indicates the database needs updating and
2222
-        //is probably out of sync with the code
2223
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2224
-            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.",
2225
-                "event_espresso")));
2226
-        }
2227
-        /** @type WPDB $wpdb */
2228
-        global $wpdb;
2229
-        if (! method_exists($wpdb, $wpdb_method)) {
2230
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2231
-                'event_espresso'), $wpdb_method));
2232
-        }
2233
-        if (WP_DEBUG) {
2234
-            $old_show_errors_value = $wpdb->show_errors;
2235
-            $wpdb->show_errors(false);
2236
-        }
2237
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2238
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2239
-        if (WP_DEBUG) {
2240
-            $wpdb->show_errors($old_show_errors_value);
2241
-            if (! empty($wpdb->last_error)) {
2242
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2243
-            } elseif ($result === false) {
2244
-                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"',
2245
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2246
-            }
2247
-        } elseif ($result === false) {
2248
-            EE_Error::add_error(
2249
-                sprintf(
2250
-                    __('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"',
2251
-                        'event_espresso'),
2252
-                    $wpdb_method,
2253
-                    var_export($arguments_to_provide, true),
2254
-                    $wpdb->last_error
2255
-                ),
2256
-                __FILE__,
2257
-                __FUNCTION__,
2258
-                __LINE__
2259
-            );
2260
-        }
2261
-        return $result;
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Attempts to run the indicated WPDB method with the provided arguments,
2268
-     * and if there's an error tries to verify the DB is correct. Uses
2269
-     * the static property EEM_Base::$_db_verification_level to determine whether
2270
-     * we should try to fix the EE core db, the addons, or just give up
2271
-     *
2272
-     * @param string $wpdb_method
2273
-     * @param array  $arguments_to_provide
2274
-     * @return mixed
2275
-     */
2276
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2277
-    {
2278
-        /** @type WPDB $wpdb */
2279
-        global $wpdb;
2280
-        $wpdb->last_error = null;
2281
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2282
-        // was there an error running the query? but we don't care on new activations
2283
-        // (we're going to setup the DB anyway on new activations)
2284
-        if (($result === false || ! empty($wpdb->last_error))
2285
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2286
-        ) {
2287
-            switch (EEM_Base::$_db_verification_level) {
2288
-                case EEM_Base::db_verified_none :
2289
-                    // let's double-check core's DB
2290
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2291
-                    break;
2292
-                case EEM_Base::db_verified_core :
2293
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2294
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2295
-                    break;
2296
-                case EEM_Base::db_verified_addons :
2297
-                    // ummmm... you in trouble
2298
-                    return $result;
2299
-                    break;
2300
-            }
2301
-            if (! empty($error_message)) {
2302
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2303
-                trigger_error($error_message);
2304
-            }
2305
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2306
-        }
2307
-        return $result;
2308
-    }
2309
-
2310
-
2311
-
2312
-    /**
2313
-     * Verifies the EE core database is up-to-date and records that we've done it on
2314
-     * EEM_Base::$_db_verification_level
2315
-     *
2316
-     * @param string $wpdb_method
2317
-     * @param array  $arguments_to_provide
2318
-     * @return string
2319
-     */
2320
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2321
-    {
2322
-        /** @type WPDB $wpdb */
2323
-        global $wpdb;
2324
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2325
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2326
-        $error_message = sprintf(
2327
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2328
-                'event_espresso'),
2329
-            $wpdb->last_error,
2330
-            $wpdb_method,
2331
-            wp_json_encode($arguments_to_provide)
2332
-        );
2333
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2334
-        return $error_message;
2335
-    }
2336
-
2337
-
2338
-
2339
-    /**
2340
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2341
-     * EEM_Base::$_db_verification_level
2342
-     *
2343
-     * @param $wpdb_method
2344
-     * @param $arguments_to_provide
2345
-     * @return string
2346
-     */
2347
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2348
-    {
2349
-        /** @type WPDB $wpdb */
2350
-        global $wpdb;
2351
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2352
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2353
-        $error_message = sprintf(
2354
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2355
-                'event_espresso'),
2356
-            $wpdb->last_error,
2357
-            $wpdb_method,
2358
-            wp_json_encode($arguments_to_provide)
2359
-        );
2360
-        EE_System::instance()->initialize_addons();
2361
-        return $error_message;
2362
-    }
2363
-
2364
-
2365
-
2366
-    /**
2367
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2368
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2369
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2370
-     * ..."
2371
-     *
2372
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2373
-     * @return string
2374
-     */
2375
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2376
-    {
2377
-        return " FROM " . $model_query_info->get_full_join_sql() .
2378
-               $model_query_info->get_where_sql() .
2379
-               $model_query_info->get_group_by_sql() .
2380
-               $model_query_info->get_having_sql() .
2381
-               $model_query_info->get_order_by_sql() .
2382
-               $model_query_info->get_limit_sql();
2383
-    }
2384
-
2385
-
2386
-
2387
-    /**
2388
-     * Set to easily debug the next X queries ran from this model.
2389
-     *
2390
-     * @param int $count
2391
-     */
2392
-    public function show_next_x_db_queries($count = 1)
2393
-    {
2394
-        $this->_show_next_x_db_queries = $count;
2395
-    }
2396
-
2397
-
2398
-
2399
-    /**
2400
-     * @param $sql_query
2401
-     */
2402
-    public function show_db_query_if_previously_requested($sql_query)
2403
-    {
2404
-        if ($this->_show_next_x_db_queries > 0) {
2405
-            echo $sql_query;
2406
-            $this->_show_next_x_db_queries--;
2407
-        }
2408
-    }
2409
-
2410
-
2411
-
2412
-    /**
2413
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2414
-     * There are the 3 cases:
2415
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2416
-     * $otherModelObject has no ID, it is first saved.
2417
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2418
-     * has no ID, it is first saved.
2419
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2420
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2421
-     * join table
2422
-     *
2423
-     * @param        EE_Base_Class                     /int $thisModelObject
2424
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2425
-     * @param string $relationName                     , key in EEM_Base::_relations
2426
-     *                                                 an attendee to a group, you also want to specify which role they
2427
-     *                                                 will have in that group. So you would use this parameter to
2428
-     *                                                 specify array('role-column-name'=>'role-id')
2429
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2430
-     *                                                 to for relation to methods that allow you to further specify
2431
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2432
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2433
-     *                                                 because these will be inserted in any new rows created as well.
2434
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2435
-     * @throws \EE_Error
2436
-     */
2437
-    public function add_relationship_to(
2438
-        $id_or_obj,
2439
-        $other_model_id_or_obj,
2440
-        $relationName,
2441
-        $extra_join_model_fields_n_values = array()
2442
-    ) {
2443
-        $relation_obj = $this->related_settings_for($relationName);
2444
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2445
-    }
2446
-
2447
-
2448
-
2449
-    /**
2450
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2451
-     * There are the 3 cases:
2452
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2453
-     * error
2454
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2455
-     * an error
2456
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2457
-     *
2458
-     * @param        EE_Base_Class /int $id_or_obj
2459
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2460
-     * @param string $relationName key in EEM_Base::_relations
2461
-     * @return boolean of success
2462
-     * @throws \EE_Error
2463
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2464
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2465
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2466
-     *                             because these will be inserted in any new rows created as well.
2467
-     */
2468
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2469
-    {
2470
-        $relation_obj = $this->related_settings_for($relationName);
2471
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2472
-    }
2473
-
2474
-
2475
-
2476
-    /**
2477
-     * @param mixed           $id_or_obj
2478
-     * @param string          $relationName
2479
-     * @param array           $where_query_params
2480
-     * @param EE_Base_Class[] objects to which relations were removed
2481
-     * @return \EE_Base_Class[]
2482
-     * @throws \EE_Error
2483
-     */
2484
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2485
-    {
2486
-        $relation_obj = $this->related_settings_for($relationName);
2487
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2488
-    }
2489
-
2490
-
2491
-
2492
-    /**
2493
-     * Gets all the related items of the specified $model_name, using $query_params.
2494
-     * Note: by default, we remove the "default query params"
2495
-     * because we want to get even deleted items etc.
2496
-     *
2497
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2498
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2499
-     * @param array  $query_params like EEM_Base::get_all
2500
-     * @return EE_Base_Class[]
2501
-     * @throws \EE_Error
2502
-     */
2503
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2504
-    {
2505
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2506
-        $relation_settings = $this->related_settings_for($model_name);
2507
-        return $relation_settings->get_all_related($model_obj, $query_params);
2508
-    }
2509
-
2510
-
2511
-
2512
-    /**
2513
-     * Deletes all the model objects across the relation indicated by $model_name
2514
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2515
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2516
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2517
-     *
2518
-     * @param EE_Base_Class|int|string $id_or_obj
2519
-     * @param string                   $model_name
2520
-     * @param array                    $query_params
2521
-     * @return int how many deleted
2522
-     * @throws \EE_Error
2523
-     */
2524
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2525
-    {
2526
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2527
-        $relation_settings = $this->related_settings_for($model_name);
2528
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2529
-    }
2530
-
2531
-
2532
-
2533
-    /**
2534
-     * Hard deletes all the model objects across the relation indicated by $model_name
2535
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2536
-     * the model objects can't be hard deleted because of blocking related model objects,
2537
-     * just does a soft-delete on them instead.
2538
-     *
2539
-     * @param EE_Base_Class|int|string $id_or_obj
2540
-     * @param string                   $model_name
2541
-     * @param array                    $query_params
2542
-     * @return int how many deleted
2543
-     * @throws \EE_Error
2544
-     */
2545
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2546
-    {
2547
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2548
-        $relation_settings = $this->related_settings_for($model_name);
2549
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2550
-    }
2551
-
2552
-
2553
-
2554
-    /**
2555
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2556
-     * unless otherwise specified in the $query_params
2557
-     *
2558
-     * @param        int             /EE_Base_Class $id_or_obj
2559
-     * @param string $model_name     like 'Event', or 'Registration'
2560
-     * @param array  $query_params   like EEM_Base::get_all's
2561
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2562
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2563
-     *                               that by the setting $distinct to TRUE;
2564
-     * @return int
2565
-     * @throws \EE_Error
2566
-     */
2567
-    public function count_related(
2568
-        $id_or_obj,
2569
-        $model_name,
2570
-        $query_params = array(),
2571
-        $field_to_count = null,
2572
-        $distinct = false
2573
-    ) {
2574
-        $related_model = $this->get_related_model_obj($model_name);
2575
-        //we're just going to use the query params on the related model's normal get_all query,
2576
-        //except add a condition to say to match the current mod
2577
-        if (! isset($query_params['default_where_conditions'])) {
2578
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2579
-        }
2580
-        $this_model_name = $this->get_this_model_name();
2581
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2582
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2583
-        return $related_model->count($query_params, $field_to_count, $distinct);
2584
-    }
2585
-
2586
-
2587
-
2588
-    /**
2589
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2590
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2591
-     *
2592
-     * @param        int           /EE_Base_Class $id_or_obj
2593
-     * @param string $model_name   like 'Event', or 'Registration'
2594
-     * @param array  $query_params like EEM_Base::get_all's
2595
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2596
-     * @return float
2597
-     * @throws \EE_Error
2598
-     */
2599
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2600
-    {
2601
-        $related_model = $this->get_related_model_obj($model_name);
2602
-        if (! is_array($query_params)) {
2603
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2604
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2605
-                    gettype($query_params)), '4.6.0');
2606
-            $query_params = array();
2607
-        }
2608
-        //we're just going to use the query params on the related model's normal get_all query,
2609
-        //except add a condition to say to match the current mod
2610
-        if (! isset($query_params['default_where_conditions'])) {
2611
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2612
-        }
2613
-        $this_model_name = $this->get_this_model_name();
2614
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2615
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2616
-        return $related_model->sum($query_params, $field_to_sum);
2617
-    }
2618
-
2619
-
2620
-
2621
-    /**
2622
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2623
-     * $modelObject
2624
-     *
2625
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2626
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2627
-     * @param array               $query_params     like EEM_Base::get_all's
2628
-     * @return EE_Base_Class
2629
-     * @throws \EE_Error
2630
-     */
2631
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2632
-    {
2633
-        $query_params['limit'] = 1;
2634
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2635
-        if ($results) {
2636
-            return array_shift($results);
2637
-        } else {
2638
-            return null;
2639
-        }
2640
-    }
2641
-
2642
-
2643
-
2644
-    /**
2645
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2646
-     *
2647
-     * @return string
2648
-     */
2649
-    public function get_this_model_name()
2650
-    {
2651
-        return str_replace("EEM_", "", get_class($this));
2652
-    }
2653
-
2654
-
2655
-
2656
-    /**
2657
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2658
-     *
2659
-     * @return EE_Any_Foreign_Model_Name_Field
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function get_field_containing_related_model_name()
2663
-    {
2664
-        foreach ($this->field_settings(true) as $field) {
2665
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2666
-                $field_with_model_name = $field;
2667
-            }
2668
-        }
2669
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2670
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2671
-                $this->get_this_model_name()));
2672
-        }
2673
-        return $field_with_model_name;
2674
-    }
2675
-
2676
-
2677
-
2678
-    /**
2679
-     * Inserts a new entry into the database, for each table.
2680
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2681
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2682
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2683
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2684
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2685
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2686
-     *
2687
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2688
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2689
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2690
-     *                              of EEM_Base)
2691
-     * @return int new primary key on main table that got inserted
2692
-     * @throws EE_Error
2693
-     */
2694
-    public function insert($field_n_values)
2695
-    {
2696
-        /**
2697
-         * Filters the fields and their values before inserting an item using the models
2698
-         *
2699
-         * @param array    $fields_n_values keys are the fields and values are their new values
2700
-         * @param EEM_Base $model           the model used
2701
-         */
2702
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2703
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2704
-            $main_table = $this->_get_main_table();
2705
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2706
-            if ($new_id !== false) {
2707
-                foreach ($this->_get_other_tables() as $other_table) {
2708
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2709
-                }
2710
-            }
2711
-            /**
2712
-             * Done just after attempting to insert a new model object
2713
-             *
2714
-             * @param EEM_Base   $model           used
2715
-             * @param array      $fields_n_values fields and their values
2716
-             * @param int|string the              ID of the newly-inserted model object
2717
-             */
2718
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2719
-            return $new_id;
2720
-        } else {
2721
-            return false;
2722
-        }
2723
-    }
2724
-
2725
-
2726
-
2727
-    /**
2728
-     * Checks that the result would satisfy the unique indexes on this model
2729
-     *
2730
-     * @param array  $field_n_values
2731
-     * @param string $action
2732
-     * @return boolean
2733
-     * @throws \EE_Error
2734
-     */
2735
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2736
-    {
2737
-        foreach ($this->unique_indexes() as $index_name => $index) {
2738
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2739
-            if ($this->exists(array($uniqueness_where_params))) {
2740
-                EE_Error::add_error(
2741
-                    sprintf(
2742
-                        __(
2743
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2744
-                            "event_espresso"
2745
-                        ),
2746
-                        $action,
2747
-                        $this->_get_class_name(),
2748
-                        $index_name,
2749
-                        implode(",", $index->field_names()),
2750
-                        http_build_query($uniqueness_where_params)
2751
-                    ),
2752
-                    __FILE__,
2753
-                    __FUNCTION__,
2754
-                    __LINE__
2755
-                );
2756
-                return false;
2757
-            }
2758
-        }
2759
-        return true;
2760
-    }
2761
-
2762
-
2763
-
2764
-    /**
2765
-     * Checks the database for an item that conflicts (ie, if this item were
2766
-     * saved to the DB would break some uniqueness requirement, like a primary key
2767
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2768
-     * can be either an EE_Base_Class or an array of fields n values
2769
-     *
2770
-     * @param EE_Base_Class|array $obj_or_fields_array
2771
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2772
-     *                                                 when looking for conflicts
2773
-     *                                                 (ie, if false, we ignore the model object's primary key
2774
-     *                                                 when finding "conflicts". If true, it's also considered).
2775
-     *                                                 Only works for INT primary key,
2776
-     *                                                 STRING primary keys cannot be ignored
2777
-     * @throws EE_Error
2778
-     * @return EE_Base_Class|array
2779
-     */
2780
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2781
-    {
2782
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2783
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2784
-        } elseif (is_array($obj_or_fields_array)) {
2785
-            $fields_n_values = $obj_or_fields_array;
2786
-        } else {
2787
-            throw new EE_Error(
2788
-                sprintf(
2789
-                    __(
2790
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2791
-                        "event_espresso"
2792
-                    ),
2793
-                    get_class($this),
2794
-                    $obj_or_fields_array
2795
-                )
2796
-            );
2797
-        }
2798
-        $query_params = array();
2799
-        if ($this->has_primary_key_field()
2800
-            && ($include_primary_key
2801
-                || $this->get_primary_key_field()
2802
-                   instanceof
2803
-                   EE_Primary_Key_String_Field)
2804
-            && isset($fields_n_values[$this->primary_key_name()])
2805
-        ) {
2806
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2807
-        }
2808
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2809
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2810
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2811
-        }
2812
-        //if there is nothing to base this search on, then we shouldn't find anything
2813
-        if (empty($query_params)) {
2814
-            return array();
2815
-        } else {
2816
-            return $this->get_one($query_params);
2817
-        }
2818
-    }
2819
-
2820
-
2821
-
2822
-    /**
2823
-     * Like count, but is optimized and returns a boolean instead of an int
2824
-     *
2825
-     * @param array $query_params
2826
-     * @return boolean
2827
-     * @throws \EE_Error
2828
-     */
2829
-    public function exists($query_params)
2830
-    {
2831
-        $query_params['limit'] = 1;
2832
-        return $this->count($query_params) > 0;
2833
-    }
2834
-
2835
-
2836
-
2837
-    /**
2838
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2839
-     *
2840
-     * @param int|string $id
2841
-     * @return boolean
2842
-     * @throws \EE_Error
2843
-     */
2844
-    public function exists_by_ID($id)
2845
-    {
2846
-        return $this->exists(
2847
-            array(
2848
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2849
-                array(
2850
-                    $this->primary_key_name() => $id,
2851
-                ),
2852
-            )
2853
-        );
2854
-    }
2855
-
2856
-
2857
-
2858
-    /**
2859
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2860
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2861
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2862
-     * on the main table)
2863
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2864
-     * cases where we want to call it directly rather than via insert().
2865
-     *
2866
-     * @access   protected
2867
-     * @param EE_Table_Base $table
2868
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2869
-     *                                       float
2870
-     * @param int           $new_id          for now we assume only int keys
2871
-     * @throws EE_Error
2872
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2873
-     * @return int ID of new row inserted, or FALSE on failure
2874
-     */
2875
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2876
-    {
2877
-        global $wpdb;
2878
-        $insertion_col_n_values = array();
2879
-        $format_for_insertion = array();
2880
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2881
-        foreach ($fields_on_table as $field_name => $field_obj) {
2882
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2883
-            if ($field_obj->is_auto_increment()) {
2884
-                continue;
2885
-            }
2886
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2887
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2888
-            if ($prepared_value !== null) {
2889
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2890
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2891
-            }
2892
-        }
2893
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2894
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2895
-            //so add the fk to the main table as a column
2896
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2897
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2898
-        }
2899
-        //insert the new entry
2900
-        $result = $this->_do_wpdb_query('insert',
2901
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2902
-        if ($result === false) {
2903
-            return false;
2904
-        }
2905
-        //ok, now what do we return for the ID of the newly-inserted thing?
2906
-        if ($this->has_primary_key_field()) {
2907
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2908
-                return $wpdb->insert_id;
2909
-            } else {
2910
-                //it's not an auto-increment primary key, so
2911
-                //it must have been supplied
2912
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2913
-            }
2914
-        } else {
2915
-            //we can't return a  primary key because there is none. instead return
2916
-            //a unique string indicating this model
2917
-            return $this->get_index_primary_key_string($fields_n_values);
2918
-        }
2919
-    }
2920
-
2921
-
2922
-
2923
-    /**
2924
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2925
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2926
-     * and there is no default, we pass it along. WPDB will take care of it)
2927
-     *
2928
-     * @param EE_Model_Field_Base $field_obj
2929
-     * @param array               $fields_n_values
2930
-     * @return mixed string|int|float depending on what the table column will be expecting
2931
-     * @throws \EE_Error
2932
-     */
2933
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2934
-    {
2935
-        //if this field doesn't allow nullable, don't allow it
2936
-        if (
2937
-            ! $field_obj->is_nullable()
2938
-            && (
2939
-                ! isset($fields_n_values[$field_obj->get_name()])
2940
-                || $fields_n_values[$field_obj->get_name()] === null
2941
-            )
2942
-        ) {
2943
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2944
-        }
2945
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2946
-            ? $fields_n_values[$field_obj->get_name()]
2947
-            : null;
2948
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2949
-    }
2950
-
2951
-
2952
-
2953
-    /**
2954
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2955
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2956
-     * the field's prepare_for_set() method.
2957
-     *
2958
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2959
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2960
-     *                                   top of file)
2961
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2962
-     *                                   $value is a custom selection
2963
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2964
-     */
2965
-    private function _prepare_value_for_use_in_db($value, $field)
2966
-    {
2967
-        if ($field && $field instanceof EE_Model_Field_Base) {
2968
-            switch ($this->_values_already_prepared_by_model_object) {
2969
-                /** @noinspection PhpMissingBreakStatementInspection */
2970
-                case self::not_prepared_by_model_object:
2971
-                    $value = $field->prepare_for_set($value);
2972
-                //purposefully left out "return"
2973
-                case self::prepared_by_model_object:
2974
-                    $value = $field->prepare_for_use_in_db($value);
2975
-                case self::prepared_for_use_in_db:
2976
-                    //leave the value alone
2977
-            }
2978
-            return $value;
2979
-        } else {
2980
-            return $value;
2981
-        }
2982
-    }
2983
-
2984
-
2985
-
2986
-    /**
2987
-     * Returns the main table on this model
2988
-     *
2989
-     * @return EE_Primary_Table
2990
-     * @throws EE_Error
2991
-     */
2992
-    protected function _get_main_table()
2993
-    {
2994
-        foreach ($this->_tables as $table) {
2995
-            if ($table instanceof EE_Primary_Table) {
2996
-                return $table;
2997
-            }
2998
-        }
2999
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3000
-            'event_espresso'), get_class($this)));
3001
-    }
3002
-
3003
-
3004
-
3005
-    /**
3006
-     * table
3007
-     * returns EE_Primary_Table table name
3008
-     *
3009
-     * @return string
3010
-     * @throws \EE_Error
3011
-     */
3012
-    public function table()
3013
-    {
3014
-        return $this->_get_main_table()->get_table_name();
3015
-    }
3016
-
3017
-
3018
-
3019
-    /**
3020
-     * table
3021
-     * returns first EE_Secondary_Table table name
3022
-     *
3023
-     * @return string
3024
-     */
3025
-    public function second_table()
3026
-    {
3027
-        // grab second table from tables array
3028
-        $second_table = end($this->_tables);
3029
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * get_table_obj_by_alias
3036
-     * returns table name given it's alias
3037
-     *
3038
-     * @param string $table_alias
3039
-     * @return EE_Primary_Table | EE_Secondary_Table
3040
-     */
3041
-    public function get_table_obj_by_alias($table_alias = '')
3042
-    {
3043
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3044
-    }
3045
-
3046
-
3047
-
3048
-    /**
3049
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3050
-     *
3051
-     * @return EE_Secondary_Table[]
3052
-     */
3053
-    protected function _get_other_tables()
3054
-    {
3055
-        $other_tables = array();
3056
-        foreach ($this->_tables as $table_alias => $table) {
3057
-            if ($table instanceof EE_Secondary_Table) {
3058
-                $other_tables[$table_alias] = $table;
3059
-            }
3060
-        }
3061
-        return $other_tables;
3062
-    }
3063
-
3064
-
3065
-
3066
-    /**
3067
-     * Finds all the fields that correspond to the given table
3068
-     *
3069
-     * @param string $table_alias , array key in EEM_Base::_tables
3070
-     * @return EE_Model_Field_Base[]
3071
-     */
3072
-    public function _get_fields_for_table($table_alias)
3073
-    {
3074
-        return $this->_fields[$table_alias];
3075
-    }
3076
-
3077
-
3078
-
3079
-    /**
3080
-     * Recurses through all the where parameters, and finds all the related models we'll need
3081
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3082
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3083
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3084
-     * related Registration, Transaction, and Payment models.
3085
-     *
3086
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3087
-     * @return EE_Model_Query_Info_Carrier
3088
-     * @throws \EE_Error
3089
-     */
3090
-    public function _extract_related_models_from_query($query_params)
3091
-    {
3092
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3093
-        if (array_key_exists(0, $query_params)) {
3094
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3095
-        }
3096
-        if (array_key_exists('group_by', $query_params)) {
3097
-            if (is_array($query_params['group_by'])) {
3098
-                $this->_extract_related_models_from_sub_params_array_values(
3099
-                    $query_params['group_by'],
3100
-                    $query_info_carrier,
3101
-                    'group_by'
3102
-                );
3103
-            } elseif (! empty ($query_params['group_by'])) {
3104
-                $this->_extract_related_model_info_from_query_param(
3105
-                    $query_params['group_by'],
3106
-                    $query_info_carrier,
3107
-                    'group_by'
3108
-                );
3109
-            }
3110
-        }
3111
-        if (array_key_exists('having', $query_params)) {
3112
-            $this->_extract_related_models_from_sub_params_array_keys(
3113
-                $query_params[0],
3114
-                $query_info_carrier,
3115
-                'having'
3116
-            );
3117
-        }
3118
-        if (array_key_exists('order_by', $query_params)) {
3119
-            if (is_array($query_params['order_by'])) {
3120
-                $this->_extract_related_models_from_sub_params_array_keys(
3121
-                    $query_params['order_by'],
3122
-                    $query_info_carrier,
3123
-                    'order_by'
3124
-                );
3125
-            } elseif (! empty($query_params['order_by'])) {
3126
-                $this->_extract_related_model_info_from_query_param(
3127
-                    $query_params['order_by'],
3128
-                    $query_info_carrier,
3129
-                    'order_by'
3130
-                );
3131
-            }
3132
-        }
3133
-        if (array_key_exists('force_join', $query_params)) {
3134
-            $this->_extract_related_models_from_sub_params_array_values(
3135
-                $query_params['force_join'],
3136
-                $query_info_carrier,
3137
-                'force_join'
3138
-            );
3139
-        }
3140
-        return $query_info_carrier;
3141
-    }
3142
-
3143
-
3144
-
3145
-    /**
3146
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3147
-     *
3148
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3149
-     *                                                      $query_params['having']
3150
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3151
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3152
-     * @throws EE_Error
3153
-     * @return \EE_Model_Query_Info_Carrier
3154
-     */
3155
-    private function _extract_related_models_from_sub_params_array_keys(
3156
-        $sub_query_params,
3157
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3158
-        $query_param_type
3159
-    ) {
3160
-        if (! empty($sub_query_params)) {
3161
-            $sub_query_params = (array)$sub_query_params;
3162
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3163
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3164
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3165
-                    $query_param_type);
3166
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3167
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3168
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3169
-                //of array('Registration.TXN_ID'=>23)
3170
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3171
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3172
-                    if (! is_array($possibly_array_of_params)) {
3173
-                        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'))",
3174
-                            "event_espresso"),
3175
-                            $param, $possibly_array_of_params));
3176
-                    } else {
3177
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3178
-                            $model_query_info_carrier, $query_param_type);
3179
-                    }
3180
-                } elseif ($query_param_type === 0 //ie WHERE
3181
-                          && is_array($possibly_array_of_params)
3182
-                          && isset($possibly_array_of_params[2])
3183
-                          && $possibly_array_of_params[2] == true
3184
-                ) {
3185
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3186
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3187
-                    //from which we should extract query parameters!
3188
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3189
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3190
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3191
-                    }
3192
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3193
-                        $model_query_info_carrier, $query_param_type);
3194
-                }
3195
-            }
3196
-        }
3197
-        return $model_query_info_carrier;
3198
-    }
3199
-
3200
-
3201
-
3202
-    /**
3203
-     * For extracting related models from forced_joins, where the array values contain the info about what
3204
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3205
-     *
3206
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3207
-     *                                                      $query_params['having']
3208
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3209
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3210
-     * @throws EE_Error
3211
-     * @return \EE_Model_Query_Info_Carrier
3212
-     */
3213
-    private function _extract_related_models_from_sub_params_array_values(
3214
-        $sub_query_params,
3215
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3216
-        $query_param_type
3217
-    ) {
3218
-        if (! empty($sub_query_params)) {
3219
-            if (! is_array($sub_query_params)) {
3220
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3221
-                    $sub_query_params));
3222
-            }
3223
-            foreach ($sub_query_params as $param) {
3224
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3225
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3226
-                    $query_param_type);
3227
-            }
3228
-        }
3229
-        return $model_query_info_carrier;
3230
-    }
3231
-
3232
-
3233
-
3234
-    /**
3235
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3236
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3237
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3238
-     * but use them in a different order. Eg, we need to know what models we are querying
3239
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3240
-     * other models before we can finalize the where clause SQL.
3241
-     *
3242
-     * @param array $query_params
3243
-     * @throws EE_Error
3244
-     * @return EE_Model_Query_Info_Carrier
3245
-     */
3246
-    public function _create_model_query_info_carrier($query_params)
3247
-    {
3248
-        if (! is_array($query_params)) {
3249
-            EE_Error::doing_it_wrong(
3250
-                'EEM_Base::_create_model_query_info_carrier',
3251
-                sprintf(
3252
-                    __(
3253
-                        '$query_params should be an array, you passed a variable of type %s',
3254
-                        'event_espresso'
3255
-                    ),
3256
-                    gettype($query_params)
3257
-                ),
3258
-                '4.6.0'
3259
-            );
3260
-            $query_params = array();
3261
-        }
3262
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3263
-        //first check if we should alter the query to account for caps or not
3264
-        //because the caps might require us to do extra joins
3265
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3266
-            $query_params[0] = $where_query_params = array_replace_recursive(
3267
-                $where_query_params,
3268
-                $this->caps_where_conditions(
3269
-                    $query_params['caps']
3270
-                )
3271
-            );
3272
-        }
3273
-        $query_object = $this->_extract_related_models_from_query($query_params);
3274
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3275
-        foreach ($where_query_params as $key => $value) {
3276
-            if (is_int($key)) {
3277
-                throw new EE_Error(
3278
-                    sprintf(
3279
-                        __(
3280
-                            "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.",
3281
-                            "event_espresso"
3282
-                        ),
3283
-                        $key,
3284
-                        var_export($value, true),
3285
-                        var_export($query_params, true),
3286
-                        get_class($this)
3287
-                    )
3288
-                );
3289
-            }
3290
-        }
3291
-        if (
3292
-            array_key_exists('default_where_conditions', $query_params)
3293
-            && ! empty($query_params['default_where_conditions'])
3294
-        ) {
3295
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3296
-        } else {
3297
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3298
-        }
3299
-        $where_query_params = array_merge(
3300
-            $this->_get_default_where_conditions_for_models_in_query(
3301
-                $query_object,
3302
-                $use_default_where_conditions,
3303
-                $where_query_params
3304
-            ),
3305
-            $where_query_params
3306
-        );
3307
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3308
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3309
-        // So we need to setup a subquery and use that for the main join.
3310
-        // Note for now this only works on the primary table for the model.
3311
-        // So for instance, you could set the limit array like this:
3312
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3313
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3314
-            $query_object->set_main_model_join_sql(
3315
-                $this->_construct_limit_join_select(
3316
-                    $query_params['on_join_limit'][0],
3317
-                    $query_params['on_join_limit'][1]
3318
-                )
3319
-            );
3320
-        }
3321
-        //set limit
3322
-        if (array_key_exists('limit', $query_params)) {
3323
-            if (is_array($query_params['limit'])) {
3324
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3325
-                    $e = sprintf(
3326
-                        __(
3327
-                            "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)",
3328
-                            "event_espresso"
3329
-                        ),
3330
-                        http_build_query($query_params['limit'])
3331
-                    );
3332
-                    throw new EE_Error($e . "|" . $e);
3333
-                }
3334
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3335
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3336
-            } elseif (! empty ($query_params['limit'])) {
3337
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3338
-            }
3339
-        }
3340
-        //set order by
3341
-        if (array_key_exists('order_by', $query_params)) {
3342
-            if (is_array($query_params['order_by'])) {
3343
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3344
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3345
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3346
-                if (array_key_exists('order', $query_params)) {
3347
-                    throw new EE_Error(
3348
-                        sprintf(
3349
-                            __(
3350
-                                "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 ",
3351
-                                "event_espresso"
3352
-                            ),
3353
-                            get_class($this),
3354
-                            implode(", ", array_keys($query_params['order_by'])),
3355
-                            implode(", ", $query_params['order_by']),
3356
-                            $query_params['order']
3357
-                        )
3358
-                    );
3359
-                }
3360
-                $this->_extract_related_models_from_sub_params_array_keys(
3361
-                    $query_params['order_by'],
3362
-                    $query_object,
3363
-                    'order_by'
3364
-                );
3365
-                //assume it's an array of fields to order by
3366
-                $order_array = array();
3367
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3368
-                    $order = $this->_extract_order($order);
3369
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3370
-                }
3371
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3372
-            } elseif (! empty ($query_params['order_by'])) {
3373
-                $this->_extract_related_model_info_from_query_param(
3374
-                    $query_params['order_by'],
3375
-                    $query_object,
3376
-                    'order',
3377
-                    $query_params['order_by']
3378
-                );
3379
-                $order = isset($query_params['order'])
3380
-                    ? $this->_extract_order($query_params['order'])
3381
-                    : 'DESC';
3382
-                $query_object->set_order_by_sql(
3383
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3384
-                );
3385
-            }
3386
-        }
3387
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3388
-        if (! array_key_exists('order_by', $query_params)
3389
-            && array_key_exists('order', $query_params)
3390
-            && ! empty($query_params['order'])
3391
-        ) {
3392
-            $pk_field = $this->get_primary_key_field();
3393
-            $order = $this->_extract_order($query_params['order']);
3394
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3395
-        }
3396
-        //set group by
3397
-        if (array_key_exists('group_by', $query_params)) {
3398
-            if (is_array($query_params['group_by'])) {
3399
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3400
-                $group_by_array = array();
3401
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3402
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3403
-                }
3404
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3405
-            } elseif (! empty ($query_params['group_by'])) {
3406
-                $query_object->set_group_by_sql(
3407
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3408
-                );
3409
-            }
3410
-        }
3411
-        //set having
3412
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3413
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3414
-        }
3415
-        //now, just verify they didn't pass anything wack
3416
-        foreach ($query_params as $query_key => $query_value) {
3417
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3418
-                throw new EE_Error(
3419
-                    sprintf(
3420
-                        __(
3421
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3422
-                            'event_espresso'
3423
-                        ),
3424
-                        $query_key,
3425
-                        get_class($this),
3426
-                        //						print_r( $this->_allowed_query_params, TRUE )
3427
-                        implode(',', $this->_allowed_query_params)
3428
-                    )
3429
-                );
3430
-            }
3431
-        }
3432
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3433
-        if (empty($main_model_join_sql)) {
3434
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3435
-        }
3436
-        return $query_object;
3437
-    }
3438
-
3439
-
3440
-
3441
-    /**
3442
-     * Gets the where conditions that should be imposed on the query based on the
3443
-     * context (eg reading frontend, backend, edit or delete).
3444
-     *
3445
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3446
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3447
-     * @throws \EE_Error
3448
-     */
3449
-    public function caps_where_conditions($context = self::caps_read)
3450
-    {
3451
-        EEM_Base::verify_is_valid_cap_context($context);
3452
-        $cap_where_conditions = array();
3453
-        $cap_restrictions = $this->caps_missing($context);
3454
-        /**
3455
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3456
-         */
3457
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3458
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3459
-                $restriction_if_no_cap->get_default_where_conditions());
3460
-        }
3461
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3462
-            $cap_restrictions);
3463
-    }
3464
-
3465
-
3466
-
3467
-    /**
3468
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3469
-     * otherwise throws an exception
3470
-     *
3471
-     * @param string $should_be_order_string
3472
-     * @return string either ASC, asc, DESC or desc
3473
-     * @throws EE_Error
3474
-     */
3475
-    private function _extract_order($should_be_order_string)
3476
-    {
3477
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3478
-            return $should_be_order_string;
3479
-        } else {
3480
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3481
-                "event_espresso"), get_class($this), $should_be_order_string));
3482
-        }
3483
-    }
3484
-
3485
-
3486
-
3487
-    /**
3488
-     * Looks at all the models which are included in this query, and asks each
3489
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3490
-     * so they can be merged
3491
-     *
3492
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3493
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3494
-     *                                                                  'none' means NO default where conditions will
3495
-     *                                                                  be used AT ALL during this query.
3496
-     *                                                                  'other_models_only' means default where
3497
-     *                                                                  conditions from other models will be used, but
3498
-     *                                                                  not for this primary model. 'all', the default,
3499
-     *                                                                  means default where conditions will apply as
3500
-     *                                                                  normal
3501
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3502
-     * @throws EE_Error
3503
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3504
-     */
3505
-    private function _get_default_where_conditions_for_models_in_query(
3506
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3507
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3508
-        $where_query_params = array()
3509
-    ) {
3510
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3511
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3512
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3513
-                "event_espresso"), $use_default_where_conditions,
3514
-                implode(", ", $allowed_used_default_where_conditions_values)));
3515
-        }
3516
-        $universal_query_params = array();
3517
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3518
-            $universal_query_params = $this->_get_default_where_conditions();
3519
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3520
-            $universal_query_params = $this->_get_minimum_where_conditions();
3521
-        }
3522
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3523
-            $related_model = $this->get_related_model_obj($model_name);
3524
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3525
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3526
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3527
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3528
-            } else {
3529
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3530
-                continue;
3531
-            }
3532
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3533
-                $related_model_universal_where_params,
3534
-                $where_query_params,
3535
-                $related_model,
3536
-                $model_relation_path
3537
-            );
3538
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3539
-                $universal_query_params,
3540
-                $overrides
3541
-            );
3542
-        }
3543
-        return $universal_query_params;
3544
-    }
3545
-
3546
-
3547
-
3548
-    /**
3549
-     * Determines whether or not we should use default where conditions for the model in question
3550
-     * (this model, or other related models).
3551
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3552
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3553
-     * We should use default where conditions on related models when they requested to use default where conditions
3554
-     * on all models, or specifically just on other related models
3555
-     * @param      $default_where_conditions_value
3556
-     * @param bool $for_this_model false means this is for OTHER related models
3557
-     * @return bool
3558
-     */
3559
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3560
-    {
3561
-        return (
3562
-                   $for_this_model
3563
-                   && in_array(
3564
-                       $default_where_conditions_value,
3565
-                       array(
3566
-                           EEM_Base::default_where_conditions_all,
3567
-                           EEM_Base::default_where_conditions_this_only,
3568
-                           EEM_Base::default_where_conditions_minimum_others,
3569
-                       ),
3570
-                       true
3571
-                   )
3572
-               )
3573
-               || (
3574
-                   ! $for_this_model
3575
-                   && in_array(
3576
-                       $default_where_conditions_value,
3577
-                       array(
3578
-                           EEM_Base::default_where_conditions_all,
3579
-                           EEM_Base::default_where_conditions_others_only,
3580
-                       ),
3581
-                       true
3582
-                   )
3583
-               );
3584
-    }
3585
-
3586
-    /**
3587
-     * Determines whether or not we should use default minimum conditions for the model in question
3588
-     * (this model, or other related models).
3589
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3590
-     * where conditions.
3591
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3592
-     * on this model or others
3593
-     * @param      $default_where_conditions_value
3594
-     * @param bool $for_this_model false means this is for OTHER related models
3595
-     * @return bool
3596
-     */
3597
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3598
-    {
3599
-        return (
3600
-                   $for_this_model
3601
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3602
-               )
3603
-               || (
3604
-                   ! $for_this_model
3605
-                   && in_array(
3606
-                       $default_where_conditions_value,
3607
-                       array(
3608
-                           EEM_Base::default_where_conditions_minimum_others,
3609
-                           EEM_Base::default_where_conditions_minimum_all,
3610
-                       ),
3611
-                       true
3612
-                   )
3613
-               );
3614
-    }
3615
-
3616
-
3617
-    /**
3618
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3619
-     * then we also add a special where condition which allows for that model's primary key
3620
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3621
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3622
-     *
3623
-     * @param array    $default_where_conditions
3624
-     * @param array    $provided_where_conditions
3625
-     * @param EEM_Base $model
3626
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3627
-     * @return array like EEM_Base::get_all's $query_params[0]
3628
-     * @throws \EE_Error
3629
-     */
3630
-    private function _override_defaults_or_make_null_friendly(
3631
-        $default_where_conditions,
3632
-        $provided_where_conditions,
3633
-        $model,
3634
-        $model_relation_path
3635
-    ) {
3636
-        $null_friendly_where_conditions = array();
3637
-        $none_overridden = true;
3638
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3639
-        foreach ($default_where_conditions as $key => $val) {
3640
-            if (isset($provided_where_conditions[$key])) {
3641
-                $none_overridden = false;
3642
-            } else {
3643
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3644
-            }
3645
-        }
3646
-        if ($none_overridden && $default_where_conditions) {
3647
-            if ($model->has_primary_key_field()) {
3648
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3649
-                                                                                . "."
3650
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3651
-            }/*else{
2136
+	/**
2137
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2138
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2139
+	 * column
2140
+	 *
2141
+	 * @param array  $query_params   like EEM_Base::get_all's
2142
+	 * @param string $field_to_count field on model to count by (not column name)
2143
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2144
+	 *                               that by the setting $distinct to TRUE;
2145
+	 * @return int
2146
+	 * @throws \EE_Error
2147
+	 */
2148
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2149
+	{
2150
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2151
+		if ($field_to_count) {
2152
+			$field_obj = $this->field_settings_for($field_to_count);
2153
+			$column_to_count = $field_obj->get_qualified_column();
2154
+		} elseif ($this->has_primary_key_field()) {
2155
+			$pk_field_obj = $this->get_primary_key_field();
2156
+			$column_to_count = $pk_field_obj->get_qualified_column();
2157
+		} else {
2158
+			//there's no primary key
2159
+			//if we're counting distinct items, and there's no primary key,
2160
+			//we need to list out the columns for distinction;
2161
+			//otherwise we can just use star
2162
+			if ($distinct) {
2163
+				$columns_to_use = array();
2164
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2165
+					$columns_to_use[] = $field_obj->get_qualified_column();
2166
+				}
2167
+				$column_to_count = implode(',', $columns_to_use);
2168
+			} else {
2169
+				$column_to_count = '*';
2170
+			}
2171
+		}
2172
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2173
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2174
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2175
+	}
2176
+
2177
+
2178
+
2179
+	/**
2180
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2181
+	 *
2182
+	 * @param array  $query_params like EEM_Base::get_all
2183
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2184
+	 * @return float
2185
+	 * @throws \EE_Error
2186
+	 */
2187
+	public function sum($query_params, $field_to_sum = null)
2188
+	{
2189
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2190
+		if ($field_to_sum) {
2191
+			$field_obj = $this->field_settings_for($field_to_sum);
2192
+		} else {
2193
+			$field_obj = $this->get_primary_key_field();
2194
+		}
2195
+		$column_to_count = $field_obj->get_qualified_column();
2196
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2197
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2198
+		$data_type = $field_obj->get_wpdb_data_type();
2199
+		if ($data_type === '%d' || $data_type === '%s') {
2200
+			return (float)$return_value;
2201
+		} else {//must be %f
2202
+			return (float)$return_value;
2203
+		}
2204
+	}
2205
+
2206
+
2207
+
2208
+	/**
2209
+	 * Just calls the specified method on $wpdb with the given arguments
2210
+	 * Consolidates a little extra error handling code
2211
+	 *
2212
+	 * @param string $wpdb_method
2213
+	 * @param array  $arguments_to_provide
2214
+	 * @throws EE_Error
2215
+	 * @global wpdb  $wpdb
2216
+	 * @return mixed
2217
+	 */
2218
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2219
+	{
2220
+		//if we're in maintenance mode level 2, DON'T run any queries
2221
+		//because level 2 indicates the database needs updating and
2222
+		//is probably out of sync with the code
2223
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2224
+			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.",
2225
+				"event_espresso")));
2226
+		}
2227
+		/** @type WPDB $wpdb */
2228
+		global $wpdb;
2229
+		if (! method_exists($wpdb, $wpdb_method)) {
2230
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2231
+				'event_espresso'), $wpdb_method));
2232
+		}
2233
+		if (WP_DEBUG) {
2234
+			$old_show_errors_value = $wpdb->show_errors;
2235
+			$wpdb->show_errors(false);
2236
+		}
2237
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2238
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2239
+		if (WP_DEBUG) {
2240
+			$wpdb->show_errors($old_show_errors_value);
2241
+			if (! empty($wpdb->last_error)) {
2242
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2243
+			} elseif ($result === false) {
2244
+				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"',
2245
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2246
+			}
2247
+		} elseif ($result === false) {
2248
+			EE_Error::add_error(
2249
+				sprintf(
2250
+					__('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"',
2251
+						'event_espresso'),
2252
+					$wpdb_method,
2253
+					var_export($arguments_to_provide, true),
2254
+					$wpdb->last_error
2255
+				),
2256
+				__FILE__,
2257
+				__FUNCTION__,
2258
+				__LINE__
2259
+			);
2260
+		}
2261
+		return $result;
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2268
+	 * and if there's an error tries to verify the DB is correct. Uses
2269
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2270
+	 * we should try to fix the EE core db, the addons, or just give up
2271
+	 *
2272
+	 * @param string $wpdb_method
2273
+	 * @param array  $arguments_to_provide
2274
+	 * @return mixed
2275
+	 */
2276
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2277
+	{
2278
+		/** @type WPDB $wpdb */
2279
+		global $wpdb;
2280
+		$wpdb->last_error = null;
2281
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2282
+		// was there an error running the query? but we don't care on new activations
2283
+		// (we're going to setup the DB anyway on new activations)
2284
+		if (($result === false || ! empty($wpdb->last_error))
2285
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2286
+		) {
2287
+			switch (EEM_Base::$_db_verification_level) {
2288
+				case EEM_Base::db_verified_none :
2289
+					// let's double-check core's DB
2290
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2291
+					break;
2292
+				case EEM_Base::db_verified_core :
2293
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2294
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2295
+					break;
2296
+				case EEM_Base::db_verified_addons :
2297
+					// ummmm... you in trouble
2298
+					return $result;
2299
+					break;
2300
+			}
2301
+			if (! empty($error_message)) {
2302
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2303
+				trigger_error($error_message);
2304
+			}
2305
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2306
+		}
2307
+		return $result;
2308
+	}
2309
+
2310
+
2311
+
2312
+	/**
2313
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2314
+	 * EEM_Base::$_db_verification_level
2315
+	 *
2316
+	 * @param string $wpdb_method
2317
+	 * @param array  $arguments_to_provide
2318
+	 * @return string
2319
+	 */
2320
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2321
+	{
2322
+		/** @type WPDB $wpdb */
2323
+		global $wpdb;
2324
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2325
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2326
+		$error_message = sprintf(
2327
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2328
+				'event_espresso'),
2329
+			$wpdb->last_error,
2330
+			$wpdb_method,
2331
+			wp_json_encode($arguments_to_provide)
2332
+		);
2333
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2334
+		return $error_message;
2335
+	}
2336
+
2337
+
2338
+
2339
+	/**
2340
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2341
+	 * EEM_Base::$_db_verification_level
2342
+	 *
2343
+	 * @param $wpdb_method
2344
+	 * @param $arguments_to_provide
2345
+	 * @return string
2346
+	 */
2347
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2348
+	{
2349
+		/** @type WPDB $wpdb */
2350
+		global $wpdb;
2351
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2352
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2353
+		$error_message = sprintf(
2354
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2355
+				'event_espresso'),
2356
+			$wpdb->last_error,
2357
+			$wpdb_method,
2358
+			wp_json_encode($arguments_to_provide)
2359
+		);
2360
+		EE_System::instance()->initialize_addons();
2361
+		return $error_message;
2362
+	}
2363
+
2364
+
2365
+
2366
+	/**
2367
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2368
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2369
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2370
+	 * ..."
2371
+	 *
2372
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2373
+	 * @return string
2374
+	 */
2375
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2376
+	{
2377
+		return " FROM " . $model_query_info->get_full_join_sql() .
2378
+			   $model_query_info->get_where_sql() .
2379
+			   $model_query_info->get_group_by_sql() .
2380
+			   $model_query_info->get_having_sql() .
2381
+			   $model_query_info->get_order_by_sql() .
2382
+			   $model_query_info->get_limit_sql();
2383
+	}
2384
+
2385
+
2386
+
2387
+	/**
2388
+	 * Set to easily debug the next X queries ran from this model.
2389
+	 *
2390
+	 * @param int $count
2391
+	 */
2392
+	public function show_next_x_db_queries($count = 1)
2393
+	{
2394
+		$this->_show_next_x_db_queries = $count;
2395
+	}
2396
+
2397
+
2398
+
2399
+	/**
2400
+	 * @param $sql_query
2401
+	 */
2402
+	public function show_db_query_if_previously_requested($sql_query)
2403
+	{
2404
+		if ($this->_show_next_x_db_queries > 0) {
2405
+			echo $sql_query;
2406
+			$this->_show_next_x_db_queries--;
2407
+		}
2408
+	}
2409
+
2410
+
2411
+
2412
+	/**
2413
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2414
+	 * There are the 3 cases:
2415
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2416
+	 * $otherModelObject has no ID, it is first saved.
2417
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2418
+	 * has no ID, it is first saved.
2419
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2420
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2421
+	 * join table
2422
+	 *
2423
+	 * @param        EE_Base_Class                     /int $thisModelObject
2424
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2425
+	 * @param string $relationName                     , key in EEM_Base::_relations
2426
+	 *                                                 an attendee to a group, you also want to specify which role they
2427
+	 *                                                 will have in that group. So you would use this parameter to
2428
+	 *                                                 specify array('role-column-name'=>'role-id')
2429
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2430
+	 *                                                 to for relation to methods that allow you to further specify
2431
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2432
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2433
+	 *                                                 because these will be inserted in any new rows created as well.
2434
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2435
+	 * @throws \EE_Error
2436
+	 */
2437
+	public function add_relationship_to(
2438
+		$id_or_obj,
2439
+		$other_model_id_or_obj,
2440
+		$relationName,
2441
+		$extra_join_model_fields_n_values = array()
2442
+	) {
2443
+		$relation_obj = $this->related_settings_for($relationName);
2444
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2445
+	}
2446
+
2447
+
2448
+
2449
+	/**
2450
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2451
+	 * There are the 3 cases:
2452
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2453
+	 * error
2454
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2455
+	 * an error
2456
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2457
+	 *
2458
+	 * @param        EE_Base_Class /int $id_or_obj
2459
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2460
+	 * @param string $relationName key in EEM_Base::_relations
2461
+	 * @return boolean of success
2462
+	 * @throws \EE_Error
2463
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2464
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2465
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2466
+	 *                             because these will be inserted in any new rows created as well.
2467
+	 */
2468
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2469
+	{
2470
+		$relation_obj = $this->related_settings_for($relationName);
2471
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2472
+	}
2473
+
2474
+
2475
+
2476
+	/**
2477
+	 * @param mixed           $id_or_obj
2478
+	 * @param string          $relationName
2479
+	 * @param array           $where_query_params
2480
+	 * @param EE_Base_Class[] objects to which relations were removed
2481
+	 * @return \EE_Base_Class[]
2482
+	 * @throws \EE_Error
2483
+	 */
2484
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2485
+	{
2486
+		$relation_obj = $this->related_settings_for($relationName);
2487
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2488
+	}
2489
+
2490
+
2491
+
2492
+	/**
2493
+	 * Gets all the related items of the specified $model_name, using $query_params.
2494
+	 * Note: by default, we remove the "default query params"
2495
+	 * because we want to get even deleted items etc.
2496
+	 *
2497
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2498
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2499
+	 * @param array  $query_params like EEM_Base::get_all
2500
+	 * @return EE_Base_Class[]
2501
+	 * @throws \EE_Error
2502
+	 */
2503
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2504
+	{
2505
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2506
+		$relation_settings = $this->related_settings_for($model_name);
2507
+		return $relation_settings->get_all_related($model_obj, $query_params);
2508
+	}
2509
+
2510
+
2511
+
2512
+	/**
2513
+	 * Deletes all the model objects across the relation indicated by $model_name
2514
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2515
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2516
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2517
+	 *
2518
+	 * @param EE_Base_Class|int|string $id_or_obj
2519
+	 * @param string                   $model_name
2520
+	 * @param array                    $query_params
2521
+	 * @return int how many deleted
2522
+	 * @throws \EE_Error
2523
+	 */
2524
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2525
+	{
2526
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2527
+		$relation_settings = $this->related_settings_for($model_name);
2528
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2529
+	}
2530
+
2531
+
2532
+
2533
+	/**
2534
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2535
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2536
+	 * the model objects can't be hard deleted because of blocking related model objects,
2537
+	 * just does a soft-delete on them instead.
2538
+	 *
2539
+	 * @param EE_Base_Class|int|string $id_or_obj
2540
+	 * @param string                   $model_name
2541
+	 * @param array                    $query_params
2542
+	 * @return int how many deleted
2543
+	 * @throws \EE_Error
2544
+	 */
2545
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2546
+	{
2547
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2548
+		$relation_settings = $this->related_settings_for($model_name);
2549
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2550
+	}
2551
+
2552
+
2553
+
2554
+	/**
2555
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2556
+	 * unless otherwise specified in the $query_params
2557
+	 *
2558
+	 * @param        int             /EE_Base_Class $id_or_obj
2559
+	 * @param string $model_name     like 'Event', or 'Registration'
2560
+	 * @param array  $query_params   like EEM_Base::get_all's
2561
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2562
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2563
+	 *                               that by the setting $distinct to TRUE;
2564
+	 * @return int
2565
+	 * @throws \EE_Error
2566
+	 */
2567
+	public function count_related(
2568
+		$id_or_obj,
2569
+		$model_name,
2570
+		$query_params = array(),
2571
+		$field_to_count = null,
2572
+		$distinct = false
2573
+	) {
2574
+		$related_model = $this->get_related_model_obj($model_name);
2575
+		//we're just going to use the query params on the related model's normal get_all query,
2576
+		//except add a condition to say to match the current mod
2577
+		if (! isset($query_params['default_where_conditions'])) {
2578
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2579
+		}
2580
+		$this_model_name = $this->get_this_model_name();
2581
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2582
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2583
+		return $related_model->count($query_params, $field_to_count, $distinct);
2584
+	}
2585
+
2586
+
2587
+
2588
+	/**
2589
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2590
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2591
+	 *
2592
+	 * @param        int           /EE_Base_Class $id_or_obj
2593
+	 * @param string $model_name   like 'Event', or 'Registration'
2594
+	 * @param array  $query_params like EEM_Base::get_all's
2595
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2596
+	 * @return float
2597
+	 * @throws \EE_Error
2598
+	 */
2599
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2600
+	{
2601
+		$related_model = $this->get_related_model_obj($model_name);
2602
+		if (! is_array($query_params)) {
2603
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2604
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2605
+					gettype($query_params)), '4.6.0');
2606
+			$query_params = array();
2607
+		}
2608
+		//we're just going to use the query params on the related model's normal get_all query,
2609
+		//except add a condition to say to match the current mod
2610
+		if (! isset($query_params['default_where_conditions'])) {
2611
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2612
+		}
2613
+		$this_model_name = $this->get_this_model_name();
2614
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2615
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2616
+		return $related_model->sum($query_params, $field_to_sum);
2617
+	}
2618
+
2619
+
2620
+
2621
+	/**
2622
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2623
+	 * $modelObject
2624
+	 *
2625
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2626
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2627
+	 * @param array               $query_params     like EEM_Base::get_all's
2628
+	 * @return EE_Base_Class
2629
+	 * @throws \EE_Error
2630
+	 */
2631
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2632
+	{
2633
+		$query_params['limit'] = 1;
2634
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2635
+		if ($results) {
2636
+			return array_shift($results);
2637
+		} else {
2638
+			return null;
2639
+		}
2640
+	}
2641
+
2642
+
2643
+
2644
+	/**
2645
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2646
+	 *
2647
+	 * @return string
2648
+	 */
2649
+	public function get_this_model_name()
2650
+	{
2651
+		return str_replace("EEM_", "", get_class($this));
2652
+	}
2653
+
2654
+
2655
+
2656
+	/**
2657
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2658
+	 *
2659
+	 * @return EE_Any_Foreign_Model_Name_Field
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function get_field_containing_related_model_name()
2663
+	{
2664
+		foreach ($this->field_settings(true) as $field) {
2665
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2666
+				$field_with_model_name = $field;
2667
+			}
2668
+		}
2669
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2670
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2671
+				$this->get_this_model_name()));
2672
+		}
2673
+		return $field_with_model_name;
2674
+	}
2675
+
2676
+
2677
+
2678
+	/**
2679
+	 * Inserts a new entry into the database, for each table.
2680
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2681
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2682
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2683
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2684
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2685
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2686
+	 *
2687
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2688
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2689
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2690
+	 *                              of EEM_Base)
2691
+	 * @return int new primary key on main table that got inserted
2692
+	 * @throws EE_Error
2693
+	 */
2694
+	public function insert($field_n_values)
2695
+	{
2696
+		/**
2697
+		 * Filters the fields and their values before inserting an item using the models
2698
+		 *
2699
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2700
+		 * @param EEM_Base $model           the model used
2701
+		 */
2702
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2703
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2704
+			$main_table = $this->_get_main_table();
2705
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2706
+			if ($new_id !== false) {
2707
+				foreach ($this->_get_other_tables() as $other_table) {
2708
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2709
+				}
2710
+			}
2711
+			/**
2712
+			 * Done just after attempting to insert a new model object
2713
+			 *
2714
+			 * @param EEM_Base   $model           used
2715
+			 * @param array      $fields_n_values fields and their values
2716
+			 * @param int|string the              ID of the newly-inserted model object
2717
+			 */
2718
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2719
+			return $new_id;
2720
+		} else {
2721
+			return false;
2722
+		}
2723
+	}
2724
+
2725
+
2726
+
2727
+	/**
2728
+	 * Checks that the result would satisfy the unique indexes on this model
2729
+	 *
2730
+	 * @param array  $field_n_values
2731
+	 * @param string $action
2732
+	 * @return boolean
2733
+	 * @throws \EE_Error
2734
+	 */
2735
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2736
+	{
2737
+		foreach ($this->unique_indexes() as $index_name => $index) {
2738
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2739
+			if ($this->exists(array($uniqueness_where_params))) {
2740
+				EE_Error::add_error(
2741
+					sprintf(
2742
+						__(
2743
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2744
+							"event_espresso"
2745
+						),
2746
+						$action,
2747
+						$this->_get_class_name(),
2748
+						$index_name,
2749
+						implode(",", $index->field_names()),
2750
+						http_build_query($uniqueness_where_params)
2751
+					),
2752
+					__FILE__,
2753
+					__FUNCTION__,
2754
+					__LINE__
2755
+				);
2756
+				return false;
2757
+			}
2758
+		}
2759
+		return true;
2760
+	}
2761
+
2762
+
2763
+
2764
+	/**
2765
+	 * Checks the database for an item that conflicts (ie, if this item were
2766
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2767
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2768
+	 * can be either an EE_Base_Class or an array of fields n values
2769
+	 *
2770
+	 * @param EE_Base_Class|array $obj_or_fields_array
2771
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2772
+	 *                                                 when looking for conflicts
2773
+	 *                                                 (ie, if false, we ignore the model object's primary key
2774
+	 *                                                 when finding "conflicts". If true, it's also considered).
2775
+	 *                                                 Only works for INT primary key,
2776
+	 *                                                 STRING primary keys cannot be ignored
2777
+	 * @throws EE_Error
2778
+	 * @return EE_Base_Class|array
2779
+	 */
2780
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2781
+	{
2782
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2783
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2784
+		} elseif (is_array($obj_or_fields_array)) {
2785
+			$fields_n_values = $obj_or_fields_array;
2786
+		} else {
2787
+			throw new EE_Error(
2788
+				sprintf(
2789
+					__(
2790
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2791
+						"event_espresso"
2792
+					),
2793
+					get_class($this),
2794
+					$obj_or_fields_array
2795
+				)
2796
+			);
2797
+		}
2798
+		$query_params = array();
2799
+		if ($this->has_primary_key_field()
2800
+			&& ($include_primary_key
2801
+				|| $this->get_primary_key_field()
2802
+				   instanceof
2803
+				   EE_Primary_Key_String_Field)
2804
+			&& isset($fields_n_values[$this->primary_key_name()])
2805
+		) {
2806
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2807
+		}
2808
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2809
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2810
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2811
+		}
2812
+		//if there is nothing to base this search on, then we shouldn't find anything
2813
+		if (empty($query_params)) {
2814
+			return array();
2815
+		} else {
2816
+			return $this->get_one($query_params);
2817
+		}
2818
+	}
2819
+
2820
+
2821
+
2822
+	/**
2823
+	 * Like count, but is optimized and returns a boolean instead of an int
2824
+	 *
2825
+	 * @param array $query_params
2826
+	 * @return boolean
2827
+	 * @throws \EE_Error
2828
+	 */
2829
+	public function exists($query_params)
2830
+	{
2831
+		$query_params['limit'] = 1;
2832
+		return $this->count($query_params) > 0;
2833
+	}
2834
+
2835
+
2836
+
2837
+	/**
2838
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2839
+	 *
2840
+	 * @param int|string $id
2841
+	 * @return boolean
2842
+	 * @throws \EE_Error
2843
+	 */
2844
+	public function exists_by_ID($id)
2845
+	{
2846
+		return $this->exists(
2847
+			array(
2848
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2849
+				array(
2850
+					$this->primary_key_name() => $id,
2851
+				),
2852
+			)
2853
+		);
2854
+	}
2855
+
2856
+
2857
+
2858
+	/**
2859
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2860
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2861
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2862
+	 * on the main table)
2863
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2864
+	 * cases where we want to call it directly rather than via insert().
2865
+	 *
2866
+	 * @access   protected
2867
+	 * @param EE_Table_Base $table
2868
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2869
+	 *                                       float
2870
+	 * @param int           $new_id          for now we assume only int keys
2871
+	 * @throws EE_Error
2872
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2873
+	 * @return int ID of new row inserted, or FALSE on failure
2874
+	 */
2875
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2876
+	{
2877
+		global $wpdb;
2878
+		$insertion_col_n_values = array();
2879
+		$format_for_insertion = array();
2880
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2881
+		foreach ($fields_on_table as $field_name => $field_obj) {
2882
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2883
+			if ($field_obj->is_auto_increment()) {
2884
+				continue;
2885
+			}
2886
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2887
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2888
+			if ($prepared_value !== null) {
2889
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2890
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2891
+			}
2892
+		}
2893
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2894
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2895
+			//so add the fk to the main table as a column
2896
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2897
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2898
+		}
2899
+		//insert the new entry
2900
+		$result = $this->_do_wpdb_query('insert',
2901
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2902
+		if ($result === false) {
2903
+			return false;
2904
+		}
2905
+		//ok, now what do we return for the ID of the newly-inserted thing?
2906
+		if ($this->has_primary_key_field()) {
2907
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2908
+				return $wpdb->insert_id;
2909
+			} else {
2910
+				//it's not an auto-increment primary key, so
2911
+				//it must have been supplied
2912
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2913
+			}
2914
+		} else {
2915
+			//we can't return a  primary key because there is none. instead return
2916
+			//a unique string indicating this model
2917
+			return $this->get_index_primary_key_string($fields_n_values);
2918
+		}
2919
+	}
2920
+
2921
+
2922
+
2923
+	/**
2924
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2925
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2926
+	 * and there is no default, we pass it along. WPDB will take care of it)
2927
+	 *
2928
+	 * @param EE_Model_Field_Base $field_obj
2929
+	 * @param array               $fields_n_values
2930
+	 * @return mixed string|int|float depending on what the table column will be expecting
2931
+	 * @throws \EE_Error
2932
+	 */
2933
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2934
+	{
2935
+		//if this field doesn't allow nullable, don't allow it
2936
+		if (
2937
+			! $field_obj->is_nullable()
2938
+			&& (
2939
+				! isset($fields_n_values[$field_obj->get_name()])
2940
+				|| $fields_n_values[$field_obj->get_name()] === null
2941
+			)
2942
+		) {
2943
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2944
+		}
2945
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
2946
+			? $fields_n_values[$field_obj->get_name()]
2947
+			: null;
2948
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2949
+	}
2950
+
2951
+
2952
+
2953
+	/**
2954
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2955
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2956
+	 * the field's prepare_for_set() method.
2957
+	 *
2958
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2959
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2960
+	 *                                   top of file)
2961
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2962
+	 *                                   $value is a custom selection
2963
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2964
+	 */
2965
+	private function _prepare_value_for_use_in_db($value, $field)
2966
+	{
2967
+		if ($field && $field instanceof EE_Model_Field_Base) {
2968
+			switch ($this->_values_already_prepared_by_model_object) {
2969
+				/** @noinspection PhpMissingBreakStatementInspection */
2970
+				case self::not_prepared_by_model_object:
2971
+					$value = $field->prepare_for_set($value);
2972
+				//purposefully left out "return"
2973
+				case self::prepared_by_model_object:
2974
+					$value = $field->prepare_for_use_in_db($value);
2975
+				case self::prepared_for_use_in_db:
2976
+					//leave the value alone
2977
+			}
2978
+			return $value;
2979
+		} else {
2980
+			return $value;
2981
+		}
2982
+	}
2983
+
2984
+
2985
+
2986
+	/**
2987
+	 * Returns the main table on this model
2988
+	 *
2989
+	 * @return EE_Primary_Table
2990
+	 * @throws EE_Error
2991
+	 */
2992
+	protected function _get_main_table()
2993
+	{
2994
+		foreach ($this->_tables as $table) {
2995
+			if ($table instanceof EE_Primary_Table) {
2996
+				return $table;
2997
+			}
2998
+		}
2999
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3000
+			'event_espresso'), get_class($this)));
3001
+	}
3002
+
3003
+
3004
+
3005
+	/**
3006
+	 * table
3007
+	 * returns EE_Primary_Table table name
3008
+	 *
3009
+	 * @return string
3010
+	 * @throws \EE_Error
3011
+	 */
3012
+	public function table()
3013
+	{
3014
+		return $this->_get_main_table()->get_table_name();
3015
+	}
3016
+
3017
+
3018
+
3019
+	/**
3020
+	 * table
3021
+	 * returns first EE_Secondary_Table table name
3022
+	 *
3023
+	 * @return string
3024
+	 */
3025
+	public function second_table()
3026
+	{
3027
+		// grab second table from tables array
3028
+		$second_table = end($this->_tables);
3029
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * get_table_obj_by_alias
3036
+	 * returns table name given it's alias
3037
+	 *
3038
+	 * @param string $table_alias
3039
+	 * @return EE_Primary_Table | EE_Secondary_Table
3040
+	 */
3041
+	public function get_table_obj_by_alias($table_alias = '')
3042
+	{
3043
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3044
+	}
3045
+
3046
+
3047
+
3048
+	/**
3049
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3050
+	 *
3051
+	 * @return EE_Secondary_Table[]
3052
+	 */
3053
+	protected function _get_other_tables()
3054
+	{
3055
+		$other_tables = array();
3056
+		foreach ($this->_tables as $table_alias => $table) {
3057
+			if ($table instanceof EE_Secondary_Table) {
3058
+				$other_tables[$table_alias] = $table;
3059
+			}
3060
+		}
3061
+		return $other_tables;
3062
+	}
3063
+
3064
+
3065
+
3066
+	/**
3067
+	 * Finds all the fields that correspond to the given table
3068
+	 *
3069
+	 * @param string $table_alias , array key in EEM_Base::_tables
3070
+	 * @return EE_Model_Field_Base[]
3071
+	 */
3072
+	public function _get_fields_for_table($table_alias)
3073
+	{
3074
+		return $this->_fields[$table_alias];
3075
+	}
3076
+
3077
+
3078
+
3079
+	/**
3080
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3081
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3082
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3083
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3084
+	 * related Registration, Transaction, and Payment models.
3085
+	 *
3086
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3087
+	 * @return EE_Model_Query_Info_Carrier
3088
+	 * @throws \EE_Error
3089
+	 */
3090
+	public function _extract_related_models_from_query($query_params)
3091
+	{
3092
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3093
+		if (array_key_exists(0, $query_params)) {
3094
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3095
+		}
3096
+		if (array_key_exists('group_by', $query_params)) {
3097
+			if (is_array($query_params['group_by'])) {
3098
+				$this->_extract_related_models_from_sub_params_array_values(
3099
+					$query_params['group_by'],
3100
+					$query_info_carrier,
3101
+					'group_by'
3102
+				);
3103
+			} elseif (! empty ($query_params['group_by'])) {
3104
+				$this->_extract_related_model_info_from_query_param(
3105
+					$query_params['group_by'],
3106
+					$query_info_carrier,
3107
+					'group_by'
3108
+				);
3109
+			}
3110
+		}
3111
+		if (array_key_exists('having', $query_params)) {
3112
+			$this->_extract_related_models_from_sub_params_array_keys(
3113
+				$query_params[0],
3114
+				$query_info_carrier,
3115
+				'having'
3116
+			);
3117
+		}
3118
+		if (array_key_exists('order_by', $query_params)) {
3119
+			if (is_array($query_params['order_by'])) {
3120
+				$this->_extract_related_models_from_sub_params_array_keys(
3121
+					$query_params['order_by'],
3122
+					$query_info_carrier,
3123
+					'order_by'
3124
+				);
3125
+			} elseif (! empty($query_params['order_by'])) {
3126
+				$this->_extract_related_model_info_from_query_param(
3127
+					$query_params['order_by'],
3128
+					$query_info_carrier,
3129
+					'order_by'
3130
+				);
3131
+			}
3132
+		}
3133
+		if (array_key_exists('force_join', $query_params)) {
3134
+			$this->_extract_related_models_from_sub_params_array_values(
3135
+				$query_params['force_join'],
3136
+				$query_info_carrier,
3137
+				'force_join'
3138
+			);
3139
+		}
3140
+		return $query_info_carrier;
3141
+	}
3142
+
3143
+
3144
+
3145
+	/**
3146
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3147
+	 *
3148
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3149
+	 *                                                      $query_params['having']
3150
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3151
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3152
+	 * @throws EE_Error
3153
+	 * @return \EE_Model_Query_Info_Carrier
3154
+	 */
3155
+	private function _extract_related_models_from_sub_params_array_keys(
3156
+		$sub_query_params,
3157
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3158
+		$query_param_type
3159
+	) {
3160
+		if (! empty($sub_query_params)) {
3161
+			$sub_query_params = (array)$sub_query_params;
3162
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3163
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3164
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3165
+					$query_param_type);
3166
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3167
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3168
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3169
+				//of array('Registration.TXN_ID'=>23)
3170
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3171
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3172
+					if (! is_array($possibly_array_of_params)) {
3173
+						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'))",
3174
+							"event_espresso"),
3175
+							$param, $possibly_array_of_params));
3176
+					} else {
3177
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3178
+							$model_query_info_carrier, $query_param_type);
3179
+					}
3180
+				} elseif ($query_param_type === 0 //ie WHERE
3181
+						  && is_array($possibly_array_of_params)
3182
+						  && isset($possibly_array_of_params[2])
3183
+						  && $possibly_array_of_params[2] == true
3184
+				) {
3185
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3186
+					//indicating that $possible_array_of_params[1] is actually a field name,
3187
+					//from which we should extract query parameters!
3188
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3189
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3190
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3191
+					}
3192
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3193
+						$model_query_info_carrier, $query_param_type);
3194
+				}
3195
+			}
3196
+		}
3197
+		return $model_query_info_carrier;
3198
+	}
3199
+
3200
+
3201
+
3202
+	/**
3203
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3204
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3205
+	 *
3206
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3207
+	 *                                                      $query_params['having']
3208
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3209
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3210
+	 * @throws EE_Error
3211
+	 * @return \EE_Model_Query_Info_Carrier
3212
+	 */
3213
+	private function _extract_related_models_from_sub_params_array_values(
3214
+		$sub_query_params,
3215
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3216
+		$query_param_type
3217
+	) {
3218
+		if (! empty($sub_query_params)) {
3219
+			if (! is_array($sub_query_params)) {
3220
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3221
+					$sub_query_params));
3222
+			}
3223
+			foreach ($sub_query_params as $param) {
3224
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3225
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3226
+					$query_param_type);
3227
+			}
3228
+		}
3229
+		return $model_query_info_carrier;
3230
+	}
3231
+
3232
+
3233
+
3234
+	/**
3235
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3236
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3237
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3238
+	 * but use them in a different order. Eg, we need to know what models we are querying
3239
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3240
+	 * other models before we can finalize the where clause SQL.
3241
+	 *
3242
+	 * @param array $query_params
3243
+	 * @throws EE_Error
3244
+	 * @return EE_Model_Query_Info_Carrier
3245
+	 */
3246
+	public function _create_model_query_info_carrier($query_params)
3247
+	{
3248
+		if (! is_array($query_params)) {
3249
+			EE_Error::doing_it_wrong(
3250
+				'EEM_Base::_create_model_query_info_carrier',
3251
+				sprintf(
3252
+					__(
3253
+						'$query_params should be an array, you passed a variable of type %s',
3254
+						'event_espresso'
3255
+					),
3256
+					gettype($query_params)
3257
+				),
3258
+				'4.6.0'
3259
+			);
3260
+			$query_params = array();
3261
+		}
3262
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3263
+		//first check if we should alter the query to account for caps or not
3264
+		//because the caps might require us to do extra joins
3265
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3266
+			$query_params[0] = $where_query_params = array_replace_recursive(
3267
+				$where_query_params,
3268
+				$this->caps_where_conditions(
3269
+					$query_params['caps']
3270
+				)
3271
+			);
3272
+		}
3273
+		$query_object = $this->_extract_related_models_from_query($query_params);
3274
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3275
+		foreach ($where_query_params as $key => $value) {
3276
+			if (is_int($key)) {
3277
+				throw new EE_Error(
3278
+					sprintf(
3279
+						__(
3280
+							"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.",
3281
+							"event_espresso"
3282
+						),
3283
+						$key,
3284
+						var_export($value, true),
3285
+						var_export($query_params, true),
3286
+						get_class($this)
3287
+					)
3288
+				);
3289
+			}
3290
+		}
3291
+		if (
3292
+			array_key_exists('default_where_conditions', $query_params)
3293
+			&& ! empty($query_params['default_where_conditions'])
3294
+		) {
3295
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3296
+		} else {
3297
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3298
+		}
3299
+		$where_query_params = array_merge(
3300
+			$this->_get_default_where_conditions_for_models_in_query(
3301
+				$query_object,
3302
+				$use_default_where_conditions,
3303
+				$where_query_params
3304
+			),
3305
+			$where_query_params
3306
+		);
3307
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3308
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3309
+		// So we need to setup a subquery and use that for the main join.
3310
+		// Note for now this only works on the primary table for the model.
3311
+		// So for instance, you could set the limit array like this:
3312
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3313
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3314
+			$query_object->set_main_model_join_sql(
3315
+				$this->_construct_limit_join_select(
3316
+					$query_params['on_join_limit'][0],
3317
+					$query_params['on_join_limit'][1]
3318
+				)
3319
+			);
3320
+		}
3321
+		//set limit
3322
+		if (array_key_exists('limit', $query_params)) {
3323
+			if (is_array($query_params['limit'])) {
3324
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3325
+					$e = sprintf(
3326
+						__(
3327
+							"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)",
3328
+							"event_espresso"
3329
+						),
3330
+						http_build_query($query_params['limit'])
3331
+					);
3332
+					throw new EE_Error($e . "|" . $e);
3333
+				}
3334
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3335
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3336
+			} elseif (! empty ($query_params['limit'])) {
3337
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3338
+			}
3339
+		}
3340
+		//set order by
3341
+		if (array_key_exists('order_by', $query_params)) {
3342
+			if (is_array($query_params['order_by'])) {
3343
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3344
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3345
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3346
+				if (array_key_exists('order', $query_params)) {
3347
+					throw new EE_Error(
3348
+						sprintf(
3349
+							__(
3350
+								"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 ",
3351
+								"event_espresso"
3352
+							),
3353
+							get_class($this),
3354
+							implode(", ", array_keys($query_params['order_by'])),
3355
+							implode(", ", $query_params['order_by']),
3356
+							$query_params['order']
3357
+						)
3358
+					);
3359
+				}
3360
+				$this->_extract_related_models_from_sub_params_array_keys(
3361
+					$query_params['order_by'],
3362
+					$query_object,
3363
+					'order_by'
3364
+				);
3365
+				//assume it's an array of fields to order by
3366
+				$order_array = array();
3367
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3368
+					$order = $this->_extract_order($order);
3369
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3370
+				}
3371
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3372
+			} elseif (! empty ($query_params['order_by'])) {
3373
+				$this->_extract_related_model_info_from_query_param(
3374
+					$query_params['order_by'],
3375
+					$query_object,
3376
+					'order',
3377
+					$query_params['order_by']
3378
+				);
3379
+				$order = isset($query_params['order'])
3380
+					? $this->_extract_order($query_params['order'])
3381
+					: 'DESC';
3382
+				$query_object->set_order_by_sql(
3383
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3384
+				);
3385
+			}
3386
+		}
3387
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3388
+		if (! array_key_exists('order_by', $query_params)
3389
+			&& array_key_exists('order', $query_params)
3390
+			&& ! empty($query_params['order'])
3391
+		) {
3392
+			$pk_field = $this->get_primary_key_field();
3393
+			$order = $this->_extract_order($query_params['order']);
3394
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3395
+		}
3396
+		//set group by
3397
+		if (array_key_exists('group_by', $query_params)) {
3398
+			if (is_array($query_params['group_by'])) {
3399
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3400
+				$group_by_array = array();
3401
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3402
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3403
+				}
3404
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3405
+			} elseif (! empty ($query_params['group_by'])) {
3406
+				$query_object->set_group_by_sql(
3407
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3408
+				);
3409
+			}
3410
+		}
3411
+		//set having
3412
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3413
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3414
+		}
3415
+		//now, just verify they didn't pass anything wack
3416
+		foreach ($query_params as $query_key => $query_value) {
3417
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3418
+				throw new EE_Error(
3419
+					sprintf(
3420
+						__(
3421
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3422
+							'event_espresso'
3423
+						),
3424
+						$query_key,
3425
+						get_class($this),
3426
+						//						print_r( $this->_allowed_query_params, TRUE )
3427
+						implode(',', $this->_allowed_query_params)
3428
+					)
3429
+				);
3430
+			}
3431
+		}
3432
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3433
+		if (empty($main_model_join_sql)) {
3434
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3435
+		}
3436
+		return $query_object;
3437
+	}
3438
+
3439
+
3440
+
3441
+	/**
3442
+	 * Gets the where conditions that should be imposed on the query based on the
3443
+	 * context (eg reading frontend, backend, edit or delete).
3444
+	 *
3445
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3446
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3447
+	 * @throws \EE_Error
3448
+	 */
3449
+	public function caps_where_conditions($context = self::caps_read)
3450
+	{
3451
+		EEM_Base::verify_is_valid_cap_context($context);
3452
+		$cap_where_conditions = array();
3453
+		$cap_restrictions = $this->caps_missing($context);
3454
+		/**
3455
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3456
+		 */
3457
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3458
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3459
+				$restriction_if_no_cap->get_default_where_conditions());
3460
+		}
3461
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3462
+			$cap_restrictions);
3463
+	}
3464
+
3465
+
3466
+
3467
+	/**
3468
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3469
+	 * otherwise throws an exception
3470
+	 *
3471
+	 * @param string $should_be_order_string
3472
+	 * @return string either ASC, asc, DESC or desc
3473
+	 * @throws EE_Error
3474
+	 */
3475
+	private function _extract_order($should_be_order_string)
3476
+	{
3477
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3478
+			return $should_be_order_string;
3479
+		} else {
3480
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3481
+				"event_espresso"), get_class($this), $should_be_order_string));
3482
+		}
3483
+	}
3484
+
3485
+
3486
+
3487
+	/**
3488
+	 * Looks at all the models which are included in this query, and asks each
3489
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3490
+	 * so they can be merged
3491
+	 *
3492
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3493
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3494
+	 *                                                                  'none' means NO default where conditions will
3495
+	 *                                                                  be used AT ALL during this query.
3496
+	 *                                                                  'other_models_only' means default where
3497
+	 *                                                                  conditions from other models will be used, but
3498
+	 *                                                                  not for this primary model. 'all', the default,
3499
+	 *                                                                  means default where conditions will apply as
3500
+	 *                                                                  normal
3501
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3502
+	 * @throws EE_Error
3503
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3504
+	 */
3505
+	private function _get_default_where_conditions_for_models_in_query(
3506
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3507
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3508
+		$where_query_params = array()
3509
+	) {
3510
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3511
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3512
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3513
+				"event_espresso"), $use_default_where_conditions,
3514
+				implode(", ", $allowed_used_default_where_conditions_values)));
3515
+		}
3516
+		$universal_query_params = array();
3517
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3518
+			$universal_query_params = $this->_get_default_where_conditions();
3519
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3520
+			$universal_query_params = $this->_get_minimum_where_conditions();
3521
+		}
3522
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3523
+			$related_model = $this->get_related_model_obj($model_name);
3524
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3525
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3526
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3527
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3528
+			} else {
3529
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3530
+				continue;
3531
+			}
3532
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3533
+				$related_model_universal_where_params,
3534
+				$where_query_params,
3535
+				$related_model,
3536
+				$model_relation_path
3537
+			);
3538
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3539
+				$universal_query_params,
3540
+				$overrides
3541
+			);
3542
+		}
3543
+		return $universal_query_params;
3544
+	}
3545
+
3546
+
3547
+
3548
+	/**
3549
+	 * Determines whether or not we should use default where conditions for the model in question
3550
+	 * (this model, or other related models).
3551
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3552
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3553
+	 * We should use default where conditions on related models when they requested to use default where conditions
3554
+	 * on all models, or specifically just on other related models
3555
+	 * @param      $default_where_conditions_value
3556
+	 * @param bool $for_this_model false means this is for OTHER related models
3557
+	 * @return bool
3558
+	 */
3559
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3560
+	{
3561
+		return (
3562
+				   $for_this_model
3563
+				   && in_array(
3564
+					   $default_where_conditions_value,
3565
+					   array(
3566
+						   EEM_Base::default_where_conditions_all,
3567
+						   EEM_Base::default_where_conditions_this_only,
3568
+						   EEM_Base::default_where_conditions_minimum_others,
3569
+					   ),
3570
+					   true
3571
+				   )
3572
+			   )
3573
+			   || (
3574
+				   ! $for_this_model
3575
+				   && in_array(
3576
+					   $default_where_conditions_value,
3577
+					   array(
3578
+						   EEM_Base::default_where_conditions_all,
3579
+						   EEM_Base::default_where_conditions_others_only,
3580
+					   ),
3581
+					   true
3582
+				   )
3583
+			   );
3584
+	}
3585
+
3586
+	/**
3587
+	 * Determines whether or not we should use default minimum conditions for the model in question
3588
+	 * (this model, or other related models).
3589
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3590
+	 * where conditions.
3591
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3592
+	 * on this model or others
3593
+	 * @param      $default_where_conditions_value
3594
+	 * @param bool $for_this_model false means this is for OTHER related models
3595
+	 * @return bool
3596
+	 */
3597
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3598
+	{
3599
+		return (
3600
+				   $for_this_model
3601
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3602
+			   )
3603
+			   || (
3604
+				   ! $for_this_model
3605
+				   && in_array(
3606
+					   $default_where_conditions_value,
3607
+					   array(
3608
+						   EEM_Base::default_where_conditions_minimum_others,
3609
+						   EEM_Base::default_where_conditions_minimum_all,
3610
+					   ),
3611
+					   true
3612
+				   )
3613
+			   );
3614
+	}
3615
+
3616
+
3617
+	/**
3618
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3619
+	 * then we also add a special where condition which allows for that model's primary key
3620
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3621
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3622
+	 *
3623
+	 * @param array    $default_where_conditions
3624
+	 * @param array    $provided_where_conditions
3625
+	 * @param EEM_Base $model
3626
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3627
+	 * @return array like EEM_Base::get_all's $query_params[0]
3628
+	 * @throws \EE_Error
3629
+	 */
3630
+	private function _override_defaults_or_make_null_friendly(
3631
+		$default_where_conditions,
3632
+		$provided_where_conditions,
3633
+		$model,
3634
+		$model_relation_path
3635
+	) {
3636
+		$null_friendly_where_conditions = array();
3637
+		$none_overridden = true;
3638
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3639
+		foreach ($default_where_conditions as $key => $val) {
3640
+			if (isset($provided_where_conditions[$key])) {
3641
+				$none_overridden = false;
3642
+			} else {
3643
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3644
+			}
3645
+		}
3646
+		if ($none_overridden && $default_where_conditions) {
3647
+			if ($model->has_primary_key_field()) {
3648
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3649
+																				. "."
3650
+																				. $model->primary_key_name()] = array('IS NULL');
3651
+			}/*else{
3652 3652
 				//@todo NO PK, use other defaults
3653 3653
 			}*/
3654
-        }
3655
-        return $null_friendly_where_conditions;
3656
-    }
3657
-
3658
-
3659
-
3660
-    /**
3661
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3662
-     * default where conditions on all get_all, update, and delete queries done by this model.
3663
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3664
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3665
-     *
3666
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3667
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3668
-     */
3669
-    private function _get_default_where_conditions($model_relation_path = null)
3670
-    {
3671
-        if ($this->_ignore_where_strategy) {
3672
-            return array();
3673
-        }
3674
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3675
-    }
3676
-
3677
-
3678
-
3679
-    /**
3680
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3681
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3682
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3683
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3684
-     * Similar to _get_default_where_conditions
3685
-     *
3686
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3687
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3688
-     */
3689
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3690
-    {
3691
-        if ($this->_ignore_where_strategy) {
3692
-            return array();
3693
-        }
3694
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3695
-    }
3696
-
3697
-
3698
-
3699
-    /**
3700
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3701
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3702
-     *
3703
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3704
-     * @return string
3705
-     * @throws \EE_Error
3706
-     */
3707
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3708
-    {
3709
-        $selects = $this->_get_columns_to_select_for_this_model();
3710
-        foreach (
3711
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3712
-            $name_of_other_model_included
3713
-        ) {
3714
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3715
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3716
-            foreach ($other_model_selects as $key => $value) {
3717
-                $selects[] = $value;
3718
-            }
3719
-        }
3720
-        return implode(", ", $selects);
3721
-    }
3722
-
3723
-
3724
-
3725
-    /**
3726
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3727
-     * So that's going to be the columns for all the fields on the model
3728
-     *
3729
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3730
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3731
-     */
3732
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3733
-    {
3734
-        $fields = $this->field_settings();
3735
-        $selects = array();
3736
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3737
-            $this->get_this_model_name());
3738
-        foreach ($fields as $field_obj) {
3739
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3740
-                         . $field_obj->get_table_alias()
3741
-                         . "."
3742
-                         . $field_obj->get_table_column()
3743
-                         . " AS '"
3744
-                         . $table_alias_with_model_relation_chain_prefix
3745
-                         . $field_obj->get_table_alias()
3746
-                         . "."
3747
-                         . $field_obj->get_table_column()
3748
-                         . "'";
3749
-        }
3750
-        //make sure we are also getting the PKs of each table
3751
-        $tables = $this->get_tables();
3752
-        if (count($tables) > 1) {
3753
-            foreach ($tables as $table_obj) {
3754
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3755
-                                       . $table_obj->get_fully_qualified_pk_column();
3756
-                if (! in_array($qualified_pk_column, $selects)) {
3757
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3758
-                }
3759
-            }
3760
-        }
3761
-        return $selects;
3762
-    }
3763
-
3764
-
3765
-
3766
-    /**
3767
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3768
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3769
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3770
-     * SQL for joining, and the data types
3771
-     *
3772
-     * @param null|string                 $original_query_param
3773
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3774
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3775
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3776
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3777
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3778
-     *                                                          or 'Registration's
3779
-     * @param string                      $original_query_param what it originally was (eg
3780
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3781
-     *                                                          matches $query_param
3782
-     * @throws EE_Error
3783
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3784
-     */
3785
-    private function _extract_related_model_info_from_query_param(
3786
-        $query_param,
3787
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3788
-        $query_param_type,
3789
-        $original_query_param = null
3790
-    ) {
3791
-        if ($original_query_param === null) {
3792
-            $original_query_param = $query_param;
3793
-        }
3794
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3795
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3796
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3797
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3798
-        //check to see if we have a field on this model
3799
-        $this_model_fields = $this->field_settings(true);
3800
-        if (array_key_exists($query_param, $this_model_fields)) {
3801
-            if ($allow_fields) {
3802
-                return;
3803
-            } else {
3804
-                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",
3805
-                    "event_espresso"),
3806
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3807
-            }
3808
-        } //check if this is a special logic query param
3809
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3810
-            if ($allow_logic_query_params) {
3811
-                return;
3812
-            } else {
3813
-                throw new EE_Error(
3814
-                    sprintf(
3815
-                        __('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',
3816
-                            'event_espresso'),
3817
-                        implode('", "', $this->_logic_query_param_keys),
3818
-                        $query_param,
3819
-                        get_class($this),
3820
-                        '<br />',
3821
-                        "\t"
3822
-                        . ' $passed_in_query_info = <pre>'
3823
-                        . print_r($passed_in_query_info, true)
3824
-                        . '</pre>'
3825
-                        . "\n\t"
3826
-                        . ' $query_param_type = '
3827
-                        . $query_param_type
3828
-                        . "\n\t"
3829
-                        . ' $original_query_param = '
3830
-                        . $original_query_param
3831
-                    )
3832
-                );
3833
-            }
3834
-        } //check if it's a custom selection
3835
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3836
-            return;
3837
-        }
3838
-        //check if has a model name at the beginning
3839
-        //and
3840
-        //check if it's a field on a related model
3841
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3842
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3843
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3844
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3845
-                if ($query_param === '') {
3846
-                    //nothing left to $query_param
3847
-                    //we should actually end in a field name, not a model like this!
3848
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3849
-                        "event_espresso"),
3850
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3851
-                } else {
3852
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3853
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3854
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3855
-                    return;
3856
-                }
3857
-            } elseif ($query_param === $valid_related_model_name) {
3858
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3859
-                return;
3860
-            }
3861
-        }
3862
-        //ok so $query_param didn't start with a model name
3863
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3864
-        //it's wack, that's what it is
3865
-        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",
3866
-            "event_espresso"),
3867
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3868
-    }
3869
-
3870
-
3871
-
3872
-    /**
3873
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3874
-     * and store it on $passed_in_query_info
3875
-     *
3876
-     * @param string                      $model_name
3877
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3878
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3879
-     *                                                          model and $model_name. Eg, if we are querying Event,
3880
-     *                                                          and are adding a join to 'Payment' with the original
3881
-     *                                                          query param key
3882
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3883
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3884
-     *                                                          Payment wants to add default query params so that it
3885
-     *                                                          will know what models to prepend onto its default query
3886
-     *                                                          params or in case it wants to rename tables (in case
3887
-     *                                                          there are multiple joins to the same table)
3888
-     * @return void
3889
-     * @throws \EE_Error
3890
-     */
3891
-    private function _add_join_to_model(
3892
-        $model_name,
3893
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3894
-        $original_query_param
3895
-    ) {
3896
-        $relation_obj = $this->related_settings_for($model_name);
3897
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3898
-        //check if the relation is HABTM, because then we're essentially doing two joins
3899
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3900
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3901
-            $join_model_obj = $relation_obj->get_join_model();
3902
-            //replace the model specified with the join model for this relation chain, whi
3903
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3904
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3905
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3906
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3907
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3908
-            $passed_in_query_info->merge($new_query_info);
3909
-        }
3910
-        //now just join to the other table pointed to by the relation object, and add its data types
3911
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3912
-            array($model_relation_chain => $model_name),
3913
-            $relation_obj->get_join_statement($model_relation_chain));
3914
-        $passed_in_query_info->merge($new_query_info);
3915
-    }
3916
-
3917
-
3918
-
3919
-    /**
3920
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3921
-     *
3922
-     * @param array $where_params like EEM_Base::get_all
3923
-     * @return string of SQL
3924
-     * @throws \EE_Error
3925
-     */
3926
-    private function _construct_where_clause($where_params)
3927
-    {
3928
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3929
-        if ($SQL) {
3930
-            return " WHERE " . $SQL;
3931
-        } else {
3932
-            return '';
3933
-        }
3934
-    }
3935
-
3936
-
3937
-
3938
-    /**
3939
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3940
-     * and should be passed HAVING parameters, not WHERE parameters
3941
-     *
3942
-     * @param array $having_params
3943
-     * @return string
3944
-     * @throws \EE_Error
3945
-     */
3946
-    private function _construct_having_clause($having_params)
3947
-    {
3948
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3949
-        if ($SQL) {
3950
-            return " HAVING " . $SQL;
3951
-        } else {
3952
-            return '';
3953
-        }
3954
-    }
3955
-
3956
-
3957
-
3958
-    /**
3959
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3960
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3961
-     * EEM_Attendee.
3962
-     *
3963
-     * @param string $field_name
3964
-     * @param string $model_name
3965
-     * @return EE_Model_Field_Base
3966
-     * @throws EE_Error
3967
-     */
3968
-    protected function _get_field_on_model($field_name, $model_name)
3969
-    {
3970
-        $model_class = 'EEM_' . $model_name;
3971
-        $model_filepath = $model_class . ".model.php";
3972
-        if (is_readable($model_filepath)) {
3973
-            require_once($model_filepath);
3974
-            $model_instance = call_user_func($model_name . "::instance");
3975
-            /* @var $model_instance EEM_Base */
3976
-            return $model_instance->field_settings_for($field_name);
3977
-        } else {
3978
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3979
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3980
-        }
3981
-    }
3982
-
3983
-
3984
-
3985
-    /**
3986
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3987
-     * Event_Meta.meta_value = 'foo'))"
3988
-     *
3989
-     * @param array  $where_params see EEM_Base::get_all for documentation
3990
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3991
-     * @throws EE_Error
3992
-     * @return string of SQL
3993
-     */
3994
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3995
-    {
3996
-        $where_clauses = array();
3997
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3998
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3999
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4000
-                switch ($query_param) {
4001
-                    case 'not':
4002
-                    case 'NOT':
4003
-                        $where_clauses[] = "! ("
4004
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4005
-                                $glue)
4006
-                                           . ")";
4007
-                        break;
4008
-                    case 'and':
4009
-                    case 'AND':
4010
-                        $where_clauses[] = " ("
4011
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4012
-                                ' AND ')
4013
-                                           . ")";
4014
-                        break;
4015
-                    case 'or':
4016
-                    case 'OR':
4017
-                        $where_clauses[] = " ("
4018
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4019
-                                ' OR ')
4020
-                                           . ")";
4021
-                        break;
4022
-                }
4023
-            } else {
4024
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4025
-                //if it's not a normal field, maybe it's a custom selection?
4026
-                if (! $field_obj) {
4027
-                    if (isset($this->_custom_selections[$query_param][1])) {
4028
-                        $field_obj = $this->_custom_selections[$query_param][1];
4029
-                    } else {
4030
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4031
-                            "event_espresso"), $query_param));
4032
-                    }
4033
-                }
4034
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4035
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4036
-            }
4037
-        }
4038
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4039
-    }
4040
-
4041
-
4042
-
4043
-    /**
4044
-     * Takes the input parameter and extract the table name (alias) and column name
4045
-     *
4046
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4047
-     * @throws EE_Error
4048
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4049
-     */
4050
-    private function _deduce_column_name_from_query_param($query_param)
4051
-    {
4052
-        $field = $this->_deduce_field_from_query_param($query_param);
4053
-        if ($field) {
4054
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4055
-                $query_param);
4056
-            return $table_alias_prefix . $field->get_qualified_column();
4057
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4058
-            //maybe it's custom selection item?
4059
-            //if so, just use it as the "column name"
4060
-            return $query_param;
4061
-        } else {
4062
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4063
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4064
-        }
4065
-    }
4066
-
4067
-
4068
-
4069
-    /**
4070
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4071
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4072
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4073
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4074
-     *
4075
-     * @param string $condition_query_param_key
4076
-     * @return string
4077
-     */
4078
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4079
-    {
4080
-        $pos_of_star = strpos($condition_query_param_key, '*');
4081
-        if ($pos_of_star === false) {
4082
-            return $condition_query_param_key;
4083
-        } else {
4084
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4085
-            return $condition_query_param_sans_star;
4086
-        }
4087
-    }
4088
-
4089
-
4090
-
4091
-    /**
4092
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4093
-     *
4094
-     * @param                            mixed      array | string    $op_and_value
4095
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4096
-     * @throws EE_Error
4097
-     * @return string
4098
-     */
4099
-    private function _construct_op_and_value($op_and_value, $field_obj)
4100
-    {
4101
-        if (is_array($op_and_value)) {
4102
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4103
-            if (! $operator) {
4104
-                $php_array_like_string = array();
4105
-                foreach ($op_and_value as $key => $value) {
4106
-                    $php_array_like_string[] = "$key=>$value";
4107
-                }
4108
-                throw new EE_Error(
4109
-                    sprintf(
4110
-                        __(
4111
-                            "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))",
4112
-                            "event_espresso"
4113
-                        ),
4114
-                        implode(",", $php_array_like_string)
4115
-                    )
4116
-                );
4117
-            }
4118
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4119
-        } else {
4120
-            $operator = '=';
4121
-            $value = $op_and_value;
4122
-        }
4123
-        //check to see if the value is actually another field
4124
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4125
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4126
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4127
-            //in this case, the value should be an array, or at least a comma-separated list
4128
-            //it will need to handle a little differently
4129
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4130
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4131
-            return $operator . SP . $cleaned_value;
4132
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4133
-            //the value should be an array with count of two.
4134
-            if (count($value) !== 2) {
4135
-                throw new EE_Error(
4136
-                    sprintf(
4137
-                        __(
4138
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4139
-                            'event_espresso'
4140
-                        ),
4141
-                        "BETWEEN"
4142
-                    )
4143
-                );
4144
-            }
4145
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4146
-            return $operator . SP . $cleaned_value;
4147
-        } elseif (in_array($operator, $this->_null_style_operators)) {
4148
-            if ($value !== null) {
4149
-                throw new EE_Error(
4150
-                    sprintf(
4151
-                        __(
4152
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4153
-                            "event_espresso"
4154
-                        ),
4155
-                        $value,
4156
-                        $operator
4157
-                    )
4158
-                );
4159
-            }
4160
-            return $operator;
4161
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
4162
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4163
-            //remove other junk. So just treat it as a string.
4164
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4165
-        } elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4166
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4167
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4168
-            throw new EE_Error(
4169
-                sprintf(
4170
-                    __(
4171
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4172
-                        'event_espresso'
4173
-                    ),
4174
-                    $operator,
4175
-                    $operator
4176
-                )
4177
-            );
4178
-        } elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4179
-            throw new EE_Error(
4180
-                sprintf(
4181
-                    __(
4182
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4183
-                        'event_espresso'
4184
-                    ),
4185
-                    $operator,
4186
-                    $operator
4187
-                )
4188
-            );
4189
-        } else {
4190
-            throw new EE_Error(
4191
-                sprintf(
4192
-                    __(
4193
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4194
-                        "event_espresso"
4195
-                    ),
4196
-                    http_build_query($op_and_value)
4197
-                )
4198
-            );
4199
-        }
4200
-    }
4201
-
4202
-
4203
-
4204
-    /**
4205
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4206
-     *
4207
-     * @param array                      $values
4208
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4209
-     *                                              '%s'
4210
-     * @return string
4211
-     * @throws \EE_Error
4212
-     */
4213
-    public function _construct_between_value($values, $field_obj)
4214
-    {
4215
-        $cleaned_values = array();
4216
-        foreach ($values as $value) {
4217
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4218
-        }
4219
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4220
-    }
4221
-
4222
-
4223
-
4224
-    /**
4225
-     * Takes an array or a comma-separated list of $values and cleans them
4226
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4227
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4228
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4229
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4230
-     *
4231
-     * @param mixed                      $values    array or comma-separated string
4232
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4233
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4234
-     * @throws \EE_Error
4235
-     */
4236
-    public function _construct_in_value($values, $field_obj)
4237
-    {
4238
-        //check if the value is a CSV list
4239
-        if (is_string($values)) {
4240
-            //in which case, turn it into an array
4241
-            $values = explode(",", $values);
4242
-        }
4243
-        $cleaned_values = array();
4244
-        foreach ($values as $value) {
4245
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4246
-        }
4247
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4248
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4249
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4250
-        if (empty($cleaned_values)) {
4251
-            $all_fields = $this->field_settings();
4252
-            $a_field = array_shift($all_fields);
4253
-            $main_table = $this->_get_main_table();
4254
-            $cleaned_values[] = "SELECT "
4255
-                                . $a_field->get_table_column()
4256
-                                . " FROM "
4257
-                                . $main_table->get_table_name()
4258
-                                . " WHERE FALSE";
4259
-        }
4260
-        return "(" . implode(",", $cleaned_values) . ")";
4261
-    }
4262
-
4263
-
4264
-
4265
-    /**
4266
-     * @param mixed                      $value
4267
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4268
-     * @throws EE_Error
4269
-     * @return false|null|string
4270
-     */
4271
-    private function _wpdb_prepare_using_field($value, $field_obj)
4272
-    {
4273
-        /** @type WPDB $wpdb */
4274
-        global $wpdb;
4275
-        if ($field_obj instanceof EE_Model_Field_Base) {
4276
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4277
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4278
-        } else {//$field_obj should really just be a data type
4279
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4280
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4281
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4282
-            }
4283
-            return $wpdb->prepare($field_obj, $value);
4284
-        }
4285
-    }
4286
-
4287
-
4288
-
4289
-    /**
4290
-     * Takes the input parameter and finds the model field that it indicates.
4291
-     *
4292
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4293
-     * @throws EE_Error
4294
-     * @return EE_Model_Field_Base
4295
-     */
4296
-    protected function _deduce_field_from_query_param($query_param_name)
4297
-    {
4298
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4299
-        //which will help us find the database table and column
4300
-        $query_param_parts = explode(".", $query_param_name);
4301
-        if (empty($query_param_parts)) {
4302
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4303
-                'event_espresso'), $query_param_name));
4304
-        }
4305
-        $number_of_parts = count($query_param_parts);
4306
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4307
-        if ($number_of_parts === 1) {
4308
-            $field_name = $last_query_param_part;
4309
-            $model_obj = $this;
4310
-        } else {// $number_of_parts >= 2
4311
-            //the last part is the column name, and there are only 2parts. therefore...
4312
-            $field_name = $last_query_param_part;
4313
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4314
-        }
4315
-        try {
4316
-            return $model_obj->field_settings_for($field_name);
4317
-        } catch (EE_Error $e) {
4318
-            return null;
4319
-        }
4320
-    }
4321
-
4322
-
4323
-
4324
-    /**
4325
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4326
-     * alias and column which corresponds to it
4327
-     *
4328
-     * @param string $field_name
4329
-     * @throws EE_Error
4330
-     * @return string
4331
-     */
4332
-    public function _get_qualified_column_for_field($field_name)
4333
-    {
4334
-        $all_fields = $this->field_settings();
4335
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4336
-        if ($field) {
4337
-            return $field->get_qualified_column();
4338
-        } else {
4339
-            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.",
4340
-                'event_espresso'), $field_name, get_class($this)));
4341
-        }
4342
-    }
4343
-
4344
-
4345
-
4346
-    /**
4347
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4348
-     * Example usage:
4349
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4350
-     *      array(),
4351
-     *      ARRAY_A,
4352
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4353
-     *  );
4354
-     * is equivalent to
4355
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4356
-     * and
4357
-     *  EEM_Event::instance()->get_all_wpdb_results(
4358
-     *      array(
4359
-     *          array(
4360
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4361
-     *          ),
4362
-     *          ARRAY_A,
4363
-     *          implode(
4364
-     *              ', ',
4365
-     *              array_merge(
4366
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4367
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4368
-     *              )
4369
-     *          )
4370
-     *      )
4371
-     *  );
4372
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4373
-     *
4374
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4375
-     *                                            and the one whose fields you are selecting for example: when querying
4376
-     *                                            tickets model and selecting fields from the tickets model you would
4377
-     *                                            leave this parameter empty, because no models are needed to join
4378
-     *                                            between the queried model and the selected one. Likewise when
4379
-     *                                            querying the datetime model and selecting fields from the tickets
4380
-     *                                            model, it would also be left empty, because there is a direct
4381
-     *                                            relation from datetimes to tickets, so no model is needed to join
4382
-     *                                            them together. However, when querying from the event model and
4383
-     *                                            selecting fields from the ticket model, you should provide the string
4384
-     *                                            'Datetime', indicating that the event model must first join to the
4385
-     *                                            datetime model in order to find its relation to ticket model.
4386
-     *                                            Also, when querying from the venue model and selecting fields from
4387
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4388
-     *                                            indicating you need to join the venue model to the event model,
4389
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4390
-     *                                            This string is used to deduce the prefix that gets added onto the
4391
-     *                                            models' tables qualified columns
4392
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4393
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4394
-     *                                            qualified column names
4395
-     * @return array|string
4396
-     */
4397
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4398
-    {
4399
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4400
-        $qualified_columns = array();
4401
-        foreach ($this->field_settings() as $field_name => $field) {
4402
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4403
-        }
4404
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4405
-    }
4406
-
4407
-
4408
-
4409
-    /**
4410
-     * constructs the select use on special limit joins
4411
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4412
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4413
-     * (as that is typically where the limits would be set).
4414
-     *
4415
-     * @param  string       $table_alias The table the select is being built for
4416
-     * @param  mixed|string $limit       The limit for this select
4417
-     * @return string                The final select join element for the query.
4418
-     */
4419
-    public function _construct_limit_join_select($table_alias, $limit)
4420
-    {
4421
-        $SQL = '';
4422
-        foreach ($this->_tables as $table_obj) {
4423
-            if ($table_obj instanceof EE_Primary_Table) {
4424
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4425
-                    ? $table_obj->get_select_join_limit($limit)
4426
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4427
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4428
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4429
-                    ? $table_obj->get_select_join_limit_join($limit)
4430
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4431
-            }
4432
-        }
4433
-        return $SQL;
4434
-    }
4435
-
4436
-
4437
-
4438
-    /**
4439
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4440
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4441
-     *
4442
-     * @return string SQL
4443
-     * @throws \EE_Error
4444
-     */
4445
-    public function _construct_internal_join()
4446
-    {
4447
-        $SQL = $this->_get_main_table()->get_table_sql();
4448
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4449
-        return $SQL;
4450
-    }
4451
-
4452
-
4453
-
4454
-    /**
4455
-     * Constructs the SQL for joining all the tables on this model.
4456
-     * Normally $alias should be the primary table's alias, but in cases where
4457
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4458
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4459
-     * alias, this will construct SQL like:
4460
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4461
-     * With $alias being a secondary table's alias, this will construct SQL like:
4462
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4463
-     *
4464
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4465
-     * @return string
4466
-     */
4467
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4468
-    {
4469
-        $SQL = '';
4470
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4471
-        foreach ($this->_tables as $table_obj) {
4472
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4473
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4474
-                    //so we're joining to this table, meaning the table is already in
4475
-                    //the FROM statement, BUT the primary table isn't. So we want
4476
-                    //to add the inverse join sql
4477
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4478
-                } else {
4479
-                    //just add a regular JOIN to this table from the primary table
4480
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4481
-                }
4482
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4483
-        }
4484
-        return $SQL;
4485
-    }
4486
-
4487
-
4488
-
4489
-    /**
4490
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4491
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4492
-     * their data type (eg, '%s', '%d', etc)
4493
-     *
4494
-     * @return array
4495
-     */
4496
-    public function _get_data_types()
4497
-    {
4498
-        $data_types = array();
4499
-        foreach ($this->field_settings() as $field_obj) {
4500
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4501
-            /** @var $field_obj EE_Model_Field_Base */
4502
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4503
-        }
4504
-        return $data_types;
4505
-    }
4506
-
4507
-
4508
-
4509
-    /**
4510
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4511
-     *
4512
-     * @param string $model_name
4513
-     * @throws EE_Error
4514
-     * @return EEM_Base
4515
-     */
4516
-    public function get_related_model_obj($model_name)
4517
-    {
4518
-        $model_classname = "EEM_" . $model_name;
4519
-        if (! class_exists($model_classname)) {
4520
-            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",
4521
-                'event_espresso'), $model_name, $model_classname));
4522
-        }
4523
-        return call_user_func($model_classname . "::instance");
4524
-    }
4525
-
4526
-
4527
-
4528
-    /**
4529
-     * Returns the array of EE_ModelRelations for this model.
4530
-     *
4531
-     * @return EE_Model_Relation_Base[]
4532
-     */
4533
-    public function relation_settings()
4534
-    {
4535
-        return $this->_model_relations;
4536
-    }
4537
-
4538
-
4539
-
4540
-    /**
4541
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4542
-     * because without THOSE models, this model probably doesn't have much purpose.
4543
-     * (Eg, without an event, datetimes have little purpose.)
4544
-     *
4545
-     * @return EE_Belongs_To_Relation[]
4546
-     */
4547
-    public function belongs_to_relations()
4548
-    {
4549
-        $belongs_to_relations = array();
4550
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4551
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4552
-                $belongs_to_relations[$model_name] = $relation_obj;
4553
-            }
4554
-        }
4555
-        return $belongs_to_relations;
4556
-    }
4557
-
4558
-
4559
-
4560
-    /**
4561
-     * Returns the specified EE_Model_Relation, or throws an exception
4562
-     *
4563
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4564
-     * @throws EE_Error
4565
-     * @return EE_Model_Relation_Base
4566
-     */
4567
-    public function related_settings_for($relation_name)
4568
-    {
4569
-        $relatedModels = $this->relation_settings();
4570
-        if (! array_key_exists($relation_name, $relatedModels)) {
4571
-            throw new EE_Error(
4572
-                sprintf(
4573
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4574
-                        'event_espresso'),
4575
-                    $relation_name,
4576
-                    $this->_get_class_name(),
4577
-                    implode(', ', array_keys($relatedModels))
4578
-                )
4579
-            );
4580
-        }
4581
-        return $relatedModels[$relation_name];
4582
-    }
4583
-
4584
-
4585
-
4586
-    /**
4587
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4588
-     * fields
4589
-     *
4590
-     * @param string $fieldName
4591
-     * @throws EE_Error
4592
-     * @return EE_Model_Field_Base
4593
-     */
4594
-    public function field_settings_for($fieldName)
4595
-    {
4596
-        $fieldSettings = $this->field_settings(true);
4597
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4598
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4599
-                get_class($this)));
4600
-        }
4601
-        return $fieldSettings[$fieldName];
4602
-    }
4603
-
4604
-
4605
-
4606
-    /**
4607
-     * Checks if this field exists on this model
4608
-     *
4609
-     * @param string $fieldName a key in the model's _field_settings array
4610
-     * @return boolean
4611
-     */
4612
-    public function has_field($fieldName)
4613
-    {
4614
-        $fieldSettings = $this->field_settings(true);
4615
-        if (isset($fieldSettings[$fieldName])) {
4616
-            return true;
4617
-        } else {
4618
-            return false;
4619
-        }
4620
-    }
4621
-
4622
-
4623
-
4624
-    /**
4625
-     * Returns whether or not this model has a relation to the specified model
4626
-     *
4627
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4628
-     * @return boolean
4629
-     */
4630
-    public function has_relation($relation_name)
4631
-    {
4632
-        $relations = $this->relation_settings();
4633
-        if (isset($relations[$relation_name])) {
4634
-            return true;
4635
-        } else {
4636
-            return false;
4637
-        }
4638
-    }
4639
-
4640
-
4641
-
4642
-    /**
4643
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4644
-     * Eg, on EE_Answer that would be ANS_ID field object
4645
-     *
4646
-     * @param $field_obj
4647
-     * @return boolean
4648
-     */
4649
-    public function is_primary_key_field($field_obj)
4650
-    {
4651
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4652
-    }
4653
-
4654
-
4655
-
4656
-    /**
4657
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4658
-     * Eg, on EE_Answer that would be ANS_ID field object
4659
-     *
4660
-     * @return EE_Model_Field_Base
4661
-     * @throws EE_Error
4662
-     */
4663
-    public function get_primary_key_field()
4664
-    {
4665
-        if ($this->_primary_key_field === null) {
4666
-            foreach ($this->field_settings(true) as $field_obj) {
4667
-                if ($this->is_primary_key_field($field_obj)) {
4668
-                    $this->_primary_key_field = $field_obj;
4669
-                    break;
4670
-                }
4671
-            }
4672
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4673
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4674
-                    get_class($this)));
4675
-            }
4676
-        }
4677
-        return $this->_primary_key_field;
4678
-    }
4679
-
4680
-
4681
-
4682
-    /**
4683
-     * Returns whether or not not there is a primary key on this model.
4684
-     * Internally does some caching.
4685
-     *
4686
-     * @return boolean
4687
-     */
4688
-    public function has_primary_key_field()
4689
-    {
4690
-        if ($this->_has_primary_key_field === null) {
4691
-            try {
4692
-                $this->get_primary_key_field();
4693
-                $this->_has_primary_key_field = true;
4694
-            } catch (EE_Error $e) {
4695
-                $this->_has_primary_key_field = false;
4696
-            }
4697
-        }
4698
-        return $this->_has_primary_key_field;
4699
-    }
4700
-
4701
-
4702
-
4703
-    /**
4704
-     * Finds the first field of type $field_class_name.
4705
-     *
4706
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4707
-     *                                 EE_Foreign_Key_Field, etc
4708
-     * @return EE_Model_Field_Base or null if none is found
4709
-     */
4710
-    public function get_a_field_of_type($field_class_name)
4711
-    {
4712
-        foreach ($this->field_settings() as $field) {
4713
-            if ($field instanceof $field_class_name) {
4714
-                return $field;
4715
-            }
4716
-        }
4717
-        return null;
4718
-    }
4719
-
4720
-
4721
-
4722
-    /**
4723
-     * Gets a foreign key field pointing to model.
4724
-     *
4725
-     * @param string $model_name eg Event, Registration, not EEM_Event
4726
-     * @return EE_Foreign_Key_Field_Base
4727
-     * @throws EE_Error
4728
-     */
4729
-    public function get_foreign_key_to($model_name)
4730
-    {
4731
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4732
-            foreach ($this->field_settings() as $field) {
4733
-                if (
4734
-                    $field instanceof EE_Foreign_Key_Field_Base
4735
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4736
-                ) {
4737
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4738
-                    break;
4739
-                }
4740
-            }
4741
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4742
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4743
-                    'event_espresso'), $model_name, get_class($this)));
4744
-            }
4745
-        }
4746
-        return $this->_cache_foreign_key_to_fields[$model_name];
4747
-    }
4748
-
4749
-
4750
-
4751
-    /**
4752
-     * Gets the actual table for the table alias
4753
-     *
4754
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4755
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4756
-     *                            Either one works
4757
-     * @return EE_Table_Base
4758
-     */
4759
-    public function get_table_for_alias($table_alias)
4760
-    {
4761
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4762
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4763
-    }
4764
-
4765
-
4766
-
4767
-    /**
4768
-     * Returns a flat array of all field son this model, instead of organizing them
4769
-     * by table_alias as they are in the constructor.
4770
-     *
4771
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4772
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4773
-     */
4774
-    public function field_settings($include_db_only_fields = false)
4775
-    {
4776
-        if ($include_db_only_fields) {
4777
-            if ($this->_cached_fields === null) {
4778
-                $this->_cached_fields = array();
4779
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4780
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4781
-                        $this->_cached_fields[$field_name] = $field_obj;
4782
-                    }
4783
-                }
4784
-            }
4785
-            return $this->_cached_fields;
4786
-        } else {
4787
-            if ($this->_cached_fields_non_db_only === null) {
4788
-                $this->_cached_fields_non_db_only = array();
4789
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4790
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4791
-                        /** @var $field_obj EE_Model_Field_Base */
4792
-                        if (! $field_obj->is_db_only_field()) {
4793
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4794
-                        }
4795
-                    }
4796
-                }
4797
-            }
4798
-            return $this->_cached_fields_non_db_only;
4799
-        }
4800
-    }
4801
-
4802
-
4803
-
4804
-    /**
4805
-     *        cycle though array of attendees and create objects out of each item
4806
-     *
4807
-     * @access        private
4808
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4809
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4810
-     *                           numerically indexed)
4811
-     * @throws \EE_Error
4812
-     */
4813
-    protected function _create_objects($rows = array())
4814
-    {
4815
-        $array_of_objects = array();
4816
-        if (empty($rows)) {
4817
-            return array();
4818
-        }
4819
-        $count_if_model_has_no_primary_key = 0;
4820
-        $has_primary_key = $this->has_primary_key_field();
4821
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4822
-        foreach ((array)$rows as $row) {
4823
-            if (empty($row)) {
4824
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4825
-                return array();
4826
-            }
4827
-            //check if we've already set this object in the results array,
4828
-            //in which case there's no need to process it further (again)
4829
-            if ($has_primary_key) {
4830
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4831
-                    $row,
4832
-                    $primary_key_field->get_qualified_column(),
4833
-                    $primary_key_field->get_table_column()
4834
-                );
4835
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4836
-                    continue;
4837
-                }
4838
-            }
4839
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4840
-            if (! $classInstance) {
4841
-                throw new EE_Error(
4842
-                    sprintf(
4843
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4844
-                        $this->get_this_model_name(),
4845
-                        http_build_query($row)
4846
-                    )
4847
-                );
4848
-            }
4849
-            //set the timezone on the instantiated objects
4850
-            $classInstance->set_timezone($this->_timezone);
4851
-            //make sure if there is any timezone setting present that we set the timezone for the object
4852
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4853
-            $array_of_objects[$key] = $classInstance;
4854
-            //also, for all the relations of type BelongsTo, see if we can cache
4855
-            //those related models
4856
-            //(we could do this for other relations too, but if there are conditions
4857
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4858
-            //so it requires a little more thought than just caching them immediately...)
4859
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4860
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4861
-                    //check if this model's INFO is present. If so, cache it on the model
4862
-                    $other_model = $relation_obj->get_other_model();
4863
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4864
-                    //if we managed to make a model object from the results, cache it on the main model object
4865
-                    if ($other_model_obj_maybe) {
4866
-                        //set timezone on these other model objects if they are present
4867
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4868
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4869
-                    }
4870
-                }
4871
-            }
4872
-        }
4873
-        return $array_of_objects;
4874
-    }
4875
-
4876
-
4877
-
4878
-    /**
4879
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4880
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4881
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4882
-     * object (as set in the model_field!).
4883
-     *
4884
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4885
-     */
4886
-    public function create_default_object()
4887
-    {
4888
-        $this_model_fields_and_values = array();
4889
-        //setup the row using default values;
4890
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4891
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4892
-        }
4893
-        $className = $this->_get_class_name();
4894
-        $classInstance = EE_Registry::instance()
4895
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4896
-        return $classInstance;
4897
-    }
4898
-
4899
-
4900
-
4901
-    /**
4902
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4903
-     *                             or an stdClass where each property is the name of a column,
4904
-     * @return EE_Base_Class
4905
-     * @throws \EE_Error
4906
-     */
4907
-    public function instantiate_class_from_array_or_object($cols_n_values)
4908
-    {
4909
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4910
-            $cols_n_values = get_object_vars($cols_n_values);
4911
-        }
4912
-        $primary_key = null;
4913
-        //make sure the array only has keys that are fields/columns on this model
4914
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4915
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4916
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4917
-        }
4918
-        $className = $this->_get_class_name();
4919
-        //check we actually found results that we can use to build our model object
4920
-        //if not, return null
4921
-        if ($this->has_primary_key_field()) {
4922
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4923
-                return null;
4924
-            }
4925
-        } else if ($this->unique_indexes()) {
4926
-            $first_column = reset($this_model_fields_n_values);
4927
-            if (empty($first_column)) {
4928
-                return null;
4929
-            }
4930
-        }
4931
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4932
-        if ($primary_key) {
4933
-            $classInstance = $this->get_from_entity_map($primary_key);
4934
-            if (! $classInstance) {
4935
-                $classInstance = EE_Registry::instance()
4936
-                                            ->load_class($className,
4937
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4938
-                // add this new object to the entity map
4939
-                $classInstance = $this->add_to_entity_map($classInstance);
4940
-            }
4941
-        } else {
4942
-            $classInstance = EE_Registry::instance()
4943
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4944
-                                            true, false);
4945
-        }
4946
-        //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.
4947
-        $this->set_timezone($classInstance->get_timezone());
4948
-        return $classInstance;
4949
-    }
4950
-
4951
-
4952
-
4953
-    /**
4954
-     * Gets the model object from the  entity map if it exists
4955
-     *
4956
-     * @param int|string $id the ID of the model object
4957
-     * @return EE_Base_Class
4958
-     */
4959
-    public function get_from_entity_map($id)
4960
-    {
4961
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4962
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4963
-    }
4964
-
4965
-
4966
-
4967
-    /**
4968
-     * add_to_entity_map
4969
-     * Adds the object to the model's entity mappings
4970
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4971
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4972
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4973
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4974
-     *        then this method should be called immediately after the update query
4975
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4976
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4977
-     *
4978
-     * @param    EE_Base_Class $object
4979
-     * @throws EE_Error
4980
-     * @return \EE_Base_Class
4981
-     */
4982
-    public function add_to_entity_map(EE_Base_Class $object)
4983
-    {
4984
-        $className = $this->_get_class_name();
4985
-        if (! $object instanceof $className) {
4986
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4987
-                is_object($object) ? get_class($object) : $object, $className));
4988
-        }
4989
-        /** @var $object EE_Base_Class */
4990
-        if (! $object->ID()) {
4991
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4992
-                "event_espresso"), get_class($this)));
4993
-        }
4994
-        // double check it's not already there
4995
-        $classInstance = $this->get_from_entity_map($object->ID());
4996
-        if ($classInstance) {
4997
-            return $classInstance;
4998
-        } else {
4999
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5000
-            return $object;
5001
-        }
5002
-    }
5003
-
5004
-
5005
-
5006
-    /**
5007
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5008
-     * if no identifier is provided, then the entire entity map is emptied
5009
-     *
5010
-     * @param int|string $id the ID of the model object
5011
-     * @return boolean
5012
-     */
5013
-    public function clear_entity_map($id = null)
5014
-    {
5015
-        if (empty($id)) {
5016
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5017
-            return true;
5018
-        }
5019
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5020
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5021
-            return true;
5022
-        }
5023
-        return false;
5024
-    }
5025
-
5026
-
5027
-
5028
-    /**
5029
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5030
-     * Given an array where keys are column (or column alias) names and values,
5031
-     * returns an array of their corresponding field names and database values
5032
-     *
5033
-     * @param array $cols_n_values
5034
-     * @return array
5035
-     */
5036
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5037
-    {
5038
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5039
-    }
5040
-
5041
-
5042
-
5043
-    /**
5044
-     * _deduce_fields_n_values_from_cols_n_values
5045
-     * Given an array where keys are column (or column alias) names and values,
5046
-     * returns an array of their corresponding field names and database values
5047
-     *
5048
-     * @param string $cols_n_values
5049
-     * @return array
5050
-     */
5051
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5052
-    {
5053
-        $this_model_fields_n_values = array();
5054
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5055
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5056
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5057
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5058
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5059
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5060
-                    if (! $field_obj->is_db_only_field()) {
5061
-                        //prepare field as if its coming from db
5062
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5063
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5064
-                    }
5065
-                }
5066
-            } else {
5067
-                //the table's rows existed. Use their values
5068
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5069
-                    if (! $field_obj->is_db_only_field()) {
5070
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5071
-                            $cols_n_values, $field_obj->get_qualified_column(),
5072
-                            $field_obj->get_table_column()
5073
-                        );
5074
-                    }
5075
-                }
5076
-            }
5077
-        }
5078
-        return $this_model_fields_n_values;
5079
-    }
5080
-
5081
-
5082
-
5083
-    /**
5084
-     * @param $cols_n_values
5085
-     * @param $qualified_column
5086
-     * @param $regular_column
5087
-     * @return null
5088
-     */
5089
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5090
-    {
5091
-        $value = null;
5092
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5093
-        //does the field on the model relate to this column retrieved from the db?
5094
-        //or is it a db-only field? (not relating to the model)
5095
-        if (isset($cols_n_values[$qualified_column])) {
5096
-            $value = $cols_n_values[$qualified_column];
5097
-        } elseif (isset($cols_n_values[$regular_column])) {
5098
-            $value = $cols_n_values[$regular_column];
5099
-        }
5100
-        return $value;
5101
-    }
5102
-
5103
-
5104
-
5105
-    /**
5106
-     * refresh_entity_map_from_db
5107
-     * Makes sure the model object in the entity map at $id assumes the values
5108
-     * of the database (opposite of EE_base_Class::save())
5109
-     *
5110
-     * @param int|string $id
5111
-     * @return EE_Base_Class
5112
-     * @throws \EE_Error
5113
-     */
5114
-    public function refresh_entity_map_from_db($id)
5115
-    {
5116
-        $obj_in_map = $this->get_from_entity_map($id);
5117
-        if ($obj_in_map) {
5118
-            $wpdb_results = $this->_get_all_wpdb_results(
5119
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5120
-            );
5121
-            if ($wpdb_results && is_array($wpdb_results)) {
5122
-                $one_row = reset($wpdb_results);
5123
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5124
-                    $obj_in_map->set_from_db($field_name, $db_value);
5125
-                }
5126
-                //clear the cache of related model objects
5127
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5128
-                    $obj_in_map->clear_cache($relation_name, null, true);
5129
-                }
5130
-            }
5131
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5132
-            return $obj_in_map;
5133
-        } else {
5134
-            return $this->get_one_by_ID($id);
5135
-        }
5136
-    }
5137
-
5138
-
5139
-
5140
-    /**
5141
-     * refresh_entity_map_with
5142
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5143
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5144
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5145
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5146
-     *
5147
-     * @param int|string    $id
5148
-     * @param EE_Base_Class $replacing_model_obj
5149
-     * @return \EE_Base_Class
5150
-     * @throws \EE_Error
5151
-     */
5152
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5153
-    {
5154
-        $obj_in_map = $this->get_from_entity_map($id);
5155
-        if ($obj_in_map) {
5156
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5157
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5158
-                    $obj_in_map->set($field_name, $value);
5159
-                }
5160
-                //make the model object in the entity map's cache match the $replacing_model_obj
5161
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5162
-                    $obj_in_map->clear_cache($relation_name, null, true);
5163
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5164
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5165
-                    }
5166
-                }
5167
-            }
5168
-            return $obj_in_map;
5169
-        } else {
5170
-            $this->add_to_entity_map($replacing_model_obj);
5171
-            return $replacing_model_obj;
5172
-        }
5173
-    }
5174
-
5175
-
5176
-
5177
-    /**
5178
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5179
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5180
-     * require_once($this->_getClassName().".class.php");
5181
-     *
5182
-     * @return string
5183
-     */
5184
-    private function _get_class_name()
5185
-    {
5186
-        return "EE_" . $this->get_this_model_name();
5187
-    }
5188
-
5189
-
5190
-
5191
-    /**
5192
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5193
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5194
-     * it would be 'Events'.
5195
-     *
5196
-     * @param int $quantity
5197
-     * @return string
5198
-     */
5199
-    public function item_name($quantity = 1)
5200
-    {
5201
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5202
-    }
5203
-
5204
-
5205
-
5206
-    /**
5207
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5208
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5209
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5210
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5211
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5212
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5213
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5214
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5215
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5216
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5217
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5218
-     *        return $previousReturnValue.$returnString;
5219
-     * }
5220
-     * require('EEM_Answer.model.php');
5221
-     * $answer=EEM_Answer::instance();
5222
-     * echo $answer->my_callback('monkeys',100);
5223
-     * //will output "you called my_callback! and passed args:monkeys,100"
5224
-     *
5225
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5226
-     * @param array  $args       array of original arguments passed to the function
5227
-     * @throws EE_Error
5228
-     * @return mixed whatever the plugin which calls add_filter decides
5229
-     */
5230
-    public function __call($methodName, $args)
5231
-    {
5232
-        $className = get_class($this);
5233
-        $tagName = "FHEE__{$className}__{$methodName}";
5234
-        if (! has_filter($tagName)) {
5235
-            throw new EE_Error(
5236
-                sprintf(
5237
-                    __('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 );',
5238
-                        'event_espresso'),
5239
-                    $methodName,
5240
-                    $className,
5241
-                    $tagName,
5242
-                    '<br />'
5243
-                )
5244
-            );
5245
-        }
5246
-        return apply_filters($tagName, null, $this, $args);
5247
-    }
5248
-
5249
-
5250
-
5251
-    /**
5252
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5253
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5254
-     *
5255
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5256
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5257
-     *                                                       the object's class name
5258
-     *                                                       or object's ID
5259
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5260
-     *                                                       exists in the database. If it does not, we add it
5261
-     * @throws EE_Error
5262
-     * @return EE_Base_Class
5263
-     */
5264
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5265
-    {
5266
-        $className = $this->_get_class_name();
5267
-        if ($base_class_obj_or_id instanceof $className) {
5268
-            $model_object = $base_class_obj_or_id;
5269
-        } else {
5270
-            $primary_key_field = $this->get_primary_key_field();
5271
-            if (
5272
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5273
-                && (
5274
-                    is_int($base_class_obj_or_id)
5275
-                    || is_string($base_class_obj_or_id)
5276
-                )
5277
-            ) {
5278
-                // assume it's an ID.
5279
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5280
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5281
-            } else if (
5282
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5283
-                && is_string($base_class_obj_or_id)
5284
-            ) {
5285
-                // assume its a string representation of the object
5286
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5287
-            } else {
5288
-                throw new EE_Error(
5289
-                    sprintf(
5290
-                        __(
5291
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5292
-                            'event_espresso'
5293
-                        ),
5294
-                        $base_class_obj_or_id,
5295
-                        $this->_get_class_name(),
5296
-                        print_r($base_class_obj_or_id, true)
5297
-                    )
5298
-                );
5299
-            }
5300
-        }
5301
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5302
-            $model_object->save();
5303
-        }
5304
-        return $model_object;
5305
-    }
5306
-
5307
-
5308
-
5309
-    /**
5310
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5311
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5312
-     * returns it ID.
5313
-     *
5314
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5315
-     * @return int|string depending on the type of this model object's ID
5316
-     * @throws EE_Error
5317
-     */
5318
-    public function ensure_is_ID($base_class_obj_or_id)
5319
-    {
5320
-        $className = $this->_get_class_name();
5321
-        if ($base_class_obj_or_id instanceof $className) {
5322
-            /** @var $base_class_obj_or_id EE_Base_Class */
5323
-            $id = $base_class_obj_or_id->ID();
5324
-        } elseif (is_int($base_class_obj_or_id)) {
5325
-            //assume it's an ID
5326
-            $id = $base_class_obj_or_id;
5327
-        } elseif (is_string($base_class_obj_or_id)) {
5328
-            //assume its a string representation of the object
5329
-            $id = $base_class_obj_or_id;
5330
-        } else {
5331
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5332
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5333
-                print_r($base_class_obj_or_id, true)));
5334
-        }
5335
-        return $id;
5336
-    }
5337
-
5338
-
5339
-
5340
-    /**
5341
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5342
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5343
-     * been sanitized and converted into the appropriate domain.
5344
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5345
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5346
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5347
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5348
-     * $EVT = EEM_Event::instance(); $old_setting =
5349
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5350
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5351
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5352
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5353
-     *
5354
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5355
-     * @return void
5356
-     */
5357
-    public function assume_values_already_prepared_by_model_object(
5358
-        $values_already_prepared = self::not_prepared_by_model_object
5359
-    ) {
5360
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5361
-    }
5362
-
5363
-
5364
-
5365
-    /**
5366
-     * Read comments for assume_values_already_prepared_by_model_object()
5367
-     *
5368
-     * @return int
5369
-     */
5370
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5371
-    {
5372
-        return $this->_values_already_prepared_by_model_object;
5373
-    }
5374
-
5375
-
5376
-
5377
-    /**
5378
-     * Gets all the indexes on this model
5379
-     *
5380
-     * @return EE_Index[]
5381
-     */
5382
-    public function indexes()
5383
-    {
5384
-        return $this->_indexes;
5385
-    }
5386
-
5387
-
5388
-
5389
-    /**
5390
-     * Gets all the Unique Indexes on this model
5391
-     *
5392
-     * @return EE_Unique_Index[]
5393
-     */
5394
-    public function unique_indexes()
5395
-    {
5396
-        $unique_indexes = array();
5397
-        foreach ($this->_indexes as $name => $index) {
5398
-            if ($index instanceof EE_Unique_Index) {
5399
-                $unique_indexes [$name] = $index;
5400
-            }
5401
-        }
5402
-        return $unique_indexes;
5403
-    }
5404
-
5405
-
5406
-
5407
-    /**
5408
-     * Gets all the fields which, when combined, make the primary key.
5409
-     * This is usually just an array with 1 element (the primary key), but in cases
5410
-     * where there is no primary key, it's a combination of fields as defined
5411
-     * on a primary index
5412
-     *
5413
-     * @return EE_Model_Field_Base[] indexed by the field's name
5414
-     * @throws \EE_Error
5415
-     */
5416
-    public function get_combined_primary_key_fields()
5417
-    {
5418
-        foreach ($this->indexes() as $index) {
5419
-            if ($index instanceof EE_Primary_Key_Index) {
5420
-                return $index->fields();
5421
-            }
5422
-        }
5423
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5424
-    }
5425
-
5426
-
5427
-
5428
-    /**
5429
-     * Used to build a primary key string (when the model has no primary key),
5430
-     * which can be used a unique string to identify this model object.
5431
-     *
5432
-     * @param array $cols_n_values keys are field names, values are their values
5433
-     * @return string
5434
-     * @throws \EE_Error
5435
-     */
5436
-    public function get_index_primary_key_string($cols_n_values)
5437
-    {
5438
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5439
-            $this->get_combined_primary_key_fields());
5440
-        return http_build_query($cols_n_values_for_primary_key_index);
5441
-    }
5442
-
5443
-
5444
-
5445
-    /**
5446
-     * Gets the field values from the primary key string
5447
-     *
5448
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5449
-     * @param string $index_primary_key_string
5450
-     * @return null|array
5451
-     * @throws \EE_Error
5452
-     */
5453
-    public function parse_index_primary_key_string($index_primary_key_string)
5454
-    {
5455
-        $key_fields = $this->get_combined_primary_key_fields();
5456
-        //check all of them are in the $id
5457
-        $key_vals_in_combined_pk = array();
5458
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5459
-        foreach ($key_fields as $key_field_name => $field_obj) {
5460
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5461
-                return null;
5462
-            }
5463
-        }
5464
-        return $key_vals_in_combined_pk;
5465
-    }
5466
-
5467
-
5468
-
5469
-    /**
5470
-     * verifies that an array of key-value pairs for model fields has a key
5471
-     * for each field comprising the primary key index
5472
-     *
5473
-     * @param array $key_vals
5474
-     * @return boolean
5475
-     * @throws \EE_Error
5476
-     */
5477
-    public function has_all_combined_primary_key_fields($key_vals)
5478
-    {
5479
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5480
-        foreach ($keys_it_should_have as $key) {
5481
-            if (! isset($key_vals[$key])) {
5482
-                return false;
5483
-            }
5484
-        }
5485
-        return true;
5486
-    }
5487
-
5488
-
5489
-
5490
-    /**
5491
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5492
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5493
-     *
5494
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5495
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5496
-     * @throws EE_Error
5497
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5498
-     *                                                              indexed)
5499
-     */
5500
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5501
-    {
5502
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5503
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5504
-        } elseif (is_array($model_object_or_attributes_array)) {
5505
-            $attributes_array = $model_object_or_attributes_array;
5506
-        } else {
5507
-            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",
5508
-                "event_espresso"), $model_object_or_attributes_array));
5509
-        }
5510
-        //even copies obviously won't have the same ID, so remove the primary key
5511
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5512
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5513
-            unset($attributes_array[$this->primary_key_name()]);
5514
-        }
5515
-        if (isset($query_params[0])) {
5516
-            $query_params[0] = array_merge($attributes_array, $query_params);
5517
-        } else {
5518
-            $query_params[0] = $attributes_array;
5519
-        }
5520
-        return $this->get_all($query_params);
5521
-    }
5522
-
5523
-
5524
-
5525
-    /**
5526
-     * Gets the first copy we find. See get_all_copies for more details
5527
-     *
5528
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5529
-     * @param array $query_params
5530
-     * @return EE_Base_Class
5531
-     * @throws \EE_Error
5532
-     */
5533
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5534
-    {
5535
-        if (! is_array($query_params)) {
5536
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5537
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5538
-                    gettype($query_params)), '4.6.0');
5539
-            $query_params = array();
5540
-        }
5541
-        $query_params['limit'] = 1;
5542
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5543
-        if (is_array($copies)) {
5544
-            return array_shift($copies);
5545
-        } else {
5546
-            return null;
5547
-        }
5548
-    }
5549
-
5550
-
5551
-
5552
-    /**
5553
-     * Updates the item with the specified id. Ignores default query parameters because
5554
-     * we have specified the ID, and its assumed we KNOW what we're doing
5555
-     *
5556
-     * @param array      $fields_n_values keys are field names, values are their new values
5557
-     * @param int|string $id              the value of the primary key to update
5558
-     * @return int number of rows updated
5559
-     * @throws \EE_Error
5560
-     */
5561
-    public function update_by_ID($fields_n_values, $id)
5562
-    {
5563
-        $query_params = array(
5564
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5565
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5566
-        );
5567
-        return $this->update($fields_n_values, $query_params);
5568
-    }
5569
-
5570
-
5571
-
5572
-    /**
5573
-     * Changes an operator which was supplied to the models into one usable in SQL
5574
-     *
5575
-     * @param string $operator_supplied
5576
-     * @return string an operator which can be used in SQL
5577
-     * @throws EE_Error
5578
-     */
5579
-    private function _prepare_operator_for_sql($operator_supplied)
5580
-    {
5581
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5582
-            : null;
5583
-        if ($sql_operator) {
5584
-            return $sql_operator;
5585
-        } else {
5586
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5587
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5588
-        }
5589
-    }
5590
-
5591
-
5592
-
5593
-    /**
5594
-     * Gets an array where keys are the primary keys and values are their 'names'
5595
-     * (as determined by the model object's name() function, which is often overridden)
5596
-     *
5597
-     * @param array $query_params like get_all's
5598
-     * @return string[]
5599
-     * @throws \EE_Error
5600
-     */
5601
-    public function get_all_names($query_params = array())
5602
-    {
5603
-        $objs = $this->get_all($query_params);
5604
-        $names = array();
5605
-        foreach ($objs as $obj) {
5606
-            $names[$obj->ID()] = $obj->name();
5607
-        }
5608
-        return $names;
5609
-    }
5610
-
5611
-
5612
-
5613
-    /**
5614
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5615
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5616
-     * this is duplicated effort and reduces efficiency) you would be better to use
5617
-     * array_keys() on $model_objects.
5618
-     *
5619
-     * @param \EE_Base_Class[] $model_objects
5620
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5621
-     *                                               in the returned array
5622
-     * @return array
5623
-     * @throws \EE_Error
5624
-     */
5625
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5626
-    {
5627
-        if (! $this->has_primary_key_field()) {
5628
-            if (WP_DEBUG) {
5629
-                EE_Error::add_error(
5630
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5631
-                    __FILE__,
5632
-                    __FUNCTION__,
5633
-                    __LINE__
5634
-                );
5635
-            }
5636
-        }
5637
-        $IDs = array();
5638
-        foreach ($model_objects as $model_object) {
5639
-            $id = $model_object->ID();
5640
-            if (! $id) {
5641
-                if ($filter_out_empty_ids) {
5642
-                    continue;
5643
-                }
5644
-                if (WP_DEBUG) {
5645
-                    EE_Error::add_error(
5646
-                        __(
5647
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5648
-                            'event_espresso'
5649
-                        ),
5650
-                        __FILE__,
5651
-                        __FUNCTION__,
5652
-                        __LINE__
5653
-                    );
5654
-                }
5655
-            }
5656
-            $IDs[] = $id;
5657
-        }
5658
-        return $IDs;
5659
-    }
5660
-
5661
-
5662
-
5663
-    /**
5664
-     * Returns the string used in capabilities relating to this model. If there
5665
-     * are no capabilities that relate to this model returns false
5666
-     *
5667
-     * @return string|false
5668
-     */
5669
-    public function cap_slug()
5670
-    {
5671
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5672
-    }
5673
-
5674
-
5675
-
5676
-    /**
5677
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5678
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5679
-     * only returns the cap restrictions array in that context (ie, the array
5680
-     * at that key)
5681
-     *
5682
-     * @param string $context
5683
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5684
-     * @throws \EE_Error
5685
-     */
5686
-    public function cap_restrictions($context = EEM_Base::caps_read)
5687
-    {
5688
-        EEM_Base::verify_is_valid_cap_context($context);
5689
-        //check if we ought to run the restriction generator first
5690
-        if (
5691
-            isset($this->_cap_restriction_generators[$context])
5692
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5693
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5694
-        ) {
5695
-            $this->_cap_restrictions[$context] = array_merge(
5696
-                $this->_cap_restrictions[$context],
5697
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5698
-            );
5699
-        }
5700
-        //and make sure we've finalized the construction of each restriction
5701
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5702
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5703
-                $where_conditions_obj->_finalize_construct($this);
5704
-            }
5705
-        }
5706
-        return $this->_cap_restrictions[$context];
5707
-    }
5708
-
5709
-
5710
-
5711
-    /**
5712
-     * Indicating whether or not this model thinks its a wp core model
5713
-     *
5714
-     * @return boolean
5715
-     */
5716
-    public function is_wp_core_model()
5717
-    {
5718
-        return $this->_wp_core_model;
5719
-    }
5720
-
5721
-
5722
-
5723
-    /**
5724
-     * Gets all the caps that are missing which impose a restriction on
5725
-     * queries made in this context
5726
-     *
5727
-     * @param string $context one of EEM_Base::caps_ constants
5728
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5729
-     * @throws \EE_Error
5730
-     */
5731
-    public function caps_missing($context = EEM_Base::caps_read)
5732
-    {
5733
-        $missing_caps = array();
5734
-        $cap_restrictions = $this->cap_restrictions($context);
5735
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5736
-            if (! EE_Capabilities::instance()
5737
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5738
-            ) {
5739
-                $missing_caps[$cap] = $restriction_if_no_cap;
5740
-            }
5741
-        }
5742
-        return $missing_caps;
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Gets the mapping from capability contexts to action strings used in capability names
5749
-     *
5750
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5751
-     * one of 'read', 'edit', or 'delete'
5752
-     */
5753
-    public function cap_contexts_to_cap_action_map()
5754
-    {
5755
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5756
-            $this);
5757
-    }
5758
-
5759
-
5760
-
5761
-    /**
5762
-     * Gets the action string for the specified capability context
5763
-     *
5764
-     * @param string $context
5765
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5766
-     * @throws \EE_Error
5767
-     */
5768
-    public function cap_action_for_context($context)
5769
-    {
5770
-        $mapping = $this->cap_contexts_to_cap_action_map();
5771
-        if (isset($mapping[$context])) {
5772
-            return $mapping[$context];
5773
-        }
5774
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5775
-            return $action;
5776
-        }
5777
-        throw new EE_Error(
5778
-            sprintf(
5779
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5780
-                $context,
5781
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5782
-            )
5783
-        );
5784
-    }
5785
-
5786
-
5787
-
5788
-    /**
5789
-     * Returns all the capability contexts which are valid when querying models
5790
-     *
5791
-     * @return array
5792
-     */
5793
-    public static function valid_cap_contexts()
5794
-    {
5795
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5796
-            self::caps_read,
5797
-            self::caps_read_admin,
5798
-            self::caps_edit,
5799
-            self::caps_delete,
5800
-        ));
5801
-    }
5802
-
5803
-
5804
-
5805
-    /**
5806
-     * Returns all valid options for 'default_where_conditions'
5807
-     *
5808
-     * @return array
5809
-     */
5810
-    public static function valid_default_where_conditions()
5811
-    {
5812
-        return array(
5813
-            EEM_Base::default_where_conditions_all,
5814
-            EEM_Base::default_where_conditions_this_only,
5815
-            EEM_Base::default_where_conditions_others_only,
5816
-            EEM_Base::default_where_conditions_minimum_all,
5817
-            EEM_Base::default_where_conditions_minimum_others,
5818
-            EEM_Base::default_where_conditions_none
5819
-        );
5820
-    }
5821
-
5822
-    // public static function default_where_conditions_full
5823
-    /**
5824
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5825
-     *
5826
-     * @param string $context
5827
-     * @return bool
5828
-     * @throws \EE_Error
5829
-     */
5830
-    static public function verify_is_valid_cap_context($context)
5831
-    {
5832
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5833
-        if (in_array($context, $valid_cap_contexts)) {
5834
-            return true;
5835
-        } else {
5836
-            throw new EE_Error(
5837
-                sprintf(
5838
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5839
-                        'event_espresso'),
5840
-                    $context,
5841
-                    'EEM_Base',
5842
-                    implode(',', $valid_cap_contexts)
5843
-                )
5844
-            );
5845
-        }
5846
-    }
5847
-
5848
-
5849
-
5850
-    /**
5851
-     * Clears all the models field caches. This is only useful when a sub-class
5852
-     * might have added a field or something and these caches might be invalidated
5853
-     */
5854
-    protected function _invalidate_field_caches()
5855
-    {
5856
-        $this->_cache_foreign_key_to_fields = array();
5857
-        $this->_cached_fields = null;
5858
-        $this->_cached_fields_non_db_only = null;
5859
-    }
5860
-
5861
-
5862
-
5863
-    /**
5864
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5865
-     * (eg "and", "or", "not").
5866
-     *
5867
-     * @return array
5868
-     */
5869
-    public function logic_query_param_keys()
5870
-    {
5871
-        return $this->_logic_query_param_keys;
5872
-    }
5873
-
5874
-
5875
-
5876
-    /**
5877
-     * Determines whether or not the where query param array key is for a logic query param.
5878
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5879
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5880
-     *
5881
-     * @param $query_param_key
5882
-     * @return bool
5883
-     */
5884
-    public function is_logic_query_param_key($query_param_key)
5885
-    {
5886
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5887
-            if ($query_param_key === $logic_query_param_key
5888
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5889
-            ) {
5890
-                return true;
5891
-            }
5892
-        }
5893
-        return false;
5894
-    }
3654
+		}
3655
+		return $null_friendly_where_conditions;
3656
+	}
3657
+
3658
+
3659
+
3660
+	/**
3661
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3662
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3663
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3664
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3665
+	 *
3666
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3667
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3668
+	 */
3669
+	private function _get_default_where_conditions($model_relation_path = null)
3670
+	{
3671
+		if ($this->_ignore_where_strategy) {
3672
+			return array();
3673
+		}
3674
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3675
+	}
3676
+
3677
+
3678
+
3679
+	/**
3680
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3681
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3682
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3683
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3684
+	 * Similar to _get_default_where_conditions
3685
+	 *
3686
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3687
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3688
+	 */
3689
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3690
+	{
3691
+		if ($this->_ignore_where_strategy) {
3692
+			return array();
3693
+		}
3694
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3695
+	}
3696
+
3697
+
3698
+
3699
+	/**
3700
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3701
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3702
+	 *
3703
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3704
+	 * @return string
3705
+	 * @throws \EE_Error
3706
+	 */
3707
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3708
+	{
3709
+		$selects = $this->_get_columns_to_select_for_this_model();
3710
+		foreach (
3711
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3712
+			$name_of_other_model_included
3713
+		) {
3714
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3715
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3716
+			foreach ($other_model_selects as $key => $value) {
3717
+				$selects[] = $value;
3718
+			}
3719
+		}
3720
+		return implode(", ", $selects);
3721
+	}
3722
+
3723
+
3724
+
3725
+	/**
3726
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3727
+	 * So that's going to be the columns for all the fields on the model
3728
+	 *
3729
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3730
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3731
+	 */
3732
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3733
+	{
3734
+		$fields = $this->field_settings();
3735
+		$selects = array();
3736
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3737
+			$this->get_this_model_name());
3738
+		foreach ($fields as $field_obj) {
3739
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3740
+						 . $field_obj->get_table_alias()
3741
+						 . "."
3742
+						 . $field_obj->get_table_column()
3743
+						 . " AS '"
3744
+						 . $table_alias_with_model_relation_chain_prefix
3745
+						 . $field_obj->get_table_alias()
3746
+						 . "."
3747
+						 . $field_obj->get_table_column()
3748
+						 . "'";
3749
+		}
3750
+		//make sure we are also getting the PKs of each table
3751
+		$tables = $this->get_tables();
3752
+		if (count($tables) > 1) {
3753
+			foreach ($tables as $table_obj) {
3754
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3755
+									   . $table_obj->get_fully_qualified_pk_column();
3756
+				if (! in_array($qualified_pk_column, $selects)) {
3757
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3758
+				}
3759
+			}
3760
+		}
3761
+		return $selects;
3762
+	}
3763
+
3764
+
3765
+
3766
+	/**
3767
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3768
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3769
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3770
+	 * SQL for joining, and the data types
3771
+	 *
3772
+	 * @param null|string                 $original_query_param
3773
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3774
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3775
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3776
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3777
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3778
+	 *                                                          or 'Registration's
3779
+	 * @param string                      $original_query_param what it originally was (eg
3780
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3781
+	 *                                                          matches $query_param
3782
+	 * @throws EE_Error
3783
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3784
+	 */
3785
+	private function _extract_related_model_info_from_query_param(
3786
+		$query_param,
3787
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3788
+		$query_param_type,
3789
+		$original_query_param = null
3790
+	) {
3791
+		if ($original_query_param === null) {
3792
+			$original_query_param = $query_param;
3793
+		}
3794
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3795
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3796
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3797
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3798
+		//check to see if we have a field on this model
3799
+		$this_model_fields = $this->field_settings(true);
3800
+		if (array_key_exists($query_param, $this_model_fields)) {
3801
+			if ($allow_fields) {
3802
+				return;
3803
+			} else {
3804
+				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",
3805
+					"event_espresso"),
3806
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3807
+			}
3808
+		} //check if this is a special logic query param
3809
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3810
+			if ($allow_logic_query_params) {
3811
+				return;
3812
+			} else {
3813
+				throw new EE_Error(
3814
+					sprintf(
3815
+						__('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',
3816
+							'event_espresso'),
3817
+						implode('", "', $this->_logic_query_param_keys),
3818
+						$query_param,
3819
+						get_class($this),
3820
+						'<br />',
3821
+						"\t"
3822
+						. ' $passed_in_query_info = <pre>'
3823
+						. print_r($passed_in_query_info, true)
3824
+						. '</pre>'
3825
+						. "\n\t"
3826
+						. ' $query_param_type = '
3827
+						. $query_param_type
3828
+						. "\n\t"
3829
+						. ' $original_query_param = '
3830
+						. $original_query_param
3831
+					)
3832
+				);
3833
+			}
3834
+		} //check if it's a custom selection
3835
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3836
+			return;
3837
+		}
3838
+		//check if has a model name at the beginning
3839
+		//and
3840
+		//check if it's a field on a related model
3841
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3842
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3843
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3844
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3845
+				if ($query_param === '') {
3846
+					//nothing left to $query_param
3847
+					//we should actually end in a field name, not a model like this!
3848
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3849
+						"event_espresso"),
3850
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3851
+				} else {
3852
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3853
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3854
+						$passed_in_query_info, $query_param_type, $original_query_param);
3855
+					return;
3856
+				}
3857
+			} elseif ($query_param === $valid_related_model_name) {
3858
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3859
+				return;
3860
+			}
3861
+		}
3862
+		//ok so $query_param didn't start with a model name
3863
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3864
+		//it's wack, that's what it is
3865
+		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",
3866
+			"event_espresso"),
3867
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3868
+	}
3869
+
3870
+
3871
+
3872
+	/**
3873
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3874
+	 * and store it on $passed_in_query_info
3875
+	 *
3876
+	 * @param string                      $model_name
3877
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3878
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3879
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3880
+	 *                                                          and are adding a join to 'Payment' with the original
3881
+	 *                                                          query param key
3882
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3883
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3884
+	 *                                                          Payment wants to add default query params so that it
3885
+	 *                                                          will know what models to prepend onto its default query
3886
+	 *                                                          params or in case it wants to rename tables (in case
3887
+	 *                                                          there are multiple joins to the same table)
3888
+	 * @return void
3889
+	 * @throws \EE_Error
3890
+	 */
3891
+	private function _add_join_to_model(
3892
+		$model_name,
3893
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3894
+		$original_query_param
3895
+	) {
3896
+		$relation_obj = $this->related_settings_for($model_name);
3897
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3898
+		//check if the relation is HABTM, because then we're essentially doing two joins
3899
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3900
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3901
+			$join_model_obj = $relation_obj->get_join_model();
3902
+			//replace the model specified with the join model for this relation chain, whi
3903
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3904
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3905
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3906
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3907
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3908
+			$passed_in_query_info->merge($new_query_info);
3909
+		}
3910
+		//now just join to the other table pointed to by the relation object, and add its data types
3911
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3912
+			array($model_relation_chain => $model_name),
3913
+			$relation_obj->get_join_statement($model_relation_chain));
3914
+		$passed_in_query_info->merge($new_query_info);
3915
+	}
3916
+
3917
+
3918
+
3919
+	/**
3920
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3921
+	 *
3922
+	 * @param array $where_params like EEM_Base::get_all
3923
+	 * @return string of SQL
3924
+	 * @throws \EE_Error
3925
+	 */
3926
+	private function _construct_where_clause($where_params)
3927
+	{
3928
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3929
+		if ($SQL) {
3930
+			return " WHERE " . $SQL;
3931
+		} else {
3932
+			return '';
3933
+		}
3934
+	}
3935
+
3936
+
3937
+
3938
+	/**
3939
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3940
+	 * and should be passed HAVING parameters, not WHERE parameters
3941
+	 *
3942
+	 * @param array $having_params
3943
+	 * @return string
3944
+	 * @throws \EE_Error
3945
+	 */
3946
+	private function _construct_having_clause($having_params)
3947
+	{
3948
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3949
+		if ($SQL) {
3950
+			return " HAVING " . $SQL;
3951
+		} else {
3952
+			return '';
3953
+		}
3954
+	}
3955
+
3956
+
3957
+
3958
+	/**
3959
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3960
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3961
+	 * EEM_Attendee.
3962
+	 *
3963
+	 * @param string $field_name
3964
+	 * @param string $model_name
3965
+	 * @return EE_Model_Field_Base
3966
+	 * @throws EE_Error
3967
+	 */
3968
+	protected function _get_field_on_model($field_name, $model_name)
3969
+	{
3970
+		$model_class = 'EEM_' . $model_name;
3971
+		$model_filepath = $model_class . ".model.php";
3972
+		if (is_readable($model_filepath)) {
3973
+			require_once($model_filepath);
3974
+			$model_instance = call_user_func($model_name . "::instance");
3975
+			/* @var $model_instance EEM_Base */
3976
+			return $model_instance->field_settings_for($field_name);
3977
+		} else {
3978
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3979
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3980
+		}
3981
+	}
3982
+
3983
+
3984
+
3985
+	/**
3986
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3987
+	 * Event_Meta.meta_value = 'foo'))"
3988
+	 *
3989
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3990
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3991
+	 * @throws EE_Error
3992
+	 * @return string of SQL
3993
+	 */
3994
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3995
+	{
3996
+		$where_clauses = array();
3997
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3998
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3999
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4000
+				switch ($query_param) {
4001
+					case 'not':
4002
+					case 'NOT':
4003
+						$where_clauses[] = "! ("
4004
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4005
+								$glue)
4006
+										   . ")";
4007
+						break;
4008
+					case 'and':
4009
+					case 'AND':
4010
+						$where_clauses[] = " ("
4011
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4012
+								' AND ')
4013
+										   . ")";
4014
+						break;
4015
+					case 'or':
4016
+					case 'OR':
4017
+						$where_clauses[] = " ("
4018
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4019
+								' OR ')
4020
+										   . ")";
4021
+						break;
4022
+				}
4023
+			} else {
4024
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4025
+				//if it's not a normal field, maybe it's a custom selection?
4026
+				if (! $field_obj) {
4027
+					if (isset($this->_custom_selections[$query_param][1])) {
4028
+						$field_obj = $this->_custom_selections[$query_param][1];
4029
+					} else {
4030
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4031
+							"event_espresso"), $query_param));
4032
+					}
4033
+				}
4034
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4035
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4036
+			}
4037
+		}
4038
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4039
+	}
4040
+
4041
+
4042
+
4043
+	/**
4044
+	 * Takes the input parameter and extract the table name (alias) and column name
4045
+	 *
4046
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4047
+	 * @throws EE_Error
4048
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4049
+	 */
4050
+	private function _deduce_column_name_from_query_param($query_param)
4051
+	{
4052
+		$field = $this->_deduce_field_from_query_param($query_param);
4053
+		if ($field) {
4054
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4055
+				$query_param);
4056
+			return $table_alias_prefix . $field->get_qualified_column();
4057
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4058
+			//maybe it's custom selection item?
4059
+			//if so, just use it as the "column name"
4060
+			return $query_param;
4061
+		} else {
4062
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4063
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4064
+		}
4065
+	}
4066
+
4067
+
4068
+
4069
+	/**
4070
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4071
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4072
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4073
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4074
+	 *
4075
+	 * @param string $condition_query_param_key
4076
+	 * @return string
4077
+	 */
4078
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4079
+	{
4080
+		$pos_of_star = strpos($condition_query_param_key, '*');
4081
+		if ($pos_of_star === false) {
4082
+			return $condition_query_param_key;
4083
+		} else {
4084
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4085
+			return $condition_query_param_sans_star;
4086
+		}
4087
+	}
4088
+
4089
+
4090
+
4091
+	/**
4092
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4093
+	 *
4094
+	 * @param                            mixed      array | string    $op_and_value
4095
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4096
+	 * @throws EE_Error
4097
+	 * @return string
4098
+	 */
4099
+	private function _construct_op_and_value($op_and_value, $field_obj)
4100
+	{
4101
+		if (is_array($op_and_value)) {
4102
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4103
+			if (! $operator) {
4104
+				$php_array_like_string = array();
4105
+				foreach ($op_and_value as $key => $value) {
4106
+					$php_array_like_string[] = "$key=>$value";
4107
+				}
4108
+				throw new EE_Error(
4109
+					sprintf(
4110
+						__(
4111
+							"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))",
4112
+							"event_espresso"
4113
+						),
4114
+						implode(",", $php_array_like_string)
4115
+					)
4116
+				);
4117
+			}
4118
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4119
+		} else {
4120
+			$operator = '=';
4121
+			$value = $op_and_value;
4122
+		}
4123
+		//check to see if the value is actually another field
4124
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4125
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4126
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
4127
+			//in this case, the value should be an array, or at least a comma-separated list
4128
+			//it will need to handle a little differently
4129
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4130
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4131
+			return $operator . SP . $cleaned_value;
4132
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
4133
+			//the value should be an array with count of two.
4134
+			if (count($value) !== 2) {
4135
+				throw new EE_Error(
4136
+					sprintf(
4137
+						__(
4138
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4139
+							'event_espresso'
4140
+						),
4141
+						"BETWEEN"
4142
+					)
4143
+				);
4144
+			}
4145
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4146
+			return $operator . SP . $cleaned_value;
4147
+		} elseif (in_array($operator, $this->_null_style_operators)) {
4148
+			if ($value !== null) {
4149
+				throw new EE_Error(
4150
+					sprintf(
4151
+						__(
4152
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4153
+							"event_espresso"
4154
+						),
4155
+						$value,
4156
+						$operator
4157
+					)
4158
+				);
4159
+			}
4160
+			return $operator;
4161
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
4162
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4163
+			//remove other junk. So just treat it as a string.
4164
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4165
+		} elseif (! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4166
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4167
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
4168
+			throw new EE_Error(
4169
+				sprintf(
4170
+					__(
4171
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4172
+						'event_espresso'
4173
+					),
4174
+					$operator,
4175
+					$operator
4176
+				)
4177
+			);
4178
+		} elseif (! in_array($operator, $this->_in_style_operators) && is_array($value)) {
4179
+			throw new EE_Error(
4180
+				sprintf(
4181
+					__(
4182
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4183
+						'event_espresso'
4184
+					),
4185
+					$operator,
4186
+					$operator
4187
+				)
4188
+			);
4189
+		} else {
4190
+			throw new EE_Error(
4191
+				sprintf(
4192
+					__(
4193
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4194
+						"event_espresso"
4195
+					),
4196
+					http_build_query($op_and_value)
4197
+				)
4198
+			);
4199
+		}
4200
+	}
4201
+
4202
+
4203
+
4204
+	/**
4205
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4206
+	 *
4207
+	 * @param array                      $values
4208
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4209
+	 *                                              '%s'
4210
+	 * @return string
4211
+	 * @throws \EE_Error
4212
+	 */
4213
+	public function _construct_between_value($values, $field_obj)
4214
+	{
4215
+		$cleaned_values = array();
4216
+		foreach ($values as $value) {
4217
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4218
+		}
4219
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4220
+	}
4221
+
4222
+
4223
+
4224
+	/**
4225
+	 * Takes an array or a comma-separated list of $values and cleans them
4226
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4227
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4228
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4229
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4230
+	 *
4231
+	 * @param mixed                      $values    array or comma-separated string
4232
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4233
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4234
+	 * @throws \EE_Error
4235
+	 */
4236
+	public function _construct_in_value($values, $field_obj)
4237
+	{
4238
+		//check if the value is a CSV list
4239
+		if (is_string($values)) {
4240
+			//in which case, turn it into an array
4241
+			$values = explode(",", $values);
4242
+		}
4243
+		$cleaned_values = array();
4244
+		foreach ($values as $value) {
4245
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4246
+		}
4247
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4248
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4249
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4250
+		if (empty($cleaned_values)) {
4251
+			$all_fields = $this->field_settings();
4252
+			$a_field = array_shift($all_fields);
4253
+			$main_table = $this->_get_main_table();
4254
+			$cleaned_values[] = "SELECT "
4255
+								. $a_field->get_table_column()
4256
+								. " FROM "
4257
+								. $main_table->get_table_name()
4258
+								. " WHERE FALSE";
4259
+		}
4260
+		return "(" . implode(",", $cleaned_values) . ")";
4261
+	}
4262
+
4263
+
4264
+
4265
+	/**
4266
+	 * @param mixed                      $value
4267
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4268
+	 * @throws EE_Error
4269
+	 * @return false|null|string
4270
+	 */
4271
+	private function _wpdb_prepare_using_field($value, $field_obj)
4272
+	{
4273
+		/** @type WPDB $wpdb */
4274
+		global $wpdb;
4275
+		if ($field_obj instanceof EE_Model_Field_Base) {
4276
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4277
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4278
+		} else {//$field_obj should really just be a data type
4279
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4280
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4281
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4282
+			}
4283
+			return $wpdb->prepare($field_obj, $value);
4284
+		}
4285
+	}
4286
+
4287
+
4288
+
4289
+	/**
4290
+	 * Takes the input parameter and finds the model field that it indicates.
4291
+	 *
4292
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4293
+	 * @throws EE_Error
4294
+	 * @return EE_Model_Field_Base
4295
+	 */
4296
+	protected function _deduce_field_from_query_param($query_param_name)
4297
+	{
4298
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4299
+		//which will help us find the database table and column
4300
+		$query_param_parts = explode(".", $query_param_name);
4301
+		if (empty($query_param_parts)) {
4302
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4303
+				'event_espresso'), $query_param_name));
4304
+		}
4305
+		$number_of_parts = count($query_param_parts);
4306
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4307
+		if ($number_of_parts === 1) {
4308
+			$field_name = $last_query_param_part;
4309
+			$model_obj = $this;
4310
+		} else {// $number_of_parts >= 2
4311
+			//the last part is the column name, and there are only 2parts. therefore...
4312
+			$field_name = $last_query_param_part;
4313
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4314
+		}
4315
+		try {
4316
+			return $model_obj->field_settings_for($field_name);
4317
+		} catch (EE_Error $e) {
4318
+			return null;
4319
+		}
4320
+	}
4321
+
4322
+
4323
+
4324
+	/**
4325
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4326
+	 * alias and column which corresponds to it
4327
+	 *
4328
+	 * @param string $field_name
4329
+	 * @throws EE_Error
4330
+	 * @return string
4331
+	 */
4332
+	public function _get_qualified_column_for_field($field_name)
4333
+	{
4334
+		$all_fields = $this->field_settings();
4335
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4336
+		if ($field) {
4337
+			return $field->get_qualified_column();
4338
+		} else {
4339
+			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.",
4340
+				'event_espresso'), $field_name, get_class($this)));
4341
+		}
4342
+	}
4343
+
4344
+
4345
+
4346
+	/**
4347
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4348
+	 * Example usage:
4349
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4350
+	 *      array(),
4351
+	 *      ARRAY_A,
4352
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4353
+	 *  );
4354
+	 * is equivalent to
4355
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4356
+	 * and
4357
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4358
+	 *      array(
4359
+	 *          array(
4360
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4361
+	 *          ),
4362
+	 *          ARRAY_A,
4363
+	 *          implode(
4364
+	 *              ', ',
4365
+	 *              array_merge(
4366
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4367
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4368
+	 *              )
4369
+	 *          )
4370
+	 *      )
4371
+	 *  );
4372
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4373
+	 *
4374
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4375
+	 *                                            and the one whose fields you are selecting for example: when querying
4376
+	 *                                            tickets model and selecting fields from the tickets model you would
4377
+	 *                                            leave this parameter empty, because no models are needed to join
4378
+	 *                                            between the queried model and the selected one. Likewise when
4379
+	 *                                            querying the datetime model and selecting fields from the tickets
4380
+	 *                                            model, it would also be left empty, because there is a direct
4381
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4382
+	 *                                            them together. However, when querying from the event model and
4383
+	 *                                            selecting fields from the ticket model, you should provide the string
4384
+	 *                                            'Datetime', indicating that the event model must first join to the
4385
+	 *                                            datetime model in order to find its relation to ticket model.
4386
+	 *                                            Also, when querying from the venue model and selecting fields from
4387
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4388
+	 *                                            indicating you need to join the venue model to the event model,
4389
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4390
+	 *                                            This string is used to deduce the prefix that gets added onto the
4391
+	 *                                            models' tables qualified columns
4392
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4393
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4394
+	 *                                            qualified column names
4395
+	 * @return array|string
4396
+	 */
4397
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4398
+	{
4399
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4400
+		$qualified_columns = array();
4401
+		foreach ($this->field_settings() as $field_name => $field) {
4402
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4403
+		}
4404
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4405
+	}
4406
+
4407
+
4408
+
4409
+	/**
4410
+	 * constructs the select use on special limit joins
4411
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4412
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4413
+	 * (as that is typically where the limits would be set).
4414
+	 *
4415
+	 * @param  string       $table_alias The table the select is being built for
4416
+	 * @param  mixed|string $limit       The limit for this select
4417
+	 * @return string                The final select join element for the query.
4418
+	 */
4419
+	public function _construct_limit_join_select($table_alias, $limit)
4420
+	{
4421
+		$SQL = '';
4422
+		foreach ($this->_tables as $table_obj) {
4423
+			if ($table_obj instanceof EE_Primary_Table) {
4424
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4425
+					? $table_obj->get_select_join_limit($limit)
4426
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4427
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4428
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4429
+					? $table_obj->get_select_join_limit_join($limit)
4430
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4431
+			}
4432
+		}
4433
+		return $SQL;
4434
+	}
4435
+
4436
+
4437
+
4438
+	/**
4439
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4440
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4441
+	 *
4442
+	 * @return string SQL
4443
+	 * @throws \EE_Error
4444
+	 */
4445
+	public function _construct_internal_join()
4446
+	{
4447
+		$SQL = $this->_get_main_table()->get_table_sql();
4448
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4449
+		return $SQL;
4450
+	}
4451
+
4452
+
4453
+
4454
+	/**
4455
+	 * Constructs the SQL for joining all the tables on this model.
4456
+	 * Normally $alias should be the primary table's alias, but in cases where
4457
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4458
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4459
+	 * alias, this will construct SQL like:
4460
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4461
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4462
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4463
+	 *
4464
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4465
+	 * @return string
4466
+	 */
4467
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4468
+	{
4469
+		$SQL = '';
4470
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4471
+		foreach ($this->_tables as $table_obj) {
4472
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4473
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4474
+					//so we're joining to this table, meaning the table is already in
4475
+					//the FROM statement, BUT the primary table isn't. So we want
4476
+					//to add the inverse join sql
4477
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4478
+				} else {
4479
+					//just add a regular JOIN to this table from the primary table
4480
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4481
+				}
4482
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4483
+		}
4484
+		return $SQL;
4485
+	}
4486
+
4487
+
4488
+
4489
+	/**
4490
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4491
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4492
+	 * their data type (eg, '%s', '%d', etc)
4493
+	 *
4494
+	 * @return array
4495
+	 */
4496
+	public function _get_data_types()
4497
+	{
4498
+		$data_types = array();
4499
+		foreach ($this->field_settings() as $field_obj) {
4500
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4501
+			/** @var $field_obj EE_Model_Field_Base */
4502
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4503
+		}
4504
+		return $data_types;
4505
+	}
4506
+
4507
+
4508
+
4509
+	/**
4510
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4511
+	 *
4512
+	 * @param string $model_name
4513
+	 * @throws EE_Error
4514
+	 * @return EEM_Base
4515
+	 */
4516
+	public function get_related_model_obj($model_name)
4517
+	{
4518
+		$model_classname = "EEM_" . $model_name;
4519
+		if (! class_exists($model_classname)) {
4520
+			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",
4521
+				'event_espresso'), $model_name, $model_classname));
4522
+		}
4523
+		return call_user_func($model_classname . "::instance");
4524
+	}
4525
+
4526
+
4527
+
4528
+	/**
4529
+	 * Returns the array of EE_ModelRelations for this model.
4530
+	 *
4531
+	 * @return EE_Model_Relation_Base[]
4532
+	 */
4533
+	public function relation_settings()
4534
+	{
4535
+		return $this->_model_relations;
4536
+	}
4537
+
4538
+
4539
+
4540
+	/**
4541
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4542
+	 * because without THOSE models, this model probably doesn't have much purpose.
4543
+	 * (Eg, without an event, datetimes have little purpose.)
4544
+	 *
4545
+	 * @return EE_Belongs_To_Relation[]
4546
+	 */
4547
+	public function belongs_to_relations()
4548
+	{
4549
+		$belongs_to_relations = array();
4550
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4551
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4552
+				$belongs_to_relations[$model_name] = $relation_obj;
4553
+			}
4554
+		}
4555
+		return $belongs_to_relations;
4556
+	}
4557
+
4558
+
4559
+
4560
+	/**
4561
+	 * Returns the specified EE_Model_Relation, or throws an exception
4562
+	 *
4563
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4564
+	 * @throws EE_Error
4565
+	 * @return EE_Model_Relation_Base
4566
+	 */
4567
+	public function related_settings_for($relation_name)
4568
+	{
4569
+		$relatedModels = $this->relation_settings();
4570
+		if (! array_key_exists($relation_name, $relatedModels)) {
4571
+			throw new EE_Error(
4572
+				sprintf(
4573
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4574
+						'event_espresso'),
4575
+					$relation_name,
4576
+					$this->_get_class_name(),
4577
+					implode(', ', array_keys($relatedModels))
4578
+				)
4579
+			);
4580
+		}
4581
+		return $relatedModels[$relation_name];
4582
+	}
4583
+
4584
+
4585
+
4586
+	/**
4587
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4588
+	 * fields
4589
+	 *
4590
+	 * @param string $fieldName
4591
+	 * @throws EE_Error
4592
+	 * @return EE_Model_Field_Base
4593
+	 */
4594
+	public function field_settings_for($fieldName)
4595
+	{
4596
+		$fieldSettings = $this->field_settings(true);
4597
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4598
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4599
+				get_class($this)));
4600
+		}
4601
+		return $fieldSettings[$fieldName];
4602
+	}
4603
+
4604
+
4605
+
4606
+	/**
4607
+	 * Checks if this field exists on this model
4608
+	 *
4609
+	 * @param string $fieldName a key in the model's _field_settings array
4610
+	 * @return boolean
4611
+	 */
4612
+	public function has_field($fieldName)
4613
+	{
4614
+		$fieldSettings = $this->field_settings(true);
4615
+		if (isset($fieldSettings[$fieldName])) {
4616
+			return true;
4617
+		} else {
4618
+			return false;
4619
+		}
4620
+	}
4621
+
4622
+
4623
+
4624
+	/**
4625
+	 * Returns whether or not this model has a relation to the specified model
4626
+	 *
4627
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4628
+	 * @return boolean
4629
+	 */
4630
+	public function has_relation($relation_name)
4631
+	{
4632
+		$relations = $this->relation_settings();
4633
+		if (isset($relations[$relation_name])) {
4634
+			return true;
4635
+		} else {
4636
+			return false;
4637
+		}
4638
+	}
4639
+
4640
+
4641
+
4642
+	/**
4643
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4644
+	 * Eg, on EE_Answer that would be ANS_ID field object
4645
+	 *
4646
+	 * @param $field_obj
4647
+	 * @return boolean
4648
+	 */
4649
+	public function is_primary_key_field($field_obj)
4650
+	{
4651
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4652
+	}
4653
+
4654
+
4655
+
4656
+	/**
4657
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4658
+	 * Eg, on EE_Answer that would be ANS_ID field object
4659
+	 *
4660
+	 * @return EE_Model_Field_Base
4661
+	 * @throws EE_Error
4662
+	 */
4663
+	public function get_primary_key_field()
4664
+	{
4665
+		if ($this->_primary_key_field === null) {
4666
+			foreach ($this->field_settings(true) as $field_obj) {
4667
+				if ($this->is_primary_key_field($field_obj)) {
4668
+					$this->_primary_key_field = $field_obj;
4669
+					break;
4670
+				}
4671
+			}
4672
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4673
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4674
+					get_class($this)));
4675
+			}
4676
+		}
4677
+		return $this->_primary_key_field;
4678
+	}
4679
+
4680
+
4681
+
4682
+	/**
4683
+	 * Returns whether or not not there is a primary key on this model.
4684
+	 * Internally does some caching.
4685
+	 *
4686
+	 * @return boolean
4687
+	 */
4688
+	public function has_primary_key_field()
4689
+	{
4690
+		if ($this->_has_primary_key_field === null) {
4691
+			try {
4692
+				$this->get_primary_key_field();
4693
+				$this->_has_primary_key_field = true;
4694
+			} catch (EE_Error $e) {
4695
+				$this->_has_primary_key_field = false;
4696
+			}
4697
+		}
4698
+		return $this->_has_primary_key_field;
4699
+	}
4700
+
4701
+
4702
+
4703
+	/**
4704
+	 * Finds the first field of type $field_class_name.
4705
+	 *
4706
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4707
+	 *                                 EE_Foreign_Key_Field, etc
4708
+	 * @return EE_Model_Field_Base or null if none is found
4709
+	 */
4710
+	public function get_a_field_of_type($field_class_name)
4711
+	{
4712
+		foreach ($this->field_settings() as $field) {
4713
+			if ($field instanceof $field_class_name) {
4714
+				return $field;
4715
+			}
4716
+		}
4717
+		return null;
4718
+	}
4719
+
4720
+
4721
+
4722
+	/**
4723
+	 * Gets a foreign key field pointing to model.
4724
+	 *
4725
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4726
+	 * @return EE_Foreign_Key_Field_Base
4727
+	 * @throws EE_Error
4728
+	 */
4729
+	public function get_foreign_key_to($model_name)
4730
+	{
4731
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4732
+			foreach ($this->field_settings() as $field) {
4733
+				if (
4734
+					$field instanceof EE_Foreign_Key_Field_Base
4735
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4736
+				) {
4737
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4738
+					break;
4739
+				}
4740
+			}
4741
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4742
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4743
+					'event_espresso'), $model_name, get_class($this)));
4744
+			}
4745
+		}
4746
+		return $this->_cache_foreign_key_to_fields[$model_name];
4747
+	}
4748
+
4749
+
4750
+
4751
+	/**
4752
+	 * Gets the actual table for the table alias
4753
+	 *
4754
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4755
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4756
+	 *                            Either one works
4757
+	 * @return EE_Table_Base
4758
+	 */
4759
+	public function get_table_for_alias($table_alias)
4760
+	{
4761
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4762
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4763
+	}
4764
+
4765
+
4766
+
4767
+	/**
4768
+	 * Returns a flat array of all field son this model, instead of organizing them
4769
+	 * by table_alias as they are in the constructor.
4770
+	 *
4771
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4772
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4773
+	 */
4774
+	public function field_settings($include_db_only_fields = false)
4775
+	{
4776
+		if ($include_db_only_fields) {
4777
+			if ($this->_cached_fields === null) {
4778
+				$this->_cached_fields = array();
4779
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4780
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4781
+						$this->_cached_fields[$field_name] = $field_obj;
4782
+					}
4783
+				}
4784
+			}
4785
+			return $this->_cached_fields;
4786
+		} else {
4787
+			if ($this->_cached_fields_non_db_only === null) {
4788
+				$this->_cached_fields_non_db_only = array();
4789
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4790
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4791
+						/** @var $field_obj EE_Model_Field_Base */
4792
+						if (! $field_obj->is_db_only_field()) {
4793
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4794
+						}
4795
+					}
4796
+				}
4797
+			}
4798
+			return $this->_cached_fields_non_db_only;
4799
+		}
4800
+	}
4801
+
4802
+
4803
+
4804
+	/**
4805
+	 *        cycle though array of attendees and create objects out of each item
4806
+	 *
4807
+	 * @access        private
4808
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4809
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4810
+	 *                           numerically indexed)
4811
+	 * @throws \EE_Error
4812
+	 */
4813
+	protected function _create_objects($rows = array())
4814
+	{
4815
+		$array_of_objects = array();
4816
+		if (empty($rows)) {
4817
+			return array();
4818
+		}
4819
+		$count_if_model_has_no_primary_key = 0;
4820
+		$has_primary_key = $this->has_primary_key_field();
4821
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4822
+		foreach ((array)$rows as $row) {
4823
+			if (empty($row)) {
4824
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4825
+				return array();
4826
+			}
4827
+			//check if we've already set this object in the results array,
4828
+			//in which case there's no need to process it further (again)
4829
+			if ($has_primary_key) {
4830
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4831
+					$row,
4832
+					$primary_key_field->get_qualified_column(),
4833
+					$primary_key_field->get_table_column()
4834
+				);
4835
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4836
+					continue;
4837
+				}
4838
+			}
4839
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4840
+			if (! $classInstance) {
4841
+				throw new EE_Error(
4842
+					sprintf(
4843
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4844
+						$this->get_this_model_name(),
4845
+						http_build_query($row)
4846
+					)
4847
+				);
4848
+			}
4849
+			//set the timezone on the instantiated objects
4850
+			$classInstance->set_timezone($this->_timezone);
4851
+			//make sure if there is any timezone setting present that we set the timezone for the object
4852
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4853
+			$array_of_objects[$key] = $classInstance;
4854
+			//also, for all the relations of type BelongsTo, see if we can cache
4855
+			//those related models
4856
+			//(we could do this for other relations too, but if there are conditions
4857
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4858
+			//so it requires a little more thought than just caching them immediately...)
4859
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4860
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4861
+					//check if this model's INFO is present. If so, cache it on the model
4862
+					$other_model = $relation_obj->get_other_model();
4863
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4864
+					//if we managed to make a model object from the results, cache it on the main model object
4865
+					if ($other_model_obj_maybe) {
4866
+						//set timezone on these other model objects if they are present
4867
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4868
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4869
+					}
4870
+				}
4871
+			}
4872
+		}
4873
+		return $array_of_objects;
4874
+	}
4875
+
4876
+
4877
+
4878
+	/**
4879
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4880
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4881
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4882
+	 * object (as set in the model_field!).
4883
+	 *
4884
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4885
+	 */
4886
+	public function create_default_object()
4887
+	{
4888
+		$this_model_fields_and_values = array();
4889
+		//setup the row using default values;
4890
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4891
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4892
+		}
4893
+		$className = $this->_get_class_name();
4894
+		$classInstance = EE_Registry::instance()
4895
+									->load_class($className, array($this_model_fields_and_values), false, false);
4896
+		return $classInstance;
4897
+	}
4898
+
4899
+
4900
+
4901
+	/**
4902
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4903
+	 *                             or an stdClass where each property is the name of a column,
4904
+	 * @return EE_Base_Class
4905
+	 * @throws \EE_Error
4906
+	 */
4907
+	public function instantiate_class_from_array_or_object($cols_n_values)
4908
+	{
4909
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4910
+			$cols_n_values = get_object_vars($cols_n_values);
4911
+		}
4912
+		$primary_key = null;
4913
+		//make sure the array only has keys that are fields/columns on this model
4914
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4915
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4916
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4917
+		}
4918
+		$className = $this->_get_class_name();
4919
+		//check we actually found results that we can use to build our model object
4920
+		//if not, return null
4921
+		if ($this->has_primary_key_field()) {
4922
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4923
+				return null;
4924
+			}
4925
+		} else if ($this->unique_indexes()) {
4926
+			$first_column = reset($this_model_fields_n_values);
4927
+			if (empty($first_column)) {
4928
+				return null;
4929
+			}
4930
+		}
4931
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4932
+		if ($primary_key) {
4933
+			$classInstance = $this->get_from_entity_map($primary_key);
4934
+			if (! $classInstance) {
4935
+				$classInstance = EE_Registry::instance()
4936
+											->load_class($className,
4937
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4938
+				// add this new object to the entity map
4939
+				$classInstance = $this->add_to_entity_map($classInstance);
4940
+			}
4941
+		} else {
4942
+			$classInstance = EE_Registry::instance()
4943
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4944
+											true, false);
4945
+		}
4946
+		//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.
4947
+		$this->set_timezone($classInstance->get_timezone());
4948
+		return $classInstance;
4949
+	}
4950
+
4951
+
4952
+
4953
+	/**
4954
+	 * Gets the model object from the  entity map if it exists
4955
+	 *
4956
+	 * @param int|string $id the ID of the model object
4957
+	 * @return EE_Base_Class
4958
+	 */
4959
+	public function get_from_entity_map($id)
4960
+	{
4961
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4962
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4963
+	}
4964
+
4965
+
4966
+
4967
+	/**
4968
+	 * add_to_entity_map
4969
+	 * Adds the object to the model's entity mappings
4970
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4971
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4972
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4973
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4974
+	 *        then this method should be called immediately after the update query
4975
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4976
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4977
+	 *
4978
+	 * @param    EE_Base_Class $object
4979
+	 * @throws EE_Error
4980
+	 * @return \EE_Base_Class
4981
+	 */
4982
+	public function add_to_entity_map(EE_Base_Class $object)
4983
+	{
4984
+		$className = $this->_get_class_name();
4985
+		if (! $object instanceof $className) {
4986
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4987
+				is_object($object) ? get_class($object) : $object, $className));
4988
+		}
4989
+		/** @var $object EE_Base_Class */
4990
+		if (! $object->ID()) {
4991
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4992
+				"event_espresso"), get_class($this)));
4993
+		}
4994
+		// double check it's not already there
4995
+		$classInstance = $this->get_from_entity_map($object->ID());
4996
+		if ($classInstance) {
4997
+			return $classInstance;
4998
+		} else {
4999
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5000
+			return $object;
5001
+		}
5002
+	}
5003
+
5004
+
5005
+
5006
+	/**
5007
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5008
+	 * if no identifier is provided, then the entire entity map is emptied
5009
+	 *
5010
+	 * @param int|string $id the ID of the model object
5011
+	 * @return boolean
5012
+	 */
5013
+	public function clear_entity_map($id = null)
5014
+	{
5015
+		if (empty($id)) {
5016
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5017
+			return true;
5018
+		}
5019
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5020
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5021
+			return true;
5022
+		}
5023
+		return false;
5024
+	}
5025
+
5026
+
5027
+
5028
+	/**
5029
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5030
+	 * Given an array where keys are column (or column alias) names and values,
5031
+	 * returns an array of their corresponding field names and database values
5032
+	 *
5033
+	 * @param array $cols_n_values
5034
+	 * @return array
5035
+	 */
5036
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5037
+	{
5038
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5039
+	}
5040
+
5041
+
5042
+
5043
+	/**
5044
+	 * _deduce_fields_n_values_from_cols_n_values
5045
+	 * Given an array where keys are column (or column alias) names and values,
5046
+	 * returns an array of their corresponding field names and database values
5047
+	 *
5048
+	 * @param string $cols_n_values
5049
+	 * @return array
5050
+	 */
5051
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5052
+	{
5053
+		$this_model_fields_n_values = array();
5054
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5055
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5056
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5057
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5058
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5059
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5060
+					if (! $field_obj->is_db_only_field()) {
5061
+						//prepare field as if its coming from db
5062
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5063
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5064
+					}
5065
+				}
5066
+			} else {
5067
+				//the table's rows existed. Use their values
5068
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5069
+					if (! $field_obj->is_db_only_field()) {
5070
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5071
+							$cols_n_values, $field_obj->get_qualified_column(),
5072
+							$field_obj->get_table_column()
5073
+						);
5074
+					}
5075
+				}
5076
+			}
5077
+		}
5078
+		return $this_model_fields_n_values;
5079
+	}
5080
+
5081
+
5082
+
5083
+	/**
5084
+	 * @param $cols_n_values
5085
+	 * @param $qualified_column
5086
+	 * @param $regular_column
5087
+	 * @return null
5088
+	 */
5089
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5090
+	{
5091
+		$value = null;
5092
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5093
+		//does the field on the model relate to this column retrieved from the db?
5094
+		//or is it a db-only field? (not relating to the model)
5095
+		if (isset($cols_n_values[$qualified_column])) {
5096
+			$value = $cols_n_values[$qualified_column];
5097
+		} elseif (isset($cols_n_values[$regular_column])) {
5098
+			$value = $cols_n_values[$regular_column];
5099
+		}
5100
+		return $value;
5101
+	}
5102
+
5103
+
5104
+
5105
+	/**
5106
+	 * refresh_entity_map_from_db
5107
+	 * Makes sure the model object in the entity map at $id assumes the values
5108
+	 * of the database (opposite of EE_base_Class::save())
5109
+	 *
5110
+	 * @param int|string $id
5111
+	 * @return EE_Base_Class
5112
+	 * @throws \EE_Error
5113
+	 */
5114
+	public function refresh_entity_map_from_db($id)
5115
+	{
5116
+		$obj_in_map = $this->get_from_entity_map($id);
5117
+		if ($obj_in_map) {
5118
+			$wpdb_results = $this->_get_all_wpdb_results(
5119
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5120
+			);
5121
+			if ($wpdb_results && is_array($wpdb_results)) {
5122
+				$one_row = reset($wpdb_results);
5123
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5124
+					$obj_in_map->set_from_db($field_name, $db_value);
5125
+				}
5126
+				//clear the cache of related model objects
5127
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5128
+					$obj_in_map->clear_cache($relation_name, null, true);
5129
+				}
5130
+			}
5131
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5132
+			return $obj_in_map;
5133
+		} else {
5134
+			return $this->get_one_by_ID($id);
5135
+		}
5136
+	}
5137
+
5138
+
5139
+
5140
+	/**
5141
+	 * refresh_entity_map_with
5142
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5143
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5144
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5145
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5146
+	 *
5147
+	 * @param int|string    $id
5148
+	 * @param EE_Base_Class $replacing_model_obj
5149
+	 * @return \EE_Base_Class
5150
+	 * @throws \EE_Error
5151
+	 */
5152
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5153
+	{
5154
+		$obj_in_map = $this->get_from_entity_map($id);
5155
+		if ($obj_in_map) {
5156
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5157
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5158
+					$obj_in_map->set($field_name, $value);
5159
+				}
5160
+				//make the model object in the entity map's cache match the $replacing_model_obj
5161
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5162
+					$obj_in_map->clear_cache($relation_name, null, true);
5163
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5164
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5165
+					}
5166
+				}
5167
+			}
5168
+			return $obj_in_map;
5169
+		} else {
5170
+			$this->add_to_entity_map($replacing_model_obj);
5171
+			return $replacing_model_obj;
5172
+		}
5173
+	}
5174
+
5175
+
5176
+
5177
+	/**
5178
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5179
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5180
+	 * require_once($this->_getClassName().".class.php");
5181
+	 *
5182
+	 * @return string
5183
+	 */
5184
+	private function _get_class_name()
5185
+	{
5186
+		return "EE_" . $this->get_this_model_name();
5187
+	}
5188
+
5189
+
5190
+
5191
+	/**
5192
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5193
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5194
+	 * it would be 'Events'.
5195
+	 *
5196
+	 * @param int $quantity
5197
+	 * @return string
5198
+	 */
5199
+	public function item_name($quantity = 1)
5200
+	{
5201
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5202
+	}
5203
+
5204
+
5205
+
5206
+	/**
5207
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5208
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5209
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5210
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5211
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5212
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5213
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5214
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5215
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5216
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5217
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5218
+	 *        return $previousReturnValue.$returnString;
5219
+	 * }
5220
+	 * require('EEM_Answer.model.php');
5221
+	 * $answer=EEM_Answer::instance();
5222
+	 * echo $answer->my_callback('monkeys',100);
5223
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5224
+	 *
5225
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5226
+	 * @param array  $args       array of original arguments passed to the function
5227
+	 * @throws EE_Error
5228
+	 * @return mixed whatever the plugin which calls add_filter decides
5229
+	 */
5230
+	public function __call($methodName, $args)
5231
+	{
5232
+		$className = get_class($this);
5233
+		$tagName = "FHEE__{$className}__{$methodName}";
5234
+		if (! has_filter($tagName)) {
5235
+			throw new EE_Error(
5236
+				sprintf(
5237
+					__('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 );',
5238
+						'event_espresso'),
5239
+					$methodName,
5240
+					$className,
5241
+					$tagName,
5242
+					'<br />'
5243
+				)
5244
+			);
5245
+		}
5246
+		return apply_filters($tagName, null, $this, $args);
5247
+	}
5248
+
5249
+
5250
+
5251
+	/**
5252
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5253
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5254
+	 *
5255
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5256
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5257
+	 *                                                       the object's class name
5258
+	 *                                                       or object's ID
5259
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5260
+	 *                                                       exists in the database. If it does not, we add it
5261
+	 * @throws EE_Error
5262
+	 * @return EE_Base_Class
5263
+	 */
5264
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5265
+	{
5266
+		$className = $this->_get_class_name();
5267
+		if ($base_class_obj_or_id instanceof $className) {
5268
+			$model_object = $base_class_obj_or_id;
5269
+		} else {
5270
+			$primary_key_field = $this->get_primary_key_field();
5271
+			if (
5272
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5273
+				&& (
5274
+					is_int($base_class_obj_or_id)
5275
+					|| is_string($base_class_obj_or_id)
5276
+				)
5277
+			) {
5278
+				// assume it's an ID.
5279
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5280
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5281
+			} else if (
5282
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5283
+				&& is_string($base_class_obj_or_id)
5284
+			) {
5285
+				// assume its a string representation of the object
5286
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5287
+			} else {
5288
+				throw new EE_Error(
5289
+					sprintf(
5290
+						__(
5291
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5292
+							'event_espresso'
5293
+						),
5294
+						$base_class_obj_or_id,
5295
+						$this->_get_class_name(),
5296
+						print_r($base_class_obj_or_id, true)
5297
+					)
5298
+				);
5299
+			}
5300
+		}
5301
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5302
+			$model_object->save();
5303
+		}
5304
+		return $model_object;
5305
+	}
5306
+
5307
+
5308
+
5309
+	/**
5310
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5311
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5312
+	 * returns it ID.
5313
+	 *
5314
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5315
+	 * @return int|string depending on the type of this model object's ID
5316
+	 * @throws EE_Error
5317
+	 */
5318
+	public function ensure_is_ID($base_class_obj_or_id)
5319
+	{
5320
+		$className = $this->_get_class_name();
5321
+		if ($base_class_obj_or_id instanceof $className) {
5322
+			/** @var $base_class_obj_or_id EE_Base_Class */
5323
+			$id = $base_class_obj_or_id->ID();
5324
+		} elseif (is_int($base_class_obj_or_id)) {
5325
+			//assume it's an ID
5326
+			$id = $base_class_obj_or_id;
5327
+		} elseif (is_string($base_class_obj_or_id)) {
5328
+			//assume its a string representation of the object
5329
+			$id = $base_class_obj_or_id;
5330
+		} else {
5331
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5332
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5333
+				print_r($base_class_obj_or_id, true)));
5334
+		}
5335
+		return $id;
5336
+	}
5337
+
5338
+
5339
+
5340
+	/**
5341
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5342
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5343
+	 * been sanitized and converted into the appropriate domain.
5344
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5345
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5346
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5347
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5348
+	 * $EVT = EEM_Event::instance(); $old_setting =
5349
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5350
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5351
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5352
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5353
+	 *
5354
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5355
+	 * @return void
5356
+	 */
5357
+	public function assume_values_already_prepared_by_model_object(
5358
+		$values_already_prepared = self::not_prepared_by_model_object
5359
+	) {
5360
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5361
+	}
5362
+
5363
+
5364
+
5365
+	/**
5366
+	 * Read comments for assume_values_already_prepared_by_model_object()
5367
+	 *
5368
+	 * @return int
5369
+	 */
5370
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5371
+	{
5372
+		return $this->_values_already_prepared_by_model_object;
5373
+	}
5374
+
5375
+
5376
+
5377
+	/**
5378
+	 * Gets all the indexes on this model
5379
+	 *
5380
+	 * @return EE_Index[]
5381
+	 */
5382
+	public function indexes()
5383
+	{
5384
+		return $this->_indexes;
5385
+	}
5386
+
5387
+
5388
+
5389
+	/**
5390
+	 * Gets all the Unique Indexes on this model
5391
+	 *
5392
+	 * @return EE_Unique_Index[]
5393
+	 */
5394
+	public function unique_indexes()
5395
+	{
5396
+		$unique_indexes = array();
5397
+		foreach ($this->_indexes as $name => $index) {
5398
+			if ($index instanceof EE_Unique_Index) {
5399
+				$unique_indexes [$name] = $index;
5400
+			}
5401
+		}
5402
+		return $unique_indexes;
5403
+	}
5404
+
5405
+
5406
+
5407
+	/**
5408
+	 * Gets all the fields which, when combined, make the primary key.
5409
+	 * This is usually just an array with 1 element (the primary key), but in cases
5410
+	 * where there is no primary key, it's a combination of fields as defined
5411
+	 * on a primary index
5412
+	 *
5413
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5414
+	 * @throws \EE_Error
5415
+	 */
5416
+	public function get_combined_primary_key_fields()
5417
+	{
5418
+		foreach ($this->indexes() as $index) {
5419
+			if ($index instanceof EE_Primary_Key_Index) {
5420
+				return $index->fields();
5421
+			}
5422
+		}
5423
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5424
+	}
5425
+
5426
+
5427
+
5428
+	/**
5429
+	 * Used to build a primary key string (when the model has no primary key),
5430
+	 * which can be used a unique string to identify this model object.
5431
+	 *
5432
+	 * @param array $cols_n_values keys are field names, values are their values
5433
+	 * @return string
5434
+	 * @throws \EE_Error
5435
+	 */
5436
+	public function get_index_primary_key_string($cols_n_values)
5437
+	{
5438
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5439
+			$this->get_combined_primary_key_fields());
5440
+		return http_build_query($cols_n_values_for_primary_key_index);
5441
+	}
5442
+
5443
+
5444
+
5445
+	/**
5446
+	 * Gets the field values from the primary key string
5447
+	 *
5448
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5449
+	 * @param string $index_primary_key_string
5450
+	 * @return null|array
5451
+	 * @throws \EE_Error
5452
+	 */
5453
+	public function parse_index_primary_key_string($index_primary_key_string)
5454
+	{
5455
+		$key_fields = $this->get_combined_primary_key_fields();
5456
+		//check all of them are in the $id
5457
+		$key_vals_in_combined_pk = array();
5458
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5459
+		foreach ($key_fields as $key_field_name => $field_obj) {
5460
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5461
+				return null;
5462
+			}
5463
+		}
5464
+		return $key_vals_in_combined_pk;
5465
+	}
5466
+
5467
+
5468
+
5469
+	/**
5470
+	 * verifies that an array of key-value pairs for model fields has a key
5471
+	 * for each field comprising the primary key index
5472
+	 *
5473
+	 * @param array $key_vals
5474
+	 * @return boolean
5475
+	 * @throws \EE_Error
5476
+	 */
5477
+	public function has_all_combined_primary_key_fields($key_vals)
5478
+	{
5479
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5480
+		foreach ($keys_it_should_have as $key) {
5481
+			if (! isset($key_vals[$key])) {
5482
+				return false;
5483
+			}
5484
+		}
5485
+		return true;
5486
+	}
5487
+
5488
+
5489
+
5490
+	/**
5491
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5492
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5493
+	 *
5494
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5495
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5496
+	 * @throws EE_Error
5497
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5498
+	 *                                                              indexed)
5499
+	 */
5500
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5501
+	{
5502
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5503
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5504
+		} elseif (is_array($model_object_or_attributes_array)) {
5505
+			$attributes_array = $model_object_or_attributes_array;
5506
+		} else {
5507
+			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",
5508
+				"event_espresso"), $model_object_or_attributes_array));
5509
+		}
5510
+		//even copies obviously won't have the same ID, so remove the primary key
5511
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5512
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5513
+			unset($attributes_array[$this->primary_key_name()]);
5514
+		}
5515
+		if (isset($query_params[0])) {
5516
+			$query_params[0] = array_merge($attributes_array, $query_params);
5517
+		} else {
5518
+			$query_params[0] = $attributes_array;
5519
+		}
5520
+		return $this->get_all($query_params);
5521
+	}
5522
+
5523
+
5524
+
5525
+	/**
5526
+	 * Gets the first copy we find. See get_all_copies for more details
5527
+	 *
5528
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5529
+	 * @param array $query_params
5530
+	 * @return EE_Base_Class
5531
+	 * @throws \EE_Error
5532
+	 */
5533
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5534
+	{
5535
+		if (! is_array($query_params)) {
5536
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5537
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5538
+					gettype($query_params)), '4.6.0');
5539
+			$query_params = array();
5540
+		}
5541
+		$query_params['limit'] = 1;
5542
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5543
+		if (is_array($copies)) {
5544
+			return array_shift($copies);
5545
+		} else {
5546
+			return null;
5547
+		}
5548
+	}
5549
+
5550
+
5551
+
5552
+	/**
5553
+	 * Updates the item with the specified id. Ignores default query parameters because
5554
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5555
+	 *
5556
+	 * @param array      $fields_n_values keys are field names, values are their new values
5557
+	 * @param int|string $id              the value of the primary key to update
5558
+	 * @return int number of rows updated
5559
+	 * @throws \EE_Error
5560
+	 */
5561
+	public function update_by_ID($fields_n_values, $id)
5562
+	{
5563
+		$query_params = array(
5564
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5565
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5566
+		);
5567
+		return $this->update($fields_n_values, $query_params);
5568
+	}
5569
+
5570
+
5571
+
5572
+	/**
5573
+	 * Changes an operator which was supplied to the models into one usable in SQL
5574
+	 *
5575
+	 * @param string $operator_supplied
5576
+	 * @return string an operator which can be used in SQL
5577
+	 * @throws EE_Error
5578
+	 */
5579
+	private function _prepare_operator_for_sql($operator_supplied)
5580
+	{
5581
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5582
+			: null;
5583
+		if ($sql_operator) {
5584
+			return $sql_operator;
5585
+		} else {
5586
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5587
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5588
+		}
5589
+	}
5590
+
5591
+
5592
+
5593
+	/**
5594
+	 * Gets an array where keys are the primary keys and values are their 'names'
5595
+	 * (as determined by the model object's name() function, which is often overridden)
5596
+	 *
5597
+	 * @param array $query_params like get_all's
5598
+	 * @return string[]
5599
+	 * @throws \EE_Error
5600
+	 */
5601
+	public function get_all_names($query_params = array())
5602
+	{
5603
+		$objs = $this->get_all($query_params);
5604
+		$names = array();
5605
+		foreach ($objs as $obj) {
5606
+			$names[$obj->ID()] = $obj->name();
5607
+		}
5608
+		return $names;
5609
+	}
5610
+
5611
+
5612
+
5613
+	/**
5614
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5615
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5616
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5617
+	 * array_keys() on $model_objects.
5618
+	 *
5619
+	 * @param \EE_Base_Class[] $model_objects
5620
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5621
+	 *                                               in the returned array
5622
+	 * @return array
5623
+	 * @throws \EE_Error
5624
+	 */
5625
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5626
+	{
5627
+		if (! $this->has_primary_key_field()) {
5628
+			if (WP_DEBUG) {
5629
+				EE_Error::add_error(
5630
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5631
+					__FILE__,
5632
+					__FUNCTION__,
5633
+					__LINE__
5634
+				);
5635
+			}
5636
+		}
5637
+		$IDs = array();
5638
+		foreach ($model_objects as $model_object) {
5639
+			$id = $model_object->ID();
5640
+			if (! $id) {
5641
+				if ($filter_out_empty_ids) {
5642
+					continue;
5643
+				}
5644
+				if (WP_DEBUG) {
5645
+					EE_Error::add_error(
5646
+						__(
5647
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5648
+							'event_espresso'
5649
+						),
5650
+						__FILE__,
5651
+						__FUNCTION__,
5652
+						__LINE__
5653
+					);
5654
+				}
5655
+			}
5656
+			$IDs[] = $id;
5657
+		}
5658
+		return $IDs;
5659
+	}
5660
+
5661
+
5662
+
5663
+	/**
5664
+	 * Returns the string used in capabilities relating to this model. If there
5665
+	 * are no capabilities that relate to this model returns false
5666
+	 *
5667
+	 * @return string|false
5668
+	 */
5669
+	public function cap_slug()
5670
+	{
5671
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5672
+	}
5673
+
5674
+
5675
+
5676
+	/**
5677
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5678
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5679
+	 * only returns the cap restrictions array in that context (ie, the array
5680
+	 * at that key)
5681
+	 *
5682
+	 * @param string $context
5683
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5684
+	 * @throws \EE_Error
5685
+	 */
5686
+	public function cap_restrictions($context = EEM_Base::caps_read)
5687
+	{
5688
+		EEM_Base::verify_is_valid_cap_context($context);
5689
+		//check if we ought to run the restriction generator first
5690
+		if (
5691
+			isset($this->_cap_restriction_generators[$context])
5692
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5693
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5694
+		) {
5695
+			$this->_cap_restrictions[$context] = array_merge(
5696
+				$this->_cap_restrictions[$context],
5697
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5698
+			);
5699
+		}
5700
+		//and make sure we've finalized the construction of each restriction
5701
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5702
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5703
+				$where_conditions_obj->_finalize_construct($this);
5704
+			}
5705
+		}
5706
+		return $this->_cap_restrictions[$context];
5707
+	}
5708
+
5709
+
5710
+
5711
+	/**
5712
+	 * Indicating whether or not this model thinks its a wp core model
5713
+	 *
5714
+	 * @return boolean
5715
+	 */
5716
+	public function is_wp_core_model()
5717
+	{
5718
+		return $this->_wp_core_model;
5719
+	}
5720
+
5721
+
5722
+
5723
+	/**
5724
+	 * Gets all the caps that are missing which impose a restriction on
5725
+	 * queries made in this context
5726
+	 *
5727
+	 * @param string $context one of EEM_Base::caps_ constants
5728
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5729
+	 * @throws \EE_Error
5730
+	 */
5731
+	public function caps_missing($context = EEM_Base::caps_read)
5732
+	{
5733
+		$missing_caps = array();
5734
+		$cap_restrictions = $this->cap_restrictions($context);
5735
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5736
+			if (! EE_Capabilities::instance()
5737
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5738
+			) {
5739
+				$missing_caps[$cap] = $restriction_if_no_cap;
5740
+			}
5741
+		}
5742
+		return $missing_caps;
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Gets the mapping from capability contexts to action strings used in capability names
5749
+	 *
5750
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5751
+	 * one of 'read', 'edit', or 'delete'
5752
+	 */
5753
+	public function cap_contexts_to_cap_action_map()
5754
+	{
5755
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5756
+			$this);
5757
+	}
5758
+
5759
+
5760
+
5761
+	/**
5762
+	 * Gets the action string for the specified capability context
5763
+	 *
5764
+	 * @param string $context
5765
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5766
+	 * @throws \EE_Error
5767
+	 */
5768
+	public function cap_action_for_context($context)
5769
+	{
5770
+		$mapping = $this->cap_contexts_to_cap_action_map();
5771
+		if (isset($mapping[$context])) {
5772
+			return $mapping[$context];
5773
+		}
5774
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5775
+			return $action;
5776
+		}
5777
+		throw new EE_Error(
5778
+			sprintf(
5779
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5780
+				$context,
5781
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5782
+			)
5783
+		);
5784
+	}
5785
+
5786
+
5787
+
5788
+	/**
5789
+	 * Returns all the capability contexts which are valid when querying models
5790
+	 *
5791
+	 * @return array
5792
+	 */
5793
+	public static function valid_cap_contexts()
5794
+	{
5795
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5796
+			self::caps_read,
5797
+			self::caps_read_admin,
5798
+			self::caps_edit,
5799
+			self::caps_delete,
5800
+		));
5801
+	}
5802
+
5803
+
5804
+
5805
+	/**
5806
+	 * Returns all valid options for 'default_where_conditions'
5807
+	 *
5808
+	 * @return array
5809
+	 */
5810
+	public static function valid_default_where_conditions()
5811
+	{
5812
+		return array(
5813
+			EEM_Base::default_where_conditions_all,
5814
+			EEM_Base::default_where_conditions_this_only,
5815
+			EEM_Base::default_where_conditions_others_only,
5816
+			EEM_Base::default_where_conditions_minimum_all,
5817
+			EEM_Base::default_where_conditions_minimum_others,
5818
+			EEM_Base::default_where_conditions_none
5819
+		);
5820
+	}
5821
+
5822
+	// public static function default_where_conditions_full
5823
+	/**
5824
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5825
+	 *
5826
+	 * @param string $context
5827
+	 * @return bool
5828
+	 * @throws \EE_Error
5829
+	 */
5830
+	static public function verify_is_valid_cap_context($context)
5831
+	{
5832
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5833
+		if (in_array($context, $valid_cap_contexts)) {
5834
+			return true;
5835
+		} else {
5836
+			throw new EE_Error(
5837
+				sprintf(
5838
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5839
+						'event_espresso'),
5840
+					$context,
5841
+					'EEM_Base',
5842
+					implode(',', $valid_cap_contexts)
5843
+				)
5844
+			);
5845
+		}
5846
+	}
5847
+
5848
+
5849
+
5850
+	/**
5851
+	 * Clears all the models field caches. This is only useful when a sub-class
5852
+	 * might have added a field or something and these caches might be invalidated
5853
+	 */
5854
+	protected function _invalidate_field_caches()
5855
+	{
5856
+		$this->_cache_foreign_key_to_fields = array();
5857
+		$this->_cached_fields = null;
5858
+		$this->_cached_fields_non_db_only = null;
5859
+	}
5860
+
5861
+
5862
+
5863
+	/**
5864
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5865
+	 * (eg "and", "or", "not").
5866
+	 *
5867
+	 * @return array
5868
+	 */
5869
+	public function logic_query_param_keys()
5870
+	{
5871
+		return $this->_logic_query_param_keys;
5872
+	}
5873
+
5874
+
5875
+
5876
+	/**
5877
+	 * Determines whether or not the where query param array key is for a logic query param.
5878
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5879
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5880
+	 *
5881
+	 * @param $query_param_key
5882
+	 * @return bool
5883
+	 */
5884
+	public function is_logic_query_param_key($query_param_key)
5885
+	{
5886
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5887
+			if ($query_param_key === $logic_query_param_key
5888
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5889
+			) {
5890
+				return true;
5891
+			}
5892
+		}
5893
+		return false;
5894
+	}
5895 5895
 
5896 5896
 
5897 5897
 
Please login to merge, or discard this patch.