Completed
Branch FET-10240-all-qualified-column... (9c5416)
by
unknown
31:46 queued 21:39
created
core/db_models/EEM_Base.model.php 1 patch
Indentation   +5601 added lines, -5601 removed lines patch added patch discarded remove patch
@@ -29,5609 +29,5609 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    //admin posty
33
-    //basic -> grants access to mine -> if they don't have it, select none
34
-    //*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
-    //*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
-    //*_published -> grants access to published -> if they dont have it, select non-published
37
-    //*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
-    //publish_{thing} -> can change status TO publish; SPECIAL CASE
39
-    //frontend posty
40
-    //by default has access to published
41
-    //basic -> grants access to mine that arent published, and all published
42
-    //*_others ->grants access to others that arent private, all mine
43
-    //*_private -> grants full access
44
-    //frontend non-posty
45
-    //like admin posty
46
-    //category-y
47
-    //assign -> grants access to join-table
48
-    //(delete, edit)
49
-    //payment-method-y
50
-    //for each registered payment method,
51
-    //ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
-    /**
53
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
-     * They almost always WILL NOT, but it's not necessarily a requirement.
56
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
-     *
58
-     * @var boolean
59
-     */
60
-    private $_values_already_prepared_by_model_object = 0;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the data is just like form input that needs to have the model fields'
65
-     * prepare_for_set and prepare_for_use_in_db called on it
66
-     */
67
-    const not_prepared_by_model_object = 0;
68
-
69
-    /**
70
-     * when $_values_already_prepared_by_model_object equals this, we
71
-     * assume this value is coming from a model object and doesn't need to have
72
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
73
-     */
74
-    const prepared_by_model_object = 1;
75
-
76
-    /**
77
-     * when $_values_already_prepared_by_model_object equals this, we assume
78
-     * the values are already to be used in the database (ie no processing is done
79
-     * on them by the model's fields)
80
-     */
81
-    const prepared_for_use_in_db = 2;
82
-
83
-
84
-    protected $singular_item = 'Item';
85
-
86
-    protected $plural_item   = 'Items';
87
-
88
-    /**
89
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
-     */
91
-    protected $_tables;
92
-
93
-    /**
94
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
-     *
98
-     * @var \EE_Model_Field_Base[] $_fields
99
-     */
100
-    protected $_fields;
101
-
102
-    /**
103
-     * array of different kinds of relations
104
-     *
105
-     * @var \EE_Model_Relation_Base[] $_model_relations
106
-     */
107
-    protected $_model_relations;
108
-
109
-    /**
110
-     * @var \EE_Index[] $_indexes
111
-     */
112
-    protected $_indexes = array();
113
-
114
-    /**
115
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
116
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
-     * by setting the same columns as used in these queries in the query yourself.
118
-     *
119
-     * @var EE_Default_Where_Conditions
120
-     */
121
-    protected $_default_where_conditions_strategy;
122
-
123
-    /**
124
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
-     * This is particularly useful when you want something between 'none' and 'default'
126
-     *
127
-     * @var EE_Default_Where_Conditions
128
-     */
129
-    protected $_minimum_where_conditions_strategy;
130
-
131
-    /**
132
-     * String describing how to find the "owner" of this model's objects.
133
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
-     * But when there isn't, this indicates which related model, or transiently-related model,
135
-     * has the foreign key to the wp_users table.
136
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
-     * related to events, and events have a foreign key to wp_users.
138
-     * On EEM_Transaction, this would be 'Transaction.Event'
139
-     *
140
-     * @var string
141
-     */
142
-    protected $_model_chain_to_wp_user = '';
143
-
144
-    /**
145
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
-     * don't need it (particularly CPT models)
147
-     *
148
-     * @var bool
149
-     */
150
-    protected $_ignore_where_strategy = false;
151
-
152
-    /**
153
-     * String used in caps relating to this model. Eg, if the caps relating to this
154
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
-     *
156
-     * @var string. If null it hasn't been initialized yet. If false then we
157
-     * have indicated capabilities don't apply to this
158
-     */
159
-    protected $_caps_slug = null;
160
-
161
-    /**
162
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
-     * and next-level keys are capability names, and each's value is a
164
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
-     * they specify which context to use (ie, frontend, backend, edit or delete)
166
-     * and then each capability in the corresponding sub-array that they're missing
167
-     * adds the where conditions onto the query.
168
-     *
169
-     * @var array
170
-     */
171
-    protected $_cap_restrictions = array(
172
-        self::caps_read       => array(),
173
-        self::caps_read_admin => array(),
174
-        self::caps_edit       => array(),
175
-        self::caps_delete     => array(),
176
-    );
177
-
178
-    /**
179
-     * Array defining which cap restriction generators to use to create default
180
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
181
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
-     * automatically set this to false (not just null).
184
-     *
185
-     * @var EE_Restriction_Generator_Base[]
186
-     */
187
-    protected $_cap_restriction_generators = array();
188
-
189
-    /**
190
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
-     */
192
-    const caps_read       = 'read';
193
-
194
-    const caps_read_admin = 'read_admin';
195
-
196
-    const caps_edit       = 'edit';
197
-
198
-    const caps_delete     = 'delete';
199
-
200
-    /**
201
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
-     * maps to 'read' because when looking for relevant permissions we're going to use
204
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_cap_contexts_to_cap_action_map = array(
209
-        self::caps_read       => 'read',
210
-        self::caps_read_admin => 'read',
211
-        self::caps_edit       => 'edit',
212
-        self::caps_delete     => 'delete',
213
-    );
214
-
215
-    /**
216
-     * Timezone
217
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
-     * EE_Datetime_Field data type will have access to it.
221
-     *
222
-     * @var string
223
-     */
224
-    protected $_timezone;
225
-
226
-
227
-    /**
228
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
-     * multisite.
230
-     *
231
-     * @var int
232
-     */
233
-    protected static $_model_query_blog_id;
234
-
235
-    /**
236
-     * A copy of _fields, except the array keys are the model names pointed to by
237
-     * the field
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cache_foreign_key_to_fields = array();
242
-
243
-    /**
244
-     * Cached list of all the fields on the model, indexed by their name
245
-     *
246
-     * @var EE_Model_Field_Base[]
247
-     */
248
-    private $_cached_fields = null;
249
-
250
-    /**
251
-     * Cached list of all the fields on the model, except those that are
252
-     * marked as only pertinent to the database
253
-     *
254
-     * @var EE_Model_Field_Base[]
255
-     */
256
-    private $_cached_fields_non_db_only = null;
257
-
258
-    /**
259
-     * A cached reference to the primary key for quick lookup
260
-     *
261
-     * @var EE_Model_Field_Base
262
-     */
263
-    private $_primary_key_field = null;
264
-
265
-    /**
266
-     * Flag indicating whether this model has a primary key or not
267
-     *
268
-     * @var boolean
269
-     */
270
-    protected $_has_primary_key_field = null;
271
-
272
-    /**
273
-     * Whether or not this model is based off a table in WP core only (CPTs should set
274
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
-     *
276
-     * @var boolean
277
-     */
278
-    protected $_wp_core_model = false;
279
-
280
-    /**
281
-     *    List of valid operators that can be used for querying.
282
-     * The keys are all operators we'll accept, the values are the real SQL
283
-     * operators used
284
-     *
285
-     * @var array
286
-     */
287
-    protected $_valid_operators = array(
288
-        '='           => '=',
289
-        '<='          => '<=',
290
-        '<'           => '<',
291
-        '>='          => '>=',
292
-        '>'           => '>',
293
-        '!='          => '!=',
294
-        'LIKE'        => 'LIKE',
295
-        'like'        => 'LIKE',
296
-        'NOT_LIKE'    => 'NOT LIKE',
297
-        'not_like'    => 'NOT LIKE',
298
-        'NOT LIKE'    => 'NOT LIKE',
299
-        'not like'    => 'NOT LIKE',
300
-        'IN'          => 'IN',
301
-        'in'          => 'IN',
302
-        'NOT_IN'      => 'NOT IN',
303
-        'not_in'      => 'NOT IN',
304
-        'NOT IN'      => 'NOT IN',
305
-        'not in'      => 'NOT IN',
306
-        'between'     => 'BETWEEN',
307
-        'BETWEEN'     => 'BETWEEN',
308
-        'IS_NOT_NULL' => 'IS NOT NULL',
309
-        'is_not_null' => 'IS NOT NULL',
310
-        'IS NOT NULL' => 'IS NOT NULL',
311
-        'is not null' => 'IS NOT NULL',
312
-        'IS_NULL'     => 'IS NULL',
313
-        'is_null'     => 'IS NULL',
314
-        'IS NULL'     => 'IS NULL',
315
-        'is null'     => 'IS NULL',
316
-        'REGEXP'      => 'REGEXP',
317
-        'regexp'      => 'REGEXP',
318
-        'NOT_REGEXP'  => 'NOT REGEXP',
319
-        'not_regexp'  => 'NOT REGEXP',
320
-        'NOT REGEXP'  => 'NOT REGEXP',
321
-        'not regexp'  => 'NOT REGEXP',
322
-    );
323
-
324
-    /**
325
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
-     *
327
-     * @var array
328
-     */
329
-    protected $_in_style_operators = array('IN', 'NOT IN');
330
-
331
-    /**
332
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
-     * '12-31-2012'"
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_between_style_operators = array('BETWEEN');
338
-
339
-    /**
340
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
-     * on a join table.
342
-     *
343
-     * @var array
344
-     */
345
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
-
347
-    /**
348
-     * Allowed values for $query_params['order'] for ordering in queries
349
-     *
350
-     * @var array
351
-     */
352
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
-
354
-    /**
355
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
357
-     *
358
-     * @var array
359
-     */
360
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
-
362
-    /**
363
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
365
-     *
366
-     * @var array
367
-     */
368
-    private $_allowed_query_params = array(
369
-        0,
370
-        'limit',
371
-        'order_by',
372
-        'group_by',
373
-        'having',
374
-        'force_join',
375
-        'order',
376
-        'on_join_limit',
377
-        'default_where_conditions',
378
-        'caps',
379
-    );
380
-
381
-    /**
382
-     * All the data types that can be used in $wpdb->prepare statements.
383
-     *
384
-     * @var array
385
-     */
386
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
-
388
-    /**
389
-     *    EE_Registry Object
390
-     *
391
-     * @var    object
392
-     * @access    protected
393
-     */
394
-    protected $EE = null;
395
-
396
-
397
-    /**
398
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
-     *
400
-     * @var int
401
-     */
402
-    protected $_show_next_x_db_queries = 0;
403
-
404
-    /**
405
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
-     *
408
-     * @var array
409
-     */
410
-    protected $_custom_selections = array();
411
-
412
-    /**
413
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
-     * caches every model object we've fetched from the DB on this request
415
-     *
416
-     * @var array
417
-     */
418
-    protected $_entity_map;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has not yet verified the db on this http request
422
-     */
423
-    const db_verified_none = 0;
424
-
425
-    /**
426
-     * constant used to show EEM_Base has verified the EE core db on this http request,
427
-     * but not the addons' dbs
428
-     */
429
-    const db_verified_core = 1;
430
-
431
-    /**
432
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
-     * the EE core db too)
434
-     */
435
-    const db_verified_addons = 2;
436
-
437
-    /**
438
-     * indicates whether an EEM_Base child has already re-verified the DB
439
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
440
-     * looking like EEM_Base::db_verified_*
441
-     *
442
-     * @var int - 0 = none, 1 = core, 2 = addons
443
-     */
444
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
445
-
446
-
447
-
448
-    /**
449
-     * About all child constructors:
450
-     * they should define the _tables, _fields and _model_relations arrays.
451
-     * Should ALWAYS be called after child constructor.
452
-     * In order to make the child constructors to be as simple as possible, this parent constructor
453
-     * finalizes constructing all the object's attributes.
454
-     * Generally, rather than requiring a child to code
455
-     * $this->_tables = array(
456
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
-     *        ...);
458
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
-     * each EE_Table has a function to set the table's alias after the constructor, using
460
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
-     * do something similar.
462
-     *
463
-     * @param null $timezone
464
-     * @throws \EE_Error
465
-     */
466
-    protected function __construct($timezone = null)
467
-    {
468
-        // check that the model has not been loaded too soon
469
-        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
-            throw new EE_Error (
471
-                sprintf(
472
-                    __('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.',
473
-                        'event_espresso'),
474
-                    get_class($this)
475
-                )
476
-            );
477
-        }
478
-        /**
479
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
-         */
481
-        if (empty(EEM_Base::$_model_query_blog_id)) {
482
-            EEM_Base::set_model_query_blog_id();
483
-        }
484
-        /**
485
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
-         * just use EE_Register_Model_Extension
487
-         *
488
-         * @var EE_Table_Base[] $_tables
489
-         */
490
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
-        foreach ($this->_tables as $table_alias => $table_obj) {
492
-            /** @var $table_obj EE_Table_Base */
493
-            $table_obj->_construct_finalize_with_alias($table_alias);
494
-            if ($table_obj instanceof EE_Secondary_Table) {
495
-                /** @var $table_obj EE_Secondary_Table */
496
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
-            }
498
-        }
499
-        /**
500
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
-         * EE_Register_Model_Extension
502
-         *
503
-         * @param EE_Model_Field_Base[] $_fields
504
-         */
505
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
-        $this->_invalidate_field_caches();
507
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
508
-            if ( ! array_key_exists($table_alias, $this->_tables)) {
509
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
-            }
512
-            foreach ($fields_for_table as $field_name => $field_obj) {
513
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
-                //primary key field base has a slightly different _construct_finalize
515
-                /** @var $field_obj EE_Model_Field_Base */
516
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
-            }
518
-        }
519
-        // everything is related to Extra_Meta
520
-        if (get_class($this) !== 'EEM_Extra_Meta') {
521
-            //make extra meta related to everything, but don't block deleting things just
522
-            //because they have related extra meta info. For now just orphan those extra meta
523
-            //in the future we should automatically delete them
524
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
-        }
526
-        //and change logs
527
-        if (get_class($this) !== 'EEM_Change_Log') {
528
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
-        }
530
-        /**
531
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
-         * EE_Register_Model_Extension
533
-         *
534
-         * @param EE_Model_Relation_Base[] $_model_relations
535
-         */
536
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
-            $this->_model_relations);
538
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
539
-            /** @var $relation_obj EE_Model_Relation_Base */
540
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
-        }
542
-        foreach ($this->_indexes as $index_name => $index_obj) {
543
-            /** @var $index_obj EE_Index */
544
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
-        }
546
-        $this->set_timezone($timezone);
547
-        //finalize default where condition strategy, or set default
548
-        if ( ! $this->_default_where_conditions_strategy) {
549
-            //nothing was set during child constructor, so set default
550
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
-        }
552
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
553
-        if ( ! $this->_minimum_where_conditions_strategy) {
554
-            //nothing was set during child constructor, so set default
555
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
-        }
557
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
559
-        //to indicate to NOT set it, set it to the logical default
560
-        if ($this->_caps_slug === null) {
561
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
-        }
563
-        //initialize the standard cap restriction generators if none were specified by the child constructor
564
-        if ($this->_cap_restriction_generators !== false) {
565
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
-                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
568
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
-                        new EE_Restriction_Generator_Protected(),
570
-                        $cap_context,
571
-                        $this
572
-                    );
573
-                }
574
-            }
575
-        }
576
-        //if there are cap restriction generators, use them to make the default cap restrictions
577
-        if ($this->_cap_restriction_generators !== false) {
578
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
-                if ( ! $generator_object) {
580
-                    continue;
581
-                }
582
-                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
-                    throw new EE_Error(
584
-                        sprintf(
585
-                            __('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.',
586
-                                'event_espresso'),
587
-                            $context,
588
-                            $this->get_this_model_name()
589
-                        )
590
-                    );
591
-                }
592
-                $action = $this->cap_action_for_context($context);
593
-                if ( ! $generator_object->construction_finalized()) {
594
-                    $generator_object->_construct_finalize($this, $action);
595
-                }
596
-            }
597
-        }
598
-        do_action('AHEE__' . get_class($this) . '__construct__end');
599
-    }
600
-
601
-
602
-
603
-    /**
604
-     * Generates the cap restrictions for the given context, or if they were
605
-     * already generated just gets what's cached
606
-     *
607
-     * @param string $context one of EEM_Base::valid_cap_contexts()
608
-     * @return EE_Default_Where_Conditions[]
609
-     */
610
-    protected function _generate_cap_restrictions($context)
611
-    {
612
-        if (isset($this->_cap_restriction_generators[$context])
613
-            && $this->_cap_restriction_generators[$context]
614
-               instanceof
615
-               EE_Restriction_Generator_Base
616
-        ) {
617
-            return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
-        } else {
619
-            return array();
620
-        }
621
-    }
622
-
623
-
624
-
625
-    /**
626
-     * Used to set the $_model_query_blog_id static property.
627
-     *
628
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
-     *                      value for get_current_blog_id() will be used.
630
-     */
631
-    public static function set_model_query_blog_id($blog_id = 0)
632
-    {
633
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
-    }
635
-
636
-
637
-
638
-    /**
639
-     * Returns whatever is set as the internal $model_query_blog_id.
640
-     *
641
-     * @return int
642
-     */
643
-    public static function get_model_query_blog_id()
644
-    {
645
-        return EEM_Base::$_model_query_blog_id;
646
-    }
647
-
648
-
649
-
650
-    /**
651
-     *        This function is a singleton method used to instantiate the Espresso_model object
652
-     *
653
-     * @access public
654
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
-     *                         timezone in the 'timezone_string' wp option)
658
-     * @return static (as in the concrete child class)
659
-     */
660
-    public static function instance($timezone = null)
661
-    {
662
-        // check if instance of Espresso_model already exists
663
-        if ( ! static::$_instance instanceof static) {
664
-            // instantiate Espresso_model
665
-            static::$_instance = new static($timezone);
666
-        }
667
-        //we might have a timezone set, let set_timezone decide what to do with it
668
-        static::$_instance->set_timezone($timezone);
669
-        // Espresso_model object
670
-        return static::$_instance;
671
-    }
672
-
673
-
674
-
675
-    /**
676
-     * resets the model and returns it
677
-     *
678
-     * @param null | string $timezone
679
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
-     * all its properties reset; if it wasn't instantiated, returns null)
681
-     */
682
-    public static function reset($timezone = null)
683
-    {
684
-        if (static::$_instance instanceof EEM_Base) {
685
-            //let's try to NOT swap out the current instance for a new one
686
-            //because if someone has a reference to it, we can't remove their reference
687
-            //so it's best to keep using the same reference, but change the original object
688
-            //reset all its properties to their original values as defined in the class
689
-            $r = new ReflectionClass(get_class(static::$_instance));
690
-            $static_properties = $r->getStaticProperties();
691
-            foreach ($r->getDefaultProperties() as $property => $value) {
692
-                //don't set instance to null like it was originally,
693
-                //but it's static anyways, and we're ignoring static properties (for now at least)
694
-                if ( ! isset($static_properties[$property])) {
695
-                    static::$_instance->{$property} = $value;
696
-                }
697
-            }
698
-            //and then directly call its constructor again, like we would if we
699
-            //were creating a new one
700
-            static::$_instance->__construct($timezone);
701
-            return self::instance();
702
-        }
703
-        return null;
704
-    }
705
-
706
-
707
-
708
-    /**
709
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
-     *
711
-     * @param  boolean $translated return localized strings or JUST the array.
712
-     * @return array
713
-     * @throws \EE_Error
714
-     */
715
-    public function status_array($translated = false)
716
-    {
717
-        if ( ! array_key_exists('Status', $this->_model_relations)) {
718
-            return array();
719
-        }
720
-        $model_name = $this->get_this_model_name();
721
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
-        $status_array = array();
724
-        foreach ($stati as $status) {
725
-            $status_array[$status->ID()] = $status->get('STS_code');
726
-        }
727
-        return $translated
728
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
-            : $status_array;
730
-    }
731
-
732
-
733
-
734
-    /**
735
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
-     *
737
-     * @param array $query_params             {
738
-     * @var array $0 (where) array {
739
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
-     *                                        conditions based on related models (and even
743
-     *                                        models-related-to-related-models) prepend the model's name onto the field
744
-     *                                        name. Eg,
745
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
-     *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
-     *                                        "Venue.VNU_ID", you could have
752
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
-     *                                        events are related to Registrations, which are related to Attendees). You
754
-     *                                        can take it even further with
755
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
-     *                                        (from the default of '='), change the value to an numerically-indexed
757
-     *                                        array, where the first item in the list is the operator. eg: array(
758
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
-     *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
-     *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
-     *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
-     *                                        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__>' =>
767
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
-     *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
-     *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
-     *                                        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
773
-     *                                        place two or more where conditions applying to the same field. eg:
774
-     *                                        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
775
-     *                                        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 '*'
776
-     *                                        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
777
-     *                                        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 >>
778
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
-     *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
-     *                                        the OFFSET, the 2nd is the LIMIT
784
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
-     *                                        => array( 'table_alias', array(1,2) ) ).
787
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
-     *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
-     *                                        'where' conditions, these fields can be on related models. Eg
791
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
-     *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
-     *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
-     *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
-     *                                        want to order by the primary key. Eg,
797
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
-     *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
-     *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
-     *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
-     *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
-     *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
-     *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
-     *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
-     *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
-     *                                        (ie, the current model has a foreign key to them, like how Registration
813
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
814
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
-     *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
-     *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
-     *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
-     *                                        (default), set to 'all'.
820
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
-     *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
-     *                                        }
825
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
-     *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
-     *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
-     *                                        EEM_Transaction::instance()->get_all( array( array(
830
-     *                                        'OR'=>array(
831
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
-     *                                        )
834
-     *                                        ),
835
-     *                                        'limit'=>10,
836
-     *                                        'group_by'=>'TXN_ID'
837
-     *                                        ));
838
-     *                                        get all the answers to the question titled "shirt size" for event with id
839
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
-     *                                        'Question.QST_display_text'=>'shirt size',
841
-     *                                        'Registration.Event.EVT_ID'=>12
842
-     *                                        ),
843
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
844
-     *                                        ));
845
-     * @throws \EE_Error
846
-     */
847
-    public function get_all($query_params = array())
848
-    {
849
-        if (isset($query_params['limit'])
850
-            && ! isset($query_params['group_by'])
851
-        ) {
852
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
-        }
854
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
-    }
856
-
857
-
858
-
859
-    /**
860
-     * Modifies the query parameters so we only get back model objects
861
-     * that "belong" to the current user
862
-     *
863
-     * @param array $query_params @see EEM_Base::get_all()
864
-     * @return array like EEM_Base::get_all
865
-     */
866
-    public function alter_query_params_to_only_include_mine($query_params = array())
867
-    {
868
-        $wp_user_field_name = $this->wp_user_field_name();
869
-        if ($wp_user_field_name) {
870
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
871
-        }
872
-        return $query_params;
873
-    }
874
-
875
-
876
-
877
-    /**
878
-     * Returns the name of the field's name that points to the WP_User table
879
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
-     * foreign key to the WP_User table)
881
-     *
882
-     * @return string|boolean string on success, boolean false when there is no
883
-     * foreign key to the WP_User table
884
-     */
885
-    public function wp_user_field_name()
886
-    {
887
-        try {
888
-            if ( ! empty($this->_model_chain_to_wp_user)) {
889
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
-                $last_model_name = end($models_to_follow_to_wp_users);
891
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
-            } else {
894
-                $model_with_fk_to_wp_users = $this;
895
-                $model_chain_to_wp_user = '';
896
-            }
897
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
899
-        } catch (EE_Error $e) {
900
-            return false;
901
-        }
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
908
-     * (or transiently-related model) has a foreign key to the wp_users table;
909
-     * useful for finding if model objects of this type are 'owned' by the current user.
910
-     * This is an empty string when the foreign key is on this model and when it isn't,
911
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
912
-     * (or transiently-related model)
913
-     *
914
-     * @return string
915
-     */
916
-    public function model_chain_to_wp_user()
917
-    {
918
-        return $this->_model_chain_to_wp_user;
919
-    }
920
-
921
-
922
-
923
-    /**
924
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
-     * like how registrations don't have a foreign key to wp_users, but the
926
-     * events they are for are), or is unrelated to wp users.
927
-     * generally available
928
-     *
929
-     * @return boolean
930
-     */
931
-    public function is_owned()
932
-    {
933
-        if ($this->model_chain_to_wp_user()) {
934
-            return true;
935
-        } else {
936
-            try {
937
-                $this->get_foreign_key_to('WP_User');
938
-                return true;
939
-            } catch (EE_Error $e) {
940
-                return false;
941
-            }
942
-        }
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
-     * the model)
951
-     *
952
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
953
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
-     *                                  fields on the model, and the models we joined to in the query. However, you can
956
-     *                                  override this and set the select to "*", or a specific column name, like
957
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
-     *                                  the aliases used to refer to this selection, and values are to be
960
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
-     * @throws \EE_Error
964
-     */
965
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
-    {
967
-        // remember the custom selections, if any, and type cast as array
968
-        // (unless $columns_to_select is an object, then just set as an empty array)
969
-        // Note: (array) 'some string' === array( 'some string' )
970
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
972
-        $select_expressions = $columns_to_select !== null
973
-            ? $this->_construct_select_from_input($columns_to_select)
974
-            : $this->_construct_default_select_sql($model_query_info);
975
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
-    }
978
-
979
-
980
-
981
-    /**
982
-     * Gets an array of rows from the database just like $wpdb->get_results would,
983
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
-     * take care of joins, field preparation etc.
985
-     *
986
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
987
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
-     *                                  fields on the model, and the models we joined to in the query. However, you can
990
-     *                                  override this and set the select to "*", or a specific column name, like
991
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
-     *                                  the aliases used to refer to this selection, and values are to be
994
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
-     * @throws \EE_Error
998
-     */
999
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
-    {
1001
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
-    }
1003
-
1004
-
1005
-
1006
-    /**
1007
-     * For creating a custom select statement
1008
-     *
1009
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
-     *                                 SQL, and 1=>is the datatype
1012
-     * @throws EE_Error
1013
-     * @return string
1014
-     */
1015
-    private function _construct_select_from_input($columns_to_select)
1016
-    {
1017
-        if (is_array($columns_to_select)) {
1018
-            $select_sql_array = array();
1019
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
-                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
-                    throw new EE_Error(
1022
-                        sprintf(
1023
-                            __(
1024
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
-                                "event_espresso"
1026
-                            ),
1027
-                            $selection_and_datatype,
1028
-                            $alias
1029
-                        )
1030
-                    );
1031
-                }
1032
-                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
-                    throw new EE_Error(
1034
-                        sprintf(
1035
-                            __(
1036
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
-                                "event_espresso"
1038
-                            ),
1039
-                            $selection_and_datatype[1],
1040
-                            $selection_and_datatype[0],
1041
-                            $alias,
1042
-                            implode(",", $this->_valid_wpdb_data_types)
1043
-                        )
1044
-                    );
1045
-                }
1046
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
-            }
1048
-            $columns_to_select_string = implode(", ", $select_sql_array);
1049
-        } else {
1050
-            $columns_to_select_string = $columns_to_select;
1051
-        }
1052
-        return $columns_to_select_string;
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
-     *
1060
-     * @return string
1061
-     * @throws \EE_Error
1062
-     */
1063
-    public function primary_key_name()
1064
-    {
1065
-        return $this->get_primary_key_field()->get_name();
1066
-    }
1067
-
1068
-
1069
-
1070
-    /**
1071
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
-     * If there is no primary key on this model, $id is treated as primary key string
1073
-     *
1074
-     * @param mixed $id int or string, depending on the type of the model's primary key
1075
-     * @return EE_Base_Class
1076
-     */
1077
-    public function get_one_by_ID($id)
1078
-    {
1079
-        if ($this->get_from_entity_map($id)) {
1080
-            return $this->get_from_entity_map($id);
1081
-        }
1082
-        return $this->get_one(
1083
-            $this->alter_query_params_to_restrict_by_ID(
1084
-                $id,
1085
-                array('default_where_conditions' => 'minimum')
1086
-            )
1087
-        );
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * Alters query parameters to only get items with this ID are returned.
1094
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
-     * or could just be a simple primary key ID
1096
-     *
1097
-     * @param int   $id
1098
-     * @param array $query_params
1099
-     * @return array of normal query params, @see EEM_Base::get_all
1100
-     * @throws \EE_Error
1101
-     */
1102
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
-    {
1104
-        if ( ! isset($query_params[0])) {
1105
-            $query_params[0] = array();
1106
-        }
1107
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1108
-        if ($conditions_from_id === null) {
1109
-            $query_params[0][$this->primary_key_name()] = $id;
1110
-        } else {
1111
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1112
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
-        }
1114
-        return $query_params;
1115
-    }
1116
-
1117
-
1118
-
1119
-    /**
1120
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
-     * array. If no item is found, null is returned.
1122
-     *
1123
-     * @param array $query_params like EEM_Base's $query_params variable.
1124
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
-     * @throws \EE_Error
1126
-     */
1127
-    public function get_one($query_params = array())
1128
-    {
1129
-        if ( ! is_array($query_params)) {
1130
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
-                    gettype($query_params)), '4.6.0');
1133
-            $query_params = array();
1134
-        }
1135
-        $query_params['limit'] = 1;
1136
-        $items = $this->get_all($query_params);
1137
-        if (empty($items)) {
1138
-            return null;
1139
-        } else {
1140
-            return array_shift($items);
1141
-        }
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Returns the next x number of items in sequence from the given value as
1148
-     * found in the database matching the given query conditions.
1149
-     *
1150
-     * @param mixed $current_field_value    Value used for the reference point.
1151
-     * @param null  $field_to_order_by      What field is used for the
1152
-     *                                      reference point.
1153
-     * @param int   $limit                  How many to return.
1154
-     * @param array $query_params           Extra conditions on the query.
1155
-     * @param null  $columns_to_select      If left null, then an array of
1156
-     *                                      EE_Base_Class objects is returned,
1157
-     *                                      otherwise you can indicate just the
1158
-     *                                      columns you want returned.
1159
-     * @return EE_Base_Class[]|array
1160
-     * @throws \EE_Error
1161
-     */
1162
-    public function next_x(
1163
-        $current_field_value,
1164
-        $field_to_order_by = null,
1165
-        $limit = 1,
1166
-        $query_params = array(),
1167
-        $columns_to_select = null
1168
-    ) {
1169
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
-            $columns_to_select);
1171
-    }
1172
-
1173
-
1174
-
1175
-    /**
1176
-     * Returns the previous x number of items in sequence from the given value
1177
-     * as found in the database matching the given query conditions.
1178
-     *
1179
-     * @param mixed $current_field_value    Value used for the reference point.
1180
-     * @param null  $field_to_order_by      What field is used for the
1181
-     *                                      reference point.
1182
-     * @param int   $limit                  How many to return.
1183
-     * @param array $query_params           Extra conditions on the query.
1184
-     * @param null  $columns_to_select      If left null, then an array of
1185
-     *                                      EE_Base_Class objects is returned,
1186
-     *                                      otherwise you can indicate just the
1187
-     *                                      columns you want returned.
1188
-     * @return EE_Base_Class[]|array
1189
-     * @throws \EE_Error
1190
-     */
1191
-    public function previous_x(
1192
-        $current_field_value,
1193
-        $field_to_order_by = null,
1194
-        $limit = 1,
1195
-        $query_params = array(),
1196
-        $columns_to_select = null
1197
-    ) {
1198
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
-            $columns_to_select);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next item in sequence from the given value as found in the
1206
-     * database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param array $query_params           Extra conditions on the query.
1212
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
-     *                                      object is returned, otherwise you
1214
-     *                                      can indicate just the columns you
1215
-     *                                      want and a single array indexed by
1216
-     *                                      the columns will be returned.
1217
-     * @return EE_Base_Class|null|array()
1218
-     * @throws \EE_Error
1219
-     */
1220
-    public function next(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $query_params = array(),
1224
-        $columns_to_select = null
1225
-    ) {
1226
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
-            $columns_to_select);
1228
-        return empty($results) ? null : reset($results);
1229
-    }
1230
-
1231
-
1232
-
1233
-    /**
1234
-     * Returns the previous item in sequence from the given value as found in
1235
-     * the database matching the given query conditions.
1236
-     *
1237
-     * @param mixed $current_field_value    Value used for the reference point.
1238
-     * @param null  $field_to_order_by      What field is used for the
1239
-     *                                      reference point.
1240
-     * @param array $query_params           Extra conditions on the query.
1241
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
-     *                                      object is returned, otherwise you
1243
-     *                                      can indicate just the columns you
1244
-     *                                      want and a single array indexed by
1245
-     *                                      the columns will be returned.
1246
-     * @return EE_Base_Class|null|array()
1247
-     * @throws EE_Error
1248
-     */
1249
-    public function previous(
1250
-        $current_field_value,
1251
-        $field_to_order_by = null,
1252
-        $query_params = array(),
1253
-        $columns_to_select = null
1254
-    ) {
1255
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
-            $columns_to_select);
1257
-        return empty($results) ? null : reset($results);
1258
-    }
1259
-
1260
-
1261
-
1262
-    /**
1263
-     * Returns the a consecutive number of items in sequence from the given
1264
-     * value as found in the database matching the given query conditions.
1265
-     *
1266
-     * @param mixed  $current_field_value   Value used for the reference point.
1267
-     * @param string $operand               What operand is used for the sequence.
1268
-     * @param string $field_to_order_by     What field is used for the reference point.
1269
-     * @param int    $limit                 How many to return.
1270
-     * @param array  $query_params          Extra conditions on the query.
1271
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the columns you want returned.
1273
-     * @return EE_Base_Class[]|array
1274
-     * @throws EE_Error
1275
-     */
1276
-    protected function _get_consecutive(
1277
-        $current_field_value,
1278
-        $operand = '>',
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
-        if (empty($field_to_order_by)) {
1286
-            if ($this->has_primary_key_field()) {
1287
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1288
-            } else {
1289
-                if (WP_DEBUG) {
1290
-                    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).',
1291
-                        'event_espresso'));
1292
-                }
1293
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
-                return array();
1295
-            }
1296
-        }
1297
-        if ( ! is_array($query_params)) {
1298
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
-                    gettype($query_params)), '4.6.0');
1301
-            $query_params = array();
1302
-        }
1303
-        //let's add the where query param for consecutive look up.
1304
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
-        $query_params['limit'] = $limit;
1306
-        //set direction
1307
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
-        $query_params['order_by'] = $operand === '>'
1309
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
-        if (empty($columns_to_select)) {
1313
-            return $this->get_all($query_params);
1314
-        } else {
1315
-            //getting just the fields
1316
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
-        }
1318
-    }
1319
-
1320
-
1321
-
1322
-    /**
1323
-     * This sets the _timezone property after model object has been instantiated.
1324
-     *
1325
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
-     */
1327
-    public function set_timezone($timezone)
1328
-    {
1329
-        if ($timezone !== null) {
1330
-            $this->_timezone = $timezone;
1331
-        }
1332
-        //note we need to loop through relations and set the timezone on those objects as well.
1333
-        foreach ($this->_model_relations as $relation) {
1334
-            $relation->set_timezone($timezone);
1335
-        }
1336
-        //and finally we do the same for any datetime fields
1337
-        foreach ($this->_fields as $field) {
1338
-            if ($field instanceof EE_Datetime_Field) {
1339
-                $field->set_timezone($timezone);
1340
-            }
1341
-        }
1342
-    }
1343
-
1344
-
1345
-
1346
-    /**
1347
-     * This just returns whatever is set for the current timezone.
1348
-     *
1349
-     * @access public
1350
-     * @return string
1351
-     */
1352
-    public function get_timezone()
1353
-    {
1354
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
-        if (empty($this->_timezone)) {
1356
-            foreach ($this->_fields as $field) {
1357
-                if ($field instanceof EE_Datetime_Field) {
1358
-                    $this->set_timezone($field->get_timezone());
1359
-                    break;
1360
-                }
1361
-            }
1362
-        }
1363
-        //if timezone STILL empty then return the default timezone for the site.
1364
-        if (empty($this->_timezone)) {
1365
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
-        }
1367
-        return $this->_timezone;
1368
-    }
1369
-
1370
-
1371
-
1372
-    /**
1373
-     * This returns the date formats set for the given field name and also ensures that
1374
-     * $this->_timezone property is set correctly.
1375
-     *
1376
-     * @since 4.6.x
1377
-     * @param string $field_name The name of the field the formats are being retrieved for.
1378
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
-     * @return array formats in an array with the date format first, and the time format last.
1381
-     */
1382
-    public function get_formats_for($field_name, $pretty = false)
1383
-    {
1384
-        $field_settings = $this->field_settings_for($field_name);
1385
-        //if not a valid EE_Datetime_Field then throw error
1386
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
-            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.',
1388
-                'event_espresso'), $field_name));
1389
-        }
1390
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
-        //the field.
1392
-        $this->_timezone = $field_settings->get_timezone();
1393
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
-    }
1395
-
1396
-
1397
-
1398
-    /**
1399
-     * This returns the current time in a format setup for a query on this model.
1400
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
-     * it will return:
1402
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
-     *  NOW
1404
-     *  - or a unix timestamp (equivalent to time())
1405
-     *
1406
-     * @since 4.6.x
1407
-     * @param string $field_name       The field the current time is needed for.
1408
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
-     *                                 formatted string matching the set format for the field in the set timezone will
1410
-     *                                 be returned.
1411
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
-     *                                 exception is triggered.
1415
-     */
1416
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
-    {
1418
-        $formats = $this->get_formats_for($field_name);
1419
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
-        if ($timestamp) {
1421
-            return $DateTime->format('U');
1422
-        }
1423
-        //not returning timestamp, so return formatted string in timezone.
1424
-        switch ($what) {
1425
-            case 'time' :
1426
-                return $DateTime->format($formats[1]);
1427
-                break;
1428
-            case 'date' :
1429
-                return $DateTime->format($formats[0]);
1430
-                break;
1431
-            default :
1432
-                return $DateTime->format(implode(' ', $formats));
1433
-                break;
1434
-        }
1435
-    }
1436
-
1437
-
1438
-
1439
-    /**
1440
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
-     * for the model are.  Returns a DateTime object.
1442
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
-     * ignored.
1445
-     *
1446
-     * @param string $field_name      The field being setup.
1447
-     * @param string $timestring      The date time string being used.
1448
-     * @param string $incoming_format The format for the time string.
1449
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
-     *                                format is
1452
-     *                                'U', this is ignored.
1453
-     * @return DateTime
1454
-     * @throws \EE_Error
1455
-     */
1456
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
-    {
1458
-        //just using this to ensure the timezone is set correctly internally
1459
-        $this->get_formats_for($field_name);
1460
-        //load EEH_DTT_Helper
1461
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
-        return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
-    }
1465
-
1466
-
1467
-
1468
-    /**
1469
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
-     *
1471
-     * @return EE_Table_Base[]
1472
-     */
1473
-    public function get_tables()
1474
-    {
1475
-        return $this->_tables;
1476
-    }
1477
-
1478
-
1479
-
1480
-    /**
1481
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
-     * model object with EVT_ID = 1
1487
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
-     * are not specified)
1492
-     *
1493
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1498
-     *                                         ID=34, we'd use this method as follows:
1499
-     *                                         EEM_Transaction::instance()->update(
1500
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
-     *                                         array(array('TXN_ID'=>34)));
1502
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
-     *                                         in client code into what's expected to be stored on each field. Eg,
1504
-     *                                         consider updating Question's QST_admin_label field is of type
1505
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
-     *                                         TRUE, it is assumed that you've already called
1510
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
-     *                                         malicious javascript. However, if
1512
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
-     *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
-     *                                         in this model's entity map according to $fields_n_values that match
1517
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1518
-     *                                         by setting this to FALSE, but be aware that model objects being used
1519
-     *                                         could get out-of-sync with the database
1520
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
-    {
1526
-        if ( ! is_array($query_params)) {
1527
-            EE_Error::doing_it_wrong('EEM_Base::update',
1528
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
-                    gettype($query_params)), '4.6.0');
1530
-            $query_params = array();
1531
-        }
1532
-        /**
1533
-         * Action called before a model update call has been made.
1534
-         *
1535
-         * @param EEM_Base $model
1536
-         * @param array    $fields_n_values the updated fields and their new values
1537
-         * @param array    $query_params    @see EEM_Base::get_all()
1538
-         */
1539
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
-        /**
1541
-         * Filters the fields about to be updated given the query parameters. You can provide the
1542
-         * $query_params to $this->get_all() to find exactly which records will be updated
1543
-         *
1544
-         * @param array    $fields_n_values fields and their new values
1545
-         * @param EEM_Base $model           the model being queried
1546
-         * @param array    $query_params    see EEM_Base::get_all()
1547
-         */
1548
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
-            $query_params);
1550
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
-        //to do that, for each table, verify that it's PK isn't null.
1552
-        $tables = $this->get_tables();
1553
-        //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
1554
-        //NOTE: we should make this code more efficient by NOT querying twice
1555
-        //before the real update, but that needs to first go through ALPHA testing
1556
-        //as it's dangerous. says Mike August 8 2014
1557
-        //we want to make sure the default_where strategy is ignored
1558
-        $this->_ignore_where_strategy = true;
1559
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
-        foreach ($wpdb_select_results as $wpdb_result) {
1561
-            // type cast stdClass as array
1562
-            $wpdb_result = (array)$wpdb_result;
1563
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
-            if ($this->has_primary_key_field()) {
1565
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
-            } else {
1567
-                //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)
1568
-                $main_table_pk_value = null;
1569
-            }
1570
-            //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
1571
-            //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
1572
-            if (count($tables) > 1) {
1573
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
-                //in that table, and so we'll want to insert one
1575
-                foreach ($tables as $table_obj) {
1576
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
-                    //if there is no private key for this table on the results, it means there's no entry
1578
-                    //in this table, right? so insert a row in the current table, using any fields available
1579
-                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
-                            && $wpdb_result[$this_table_pk_column])
1581
-                    ) {
1582
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
-                            $main_table_pk_value);
1584
-                        //if we died here, report the error
1585
-                        if ( ! $success) {
1586
-                            return false;
1587
-                        }
1588
-                    }
1589
-                }
1590
-            }
1591
-            //				//and now check that if we have cached any models by that ID on the model, that
1592
-            //				//they also get updated properly
1593
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
-            //				if( $model_object ){
1595
-            //					foreach( $fields_n_values as $field => $value ){
1596
-            //						$model_object->set($field, $value);
1597
-            //let's make sure default_where strategy is followed now
1598
-            $this->_ignore_where_strategy = false;
1599
-        }
1600
-        //if we want to keep model objects in sync, AND
1601
-        //if this wasn't called from a model object (to update itself)
1602
-        //then we want to make sure we keep all the existing
1603
-        //model objects in sync with the db
1604
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
-            if ($this->has_primary_key_field()) {
1606
-                $model_objs_affected_ids = $this->get_col($query_params);
1607
-            } else {
1608
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
-                $model_objs_affected_ids = array();
1611
-                foreach ($models_affected_key_columns as $row) {
1612
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1613
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
-                }
1615
-            }
1616
-            if ( ! $model_objs_affected_ids) {
1617
-                //wait wait wait- if nothing was affected let's stop here
1618
-                return 0;
1619
-            }
1620
-            foreach ($model_objs_affected_ids as $id) {
1621
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
-                if ($model_obj_in_entity_map) {
1623
-                    foreach ($fields_n_values as $field => $new_value) {
1624
-                        $model_obj_in_entity_map->set($field, $new_value);
1625
-                    }
1626
-                }
1627
-            }
1628
-            //if there is a primary key on this model, we can now do a slight optimization
1629
-            if ($this->has_primary_key_field()) {
1630
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
-                $query_params = array(
1632
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
-                    'limit'                    => count($model_objs_affected_ids),
1634
-                    'default_where_conditions' => 'none',
1635
-                );
1636
-            }
1637
-        }
1638
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
-        $SQL = "UPDATE "
1640
-               . $model_query_info->get_full_join_sql()
1641
-               . " SET "
1642
-               . $this->_construct_update_sql($fields_n_values)
1643
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
-        /**
1646
-         * Action called after a model update call has been made.
1647
-         *
1648
-         * @param EEM_Base $model
1649
-         * @param array    $fields_n_values the updated fields and their new values
1650
-         * @param array    $query_params    @see EEM_Base::get_all()
1651
-         * @param int      $rows_affected
1652
-         */
1653
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
-        return $rows_affected;//how many supposedly got updated
1655
-    }
1656
-
1657
-
1658
-
1659
-    /**
1660
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
-     * are teh values of the field specified (or by default the primary key field)
1662
-     * that matched the query params. Note that you should pass the name of the
1663
-     * model FIELD, not the database table's column name.
1664
-     *
1665
-     * @param array  $query_params @see EEM_Base::get_all()
1666
-     * @param string $field_to_select
1667
-     * @return array just like $wpdb->get_col()
1668
-     * @throws \EE_Error
1669
-     */
1670
-    public function get_col($query_params = array(), $field_to_select = null)
1671
-    {
1672
-        if ($field_to_select) {
1673
-            $field = $this->field_settings_for($field_to_select);
1674
-        } elseif ($this->has_primary_key_field()) {
1675
-            $field = $this->get_primary_key_field();
1676
-        } else {
1677
-            //no primary key, just grab the first column
1678
-            $field = reset($this->field_settings());
1679
-        }
1680
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
-        $select_expressions = $field->get_qualified_column();
1682
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
-        return $this->_do_wpdb_query('get_col', array($SQL));
1684
-    }
1685
-
1686
-
1687
-
1688
-    /**
1689
-     * Returns a single column value for a single row from the database
1690
-     *
1691
-     * @param array  $query_params    @see EEM_Base::get_all()
1692
-     * @param string $field_to_select @see EEM_Base::get_col()
1693
-     * @return string
1694
-     * @throws \EE_Error
1695
-     */
1696
-    public function get_var($query_params = array(), $field_to_select = null)
1697
-    {
1698
-        $query_params['limit'] = 1;
1699
-        $col = $this->get_col($query_params, $field_to_select);
1700
-        if ( ! empty($col)) {
1701
-            return reset($col);
1702
-        } else {
1703
-            return null;
1704
-        }
1705
-    }
1706
-
1707
-
1708
-
1709
-    /**
1710
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
-     * injection, but currently no further filtering is done
1713
-     *
1714
-     * @global      $wpdb
1715
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
-     *                               be updated to in the DB
1717
-     * @return string of SQL
1718
-     * @throws \EE_Error
1719
-     */
1720
-    public function _construct_update_sql($fields_n_values)
1721
-    {
1722
-        /** @type WPDB $wpdb */
1723
-        global $wpdb;
1724
-        $cols_n_values = array();
1725
-        foreach ($fields_n_values as $field_name => $value) {
1726
-            $field_obj = $this->field_settings_for($field_name);
1727
-            //if the value is NULL, we want to assign the value to that.
1728
-            //wpdb->prepare doesn't really handle that properly
1729
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
-            $value_sql = $prepared_value === null ? 'NULL'
1731
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
-        }
1734
-        return implode(",", $cols_n_values);
1735
-    }
1736
-
1737
-
1738
-
1739
-    /**
1740
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
-     * Performs a HARD delete, meaning the database row should always be removed,
1742
-     * not just have a flag field on it switched
1743
-     * Wrapper for EEM_Base::delete_permanently()
1744
-     *
1745
-     * @param mixed $id
1746
-     * @return boolean whether the row got deleted or not
1747
-     * @throws \EE_Error
1748
-     */
1749
-    public function delete_permanently_by_ID($id)
1750
-    {
1751
-        return $this->delete_permanently(
1752
-            array(
1753
-                array($this->get_primary_key_field()->get_name() => $id),
1754
-                'limit' => 1,
1755
-            )
1756
-        );
1757
-    }
1758
-
1759
-
1760
-
1761
-    /**
1762
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
-     * Wrapper for EEM_Base::delete()
1764
-     *
1765
-     * @param mixed $id
1766
-     * @return boolean whether the row got deleted or not
1767
-     * @throws \EE_Error
1768
-     */
1769
-    public function delete_by_ID($id)
1770
-    {
1771
-        return $this->delete(
1772
-            array(
1773
-                array($this->get_primary_key_field()->get_name() => $id),
1774
-                'limit' => 1,
1775
-            )
1776
-        );
1777
-    }
1778
-
1779
-
1780
-
1781
-    /**
1782
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1783
-     * meaning if the model has a field that indicates its been "trashed" or
1784
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1785
-     *
1786
-     * @see EEM_Base::delete_permanently
1787
-     * @param array   $query_params
1788
-     * @param boolean $allow_blocking
1789
-     * @return int how many rows got deleted
1790
-     * @throws \EE_Error
1791
-     */
1792
-    public function delete($query_params, $allow_blocking = true)
1793
-    {
1794
-        return $this->delete_permanently($query_params, $allow_blocking);
1795
-    }
1796
-
1797
-
1798
-
1799
-    /**
1800
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1801
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
-     * as archived, not actually deleted
1803
-     *
1804
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
-     *                                deletes regardless of other objects which may depend on it. Its generally
1808
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
-     *                                DB
1810
-     * @return int how many rows got deleted
1811
-     * @throws \EE_Error
1812
-     */
1813
-    public function delete_permanently($query_params, $allow_blocking = true)
1814
-    {
1815
-        /**
1816
-         * Action called just before performing a real deletion query. You can use the
1817
-         * model and its $query_params to find exactly which items will be deleted
1818
-         *
1819
-         * @param EEM_Base $model
1820
-         * @param array    $query_params   @see EEM_Base::get_all()
1821
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1822
-         *                                 to block (prevent) this deletion
1823
-         */
1824
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
-        //some MySQL databases may be running safe mode, which may restrict
1826
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
-        //to delete them
1829
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
-        if ($deletion_where) {
1832
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1833
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
-            $table_aliases = array_keys($this->_tables);
1835
-            $SQL = "DELETE "
1836
-                   . implode(", ", $table_aliases)
1837
-                   . " FROM "
1838
-                   . $model_query_info->get_full_join_sql()
1839
-                   . " WHERE "
1840
-                   . $deletion_where;
1841
-            //		/echo "delete sql:$SQL";
1842
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
-        } else {
1844
-            $rows_deleted = 0;
1845
-        }
1846
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
-        if ($this->has_primary_key_field()) {
1848
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1849
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
-                }
1853
-            }
1854
-        }
1855
-        /**
1856
-         * Action called just after performing a real deletion query. Although at this point the
1857
-         * items should have been deleted
1858
-         *
1859
-         * @param EEM_Base $model
1860
-         * @param array    $query_params @see EEM_Base::get_all()
1861
-         * @param int      $rows_deleted
1862
-         */
1863
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
-        return $rows_deleted;//how many supposedly got deleted
1865
-    }
1866
-
1867
-
1868
-
1869
-    /**
1870
-     * Checks all the relations that throw error messages when there are blocking related objects
1871
-     * for related model objects. If there are any related model objects on those relations,
1872
-     * adds an EE_Error, and return true
1873
-     *
1874
-     * @param EE_Base_Class|int $this_model_obj_or_id
1875
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
-     *                                                 should be ignored when determining whether there are related
1877
-     *                                                 model objects which block this model object's deletion. Useful
1878
-     *                                                 if you know A is related to B and are considering deleting A,
1879
-     *                                                 but want to see if A has any other objects blocking its deletion
1880
-     *                                                 before removing the relation between A and B
1881
-     * @return boolean
1882
-     * @throws \EE_Error
1883
-     */
1884
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
-    {
1886
-        //first, if $ignore_this_model_obj was supplied, get its model
1887
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
-            $ignored_model = $ignore_this_model_obj->get_model();
1889
-        } else {
1890
-            $ignored_model = null;
1891
-        }
1892
-        //now check all the relations of $this_model_obj_or_id and see if there
1893
-        //are any related model objects blocking it?
1894
-        $is_blocked = false;
1895
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1897
-                //if $ignore_this_model_obj was supplied, then for the query
1898
-                //on that model needs to be told to ignore $ignore_this_model_obj
1899
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
-                        array(
1902
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1903
-                                '!=',
1904
-                                $ignore_this_model_obj->ID(),
1905
-                            ),
1906
-                        ),
1907
-                    ));
1908
-                } else {
1909
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
-                }
1911
-                if ($related_model_objects) {
1912
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
-                    $is_blocked = true;
1914
-                }
1915
-            }
1916
-        }
1917
-        return $is_blocked;
1918
-    }
1919
-
1920
-
1921
-
1922
-    /**
1923
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
-     * well.
1925
-     *
1926
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
-     *                                      easily corrupt your DB
1932
-     * @throws EE_Error
1933
-     * @return string    everything that comes after the WHERE statement.
1934
-     */
1935
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
-    {
1937
-        if ($this->has_primary_key_field()) {
1938
-            $primary_table = $this->_get_main_table();
1939
-            $other_tables = $this->_get_other_tables();
1940
-            $deletes = $query = array();
1941
-            foreach ($objects_for_deletion as $delete_object) {
1942
-                //before we mark this object for deletion,
1943
-                //make sure there's no related objects blocking its deletion (if we're checking)
1944
-                if (
1945
-                    $allow_blocking
1946
-                    && $this->delete_is_blocked_by_related_models(
1947
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
-                    )
1949
-                ) {
1950
-                    continue;
1951
-                }
1952
-                //primary table deletes
1953
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
-                }
1956
-                //other tables
1957
-                if ( ! empty($other_tables)) {
1958
-                    foreach ($other_tables as $ot) {
1959
-                        //first check if we've got the foreign key column here.
1960
-                        if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
-                        }
1963
-                        // wait! it's entirely possible that we'll have a the primary key
1964
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
1965
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
-                        }
1968
-                        // finally, it is possible that the fk for this table is found
1969
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
1970
-                        if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
-                            $deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
-                        }
1973
-                    }
1974
-                }
1975
-            }
1976
-            //we should have deletes now, so let's just go through and setup the where statement
1977
-            foreach ($deletes as $column => $values) {
1978
-                //make sure we have unique $values;
1979
-                $values = array_unique($values);
1980
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
-            }
1982
-            return ! empty($query) ? implode(' AND ', $query) : '';
1983
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
-            $ways_to_identify_a_row = array();
1985
-            $fields = $this->get_combined_primary_key_fields();
1986
-            //note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
-            foreach ($objects_for_deletion as $delete_object) {
1988
-                $values_for_each_cpk_for_a_row = array();
1989
-                foreach ($fields as $cpk_field) {
1990
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
1991
-                        $values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
-                                                           . "="
1993
-                                                           . $delete_object[$cpk_field->get_qualified_column()];
1994
-                    }
1995
-                }
1996
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
-            }
1998
-            return implode(" OR ", $ways_to_identify_a_row);
1999
-        } else {
2000
-            //so there's no primary key and no combined key...
2001
-            //sorry, can't help you
2002
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
-                "event_espresso"), get_class($this)));
2004
-        }
2005
-    }
2006
-
2007
-
2008
-
2009
-    /**
2010
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
-     * column
2013
-     *
2014
-     * @param array  $query_params   like EEM_Base::get_all's
2015
-     * @param string $field_to_count field on model to count by (not column name)
2016
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
-     *                               that by the setting $distinct to TRUE;
2018
-     * @return int
2019
-     * @throws \EE_Error
2020
-     */
2021
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
-    {
2023
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
-        if ($field_to_count) {
2025
-            $field_obj = $this->field_settings_for($field_to_count);
2026
-            $column_to_count = $field_obj->get_qualified_column();
2027
-        } elseif ($this->has_primary_key_field()) {
2028
-            $pk_field_obj = $this->get_primary_key_field();
2029
-            $column_to_count = $pk_field_obj->get_qualified_column();
2030
-        } else {
2031
-            //there's no primary key
2032
-            //if we're counting distinct items, and there's no primary key,
2033
-            //we need to list out the columns for distinction;
2034
-            //otherwise we can just use star
2035
-            if ($distinct) {
2036
-                $columns_to_use = array();
2037
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2039
-                }
2040
-                $column_to_count = implode(',', $columns_to_use);
2041
-            } else {
2042
-                $column_to_count = '*';
2043
-            }
2044
-        }
2045
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
-    }
2049
-
2050
-
2051
-
2052
-    /**
2053
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
-     *
2055
-     * @param array  $query_params like EEM_Base::get_all
2056
-     * @param string $field_to_sum name of field (array key in $_fields array)
2057
-     * @return float
2058
-     * @throws \EE_Error
2059
-     */
2060
-    public function sum($query_params, $field_to_sum = null)
2061
-    {
2062
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
-        if ($field_to_sum) {
2064
-            $field_obj = $this->field_settings_for($field_to_sum);
2065
-        } else {
2066
-            $field_obj = $this->get_primary_key_field();
2067
-        }
2068
-        $column_to_count = $field_obj->get_qualified_column();
2069
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
-        $data_type = $field_obj->get_wpdb_data_type();
2072
-        if ($data_type === '%d' || $data_type === '%s') {
2073
-            return (float)$return_value;
2074
-        } else {//must be %f
2075
-            return (float)$return_value;
2076
-        }
2077
-    }
2078
-
2079
-
2080
-
2081
-    /**
2082
-     * Just calls the specified method on $wpdb with the given arguments
2083
-     * Consolidates a little extra error handling code
2084
-     *
2085
-     * @param string $wpdb_method
2086
-     * @param array  $arguments_to_provide
2087
-     * @throws EE_Error
2088
-     * @global wpdb  $wpdb
2089
-     * @return mixed
2090
-     */
2091
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
-    {
2093
-        //if we're in maintenance mode level 2, DON'T run any queries
2094
-        //because level 2 indicates the database needs updating and
2095
-        //is probably out of sync with the code
2096
-        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
-            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.",
2098
-                "event_espresso")));
2099
-        }
2100
-        /** @type WPDB $wpdb */
2101
-        global $wpdb;
2102
-        if ( ! method_exists($wpdb, $wpdb_method)) {
2103
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
-                'event_espresso'), $wpdb_method));
2105
-        }
2106
-        if (WP_DEBUG) {
2107
-            $old_show_errors_value = $wpdb->show_errors;
2108
-            $wpdb->show_errors(false);
2109
-        }
2110
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2112
-        if (WP_DEBUG) {
2113
-            $wpdb->show_errors($old_show_errors_value);
2114
-            if ( ! empty($wpdb->last_error)) {
2115
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
-            } elseif ($result === false) {
2117
-                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"',
2118
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
-            }
2120
-        } elseif ($result === false) {
2121
-            EE_Error::add_error(
2122
-                sprintf(
2123
-                    __('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"',
2124
-                        'event_espresso'),
2125
-                    $wpdb_method,
2126
-                    var_export($arguments_to_provide, true),
2127
-                    $wpdb->last_error
2128
-                ),
2129
-                __FILE__,
2130
-                __FUNCTION__,
2131
-                __LINE__
2132
-            );
2133
-        }
2134
-        return $result;
2135
-    }
2136
-
2137
-
2138
-
2139
-    /**
2140
-     * Attempts to run the indicated WPDB method with the provided arguments,
2141
-     * and if there's an error tries to verify the DB is correct. Uses
2142
-     * the static property EEM_Base::$_db_verification_level to determine whether
2143
-     * we should try to fix the EE core db, the addons, or just give up
2144
-     *
2145
-     * @param string $wpdb_method
2146
-     * @param array  $arguments_to_provide
2147
-     * @return mixed
2148
-     */
2149
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
-    {
2151
-        /** @type WPDB $wpdb */
2152
-        global $wpdb;
2153
-        $wpdb->last_error = null;
2154
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
-        // was there an error running the query? but we don't care on new activations
2156
-        // (we're going to setup the DB anyway on new activations)
2157
-        if (($result === false || ! empty($wpdb->last_error))
2158
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
-        ) {
2160
-            switch (EEM_Base::$_db_verification_level) {
2161
-                case EEM_Base::db_verified_none :
2162
-                    // let's double-check core's DB
2163
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
-                    break;
2165
-                case EEM_Base::db_verified_core :
2166
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
-                    break;
2169
-                case EEM_Base::db_verified_addons :
2170
-                    // ummmm... you in trouble
2171
-                    return $result;
2172
-                    break;
2173
-            }
2174
-            if ( ! empty($error_message)) {
2175
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
-                trigger_error($error_message);
2177
-            }
2178
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
-        }
2180
-        return $result;
2181
-    }
2182
-
2183
-
2184
-
2185
-    /**
2186
-     * Verifies the EE core database is up-to-date and records that we've done it on
2187
-     * EEM_Base::$_db_verification_level
2188
-     *
2189
-     * @param string $wpdb_method
2190
-     * @param array  $arguments_to_provide
2191
-     * @return string
2192
-     */
2193
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
-    {
2195
-        /** @type WPDB $wpdb */
2196
-        global $wpdb;
2197
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2198
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
-        $error_message = sprintf(
2200
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
-                'event_espresso'),
2202
-            $wpdb->last_error,
2203
-            $wpdb_method,
2204
-            json_encode($arguments_to_provide)
2205
-        );
2206
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
-        return $error_message;
2208
-    }
2209
-
2210
-
2211
-
2212
-    /**
2213
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
-     * EEM_Base::$_db_verification_level
2215
-     *
2216
-     * @param $wpdb_method
2217
-     * @param $arguments_to_provide
2218
-     * @return string
2219
-     */
2220
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
-    {
2222
-        /** @type WPDB $wpdb */
2223
-        global $wpdb;
2224
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
-        $error_message = sprintf(
2227
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
-                'event_espresso'),
2229
-            $wpdb->last_error,
2230
-            $wpdb_method,
2231
-            json_encode($arguments_to_provide)
2232
-        );
2233
-        EE_System::instance()->initialize_addons();
2234
-        return $error_message;
2235
-    }
2236
-
2237
-
2238
-
2239
-    /**
2240
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
-     * ..."
2244
-     *
2245
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2246
-     * @return string
2247
-     */
2248
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
-    {
2250
-        return " FROM " . $model_query_info->get_full_join_sql() .
2251
-               $model_query_info->get_where_sql() .
2252
-               $model_query_info->get_group_by_sql() .
2253
-               $model_query_info->get_having_sql() .
2254
-               $model_query_info->get_order_by_sql() .
2255
-               $model_query_info->get_limit_sql();
2256
-    }
2257
-
2258
-
2259
-
2260
-    /**
2261
-     * Set to easily debug the next X queries ran from this model.
2262
-     *
2263
-     * @param int $count
2264
-     */
2265
-    public function show_next_x_db_queries($count = 1)
2266
-    {
2267
-        $this->_show_next_x_db_queries = $count;
2268
-    }
2269
-
2270
-
2271
-
2272
-    /**
2273
-     * @param $sql_query
2274
-     */
2275
-    public function show_db_query_if_previously_requested($sql_query)
2276
-    {
2277
-        if ($this->_show_next_x_db_queries > 0) {
2278
-            echo $sql_query;
2279
-            $this->_show_next_x_db_queries--;
2280
-        }
2281
-    }
2282
-
2283
-
2284
-
2285
-    /**
2286
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
-     * There are the 3 cases:
2288
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
-     * $otherModelObject has no ID, it is first saved.
2290
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
-     * has no ID, it is first saved.
2292
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
-     * join table
2295
-     *
2296
-     * @param        EE_Base_Class                     /int $thisModelObject
2297
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
-     * @param string $relationName                     , key in EEM_Base::_relations
2299
-     *                                                 an attendee to a group, you also want to specify which role they
2300
-     *                                                 will have in that group. So you would use this parameter to
2301
-     *                                                 specify array('role-column-name'=>'role-id')
2302
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
-     *                                                 to for relation to methods that allow you to further specify
2304
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
-     *                                                 because these will be inserted in any new rows created as well.
2307
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
-     * @throws \EE_Error
2309
-     */
2310
-    public function add_relationship_to(
2311
-        $id_or_obj,
2312
-        $other_model_id_or_obj,
2313
-        $relationName,
2314
-        $extra_join_model_fields_n_values = array()
2315
-    ) {
2316
-        $relation_obj = $this->related_settings_for($relationName);
2317
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
-    }
2319
-
2320
-
2321
-
2322
-    /**
2323
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
-     * There are the 3 cases:
2325
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
-     * error
2327
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
-     * an error
2329
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
-     *
2331
-     * @param        EE_Base_Class /int $id_or_obj
2332
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
-     * @param string $relationName key in EEM_Base::_relations
2334
-     * @return boolean of success
2335
-     * @throws \EE_Error
2336
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
-     *                             because these will be inserted in any new rows created as well.
2340
-     */
2341
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
-    {
2343
-        $relation_obj = $this->related_settings_for($relationName);
2344
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
-    }
2346
-
2347
-
2348
-
2349
-    /**
2350
-     * @param mixed           $id_or_obj
2351
-     * @param string          $relationName
2352
-     * @param array           $where_query_params
2353
-     * @param EE_Base_Class[] objects to which relations were removed
2354
-     * @return \EE_Base_Class[]
2355
-     * @throws \EE_Error
2356
-     */
2357
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
-    {
2359
-        $relation_obj = $this->related_settings_for($relationName);
2360
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
-    }
2362
-
2363
-
2364
-
2365
-    /**
2366
-     * Gets all the related items of the specified $model_name, using $query_params.
2367
-     * Note: by default, we remove the "default query params"
2368
-     * because we want to get even deleted items etc.
2369
-     *
2370
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
-     * @param array  $query_params like EEM_Base::get_all
2373
-     * @return EE_Base_Class[]
2374
-     * @throws \EE_Error
2375
-     */
2376
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
-    {
2378
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2379
-        $relation_settings = $this->related_settings_for($model_name);
2380
-        return $relation_settings->get_all_related($model_obj, $query_params);
2381
-    }
2382
-
2383
-
2384
-
2385
-    /**
2386
-     * Deletes all the model objects across the relation indicated by $model_name
2387
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2389
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
-     *
2391
-     * @param EE_Base_Class|int|string $id_or_obj
2392
-     * @param string                   $model_name
2393
-     * @param array                    $query_params
2394
-     * @return int how many deleted
2395
-     * @throws \EE_Error
2396
-     */
2397
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
-    {
2399
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2400
-        $relation_settings = $this->related_settings_for($model_name);
2401
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2402
-    }
2403
-
2404
-
2405
-
2406
-    /**
2407
-     * Hard deletes all the model objects across the relation indicated by $model_name
2408
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
-     * the model objects can't be hard deleted because of blocking related model objects,
2410
-     * just does a soft-delete on them instead.
2411
-     *
2412
-     * @param EE_Base_Class|int|string $id_or_obj
2413
-     * @param string                   $model_name
2414
-     * @param array                    $query_params
2415
-     * @return int how many deleted
2416
-     * @throws \EE_Error
2417
-     */
2418
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
-    {
2420
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2421
-        $relation_settings = $this->related_settings_for($model_name);
2422
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
-    }
2424
-
2425
-
2426
-
2427
-    /**
2428
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
-     * unless otherwise specified in the $query_params
2430
-     *
2431
-     * @param        int             /EE_Base_Class $id_or_obj
2432
-     * @param string $model_name     like 'Event', or 'Registration'
2433
-     * @param array  $query_params   like EEM_Base::get_all's
2434
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2435
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
-     *                               that by the setting $distinct to TRUE;
2437
-     * @return int
2438
-     * @throws \EE_Error
2439
-     */
2440
-    public function count_related(
2441
-        $id_or_obj,
2442
-        $model_name,
2443
-        $query_params = array(),
2444
-        $field_to_count = null,
2445
-        $distinct = false
2446
-    ) {
2447
-        $related_model = $this->get_related_model_obj($model_name);
2448
-        //we're just going to use the query params on the related model's normal get_all query,
2449
-        //except add a condition to say to match the current mod
2450
-        if ( ! isset($query_params['default_where_conditions'])) {
2451
-            $query_params['default_where_conditions'] = 'none';
2452
-        }
2453
-        $this_model_name = $this->get_this_model_name();
2454
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
-        return $related_model->count($query_params, $field_to_count, $distinct);
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
-     *
2465
-     * @param        int           /EE_Base_Class $id_or_obj
2466
-     * @param string $model_name   like 'Event', or 'Registration'
2467
-     * @param array  $query_params like EEM_Base::get_all's
2468
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
-     * @return float
2470
-     * @throws \EE_Error
2471
-     */
2472
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
-    {
2474
-        $related_model = $this->get_related_model_obj($model_name);
2475
-        if ( ! is_array($query_params)) {
2476
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
-                    gettype($query_params)), '4.6.0');
2479
-            $query_params = array();
2480
-        }
2481
-        //we're just going to use the query params on the related model's normal get_all query,
2482
-        //except add a condition to say to match the current mod
2483
-        if ( ! isset($query_params['default_where_conditions'])) {
2484
-            $query_params['default_where_conditions'] = 'none';
2485
-        }
2486
-        $this_model_name = $this->get_this_model_name();
2487
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
-        return $related_model->sum($query_params, $field_to_sum);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
-     * $modelObject
2497
-     *
2498
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
-     * @param array               $query_params     like EEM_Base::get_all's
2501
-     * @return EE_Base_Class
2502
-     * @throws \EE_Error
2503
-     */
2504
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
-    {
2506
-        $query_params['limit'] = 1;
2507
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
-        if ($results) {
2509
-            return array_shift($results);
2510
-        } else {
2511
-            return null;
2512
-        }
2513
-    }
2514
-
2515
-
2516
-
2517
-    /**
2518
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
-     *
2520
-     * @return string
2521
-     */
2522
-    public function get_this_model_name()
2523
-    {
2524
-        return str_replace("EEM_", "", get_class($this));
2525
-    }
2526
-
2527
-
2528
-
2529
-    /**
2530
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
-     *
2532
-     * @return EE_Any_Foreign_Model_Name_Field
2533
-     * @throws EE_Error
2534
-     */
2535
-    public function get_field_containing_related_model_name()
2536
-    {
2537
-        foreach ($this->field_settings(true) as $field) {
2538
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
-                $field_with_model_name = $field;
2540
-            }
2541
-        }
2542
-        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
-                $this->get_this_model_name()));
2545
-        }
2546
-        return $field_with_model_name;
2547
-    }
2548
-
2549
-
2550
-
2551
-    /**
2552
-     * Inserts a new entry into the database, for each table.
2553
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
-     *
2560
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
-     *                              of EEM_Base)
2564
-     * @return int new primary key on main table that got inserted
2565
-     * @throws EE_Error
2566
-     */
2567
-    public function insert($field_n_values)
2568
-    {
2569
-        /**
2570
-         * Filters the fields and their values before inserting an item using the models
2571
-         *
2572
-         * @param array    $fields_n_values keys are the fields and values are their new values
2573
-         * @param EEM_Base $model           the model used
2574
-         */
2575
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
-            $main_table = $this->_get_main_table();
2578
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
-            if ($new_id !== false) {
2580
-                foreach ($this->_get_other_tables() as $other_table) {
2581
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
-                }
2583
-            }
2584
-            /**
2585
-             * Done just after attempting to insert a new model object
2586
-             *
2587
-             * @param EEM_Base   $model           used
2588
-             * @param array      $fields_n_values fields and their values
2589
-             * @param int|string the              ID of the newly-inserted model object
2590
-             */
2591
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
-            return $new_id;
2593
-        } else {
2594
-            return false;
2595
-        }
2596
-    }
2597
-
2598
-
2599
-
2600
-    /**
2601
-     * Checks that the result would satisfy the unique indexes on this model
2602
-     *
2603
-     * @param array  $field_n_values
2604
-     * @param string $action
2605
-     * @return boolean
2606
-     * @throws \EE_Error
2607
-     */
2608
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
-    {
2610
-        foreach ($this->unique_indexes() as $index_name => $index) {
2611
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
-            if ($this->exists(array($uniqueness_where_params))) {
2613
-                EE_Error::add_error(
2614
-                    sprintf(
2615
-                        __(
2616
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
-                            "event_espresso"
2618
-                        ),
2619
-                        $action,
2620
-                        $this->_get_class_name(),
2621
-                        $index_name,
2622
-                        implode(",", $index->field_names()),
2623
-                        http_build_query($uniqueness_where_params)
2624
-                    ),
2625
-                    __FILE__,
2626
-                    __FUNCTION__,
2627
-                    __LINE__
2628
-                );
2629
-                return false;
2630
-            }
2631
-        }
2632
-        return true;
2633
-    }
2634
-
2635
-
2636
-
2637
-    /**
2638
-     * Checks the database for an item that conflicts (ie, if this item were
2639
-     * saved to the DB would break some uniqueness requirement, like a primary key
2640
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
-     * can be either an EE_Base_Class or an array of fields n values
2642
-     *
2643
-     * @param EE_Base_Class|array $obj_or_fields_array
2644
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2645
-     *                                                 when looking for conflicts
2646
-     *                                                 (ie, if false, we ignore the model object's primary key
2647
-     *                                                 when finding "conflicts". If true, it's also considered).
2648
-     *                                                 Only works for INT primary key,
2649
-     *                                                 STRING primary keys cannot be ignored
2650
-     * @throws EE_Error
2651
-     * @return EE_Base_Class|array
2652
-     */
2653
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
-    {
2655
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2657
-        } elseif (is_array($obj_or_fields_array)) {
2658
-            $fields_n_values = $obj_or_fields_array;
2659
-        } else {
2660
-            throw new EE_Error(
2661
-                sprintf(
2662
-                    __(
2663
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
-                        "event_espresso"
2665
-                    ),
2666
-                    get_class($this),
2667
-                    $obj_or_fields_array
2668
-                )
2669
-            );
2670
-        }
2671
-        $query_params = array();
2672
-        if ($this->has_primary_key_field()
2673
-            && ($include_primary_key
2674
-                || $this->get_primary_key_field()
2675
-                   instanceof
2676
-                   EE_Primary_Key_String_Field)
2677
-            && isset($fields_n_values[$this->primary_key_name()])
2678
-        ) {
2679
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
-        }
2681
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
-        }
2685
-        //if there is nothing to base this search on, then we shouldn't find anything
2686
-        if (empty($query_params)) {
2687
-            return array();
2688
-        } else {
2689
-            return $this->get_one($query_params);
2690
-        }
2691
-    }
2692
-
2693
-
2694
-
2695
-    /**
2696
-     * Like count, but is optimized and returns a boolean instead of an int
2697
-     *
2698
-     * @param array $query_params
2699
-     * @return boolean
2700
-     * @throws \EE_Error
2701
-     */
2702
-    public function exists($query_params)
2703
-    {
2704
-        $query_params['limit'] = 1;
2705
-        return $this->count($query_params) > 0;
2706
-    }
2707
-
2708
-
2709
-
2710
-    /**
2711
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
-     *
2713
-     * @param int|string $id
2714
-     * @return boolean
2715
-     * @throws \EE_Error
2716
-     */
2717
-    public function exists_by_ID($id)
2718
-    {
2719
-        return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
-    }
2721
-
2722
-
2723
-
2724
-    /**
2725
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
-     * on the main table)
2729
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
-     * cases where we want to call it directly rather than via insert().
2731
-     *
2732
-     * @access   protected
2733
-     * @param EE_Table_Base $table
2734
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
-     *                                       float
2736
-     * @param int           $new_id          for now we assume only int keys
2737
-     * @throws EE_Error
2738
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
-     * @return int ID of new row inserted, or FALSE on failure
2740
-     */
2741
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
-    {
2743
-        global $wpdb;
2744
-        $insertion_col_n_values = array();
2745
-        $format_for_insertion = array();
2746
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
-        foreach ($fields_on_table as $field_name => $field_obj) {
2748
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
-            if ($field_obj->is_auto_increment()) {
2750
-                continue;
2751
-            }
2752
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
-            if ($prepared_value !== null) {
2755
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
-            }
2758
-        }
2759
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2760
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2761
-            //so add the fk to the main table as a column
2762
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
-        }
2765
-        //insert the new entry
2766
-        $result = $this->_do_wpdb_query('insert',
2767
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
-        if ($result === false) {
2769
-            return false;
2770
-        }
2771
-        //ok, now what do we return for the ID of the newly-inserted thing?
2772
-        if ($this->has_primary_key_field()) {
2773
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2774
-                return $wpdb->insert_id;
2775
-            } else {
2776
-                //it's not an auto-increment primary key, so
2777
-                //it must have been supplied
2778
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
-            }
2780
-        } else {
2781
-            //we can't return a  primary key because there is none. instead return
2782
-            //a unique string indicating this model
2783
-            return $this->get_index_primary_key_string($fields_n_values);
2784
-        }
2785
-    }
2786
-
2787
-
2788
-
2789
-    /**
2790
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
-     * and there is no default, we pass it along. WPDB will take care of it)
2793
-     *
2794
-     * @param EE_Model_Field_Base $field_obj
2795
-     * @param array               $fields_n_values
2796
-     * @return mixed string|int|float depending on what the table column will be expecting
2797
-     * @throws \EE_Error
2798
-     */
2799
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
-    {
2801
-        //if this field doesn't allow nullable, don't allow it
2802
-        if ( ! $field_obj->is_nullable()
2803
-             && (
2804
-                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
-        ) {
2806
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
-        }
2808
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
-            : null;
2810
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
-    }
2812
-
2813
-
2814
-
2815
-    /**
2816
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
-     * the field's prepare_for_set() method.
2819
-     *
2820
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
-     *                                   top of file)
2823
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
-     *                                   $value is a custom selection
2825
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
-     */
2827
-    private function _prepare_value_for_use_in_db($value, $field)
2828
-    {
2829
-        if ($field && $field instanceof EE_Model_Field_Base) {
2830
-            switch ($this->_values_already_prepared_by_model_object) {
2831
-                /** @noinspection PhpMissingBreakStatementInspection */
2832
-                case self::not_prepared_by_model_object:
2833
-                    $value = $field->prepare_for_set($value);
2834
-                //purposefully left out "return"
2835
-                case self::prepared_by_model_object:
2836
-                    $value = $field->prepare_for_use_in_db($value);
2837
-                case self::prepared_for_use_in_db:
2838
-                    //leave the value alone
2839
-            }
2840
-            return $value;
2841
-        } else {
2842
-            return $value;
2843
-        }
2844
-    }
2845
-
2846
-
2847
-
2848
-    /**
2849
-     * Returns the main table on this model
2850
-     *
2851
-     * @return EE_Primary_Table
2852
-     * @throws EE_Error
2853
-     */
2854
-    protected function _get_main_table()
2855
-    {
2856
-        foreach ($this->_tables as $table) {
2857
-            if ($table instanceof EE_Primary_Table) {
2858
-                return $table;
2859
-            }
2860
-        }
2861
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
-            'event_espresso'), get_class($this)));
2863
-    }
2864
-
2865
-
2866
-
2867
-    /**
2868
-     * table
2869
-     * returns EE_Primary_Table table name
2870
-     *
2871
-     * @return string
2872
-     * @throws \EE_Error
2873
-     */
2874
-    public function table()
2875
-    {
2876
-        return $this->_get_main_table()->get_table_name();
2877
-    }
2878
-
2879
-
2880
-
2881
-    /**
2882
-     * table
2883
-     * returns first EE_Secondary_Table table name
2884
-     *
2885
-     * @return string
2886
-     */
2887
-    public function second_table()
2888
-    {
2889
-        // grab second table from tables array
2890
-        $second_table = end($this->_tables);
2891
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
-    }
2893
-
2894
-
2895
-
2896
-    /**
2897
-     * get_table_obj_by_alias
2898
-     * returns table name given it's alias
2899
-     *
2900
-     * @param string $table_alias
2901
-     * @return EE_Primary_Table | EE_Secondary_Table
2902
-     */
2903
-    public function get_table_obj_by_alias($table_alias = '')
2904
-    {
2905
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
-    }
2907
-
2908
-
2909
-
2910
-    /**
2911
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
-     *
2913
-     * @return EE_Secondary_Table[]
2914
-     */
2915
-    protected function _get_other_tables()
2916
-    {
2917
-        $other_tables = array();
2918
-        foreach ($this->_tables as $table_alias => $table) {
2919
-            if ($table instanceof EE_Secondary_Table) {
2920
-                $other_tables[$table_alias] = $table;
2921
-            }
2922
-        }
2923
-        return $other_tables;
2924
-    }
2925
-
2926
-
2927
-
2928
-    /**
2929
-     * Finds all the fields that correspond to the given table
2930
-     *
2931
-     * @param string $table_alias , array key in EEM_Base::_tables
2932
-     * @return EE_Model_Field_Base[]
2933
-     */
2934
-    public function _get_fields_for_table($table_alias)
2935
-    {
2936
-        return $this->_fields[$table_alias];
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Recurses through all the where parameters, and finds all the related models we'll need
2943
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
-     * related Registration, Transaction, and Payment models.
2947
-     *
2948
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
-     * @return EE_Model_Query_Info_Carrier
2950
-     * @throws \EE_Error
2951
-     */
2952
-    public function _extract_related_models_from_query($query_params)
2953
-    {
2954
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
-        if (array_key_exists(0, $query_params)) {
2956
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
-        }
2958
-        if (array_key_exists('group_by', $query_params)) {
2959
-            if (is_array($query_params['group_by'])) {
2960
-                $this->_extract_related_models_from_sub_params_array_values(
2961
-                    $query_params['group_by'],
2962
-                    $query_info_carrier,
2963
-                    'group_by'
2964
-                );
2965
-            } elseif ( ! empty ($query_params['group_by'])) {
2966
-                $this->_extract_related_model_info_from_query_param(
2967
-                    $query_params['group_by'],
2968
-                    $query_info_carrier,
2969
-                    'group_by'
2970
-                );
2971
-            }
2972
-        }
2973
-        if (array_key_exists('having', $query_params)) {
2974
-            $this->_extract_related_models_from_sub_params_array_keys(
2975
-                $query_params[0],
2976
-                $query_info_carrier,
2977
-                'having'
2978
-            );
2979
-        }
2980
-        if (array_key_exists('order_by', $query_params)) {
2981
-            if (is_array($query_params['order_by'])) {
2982
-                $this->_extract_related_models_from_sub_params_array_keys(
2983
-                    $query_params['order_by'],
2984
-                    $query_info_carrier,
2985
-                    'order_by'
2986
-                );
2987
-            } elseif ( ! empty($query_params['order_by'])) {
2988
-                $this->_extract_related_model_info_from_query_param(
2989
-                    $query_params['order_by'],
2990
-                    $query_info_carrier,
2991
-                    'order_by'
2992
-                );
2993
-            }
2994
-        }
2995
-        if (array_key_exists('force_join', $query_params)) {
2996
-            $this->_extract_related_models_from_sub_params_array_values(
2997
-                $query_params['force_join'],
2998
-                $query_info_carrier,
2999
-                'force_join'
3000
-            );
3001
-        }
3002
-        return $query_info_carrier;
3003
-    }
3004
-
3005
-
3006
-
3007
-    /**
3008
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
-     *
3010
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
-     *                                                      $query_params['having']
3012
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3014
-     * @throws EE_Error
3015
-     * @return \EE_Model_Query_Info_Carrier
3016
-     */
3017
-    private function _extract_related_models_from_sub_params_array_keys(
3018
-        $sub_query_params,
3019
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
-        $query_param_type
3021
-    ) {
3022
-        if ( ! empty($sub_query_params)) {
3023
-            $sub_query_params = (array)$sub_query_params;
3024
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
-                    $query_param_type);
3028
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
-                //of array('Registration.TXN_ID'=>23)
3032
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
-                    if ( ! is_array($possibly_array_of_params)) {
3035
-                        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'))",
3036
-                            "event_espresso"),
3037
-                            $param, $possibly_array_of_params));
3038
-                    } else {
3039
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
-                            $model_query_info_carrier, $query_param_type);
3041
-                    }
3042
-                } elseif ($query_param_type === 0 //ie WHERE
3043
-                          && is_array($possibly_array_of_params)
3044
-                          && isset($possibly_array_of_params[2])
3045
-                          && $possibly_array_of_params[2] == true
3046
-                ) {
3047
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3049
-                    //from which we should extract query parameters!
3050
-                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
-                    }
3054
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
-                        $model_query_info_carrier, $query_param_type);
3056
-                }
3057
-            }
3058
-        }
3059
-        return $model_query_info_carrier;
3060
-    }
3061
-
3062
-
3063
-
3064
-    /**
3065
-     * For extracting related models from forced_joins, where the array values contain the info about what
3066
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
-     *
3068
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
-     *                                                      $query_params['having']
3070
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3072
-     * @throws EE_Error
3073
-     * @return \EE_Model_Query_Info_Carrier
3074
-     */
3075
-    private function _extract_related_models_from_sub_params_array_values(
3076
-        $sub_query_params,
3077
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
-        $query_param_type
3079
-    ) {
3080
-        if ( ! empty($sub_query_params)) {
3081
-            if ( ! is_array($sub_query_params)) {
3082
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
-                    $sub_query_params));
3084
-            }
3085
-            foreach ($sub_query_params as $param) {
3086
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
-                    $query_param_type);
3089
-            }
3090
-        }
3091
-        return $model_query_info_carrier;
3092
-    }
3093
-
3094
-
3095
-
3096
-    /**
3097
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
-     * but use them in a different order. Eg, we need to know what models we are querying
3101
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
-     * other models before we can finalize the where clause SQL.
3103
-     *
3104
-     * @param array $query_params
3105
-     * @throws EE_Error
3106
-     * @return EE_Model_Query_Info_Carrier
3107
-     */
3108
-    public function _create_model_query_info_carrier($query_params)
3109
-    {
3110
-        if ( ! is_array($query_params)) {
3111
-            EE_Error::doing_it_wrong(
3112
-                'EEM_Base::_create_model_query_info_carrier',
3113
-                sprintf(
3114
-                    __(
3115
-                        '$query_params should be an array, you passed a variable of type %s',
3116
-                        'event_espresso'
3117
-                    ),
3118
-                    gettype($query_params)
3119
-                ),
3120
-                '4.6.0'
3121
-            );
3122
-            $query_params = array();
3123
-        }
3124
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
-        //first check if we should alter the query to account for caps or not
3126
-        //because the caps might require us to do extra joins
3127
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
-            $query_params[0] = $where_query_params = array_replace_recursive(
3129
-                $where_query_params,
3130
-                $this->caps_where_conditions(
3131
-                    $query_params['caps']
3132
-                )
3133
-            );
3134
-        }
3135
-        $query_object = $this->_extract_related_models_from_query($query_params);
3136
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
-        foreach ($where_query_params as $key => $value) {
3138
-            if (is_int($key)) {
3139
-                throw new EE_Error(
3140
-                    sprintf(
3141
-                        __(
3142
-                            "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.",
3143
-                            "event_espresso"
3144
-                        ),
3145
-                        $key,
3146
-                        var_export($value, true),
3147
-                        var_export($query_params, true),
3148
-                        get_class($this)
3149
-                    )
3150
-                );
3151
-            }
3152
-        }
3153
-        if (
3154
-            array_key_exists('default_where_conditions', $query_params)
3155
-            && ! empty($query_params['default_where_conditions'])
3156
-        ) {
3157
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3158
-        } else {
3159
-            $use_default_where_conditions = 'all';
3160
-        }
3161
-        $where_query_params = array_merge(
3162
-            $this->_get_default_where_conditions_for_models_in_query(
3163
-                $query_object,
3164
-                $use_default_where_conditions,
3165
-                $where_query_params
3166
-            ),
3167
-            $where_query_params
3168
-        );
3169
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
-        // So we need to setup a subquery and use that for the main join.
3172
-        // Note for now this only works on the primary table for the model.
3173
-        // So for instance, you could set the limit array like this:
3174
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
-            $query_object->set_main_model_join_sql(
3177
-                $this->_construct_limit_join_select(
3178
-                    $query_params['on_join_limit'][0],
3179
-                    $query_params['on_join_limit'][1]
3180
-                )
3181
-            );
3182
-        }
3183
-        //set limit
3184
-        if (array_key_exists('limit', $query_params)) {
3185
-            if (is_array($query_params['limit'])) {
3186
-                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
-                    $e = sprintf(
3188
-                        __(
3189
-                            "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)",
3190
-                            "event_espresso"
3191
-                        ),
3192
-                        http_build_query($query_params['limit'])
3193
-                    );
3194
-                    throw new EE_Error($e . "|" . $e);
3195
-                }
3196
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
-            } elseif ( ! empty ($query_params['limit'])) {
3199
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
-            }
3201
-        }
3202
-        //set order by
3203
-        if (array_key_exists('order_by', $query_params)) {
3204
-            if (is_array($query_params['order_by'])) {
3205
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
-                if (array_key_exists('order', $query_params)) {
3209
-                    throw new EE_Error(
3210
-                        sprintf(
3211
-                            __(
3212
-                                "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 ",
3213
-                                "event_espresso"
3214
-                            ),
3215
-                            get_class($this),
3216
-                            implode(", ", array_keys($query_params['order_by'])),
3217
-                            implode(", ", $query_params['order_by']),
3218
-                            $query_params['order']
3219
-                        )
3220
-                    );
3221
-                }
3222
-                $this->_extract_related_models_from_sub_params_array_keys(
3223
-                    $query_params['order_by'],
3224
-                    $query_object,
3225
-                    'order_by'
3226
-                );
3227
-                //assume it's an array of fields to order by
3228
-                $order_array = array();
3229
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
-                    $order = $this->_extract_order($order);
3231
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
-                }
3233
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
-            } elseif ( ! empty ($query_params['order_by'])) {
3235
-                $this->_extract_related_model_info_from_query_param(
3236
-                    $query_params['order_by'],
3237
-                    $query_object,
3238
-                    'order',
3239
-                    $query_params['order_by']
3240
-                );
3241
-                $order = isset($query_params['order'])
3242
-                    ? $this->_extract_order($query_params['order'])
3243
-                    : 'DESC';
3244
-                $query_object->set_order_by_sql(
3245
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
-                );
3247
-            }
3248
-        }
3249
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
-        if ( ! array_key_exists('order_by', $query_params)
3251
-             && array_key_exists('order', $query_params)
3252
-             && ! empty($query_params['order'])
3253
-        ) {
3254
-            $pk_field = $this->get_primary_key_field();
3255
-            $order = $this->_extract_order($query_params['order']);
3256
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
-        }
3258
-        //set group by
3259
-        if (array_key_exists('group_by', $query_params)) {
3260
-            if (is_array($query_params['group_by'])) {
3261
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3262
-                $group_by_array = array();
3263
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
-                }
3266
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
-            } elseif ( ! empty ($query_params['group_by'])) {
3268
-                $query_object->set_group_by_sql(
3269
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
-                );
3271
-            }
3272
-        }
3273
-        //set having
3274
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
-        }
3277
-        //now, just verify they didn't pass anything wack
3278
-        foreach ($query_params as $query_key => $query_value) {
3279
-            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
-                throw new EE_Error(
3281
-                    sprintf(
3282
-                        __(
3283
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
-                            'event_espresso'
3285
-                        ),
3286
-                        $query_key,
3287
-                        get_class($this),
3288
-                        //						print_r( $this->_allowed_query_params, TRUE )
3289
-                        implode(',', $this->_allowed_query_params)
3290
-                    )
3291
-                );
3292
-            }
3293
-        }
3294
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3295
-        if (empty($main_model_join_sql)) {
3296
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
-        }
3298
-        return $query_object;
3299
-    }
3300
-
3301
-
3302
-
3303
-    /**
3304
-     * Gets the where conditions that should be imposed on the query based on the
3305
-     * context (eg reading frontend, backend, edit or delete).
3306
-     *
3307
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3308
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3309
-     * @throws \EE_Error
3310
-     */
3311
-    public function caps_where_conditions($context = self::caps_read)
3312
-    {
3313
-        EEM_Base::verify_is_valid_cap_context($context);
3314
-        $cap_where_conditions = array();
3315
-        $cap_restrictions = $this->caps_missing($context);
3316
-        /**
3317
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
-         */
3319
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
-                $restriction_if_no_cap->get_default_where_conditions());
3322
-        }
3323
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
-            $cap_restrictions);
3325
-    }
3326
-
3327
-
3328
-
3329
-    /**
3330
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
-     * otherwise throws an exception
3332
-     *
3333
-     * @param string $should_be_order_string
3334
-     * @return string either ASC, asc, DESC or desc
3335
-     * @throws EE_Error
3336
-     */
3337
-    private function _extract_order($should_be_order_string)
3338
-    {
3339
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
-            return $should_be_order_string;
3341
-        } else {
3342
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
-                "event_espresso"), get_class($this), $should_be_order_string));
3344
-        }
3345
-    }
3346
-
3347
-
3348
-
3349
-    /**
3350
-     * Looks at all the models which are included in this query, and asks each
3351
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
-     * so they can be merged
3353
-     *
3354
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
-     *                                                                  'none' means NO default where conditions will
3357
-     *                                                                  be used AT ALL during this query.
3358
-     *                                                                  'other_models_only' means default where
3359
-     *                                                                  conditions from other models will be used, but
3360
-     *                                                                  not for this primary model. 'all', the default,
3361
-     *                                                                  means default where conditions will apply as
3362
-     *                                                                  normal
3363
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
-     * @throws EE_Error
3365
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
-     */
3367
-    private function _get_default_where_conditions_for_models_in_query(
3368
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3369
-        $use_default_where_conditions = 'all',
3370
-        $where_query_params = array()
3371
-    ) {
3372
-        $allowed_used_default_where_conditions_values = array(
3373
-            'all',
3374
-            'this_model_only',
3375
-            'other_models_only',
3376
-            'minimum',
3377
-            'none',
3378
-        );
3379
-        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
-                "event_espresso"), $use_default_where_conditions,
3382
-                implode(", ", $allowed_used_default_where_conditions_values)));
3383
-        }
3384
-        $universal_query_params = array();
3385
-        if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
-            $universal_query_params = $this->_get_default_where_conditions();
3387
-        } else if ($use_default_where_conditions === 'minimum') {
3388
-            $universal_query_params = $this->_get_minimum_where_conditions();
3389
-        }
3390
-        if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
-            foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
-                $related_model = $this->get_related_model_obj($model_name);
3393
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
-                $overrides = $this->_override_defaults_or_make_null_friendly(
3395
-                    $related_model_universal_where_params,
3396
-                    $where_query_params,
3397
-                    $related_model,
3398
-                    $model_relation_path
3399
-                );
3400
-                $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
-                    $universal_query_params,
3402
-                    $overrides
3403
-                );
3404
-            }
3405
-        }
3406
-        return $universal_query_params;
3407
-    }
3408
-
3409
-
3410
-
3411
-    /**
3412
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
-     * then we also add a special where condition which allows for that model's primary key
3414
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
-     *
3417
-     * @param array    $default_where_conditions
3418
-     * @param array    $provided_where_conditions
3419
-     * @param EEM_Base $model
3420
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3421
-     * @return array like EEM_Base::get_all's $query_params[0]
3422
-     * @throws \EE_Error
3423
-     */
3424
-    private function _override_defaults_or_make_null_friendly(
3425
-        $default_where_conditions,
3426
-        $provided_where_conditions,
3427
-        $model,
3428
-        $model_relation_path
3429
-    ) {
3430
-        $null_friendly_where_conditions = array();
3431
-        $none_overridden = true;
3432
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
-        foreach ($default_where_conditions as $key => $val) {
3434
-            if (isset($provided_where_conditions[$key])) {
3435
-                $none_overridden = false;
3436
-            } else {
3437
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
-            }
3439
-        }
3440
-        if ($none_overridden && $default_where_conditions) {
3441
-            if ($model->has_primary_key_field()) {
3442
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
-                                                                                . "."
3444
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3445
-            }/*else{
32
+	//admin posty
33
+	//basic -> grants access to mine -> if they don't have it, select none
34
+	//*_others -> grants access to others that arent private, and all mine -> if they don't have it, select mine
35
+	//*_private -> grants full access -> if dont have it, select all mine and others' non-private
36
+	//*_published -> grants access to published -> if they dont have it, select non-published
37
+	//*_global/default/system -> grants access to global items -> if they don't have it, select non-global
38
+	//publish_{thing} -> can change status TO publish; SPECIAL CASE
39
+	//frontend posty
40
+	//by default has access to published
41
+	//basic -> grants access to mine that arent published, and all published
42
+	//*_others ->grants access to others that arent private, all mine
43
+	//*_private -> grants full access
44
+	//frontend non-posty
45
+	//like admin posty
46
+	//category-y
47
+	//assign -> grants access to join-table
48
+	//(delete, edit)
49
+	//payment-method-y
50
+	//for each registered payment method,
51
+	//ee_payment_method_{pmttype} -> if they don't have it, select all where they aren't of that type
52
+	/**
53
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
54
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
55
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
56
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
57
+	 *
58
+	 * @var boolean
59
+	 */
60
+	private $_values_already_prepared_by_model_object = 0;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the data is just like form input that needs to have the model fields'
65
+	 * prepare_for_set and prepare_for_use_in_db called on it
66
+	 */
67
+	const not_prepared_by_model_object = 0;
68
+
69
+	/**
70
+	 * when $_values_already_prepared_by_model_object equals this, we
71
+	 * assume this value is coming from a model object and doesn't need to have
72
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
73
+	 */
74
+	const prepared_by_model_object = 1;
75
+
76
+	/**
77
+	 * when $_values_already_prepared_by_model_object equals this, we assume
78
+	 * the values are already to be used in the database (ie no processing is done
79
+	 * on them by the model's fields)
80
+	 */
81
+	const prepared_for_use_in_db = 2;
82
+
83
+
84
+	protected $singular_item = 'Item';
85
+
86
+	protected $plural_item   = 'Items';
87
+
88
+	/**
89
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
90
+	 */
91
+	protected $_tables;
92
+
93
+	/**
94
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
95
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
96
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
97
+	 *
98
+	 * @var \EE_Model_Field_Base[] $_fields
99
+	 */
100
+	protected $_fields;
101
+
102
+	/**
103
+	 * array of different kinds of relations
104
+	 *
105
+	 * @var \EE_Model_Relation_Base[] $_model_relations
106
+	 */
107
+	protected $_model_relations;
108
+
109
+	/**
110
+	 * @var \EE_Index[] $_indexes
111
+	 */
112
+	protected $_indexes = array();
113
+
114
+	/**
115
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
116
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
117
+	 * by setting the same columns as used in these queries in the query yourself.
118
+	 *
119
+	 * @var EE_Default_Where_Conditions
120
+	 */
121
+	protected $_default_where_conditions_strategy;
122
+
123
+	/**
124
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
125
+	 * This is particularly useful when you want something between 'none' and 'default'
126
+	 *
127
+	 * @var EE_Default_Where_Conditions
128
+	 */
129
+	protected $_minimum_where_conditions_strategy;
130
+
131
+	/**
132
+	 * String describing how to find the "owner" of this model's objects.
133
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
134
+	 * But when there isn't, this indicates which related model, or transiently-related model,
135
+	 * has the foreign key to the wp_users table.
136
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
137
+	 * related to events, and events have a foreign key to wp_users.
138
+	 * On EEM_Transaction, this would be 'Transaction.Event'
139
+	 *
140
+	 * @var string
141
+	 */
142
+	protected $_model_chain_to_wp_user = '';
143
+
144
+	/**
145
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
146
+	 * don't need it (particularly CPT models)
147
+	 *
148
+	 * @var bool
149
+	 */
150
+	protected $_ignore_where_strategy = false;
151
+
152
+	/**
153
+	 * String used in caps relating to this model. Eg, if the caps relating to this
154
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
155
+	 *
156
+	 * @var string. If null it hasn't been initialized yet. If false then we
157
+	 * have indicated capabilities don't apply to this
158
+	 */
159
+	protected $_caps_slug = null;
160
+
161
+	/**
162
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
163
+	 * and next-level keys are capability names, and each's value is a
164
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
165
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
166
+	 * and then each capability in the corresponding sub-array that they're missing
167
+	 * adds the where conditions onto the query.
168
+	 *
169
+	 * @var array
170
+	 */
171
+	protected $_cap_restrictions = array(
172
+		self::caps_read       => array(),
173
+		self::caps_read_admin => array(),
174
+		self::caps_edit       => array(),
175
+		self::caps_delete     => array(),
176
+	);
177
+
178
+	/**
179
+	 * Array defining which cap restriction generators to use to create default
180
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
181
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
182
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
183
+	 * automatically set this to false (not just null).
184
+	 *
185
+	 * @var EE_Restriction_Generator_Base[]
186
+	 */
187
+	protected $_cap_restriction_generators = array();
188
+
189
+	/**
190
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
191
+	 */
192
+	const caps_read       = 'read';
193
+
194
+	const caps_read_admin = 'read_admin';
195
+
196
+	const caps_edit       = 'edit';
197
+
198
+	const caps_delete     = 'delete';
199
+
200
+	/**
201
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
202
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
203
+	 * maps to 'read' because when looking for relevant permissions we're going to use
204
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_cap_contexts_to_cap_action_map = array(
209
+		self::caps_read       => 'read',
210
+		self::caps_read_admin => 'read',
211
+		self::caps_edit       => 'edit',
212
+		self::caps_delete     => 'delete',
213
+	);
214
+
215
+	/**
216
+	 * Timezone
217
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
218
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
219
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
220
+	 * EE_Datetime_Field data type will have access to it.
221
+	 *
222
+	 * @var string
223
+	 */
224
+	protected $_timezone;
225
+
226
+
227
+	/**
228
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
229
+	 * multisite.
230
+	 *
231
+	 * @var int
232
+	 */
233
+	protected static $_model_query_blog_id;
234
+
235
+	/**
236
+	 * A copy of _fields, except the array keys are the model names pointed to by
237
+	 * the field
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cache_foreign_key_to_fields = array();
242
+
243
+	/**
244
+	 * Cached list of all the fields on the model, indexed by their name
245
+	 *
246
+	 * @var EE_Model_Field_Base[]
247
+	 */
248
+	private $_cached_fields = null;
249
+
250
+	/**
251
+	 * Cached list of all the fields on the model, except those that are
252
+	 * marked as only pertinent to the database
253
+	 *
254
+	 * @var EE_Model_Field_Base[]
255
+	 */
256
+	private $_cached_fields_non_db_only = null;
257
+
258
+	/**
259
+	 * A cached reference to the primary key for quick lookup
260
+	 *
261
+	 * @var EE_Model_Field_Base
262
+	 */
263
+	private $_primary_key_field = null;
264
+
265
+	/**
266
+	 * Flag indicating whether this model has a primary key or not
267
+	 *
268
+	 * @var boolean
269
+	 */
270
+	protected $_has_primary_key_field = null;
271
+
272
+	/**
273
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
274
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
275
+	 *
276
+	 * @var boolean
277
+	 */
278
+	protected $_wp_core_model = false;
279
+
280
+	/**
281
+	 *    List of valid operators that can be used for querying.
282
+	 * The keys are all operators we'll accept, the values are the real SQL
283
+	 * operators used
284
+	 *
285
+	 * @var array
286
+	 */
287
+	protected $_valid_operators = array(
288
+		'='           => '=',
289
+		'<='          => '<=',
290
+		'<'           => '<',
291
+		'>='          => '>=',
292
+		'>'           => '>',
293
+		'!='          => '!=',
294
+		'LIKE'        => 'LIKE',
295
+		'like'        => 'LIKE',
296
+		'NOT_LIKE'    => 'NOT LIKE',
297
+		'not_like'    => 'NOT LIKE',
298
+		'NOT LIKE'    => 'NOT LIKE',
299
+		'not like'    => 'NOT LIKE',
300
+		'IN'          => 'IN',
301
+		'in'          => 'IN',
302
+		'NOT_IN'      => 'NOT IN',
303
+		'not_in'      => 'NOT IN',
304
+		'NOT IN'      => 'NOT IN',
305
+		'not in'      => 'NOT IN',
306
+		'between'     => 'BETWEEN',
307
+		'BETWEEN'     => 'BETWEEN',
308
+		'IS_NOT_NULL' => 'IS NOT NULL',
309
+		'is_not_null' => 'IS NOT NULL',
310
+		'IS NOT NULL' => 'IS NOT NULL',
311
+		'is not null' => 'IS NOT NULL',
312
+		'IS_NULL'     => 'IS NULL',
313
+		'is_null'     => 'IS NULL',
314
+		'IS NULL'     => 'IS NULL',
315
+		'is null'     => 'IS NULL',
316
+		'REGEXP'      => 'REGEXP',
317
+		'regexp'      => 'REGEXP',
318
+		'NOT_REGEXP'  => 'NOT REGEXP',
319
+		'not_regexp'  => 'NOT REGEXP',
320
+		'NOT REGEXP'  => 'NOT REGEXP',
321
+		'not regexp'  => 'NOT REGEXP',
322
+	);
323
+
324
+	/**
325
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
326
+	 *
327
+	 * @var array
328
+	 */
329
+	protected $_in_style_operators = array('IN', 'NOT IN');
330
+
331
+	/**
332
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
333
+	 * '12-31-2012'"
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_between_style_operators = array('BETWEEN');
338
+
339
+	/**
340
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
341
+	 * on a join table.
342
+	 *
343
+	 * @var array
344
+	 */
345
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
346
+
347
+	/**
348
+	 * Allowed values for $query_params['order'] for ordering in queries
349
+	 *
350
+	 * @var array
351
+	 */
352
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
353
+
354
+	/**
355
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
356
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
361
+
362
+	/**
363
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
364
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
365
+	 *
366
+	 * @var array
367
+	 */
368
+	private $_allowed_query_params = array(
369
+		0,
370
+		'limit',
371
+		'order_by',
372
+		'group_by',
373
+		'having',
374
+		'force_join',
375
+		'order',
376
+		'on_join_limit',
377
+		'default_where_conditions',
378
+		'caps',
379
+	);
380
+
381
+	/**
382
+	 * All the data types that can be used in $wpdb->prepare statements.
383
+	 *
384
+	 * @var array
385
+	 */
386
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
387
+
388
+	/**
389
+	 *    EE_Registry Object
390
+	 *
391
+	 * @var    object
392
+	 * @access    protected
393
+	 */
394
+	protected $EE = null;
395
+
396
+
397
+	/**
398
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
399
+	 *
400
+	 * @var int
401
+	 */
402
+	protected $_show_next_x_db_queries = 0;
403
+
404
+	/**
405
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
406
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
407
+	 *
408
+	 * @var array
409
+	 */
410
+	protected $_custom_selections = array();
411
+
412
+	/**
413
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
414
+	 * caches every model object we've fetched from the DB on this request
415
+	 *
416
+	 * @var array
417
+	 */
418
+	protected $_entity_map;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has not yet verified the db on this http request
422
+	 */
423
+	const db_verified_none = 0;
424
+
425
+	/**
426
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
427
+	 * but not the addons' dbs
428
+	 */
429
+	const db_verified_core = 1;
430
+
431
+	/**
432
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
433
+	 * the EE core db too)
434
+	 */
435
+	const db_verified_addons = 2;
436
+
437
+	/**
438
+	 * indicates whether an EEM_Base child has already re-verified the DB
439
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
440
+	 * looking like EEM_Base::db_verified_*
441
+	 *
442
+	 * @var int - 0 = none, 1 = core, 2 = addons
443
+	 */
444
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
445
+
446
+
447
+
448
+	/**
449
+	 * About all child constructors:
450
+	 * they should define the _tables, _fields and _model_relations arrays.
451
+	 * Should ALWAYS be called after child constructor.
452
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
453
+	 * finalizes constructing all the object's attributes.
454
+	 * Generally, rather than requiring a child to code
455
+	 * $this->_tables = array(
456
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
457
+	 *        ...);
458
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
459
+	 * each EE_Table has a function to set the table's alias after the constructor, using
460
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
461
+	 * do something similar.
462
+	 *
463
+	 * @param null $timezone
464
+	 * @throws \EE_Error
465
+	 */
466
+	protected function __construct($timezone = null)
467
+	{
468
+		// check that the model has not been loaded too soon
469
+		if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
470
+			throw new EE_Error (
471
+				sprintf(
472
+					__('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.',
473
+						'event_espresso'),
474
+					get_class($this)
475
+				)
476
+			);
477
+		}
478
+		/**
479
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
480
+		 */
481
+		if (empty(EEM_Base::$_model_query_blog_id)) {
482
+			EEM_Base::set_model_query_blog_id();
483
+		}
484
+		/**
485
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
486
+		 * just use EE_Register_Model_Extension
487
+		 *
488
+		 * @var EE_Table_Base[] $_tables
489
+		 */
490
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
491
+		foreach ($this->_tables as $table_alias => $table_obj) {
492
+			/** @var $table_obj EE_Table_Base */
493
+			$table_obj->_construct_finalize_with_alias($table_alias);
494
+			if ($table_obj instanceof EE_Secondary_Table) {
495
+				/** @var $table_obj EE_Secondary_Table */
496
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
497
+			}
498
+		}
499
+		/**
500
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
501
+		 * EE_Register_Model_Extension
502
+		 *
503
+		 * @param EE_Model_Field_Base[] $_fields
504
+		 */
505
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
506
+		$this->_invalidate_field_caches();
507
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
508
+			if ( ! array_key_exists($table_alias, $this->_tables)) {
509
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
510
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
511
+			}
512
+			foreach ($fields_for_table as $field_name => $field_obj) {
513
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
514
+				//primary key field base has a slightly different _construct_finalize
515
+				/** @var $field_obj EE_Model_Field_Base */
516
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
517
+			}
518
+		}
519
+		// everything is related to Extra_Meta
520
+		if (get_class($this) !== 'EEM_Extra_Meta') {
521
+			//make extra meta related to everything, but don't block deleting things just
522
+			//because they have related extra meta info. For now just orphan those extra meta
523
+			//in the future we should automatically delete them
524
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
525
+		}
526
+		//and change logs
527
+		if (get_class($this) !== 'EEM_Change_Log') {
528
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
529
+		}
530
+		/**
531
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
532
+		 * EE_Register_Model_Extension
533
+		 *
534
+		 * @param EE_Model_Relation_Base[] $_model_relations
535
+		 */
536
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
537
+			$this->_model_relations);
538
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
539
+			/** @var $relation_obj EE_Model_Relation_Base */
540
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
541
+		}
542
+		foreach ($this->_indexes as $index_name => $index_obj) {
543
+			/** @var $index_obj EE_Index */
544
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
545
+		}
546
+		$this->set_timezone($timezone);
547
+		//finalize default where condition strategy, or set default
548
+		if ( ! $this->_default_where_conditions_strategy) {
549
+			//nothing was set during child constructor, so set default
550
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
551
+		}
552
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
553
+		if ( ! $this->_minimum_where_conditions_strategy) {
554
+			//nothing was set during child constructor, so set default
555
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
556
+		}
557
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
558
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
559
+		//to indicate to NOT set it, set it to the logical default
560
+		if ($this->_caps_slug === null) {
561
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
562
+		}
563
+		//initialize the standard cap restriction generators if none were specified by the child constructor
564
+		if ($this->_cap_restriction_generators !== false) {
565
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
566
+				if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
567
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
568
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
569
+						new EE_Restriction_Generator_Protected(),
570
+						$cap_context,
571
+						$this
572
+					);
573
+				}
574
+			}
575
+		}
576
+		//if there are cap restriction generators, use them to make the default cap restrictions
577
+		if ($this->_cap_restriction_generators !== false) {
578
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
579
+				if ( ! $generator_object) {
580
+					continue;
581
+				}
582
+				if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
583
+					throw new EE_Error(
584
+						sprintf(
585
+							__('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.',
586
+								'event_espresso'),
587
+							$context,
588
+							$this->get_this_model_name()
589
+						)
590
+					);
591
+				}
592
+				$action = $this->cap_action_for_context($context);
593
+				if ( ! $generator_object->construction_finalized()) {
594
+					$generator_object->_construct_finalize($this, $action);
595
+				}
596
+			}
597
+		}
598
+		do_action('AHEE__' . get_class($this) . '__construct__end');
599
+	}
600
+
601
+
602
+
603
+	/**
604
+	 * Generates the cap restrictions for the given context, or if they were
605
+	 * already generated just gets what's cached
606
+	 *
607
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
608
+	 * @return EE_Default_Where_Conditions[]
609
+	 */
610
+	protected function _generate_cap_restrictions($context)
611
+	{
612
+		if (isset($this->_cap_restriction_generators[$context])
613
+			&& $this->_cap_restriction_generators[$context]
614
+			   instanceof
615
+			   EE_Restriction_Generator_Base
616
+		) {
617
+			return $this->_cap_restriction_generators[$context]->generate_restrictions();
618
+		} else {
619
+			return array();
620
+		}
621
+	}
622
+
623
+
624
+
625
+	/**
626
+	 * Used to set the $_model_query_blog_id static property.
627
+	 *
628
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
629
+	 *                      value for get_current_blog_id() will be used.
630
+	 */
631
+	public static function set_model_query_blog_id($blog_id = 0)
632
+	{
633
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
634
+	}
635
+
636
+
637
+
638
+	/**
639
+	 * Returns whatever is set as the internal $model_query_blog_id.
640
+	 *
641
+	 * @return int
642
+	 */
643
+	public static function get_model_query_blog_id()
644
+	{
645
+		return EEM_Base::$_model_query_blog_id;
646
+	}
647
+
648
+
649
+
650
+	/**
651
+	 *        This function is a singleton method used to instantiate the Espresso_model object
652
+	 *
653
+	 * @access public
654
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
655
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
656
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
657
+	 *                         timezone in the 'timezone_string' wp option)
658
+	 * @return static (as in the concrete child class)
659
+	 */
660
+	public static function instance($timezone = null)
661
+	{
662
+		// check if instance of Espresso_model already exists
663
+		if ( ! static::$_instance instanceof static) {
664
+			// instantiate Espresso_model
665
+			static::$_instance = new static($timezone);
666
+		}
667
+		//we might have a timezone set, let set_timezone decide what to do with it
668
+		static::$_instance->set_timezone($timezone);
669
+		// Espresso_model object
670
+		return static::$_instance;
671
+	}
672
+
673
+
674
+
675
+	/**
676
+	 * resets the model and returns it
677
+	 *
678
+	 * @param null | string $timezone
679
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
680
+	 * all its properties reset; if it wasn't instantiated, returns null)
681
+	 */
682
+	public static function reset($timezone = null)
683
+	{
684
+		if (static::$_instance instanceof EEM_Base) {
685
+			//let's try to NOT swap out the current instance for a new one
686
+			//because if someone has a reference to it, we can't remove their reference
687
+			//so it's best to keep using the same reference, but change the original object
688
+			//reset all its properties to their original values as defined in the class
689
+			$r = new ReflectionClass(get_class(static::$_instance));
690
+			$static_properties = $r->getStaticProperties();
691
+			foreach ($r->getDefaultProperties() as $property => $value) {
692
+				//don't set instance to null like it was originally,
693
+				//but it's static anyways, and we're ignoring static properties (for now at least)
694
+				if ( ! isset($static_properties[$property])) {
695
+					static::$_instance->{$property} = $value;
696
+				}
697
+			}
698
+			//and then directly call its constructor again, like we would if we
699
+			//were creating a new one
700
+			static::$_instance->__construct($timezone);
701
+			return self::instance();
702
+		}
703
+		return null;
704
+	}
705
+
706
+
707
+
708
+	/**
709
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
710
+	 *
711
+	 * @param  boolean $translated return localized strings or JUST the array.
712
+	 * @return array
713
+	 * @throws \EE_Error
714
+	 */
715
+	public function status_array($translated = false)
716
+	{
717
+		if ( ! array_key_exists('Status', $this->_model_relations)) {
718
+			return array();
719
+		}
720
+		$model_name = $this->get_this_model_name();
721
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
722
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
723
+		$status_array = array();
724
+		foreach ($stati as $status) {
725
+			$status_array[$status->ID()] = $status->get('STS_code');
726
+		}
727
+		return $translated
728
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
729
+			: $status_array;
730
+	}
731
+
732
+
733
+
734
+	/**
735
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
736
+	 *
737
+	 * @param array $query_params             {
738
+	 * @var array $0 (where) array {
739
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
740
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
741
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
742
+	 *                                        conditions based on related models (and even
743
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
744
+	 *                                        name. Eg,
745
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
746
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
747
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
748
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
749
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE Venue_CPT.ID = 12 Notice that automatically
750
+	 *                                        took care of joining Events to Venues (even when each of those models actually consisted of two tables). Also, you may chain the model relations together. Eg instead of just having
751
+	 *                                        "Venue.VNU_ID", you could have
752
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
753
+	 *                                        events are related to Registrations, which are related to Attendees). You
754
+	 *                                        can take it even further with
755
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
756
+	 *                                        (from the default of '='), change the value to an numerically-indexed
757
+	 *                                        array, where the first item in the list is the operator. eg: array(
758
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
759
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
760
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
761
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
762
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN (followed by an array with exactly 2 date strings), IS NULL, and IS NOT NULL Values can be a string, int, or float. They can
763
+	 *                                        also be arrays IFF the operator is IN. Also, values can actually be field names. To indicate the value is a field, simply provide a third array item (true) to the operator-value array like so:
764
+	 *                                        eg: array( 'DTT_reg_limit' => array('>', 'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold" Note: you can also use related model field names like you would any other field
765
+	 *                                        name. eg: array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default
766
+	 *                                        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__>' =>
767
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp = 345678912...". Also, to negate an entire set of conditions, use 'NOT' as an array key. eg: array('NOT'=>array('TXN_total' =>
768
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND TXN_paid =23) Note: the 'glue' used to join each condition will continue to be what you last specified. IE, "AND"s by default,
769
+	 *                                        but if you had previously specified to use ORs to join, ORs will continue to be used. So, if you specify to use an "OR" to join conditions, it will continue to "stick" until you specify an AND.
770
+	 *                                        eg array('OR'=>array('NOT'=>array('TXN_total' => 50, 'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >> "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
771
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg: array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes
772
+	 *                                        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
773
+	 *                                        place two or more where conditions applying to the same field. eg:
774
+	 *                                        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
775
+	 *                                        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 '*'
776
+	 *                                        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
777
+	 *                                        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 >>
778
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND PAY_timestamp != 1241234123" This can be applied to condition operators too, eg:
779
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
780
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
781
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL "...LIMIT 23", "...LIMIT 25,50",
782
+	 *                                        and "...LIMIT 23,42" respectively. Remember when you provide two numbers for the limit, the 1st number is
783
+	 *                                        the OFFSET, the 2nd is the LIMIT
784
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
785
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the following format array('on_join_limit'
786
+	 *                                        => array( 'table_alias', array(1,2) ) ).
787
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
788
+	 *                                        values are either 'ASC' or 'DESC'. 'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
789
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date DESC..." respectively. Like the
790
+	 *                                        'where' conditions, these fields can be on related models. Eg
791
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is perfectly valid from any model related
792
+	 *                                        to 'Registration' (like Event, Attendee, Price, Datetime, etc.)
793
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
794
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in ascending or descending order.
795
+	 *                                        Acceptable values are 'ASC' or 'DESC'. If, 'order_by' isn't used, but 'order' is, then it is assumed you
796
+	 *                                        want to order by the primary key. Eg,
797
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC'); //(will join
798
+	 *                                        with the Datetime model's table(s) and order by its field DTT_EVT_start) or
799
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make SQL "SELECT * FROM
800
+	 *                                        wp_esp_registration ORDER BY REG_ID ASC"
801
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
802
+	 *                                        'group_by'=>'VNU_ID', or 'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note: if no
803
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the model's primary key (or combined
804
+	 *                                        primary keys). This avoids some weirdness that results when using limits, tons of joins, and no group by,
805
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
806
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
807
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped results)
808
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
809
+	 *                                        array where values are models to be joined in the query.Eg array('Attendee','Payment','Datetime'). You may
810
+	 *                                        join with transient models using period, eg "Registration.Transaction.Payment". You will probably only want
811
+	 *                                        to do this in hopes of increasing efficiency, as related models which belongs to the current model
812
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
813
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
814
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
815
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually soft-deleted objects are
816
+	 *                                        filtered-out if you want to include them, set this query param to 'none'. If you want to ONLY disable THIS
817
+	 *                                        model's default where conditions set it to 'other_models_only'. If you only want this model's default where
818
+	 *                                        conditions added to the query, use 'this_model_only'. If you want to use all default where conditions
819
+	 *                                        (default), set to 'all'.
820
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
821
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return everything? Or should we only show
822
+	 *                                        the current user items they should be able to view on the frontend, backend, edit, or delete? can be set to
823
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
824
+	 *                                        }
825
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
826
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public again. Array keys
827
+	 *                                        are object IDs (if there is a primary key on the model. if not, numerically indexed)
828
+	 *                                        Some full examples: get 10 transactions which have Scottish attendees:
829
+	 *                                        EEM_Transaction::instance()->get_all( array( array(
830
+	 *                                        'OR'=>array(
831
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
832
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
833
+	 *                                        )
834
+	 *                                        ),
835
+	 *                                        'limit'=>10,
836
+	 *                                        'group_by'=>'TXN_ID'
837
+	 *                                        ));
838
+	 *                                        get all the answers to the question titled "shirt size" for event with id
839
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
840
+	 *                                        'Question.QST_display_text'=>'shirt size',
841
+	 *                                        'Registration.Event.EVT_ID'=>12
842
+	 *                                        ),
843
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
844
+	 *                                        ));
845
+	 * @throws \EE_Error
846
+	 */
847
+	public function get_all($query_params = array())
848
+	{
849
+		if (isset($query_params['limit'])
850
+			&& ! isset($query_params['group_by'])
851
+		) {
852
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
853
+		}
854
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
855
+	}
856
+
857
+
858
+
859
+	/**
860
+	 * Modifies the query parameters so we only get back model objects
861
+	 * that "belong" to the current user
862
+	 *
863
+	 * @param array $query_params @see EEM_Base::get_all()
864
+	 * @return array like EEM_Base::get_all
865
+	 */
866
+	public function alter_query_params_to_only_include_mine($query_params = array())
867
+	{
868
+		$wp_user_field_name = $this->wp_user_field_name();
869
+		if ($wp_user_field_name) {
870
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
871
+		}
872
+		return $query_params;
873
+	}
874
+
875
+
876
+
877
+	/**
878
+	 * Returns the name of the field's name that points to the WP_User table
879
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
880
+	 * foreign key to the WP_User table)
881
+	 *
882
+	 * @return string|boolean string on success, boolean false when there is no
883
+	 * foreign key to the WP_User table
884
+	 */
885
+	public function wp_user_field_name()
886
+	{
887
+		try {
888
+			if ( ! empty($this->_model_chain_to_wp_user)) {
889
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
890
+				$last_model_name = end($models_to_follow_to_wp_users);
891
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
892
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
893
+			} else {
894
+				$model_with_fk_to_wp_users = $this;
895
+				$model_chain_to_wp_user = '';
896
+			}
897
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
898
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
899
+		} catch (EE_Error $e) {
900
+			return false;
901
+		}
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
908
+	 * (or transiently-related model) has a foreign key to the wp_users table;
909
+	 * useful for finding if model objects of this type are 'owned' by the current user.
910
+	 * This is an empty string when the foreign key is on this model and when it isn't,
911
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
912
+	 * (or transiently-related model)
913
+	 *
914
+	 * @return string
915
+	 */
916
+	public function model_chain_to_wp_user()
917
+	{
918
+		return $this->_model_chain_to_wp_user;
919
+	}
920
+
921
+
922
+
923
+	/**
924
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
925
+	 * like how registrations don't have a foreign key to wp_users, but the
926
+	 * events they are for are), or is unrelated to wp users.
927
+	 * generally available
928
+	 *
929
+	 * @return boolean
930
+	 */
931
+	public function is_owned()
932
+	{
933
+		if ($this->model_chain_to_wp_user()) {
934
+			return true;
935
+		} else {
936
+			try {
937
+				$this->get_foreign_key_to('WP_User');
938
+				return true;
939
+			} catch (EE_Error $e) {
940
+				return false;
941
+			}
942
+		}
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
949
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
950
+	 * the model)
951
+	 *
952
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
953
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
954
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
955
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
956
+	 *                                  override this and set the select to "*", or a specific column name, like
957
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
958
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
959
+	 *                                  the aliases used to refer to this selection, and values are to be
960
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
961
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
962
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
963
+	 * @throws \EE_Error
964
+	 */
965
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
966
+	{
967
+		// remember the custom selections, if any, and type cast as array
968
+		// (unless $columns_to_select is an object, then just set as an empty array)
969
+		// Note: (array) 'some string' === array( 'some string' )
970
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
971
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
972
+		$select_expressions = $columns_to_select !== null
973
+			? $this->_construct_select_from_input($columns_to_select)
974
+			: $this->_construct_default_select_sql($model_query_info);
975
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
976
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
977
+	}
978
+
979
+
980
+
981
+	/**
982
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
983
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
984
+	 * take care of joins, field preparation etc.
985
+	 *
986
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
987
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
988
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
989
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
990
+	 *                                  override this and set the select to "*", or a specific column name, like
991
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
992
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
993
+	 *                                  the aliases used to refer to this selection, and values are to be
994
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
995
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
996
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
997
+	 * @throws \EE_Error
998
+	 */
999
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1000
+	{
1001
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1002
+	}
1003
+
1004
+
1005
+
1006
+	/**
1007
+	 * For creating a custom select statement
1008
+	 *
1009
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1010
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1011
+	 *                                 SQL, and 1=>is the datatype
1012
+	 * @throws EE_Error
1013
+	 * @return string
1014
+	 */
1015
+	private function _construct_select_from_input($columns_to_select)
1016
+	{
1017
+		if (is_array($columns_to_select)) {
1018
+			$select_sql_array = array();
1019
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1020
+				if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1021
+					throw new EE_Error(
1022
+						sprintf(
1023
+							__(
1024
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1025
+								"event_espresso"
1026
+							),
1027
+							$selection_and_datatype,
1028
+							$alias
1029
+						)
1030
+					);
1031
+				}
1032
+				if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1033
+					throw new EE_Error(
1034
+						sprintf(
1035
+							__(
1036
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1037
+								"event_espresso"
1038
+							),
1039
+							$selection_and_datatype[1],
1040
+							$selection_and_datatype[0],
1041
+							$alias,
1042
+							implode(",", $this->_valid_wpdb_data_types)
1043
+						)
1044
+					);
1045
+				}
1046
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1047
+			}
1048
+			$columns_to_select_string = implode(", ", $select_sql_array);
1049
+		} else {
1050
+			$columns_to_select_string = $columns_to_select;
1051
+		}
1052
+		return $columns_to_select_string;
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1059
+	 *
1060
+	 * @return string
1061
+	 * @throws \EE_Error
1062
+	 */
1063
+	public function primary_key_name()
1064
+	{
1065
+		return $this->get_primary_key_field()->get_name();
1066
+	}
1067
+
1068
+
1069
+
1070
+	/**
1071
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1072
+	 * If there is no primary key on this model, $id is treated as primary key string
1073
+	 *
1074
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1075
+	 * @return EE_Base_Class
1076
+	 */
1077
+	public function get_one_by_ID($id)
1078
+	{
1079
+		if ($this->get_from_entity_map($id)) {
1080
+			return $this->get_from_entity_map($id);
1081
+		}
1082
+		return $this->get_one(
1083
+			$this->alter_query_params_to_restrict_by_ID(
1084
+				$id,
1085
+				array('default_where_conditions' => 'minimum')
1086
+			)
1087
+		);
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * Alters query parameters to only get items with this ID are returned.
1094
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1095
+	 * or could just be a simple primary key ID
1096
+	 *
1097
+	 * @param int   $id
1098
+	 * @param array $query_params
1099
+	 * @return array of normal query params, @see EEM_Base::get_all
1100
+	 * @throws \EE_Error
1101
+	 */
1102
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1103
+	{
1104
+		if ( ! isset($query_params[0])) {
1105
+			$query_params[0] = array();
1106
+		}
1107
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1108
+		if ($conditions_from_id === null) {
1109
+			$query_params[0][$this->primary_key_name()] = $id;
1110
+		} else {
1111
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1112
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1113
+		}
1114
+		return $query_params;
1115
+	}
1116
+
1117
+
1118
+
1119
+	/**
1120
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1121
+	 * array. If no item is found, null is returned.
1122
+	 *
1123
+	 * @param array $query_params like EEM_Base's $query_params variable.
1124
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1125
+	 * @throws \EE_Error
1126
+	 */
1127
+	public function get_one($query_params = array())
1128
+	{
1129
+		if ( ! is_array($query_params)) {
1130
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1131
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1132
+					gettype($query_params)), '4.6.0');
1133
+			$query_params = array();
1134
+		}
1135
+		$query_params['limit'] = 1;
1136
+		$items = $this->get_all($query_params);
1137
+		if (empty($items)) {
1138
+			return null;
1139
+		} else {
1140
+			return array_shift($items);
1141
+		}
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Returns the next x number of items in sequence from the given value as
1148
+	 * found in the database matching the given query conditions.
1149
+	 *
1150
+	 * @param mixed $current_field_value    Value used for the reference point.
1151
+	 * @param null  $field_to_order_by      What field is used for the
1152
+	 *                                      reference point.
1153
+	 * @param int   $limit                  How many to return.
1154
+	 * @param array $query_params           Extra conditions on the query.
1155
+	 * @param null  $columns_to_select      If left null, then an array of
1156
+	 *                                      EE_Base_Class objects is returned,
1157
+	 *                                      otherwise you can indicate just the
1158
+	 *                                      columns you want returned.
1159
+	 * @return EE_Base_Class[]|array
1160
+	 * @throws \EE_Error
1161
+	 */
1162
+	public function next_x(
1163
+		$current_field_value,
1164
+		$field_to_order_by = null,
1165
+		$limit = 1,
1166
+		$query_params = array(),
1167
+		$columns_to_select = null
1168
+	) {
1169
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1170
+			$columns_to_select);
1171
+	}
1172
+
1173
+
1174
+
1175
+	/**
1176
+	 * Returns the previous x number of items in sequence from the given value
1177
+	 * as found in the database matching the given query conditions.
1178
+	 *
1179
+	 * @param mixed $current_field_value    Value used for the reference point.
1180
+	 * @param null  $field_to_order_by      What field is used for the
1181
+	 *                                      reference point.
1182
+	 * @param int   $limit                  How many to return.
1183
+	 * @param array $query_params           Extra conditions on the query.
1184
+	 * @param null  $columns_to_select      If left null, then an array of
1185
+	 *                                      EE_Base_Class objects is returned,
1186
+	 *                                      otherwise you can indicate just the
1187
+	 *                                      columns you want returned.
1188
+	 * @return EE_Base_Class[]|array
1189
+	 * @throws \EE_Error
1190
+	 */
1191
+	public function previous_x(
1192
+		$current_field_value,
1193
+		$field_to_order_by = null,
1194
+		$limit = 1,
1195
+		$query_params = array(),
1196
+		$columns_to_select = null
1197
+	) {
1198
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1199
+			$columns_to_select);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next item in sequence from the given value as found in the
1206
+	 * database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param array $query_params           Extra conditions on the query.
1212
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1213
+	 *                                      object is returned, otherwise you
1214
+	 *                                      can indicate just the columns you
1215
+	 *                                      want and a single array indexed by
1216
+	 *                                      the columns will be returned.
1217
+	 * @return EE_Base_Class|null|array()
1218
+	 * @throws \EE_Error
1219
+	 */
1220
+	public function next(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$query_params = array(),
1224
+		$columns_to_select = null
1225
+	) {
1226
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1227
+			$columns_to_select);
1228
+		return empty($results) ? null : reset($results);
1229
+	}
1230
+
1231
+
1232
+
1233
+	/**
1234
+	 * Returns the previous item in sequence from the given value as found in
1235
+	 * the database matching the given query conditions.
1236
+	 *
1237
+	 * @param mixed $current_field_value    Value used for the reference point.
1238
+	 * @param null  $field_to_order_by      What field is used for the
1239
+	 *                                      reference point.
1240
+	 * @param array $query_params           Extra conditions on the query.
1241
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1242
+	 *                                      object is returned, otherwise you
1243
+	 *                                      can indicate just the columns you
1244
+	 *                                      want and a single array indexed by
1245
+	 *                                      the columns will be returned.
1246
+	 * @return EE_Base_Class|null|array()
1247
+	 * @throws EE_Error
1248
+	 */
1249
+	public function previous(
1250
+		$current_field_value,
1251
+		$field_to_order_by = null,
1252
+		$query_params = array(),
1253
+		$columns_to_select = null
1254
+	) {
1255
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1256
+			$columns_to_select);
1257
+		return empty($results) ? null : reset($results);
1258
+	}
1259
+
1260
+
1261
+
1262
+	/**
1263
+	 * Returns the a consecutive number of items in sequence from the given
1264
+	 * value as found in the database matching the given query conditions.
1265
+	 *
1266
+	 * @param mixed  $current_field_value   Value used for the reference point.
1267
+	 * @param string $operand               What operand is used for the sequence.
1268
+	 * @param string $field_to_order_by     What field is used for the reference point.
1269
+	 * @param int    $limit                 How many to return.
1270
+	 * @param array  $query_params          Extra conditions on the query.
1271
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the columns you want returned.
1273
+	 * @return EE_Base_Class[]|array
1274
+	 * @throws EE_Error
1275
+	 */
1276
+	protected function _get_consecutive(
1277
+		$current_field_value,
1278
+		$operand = '>',
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1285
+		if (empty($field_to_order_by)) {
1286
+			if ($this->has_primary_key_field()) {
1287
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1288
+			} else {
1289
+				if (WP_DEBUG) {
1290
+					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).',
1291
+						'event_espresso'));
1292
+				}
1293
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1294
+				return array();
1295
+			}
1296
+		}
1297
+		if ( ! is_array($query_params)) {
1298
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1299
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1300
+					gettype($query_params)), '4.6.0');
1301
+			$query_params = array();
1302
+		}
1303
+		//let's add the where query param for consecutive look up.
1304
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1305
+		$query_params['limit'] = $limit;
1306
+		//set direction
1307
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1308
+		$query_params['order_by'] = $operand === '>'
1309
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1310
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1311
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1312
+		if (empty($columns_to_select)) {
1313
+			return $this->get_all($query_params);
1314
+		} else {
1315
+			//getting just the fields
1316
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1317
+		}
1318
+	}
1319
+
1320
+
1321
+
1322
+	/**
1323
+	 * This sets the _timezone property after model object has been instantiated.
1324
+	 *
1325
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1326
+	 */
1327
+	public function set_timezone($timezone)
1328
+	{
1329
+		if ($timezone !== null) {
1330
+			$this->_timezone = $timezone;
1331
+		}
1332
+		//note we need to loop through relations and set the timezone on those objects as well.
1333
+		foreach ($this->_model_relations as $relation) {
1334
+			$relation->set_timezone($timezone);
1335
+		}
1336
+		//and finally we do the same for any datetime fields
1337
+		foreach ($this->_fields as $field) {
1338
+			if ($field instanceof EE_Datetime_Field) {
1339
+				$field->set_timezone($timezone);
1340
+			}
1341
+		}
1342
+	}
1343
+
1344
+
1345
+
1346
+	/**
1347
+	 * This just returns whatever is set for the current timezone.
1348
+	 *
1349
+	 * @access public
1350
+	 * @return string
1351
+	 */
1352
+	public function get_timezone()
1353
+	{
1354
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1355
+		if (empty($this->_timezone)) {
1356
+			foreach ($this->_fields as $field) {
1357
+				if ($field instanceof EE_Datetime_Field) {
1358
+					$this->set_timezone($field->get_timezone());
1359
+					break;
1360
+				}
1361
+			}
1362
+		}
1363
+		//if timezone STILL empty then return the default timezone for the site.
1364
+		if (empty($this->_timezone)) {
1365
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1366
+		}
1367
+		return $this->_timezone;
1368
+	}
1369
+
1370
+
1371
+
1372
+	/**
1373
+	 * This returns the date formats set for the given field name and also ensures that
1374
+	 * $this->_timezone property is set correctly.
1375
+	 *
1376
+	 * @since 4.6.x
1377
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1378
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1379
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1380
+	 * @return array formats in an array with the date format first, and the time format last.
1381
+	 */
1382
+	public function get_formats_for($field_name, $pretty = false)
1383
+	{
1384
+		$field_settings = $this->field_settings_for($field_name);
1385
+		//if not a valid EE_Datetime_Field then throw error
1386
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1387
+			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.',
1388
+				'event_espresso'), $field_name));
1389
+		}
1390
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1391
+		//the field.
1392
+		$this->_timezone = $field_settings->get_timezone();
1393
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1394
+	}
1395
+
1396
+
1397
+
1398
+	/**
1399
+	 * This returns the current time in a format setup for a query on this model.
1400
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1401
+	 * it will return:
1402
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1403
+	 *  NOW
1404
+	 *  - or a unix timestamp (equivalent to time())
1405
+	 *
1406
+	 * @since 4.6.x
1407
+	 * @param string $field_name       The field the current time is needed for.
1408
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1409
+	 *                                 formatted string matching the set format for the field in the set timezone will
1410
+	 *                                 be returned.
1411
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1412
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1413
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1414
+	 *                                 exception is triggered.
1415
+	 */
1416
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1417
+	{
1418
+		$formats = $this->get_formats_for($field_name);
1419
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1420
+		if ($timestamp) {
1421
+			return $DateTime->format('U');
1422
+		}
1423
+		//not returning timestamp, so return formatted string in timezone.
1424
+		switch ($what) {
1425
+			case 'time' :
1426
+				return $DateTime->format($formats[1]);
1427
+				break;
1428
+			case 'date' :
1429
+				return $DateTime->format($formats[0]);
1430
+				break;
1431
+			default :
1432
+				return $DateTime->format(implode(' ', $formats));
1433
+				break;
1434
+		}
1435
+	}
1436
+
1437
+
1438
+
1439
+	/**
1440
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1441
+	 * for the model are.  Returns a DateTime object.
1442
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1443
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1444
+	 * ignored.
1445
+	 *
1446
+	 * @param string $field_name      The field being setup.
1447
+	 * @param string $timestring      The date time string being used.
1448
+	 * @param string $incoming_format The format for the time string.
1449
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1450
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1451
+	 *                                format is
1452
+	 *                                'U', this is ignored.
1453
+	 * @return DateTime
1454
+	 * @throws \EE_Error
1455
+	 */
1456
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1457
+	{
1458
+		//just using this to ensure the timezone is set correctly internally
1459
+		$this->get_formats_for($field_name);
1460
+		//load EEH_DTT_Helper
1461
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1462
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1463
+		return $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone));
1464
+	}
1465
+
1466
+
1467
+
1468
+	/**
1469
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1470
+	 *
1471
+	 * @return EE_Table_Base[]
1472
+	 */
1473
+	public function get_tables()
1474
+	{
1475
+		return $this->_tables;
1476
+	}
1477
+
1478
+
1479
+
1480
+	/**
1481
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1482
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1483
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1484
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1485
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1486
+	 * model object with EVT_ID = 1
1487
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1488
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1489
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1490
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1491
+	 * are not specified)
1492
+	 *
1493
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1494
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1495
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1496
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1497
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1498
+	 *                                         ID=34, we'd use this method as follows:
1499
+	 *                                         EEM_Transaction::instance()->update(
1500
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1501
+	 *                                         array(array('TXN_ID'=>34)));
1502
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1503
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1504
+	 *                                         consider updating Question's QST_admin_label field is of type
1505
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1506
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1507
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1508
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1509
+	 *                                         TRUE, it is assumed that you've already called
1510
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1511
+	 *                                         malicious javascript. However, if
1512
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1513
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it, and every other field, before insertion. We provide this parameter because model objects perform their prepare_for_set
1514
+	 *                                         function on all their values, and so don't need to be called again (and in many cases, shouldn't be called again. Eg: if we escape HTML characters in the prepare_for_set method...)
1515
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1516
+	 *                                         in this model's entity map according to $fields_n_values that match
1517
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1518
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1519
+	 *                                         could get out-of-sync with the database
1520
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1521
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was bad)
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1525
+	{
1526
+		if ( ! is_array($query_params)) {
1527
+			EE_Error::doing_it_wrong('EEM_Base::update',
1528
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1529
+					gettype($query_params)), '4.6.0');
1530
+			$query_params = array();
1531
+		}
1532
+		/**
1533
+		 * Action called before a model update call has been made.
1534
+		 *
1535
+		 * @param EEM_Base $model
1536
+		 * @param array    $fields_n_values the updated fields and their new values
1537
+		 * @param array    $query_params    @see EEM_Base::get_all()
1538
+		 */
1539
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1540
+		/**
1541
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1542
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1543
+		 *
1544
+		 * @param array    $fields_n_values fields and their new values
1545
+		 * @param EEM_Base $model           the model being queried
1546
+		 * @param array    $query_params    see EEM_Base::get_all()
1547
+		 */
1548
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1549
+			$query_params);
1550
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1551
+		//to do that, for each table, verify that it's PK isn't null.
1552
+		$tables = $this->get_tables();
1553
+		//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
1554
+		//NOTE: we should make this code more efficient by NOT querying twice
1555
+		//before the real update, but that needs to first go through ALPHA testing
1556
+		//as it's dangerous. says Mike August 8 2014
1557
+		//we want to make sure the default_where strategy is ignored
1558
+		$this->_ignore_where_strategy = true;
1559
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1560
+		foreach ($wpdb_select_results as $wpdb_result) {
1561
+			// type cast stdClass as array
1562
+			$wpdb_result = (array)$wpdb_result;
1563
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1564
+			if ($this->has_primary_key_field()) {
1565
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1566
+			} else {
1567
+				//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)
1568
+				$main_table_pk_value = null;
1569
+			}
1570
+			//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
1571
+			//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
1572
+			if (count($tables) > 1) {
1573
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1574
+				//in that table, and so we'll want to insert one
1575
+				foreach ($tables as $table_obj) {
1576
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1577
+					//if there is no private key for this table on the results, it means there's no entry
1578
+					//in this table, right? so insert a row in the current table, using any fields available
1579
+					if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1580
+							&& $wpdb_result[$this_table_pk_column])
1581
+					) {
1582
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1583
+							$main_table_pk_value);
1584
+						//if we died here, report the error
1585
+						if ( ! $success) {
1586
+							return false;
1587
+						}
1588
+					}
1589
+				}
1590
+			}
1591
+			//				//and now check that if we have cached any models by that ID on the model, that
1592
+			//				//they also get updated properly
1593
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1594
+			//				if( $model_object ){
1595
+			//					foreach( $fields_n_values as $field => $value ){
1596
+			//						$model_object->set($field, $value);
1597
+			//let's make sure default_where strategy is followed now
1598
+			$this->_ignore_where_strategy = false;
1599
+		}
1600
+		//if we want to keep model objects in sync, AND
1601
+		//if this wasn't called from a model object (to update itself)
1602
+		//then we want to make sure we keep all the existing
1603
+		//model objects in sync with the db
1604
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1605
+			if ($this->has_primary_key_field()) {
1606
+				$model_objs_affected_ids = $this->get_col($query_params);
1607
+			} else {
1608
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1609
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1610
+				$model_objs_affected_ids = array();
1611
+				foreach ($models_affected_key_columns as $row) {
1612
+					$combined_index_key = $this->get_index_primary_key_string($row);
1613
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1614
+				}
1615
+			}
1616
+			if ( ! $model_objs_affected_ids) {
1617
+				//wait wait wait- if nothing was affected let's stop here
1618
+				return 0;
1619
+			}
1620
+			foreach ($model_objs_affected_ids as $id) {
1621
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1622
+				if ($model_obj_in_entity_map) {
1623
+					foreach ($fields_n_values as $field => $new_value) {
1624
+						$model_obj_in_entity_map->set($field, $new_value);
1625
+					}
1626
+				}
1627
+			}
1628
+			//if there is a primary key on this model, we can now do a slight optimization
1629
+			if ($this->has_primary_key_field()) {
1630
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1631
+				$query_params = array(
1632
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1633
+					'limit'                    => count($model_objs_affected_ids),
1634
+					'default_where_conditions' => 'none',
1635
+				);
1636
+			}
1637
+		}
1638
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1639
+		$SQL = "UPDATE "
1640
+			   . $model_query_info->get_full_join_sql()
1641
+			   . " SET "
1642
+			   . $this->_construct_update_sql($fields_n_values)
1643
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1644
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1645
+		/**
1646
+		 * Action called after a model update call has been made.
1647
+		 *
1648
+		 * @param EEM_Base $model
1649
+		 * @param array    $fields_n_values the updated fields and their new values
1650
+		 * @param array    $query_params    @see EEM_Base::get_all()
1651
+		 * @param int      $rows_affected
1652
+		 */
1653
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1654
+		return $rows_affected;//how many supposedly got updated
1655
+	}
1656
+
1657
+
1658
+
1659
+	/**
1660
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1661
+	 * are teh values of the field specified (or by default the primary key field)
1662
+	 * that matched the query params. Note that you should pass the name of the
1663
+	 * model FIELD, not the database table's column name.
1664
+	 *
1665
+	 * @param array  $query_params @see EEM_Base::get_all()
1666
+	 * @param string $field_to_select
1667
+	 * @return array just like $wpdb->get_col()
1668
+	 * @throws \EE_Error
1669
+	 */
1670
+	public function get_col($query_params = array(), $field_to_select = null)
1671
+	{
1672
+		if ($field_to_select) {
1673
+			$field = $this->field_settings_for($field_to_select);
1674
+		} elseif ($this->has_primary_key_field()) {
1675
+			$field = $this->get_primary_key_field();
1676
+		} else {
1677
+			//no primary key, just grab the first column
1678
+			$field = reset($this->field_settings());
1679
+		}
1680
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1681
+		$select_expressions = $field->get_qualified_column();
1682
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1683
+		return $this->_do_wpdb_query('get_col', array($SQL));
1684
+	}
1685
+
1686
+
1687
+
1688
+	/**
1689
+	 * Returns a single column value for a single row from the database
1690
+	 *
1691
+	 * @param array  $query_params    @see EEM_Base::get_all()
1692
+	 * @param string $field_to_select @see EEM_Base::get_col()
1693
+	 * @return string
1694
+	 * @throws \EE_Error
1695
+	 */
1696
+	public function get_var($query_params = array(), $field_to_select = null)
1697
+	{
1698
+		$query_params['limit'] = 1;
1699
+		$col = $this->get_col($query_params, $field_to_select);
1700
+		if ( ! empty($col)) {
1701
+			return reset($col);
1702
+		} else {
1703
+			return null;
1704
+		}
1705
+	}
1706
+
1707
+
1708
+
1709
+	/**
1710
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1711
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1712
+	 * injection, but currently no further filtering is done
1713
+	 *
1714
+	 * @global      $wpdb
1715
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1716
+	 *                               be updated to in the DB
1717
+	 * @return string of SQL
1718
+	 * @throws \EE_Error
1719
+	 */
1720
+	public function _construct_update_sql($fields_n_values)
1721
+	{
1722
+		/** @type WPDB $wpdb */
1723
+		global $wpdb;
1724
+		$cols_n_values = array();
1725
+		foreach ($fields_n_values as $field_name => $value) {
1726
+			$field_obj = $this->field_settings_for($field_name);
1727
+			//if the value is NULL, we want to assign the value to that.
1728
+			//wpdb->prepare doesn't really handle that properly
1729
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1730
+			$value_sql = $prepared_value === null ? 'NULL'
1731
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1732
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1733
+		}
1734
+		return implode(",", $cols_n_values);
1735
+	}
1736
+
1737
+
1738
+
1739
+	/**
1740
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1741
+	 * Performs a HARD delete, meaning the database row should always be removed,
1742
+	 * not just have a flag field on it switched
1743
+	 * Wrapper for EEM_Base::delete_permanently()
1744
+	 *
1745
+	 * @param mixed $id
1746
+	 * @return boolean whether the row got deleted or not
1747
+	 * @throws \EE_Error
1748
+	 */
1749
+	public function delete_permanently_by_ID($id)
1750
+	{
1751
+		return $this->delete_permanently(
1752
+			array(
1753
+				array($this->get_primary_key_field()->get_name() => $id),
1754
+				'limit' => 1,
1755
+			)
1756
+		);
1757
+	}
1758
+
1759
+
1760
+
1761
+	/**
1762
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1763
+	 * Wrapper for EEM_Base::delete()
1764
+	 *
1765
+	 * @param mixed $id
1766
+	 * @return boolean whether the row got deleted or not
1767
+	 * @throws \EE_Error
1768
+	 */
1769
+	public function delete_by_ID($id)
1770
+	{
1771
+		return $this->delete(
1772
+			array(
1773
+				array($this->get_primary_key_field()->get_name() => $id),
1774
+				'limit' => 1,
1775
+			)
1776
+		);
1777
+	}
1778
+
1779
+
1780
+
1781
+	/**
1782
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1783
+	 * meaning if the model has a field that indicates its been "trashed" or
1784
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1785
+	 *
1786
+	 * @see EEM_Base::delete_permanently
1787
+	 * @param array   $query_params
1788
+	 * @param boolean $allow_blocking
1789
+	 * @return int how many rows got deleted
1790
+	 * @throws \EE_Error
1791
+	 */
1792
+	public function delete($query_params, $allow_blocking = true)
1793
+	{
1794
+		return $this->delete_permanently($query_params, $allow_blocking);
1795
+	}
1796
+
1797
+
1798
+
1799
+	/**
1800
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1801
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1802
+	 * as archived, not actually deleted
1803
+	 *
1804
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1805
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1806
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1807
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1808
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1809
+	 *                                DB
1810
+	 * @return int how many rows got deleted
1811
+	 * @throws \EE_Error
1812
+	 */
1813
+	public function delete_permanently($query_params, $allow_blocking = true)
1814
+	{
1815
+		/**
1816
+		 * Action called just before performing a real deletion query. You can use the
1817
+		 * model and its $query_params to find exactly which items will be deleted
1818
+		 *
1819
+		 * @param EEM_Base $model
1820
+		 * @param array    $query_params   @see EEM_Base::get_all()
1821
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1822
+		 *                                 to block (prevent) this deletion
1823
+		 */
1824
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1825
+		//some MySQL databases may be running safe mode, which may restrict
1826
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1827
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1828
+		//to delete them
1829
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1830
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1831
+		if ($deletion_where) {
1832
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1833
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1834
+			$table_aliases = array_keys($this->_tables);
1835
+			$SQL = "DELETE "
1836
+				   . implode(", ", $table_aliases)
1837
+				   . " FROM "
1838
+				   . $model_query_info->get_full_join_sql()
1839
+				   . " WHERE "
1840
+				   . $deletion_where;
1841
+			//		/echo "delete sql:$SQL";
1842
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1843
+		} else {
1844
+			$rows_deleted = 0;
1845
+		}
1846
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1847
+		if ($this->has_primary_key_field()) {
1848
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1849
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1850
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1851
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1852
+				}
1853
+			}
1854
+		}
1855
+		/**
1856
+		 * Action called just after performing a real deletion query. Although at this point the
1857
+		 * items should have been deleted
1858
+		 *
1859
+		 * @param EEM_Base $model
1860
+		 * @param array    $query_params @see EEM_Base::get_all()
1861
+		 * @param int      $rows_deleted
1862
+		 */
1863
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1864
+		return $rows_deleted;//how many supposedly got deleted
1865
+	}
1866
+
1867
+
1868
+
1869
+	/**
1870
+	 * Checks all the relations that throw error messages when there are blocking related objects
1871
+	 * for related model objects. If there are any related model objects on those relations,
1872
+	 * adds an EE_Error, and return true
1873
+	 *
1874
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1875
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1876
+	 *                                                 should be ignored when determining whether there are related
1877
+	 *                                                 model objects which block this model object's deletion. Useful
1878
+	 *                                                 if you know A is related to B and are considering deleting A,
1879
+	 *                                                 but want to see if A has any other objects blocking its deletion
1880
+	 *                                                 before removing the relation between A and B
1881
+	 * @return boolean
1882
+	 * @throws \EE_Error
1883
+	 */
1884
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1885
+	{
1886
+		//first, if $ignore_this_model_obj was supplied, get its model
1887
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1888
+			$ignored_model = $ignore_this_model_obj->get_model();
1889
+		} else {
1890
+			$ignored_model = null;
1891
+		}
1892
+		//now check all the relations of $this_model_obj_or_id and see if there
1893
+		//are any related model objects blocking it?
1894
+		$is_blocked = false;
1895
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1896
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1897
+				//if $ignore_this_model_obj was supplied, then for the query
1898
+				//on that model needs to be told to ignore $ignore_this_model_obj
1899
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1900
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1901
+						array(
1902
+							$ignored_model->get_primary_key_field()->get_name() => array(
1903
+								'!=',
1904
+								$ignore_this_model_obj->ID(),
1905
+							),
1906
+						),
1907
+					));
1908
+				} else {
1909
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1910
+				}
1911
+				if ($related_model_objects) {
1912
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1913
+					$is_blocked = true;
1914
+				}
1915
+			}
1916
+		}
1917
+		return $is_blocked;
1918
+	}
1919
+
1920
+
1921
+
1922
+	/**
1923
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1924
+	 * well.
1925
+	 *
1926
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1927
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1928
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1929
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1930
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1931
+	 *                                      easily corrupt your DB
1932
+	 * @throws EE_Error
1933
+	 * @return string    everything that comes after the WHERE statement.
1934
+	 */
1935
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1936
+	{
1937
+		if ($this->has_primary_key_field()) {
1938
+			$primary_table = $this->_get_main_table();
1939
+			$other_tables = $this->_get_other_tables();
1940
+			$deletes = $query = array();
1941
+			foreach ($objects_for_deletion as $delete_object) {
1942
+				//before we mark this object for deletion,
1943
+				//make sure there's no related objects blocking its deletion (if we're checking)
1944
+				if (
1945
+					$allow_blocking
1946
+					&& $this->delete_is_blocked_by_related_models(
1947
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
1948
+					)
1949
+				) {
1950
+					continue;
1951
+				}
1952
+				//primary table deletes
1953
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
1954
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $delete_object[$primary_table->get_fully_qualified_pk_column()];
1955
+				}
1956
+				//other tables
1957
+				if ( ! empty($other_tables)) {
1958
+					foreach ($other_tables as $ot) {
1959
+						//first check if we've got the foreign key column here.
1960
+						if (isset($delete_object[$ot->get_fully_qualified_fk_column()])) {
1961
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_fk_column()];
1962
+						}
1963
+						// wait! it's entirely possible that we'll have a the primary key
1964
+						// for this table in here, if it's a foreign key for one of the other secondary tables
1965
+						if (isset($delete_object[$ot->get_fully_qualified_pk_column()])) {
1966
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1967
+						}
1968
+						// finally, it is possible that the fk for this table is found
1969
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
1970
+						if (isset($delete_object[$ot->get_fully_qualified_pk_on_fk_table()])) {
1971
+							$deletes[$ot->get_fully_qualified_pk_column()][] = $delete_object[$ot->get_fully_qualified_pk_column()];
1972
+						}
1973
+					}
1974
+				}
1975
+			}
1976
+			//we should have deletes now, so let's just go through and setup the where statement
1977
+			foreach ($deletes as $column => $values) {
1978
+				//make sure we have unique $values;
1979
+				$values = array_unique($values);
1980
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
1981
+			}
1982
+			return ! empty($query) ? implode(' AND ', $query) : '';
1983
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
1984
+			$ways_to_identify_a_row = array();
1985
+			$fields = $this->get_combined_primary_key_fields();
1986
+			//note: because there' sno primary key, that means nothing else  can be pointing to this model, right?
1987
+			foreach ($objects_for_deletion as $delete_object) {
1988
+				$values_for_each_cpk_for_a_row = array();
1989
+				foreach ($fields as $cpk_field) {
1990
+					if ($cpk_field instanceof EE_Model_Field_Base) {
1991
+						$values_for_each_cpk_for_a_row[] = $cpk_field->get_qualified_column()
1992
+														   . "="
1993
+														   . $delete_object[$cpk_field->get_qualified_column()];
1994
+					}
1995
+				}
1996
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $values_for_each_cpk_for_a_row) . ")";
1997
+			}
1998
+			return implode(" OR ", $ways_to_identify_a_row);
1999
+		} else {
2000
+			//so there's no primary key and no combined key...
2001
+			//sorry, can't help you
2002
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2003
+				"event_espresso"), get_class($this)));
2004
+		}
2005
+	}
2006
+
2007
+
2008
+
2009
+	/**
2010
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2011
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2012
+	 * column
2013
+	 *
2014
+	 * @param array  $query_params   like EEM_Base::get_all's
2015
+	 * @param string $field_to_count field on model to count by (not column name)
2016
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2017
+	 *                               that by the setting $distinct to TRUE;
2018
+	 * @return int
2019
+	 * @throws \EE_Error
2020
+	 */
2021
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2022
+	{
2023
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2024
+		if ($field_to_count) {
2025
+			$field_obj = $this->field_settings_for($field_to_count);
2026
+			$column_to_count = $field_obj->get_qualified_column();
2027
+		} elseif ($this->has_primary_key_field()) {
2028
+			$pk_field_obj = $this->get_primary_key_field();
2029
+			$column_to_count = $pk_field_obj->get_qualified_column();
2030
+		} else {
2031
+			//there's no primary key
2032
+			//if we're counting distinct items, and there's no primary key,
2033
+			//we need to list out the columns for distinction;
2034
+			//otherwise we can just use star
2035
+			if ($distinct) {
2036
+				$columns_to_use = array();
2037
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2038
+					$columns_to_use[] = $field_obj->get_qualified_column();
2039
+				}
2040
+				$column_to_count = implode(',', $columns_to_use);
2041
+			} else {
2042
+				$column_to_count = '*';
2043
+			}
2044
+		}
2045
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2046
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2047
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2048
+	}
2049
+
2050
+
2051
+
2052
+	/**
2053
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2054
+	 *
2055
+	 * @param array  $query_params like EEM_Base::get_all
2056
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2057
+	 * @return float
2058
+	 * @throws \EE_Error
2059
+	 */
2060
+	public function sum($query_params, $field_to_sum = null)
2061
+	{
2062
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2063
+		if ($field_to_sum) {
2064
+			$field_obj = $this->field_settings_for($field_to_sum);
2065
+		} else {
2066
+			$field_obj = $this->get_primary_key_field();
2067
+		}
2068
+		$column_to_count = $field_obj->get_qualified_column();
2069
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2070
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2071
+		$data_type = $field_obj->get_wpdb_data_type();
2072
+		if ($data_type === '%d' || $data_type === '%s') {
2073
+			return (float)$return_value;
2074
+		} else {//must be %f
2075
+			return (float)$return_value;
2076
+		}
2077
+	}
2078
+
2079
+
2080
+
2081
+	/**
2082
+	 * Just calls the specified method on $wpdb with the given arguments
2083
+	 * Consolidates a little extra error handling code
2084
+	 *
2085
+	 * @param string $wpdb_method
2086
+	 * @param array  $arguments_to_provide
2087
+	 * @throws EE_Error
2088
+	 * @global wpdb  $wpdb
2089
+	 * @return mixed
2090
+	 */
2091
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2092
+	{
2093
+		//if we're in maintenance mode level 2, DON'T run any queries
2094
+		//because level 2 indicates the database needs updating and
2095
+		//is probably out of sync with the code
2096
+		if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2097
+			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.",
2098
+				"event_espresso")));
2099
+		}
2100
+		/** @type WPDB $wpdb */
2101
+		global $wpdb;
2102
+		if ( ! method_exists($wpdb, $wpdb_method)) {
2103
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2104
+				'event_espresso'), $wpdb_method));
2105
+		}
2106
+		if (WP_DEBUG) {
2107
+			$old_show_errors_value = $wpdb->show_errors;
2108
+			$wpdb->show_errors(false);
2109
+		}
2110
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2111
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2112
+		if (WP_DEBUG) {
2113
+			$wpdb->show_errors($old_show_errors_value);
2114
+			if ( ! empty($wpdb->last_error)) {
2115
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2116
+			} elseif ($result === false) {
2117
+				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"',
2118
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2119
+			}
2120
+		} elseif ($result === false) {
2121
+			EE_Error::add_error(
2122
+				sprintf(
2123
+					__('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"',
2124
+						'event_espresso'),
2125
+					$wpdb_method,
2126
+					var_export($arguments_to_provide, true),
2127
+					$wpdb->last_error
2128
+				),
2129
+				__FILE__,
2130
+				__FUNCTION__,
2131
+				__LINE__
2132
+			);
2133
+		}
2134
+		return $result;
2135
+	}
2136
+
2137
+
2138
+
2139
+	/**
2140
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2141
+	 * and if there's an error tries to verify the DB is correct. Uses
2142
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2143
+	 * we should try to fix the EE core db, the addons, or just give up
2144
+	 *
2145
+	 * @param string $wpdb_method
2146
+	 * @param array  $arguments_to_provide
2147
+	 * @return mixed
2148
+	 */
2149
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2150
+	{
2151
+		/** @type WPDB $wpdb */
2152
+		global $wpdb;
2153
+		$wpdb->last_error = null;
2154
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2155
+		// was there an error running the query? but we don't care on new activations
2156
+		// (we're going to setup the DB anyway on new activations)
2157
+		if (($result === false || ! empty($wpdb->last_error))
2158
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2159
+		) {
2160
+			switch (EEM_Base::$_db_verification_level) {
2161
+				case EEM_Base::db_verified_none :
2162
+					// let's double-check core's DB
2163
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2164
+					break;
2165
+				case EEM_Base::db_verified_core :
2166
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2167
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2168
+					break;
2169
+				case EEM_Base::db_verified_addons :
2170
+					// ummmm... you in trouble
2171
+					return $result;
2172
+					break;
2173
+			}
2174
+			if ( ! empty($error_message)) {
2175
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2176
+				trigger_error($error_message);
2177
+			}
2178
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2179
+		}
2180
+		return $result;
2181
+	}
2182
+
2183
+
2184
+
2185
+	/**
2186
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2187
+	 * EEM_Base::$_db_verification_level
2188
+	 *
2189
+	 * @param string $wpdb_method
2190
+	 * @param array  $arguments_to_provide
2191
+	 * @return string
2192
+	 */
2193
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2194
+	{
2195
+		/** @type WPDB $wpdb */
2196
+		global $wpdb;
2197
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2198
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2199
+		$error_message = sprintf(
2200
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2201
+				'event_espresso'),
2202
+			$wpdb->last_error,
2203
+			$wpdb_method,
2204
+			json_encode($arguments_to_provide)
2205
+		);
2206
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2207
+		return $error_message;
2208
+	}
2209
+
2210
+
2211
+
2212
+	/**
2213
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2214
+	 * EEM_Base::$_db_verification_level
2215
+	 *
2216
+	 * @param $wpdb_method
2217
+	 * @param $arguments_to_provide
2218
+	 * @return string
2219
+	 */
2220
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2221
+	{
2222
+		/** @type WPDB $wpdb */
2223
+		global $wpdb;
2224
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2225
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2226
+		$error_message = sprintf(
2227
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2228
+				'event_espresso'),
2229
+			$wpdb->last_error,
2230
+			$wpdb_method,
2231
+			json_encode($arguments_to_provide)
2232
+		);
2233
+		EE_System::instance()->initialize_addons();
2234
+		return $error_message;
2235
+	}
2236
+
2237
+
2238
+
2239
+	/**
2240
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2241
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2242
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2243
+	 * ..."
2244
+	 *
2245
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2246
+	 * @return string
2247
+	 */
2248
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2249
+	{
2250
+		return " FROM " . $model_query_info->get_full_join_sql() .
2251
+			   $model_query_info->get_where_sql() .
2252
+			   $model_query_info->get_group_by_sql() .
2253
+			   $model_query_info->get_having_sql() .
2254
+			   $model_query_info->get_order_by_sql() .
2255
+			   $model_query_info->get_limit_sql();
2256
+	}
2257
+
2258
+
2259
+
2260
+	/**
2261
+	 * Set to easily debug the next X queries ran from this model.
2262
+	 *
2263
+	 * @param int $count
2264
+	 */
2265
+	public function show_next_x_db_queries($count = 1)
2266
+	{
2267
+		$this->_show_next_x_db_queries = $count;
2268
+	}
2269
+
2270
+
2271
+
2272
+	/**
2273
+	 * @param $sql_query
2274
+	 */
2275
+	public function show_db_query_if_previously_requested($sql_query)
2276
+	{
2277
+		if ($this->_show_next_x_db_queries > 0) {
2278
+			echo $sql_query;
2279
+			$this->_show_next_x_db_queries--;
2280
+		}
2281
+	}
2282
+
2283
+
2284
+
2285
+	/**
2286
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2287
+	 * There are the 3 cases:
2288
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2289
+	 * $otherModelObject has no ID, it is first saved.
2290
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2291
+	 * has no ID, it is first saved.
2292
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2293
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2294
+	 * join table
2295
+	 *
2296
+	 * @param        EE_Base_Class                     /int $thisModelObject
2297
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2298
+	 * @param string $relationName                     , key in EEM_Base::_relations
2299
+	 *                                                 an attendee to a group, you also want to specify which role they
2300
+	 *                                                 will have in that group. So you would use this parameter to
2301
+	 *                                                 specify array('role-column-name'=>'role-id')
2302
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2303
+	 *                                                 to for relation to methods that allow you to further specify
2304
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2305
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2306
+	 *                                                 because these will be inserted in any new rows created as well.
2307
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2308
+	 * @throws \EE_Error
2309
+	 */
2310
+	public function add_relationship_to(
2311
+		$id_or_obj,
2312
+		$other_model_id_or_obj,
2313
+		$relationName,
2314
+		$extra_join_model_fields_n_values = array()
2315
+	) {
2316
+		$relation_obj = $this->related_settings_for($relationName);
2317
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2318
+	}
2319
+
2320
+
2321
+
2322
+	/**
2323
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2324
+	 * There are the 3 cases:
2325
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2326
+	 * error
2327
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2328
+	 * an error
2329
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2330
+	 *
2331
+	 * @param        EE_Base_Class /int $id_or_obj
2332
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2333
+	 * @param string $relationName key in EEM_Base::_relations
2334
+	 * @return boolean of success
2335
+	 * @throws \EE_Error
2336
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2337
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2338
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2339
+	 *                             because these will be inserted in any new rows created as well.
2340
+	 */
2341
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2342
+	{
2343
+		$relation_obj = $this->related_settings_for($relationName);
2344
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2345
+	}
2346
+
2347
+
2348
+
2349
+	/**
2350
+	 * @param mixed           $id_or_obj
2351
+	 * @param string          $relationName
2352
+	 * @param array           $where_query_params
2353
+	 * @param EE_Base_Class[] objects to which relations were removed
2354
+	 * @return \EE_Base_Class[]
2355
+	 * @throws \EE_Error
2356
+	 */
2357
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2358
+	{
2359
+		$relation_obj = $this->related_settings_for($relationName);
2360
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2361
+	}
2362
+
2363
+
2364
+
2365
+	/**
2366
+	 * Gets all the related items of the specified $model_name, using $query_params.
2367
+	 * Note: by default, we remove the "default query params"
2368
+	 * because we want to get even deleted items etc.
2369
+	 *
2370
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2371
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2372
+	 * @param array  $query_params like EEM_Base::get_all
2373
+	 * @return EE_Base_Class[]
2374
+	 * @throws \EE_Error
2375
+	 */
2376
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2377
+	{
2378
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2379
+		$relation_settings = $this->related_settings_for($model_name);
2380
+		return $relation_settings->get_all_related($model_obj, $query_params);
2381
+	}
2382
+
2383
+
2384
+
2385
+	/**
2386
+	 * Deletes all the model objects across the relation indicated by $model_name
2387
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2388
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2389
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2390
+	 *
2391
+	 * @param EE_Base_Class|int|string $id_or_obj
2392
+	 * @param string                   $model_name
2393
+	 * @param array                    $query_params
2394
+	 * @return int how many deleted
2395
+	 * @throws \EE_Error
2396
+	 */
2397
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2398
+	{
2399
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2400
+		$relation_settings = $this->related_settings_for($model_name);
2401
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2402
+	}
2403
+
2404
+
2405
+
2406
+	/**
2407
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2408
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2409
+	 * the model objects can't be hard deleted because of blocking related model objects,
2410
+	 * just does a soft-delete on them instead.
2411
+	 *
2412
+	 * @param EE_Base_Class|int|string $id_or_obj
2413
+	 * @param string                   $model_name
2414
+	 * @param array                    $query_params
2415
+	 * @return int how many deleted
2416
+	 * @throws \EE_Error
2417
+	 */
2418
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2419
+	{
2420
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2421
+		$relation_settings = $this->related_settings_for($model_name);
2422
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2423
+	}
2424
+
2425
+
2426
+
2427
+	/**
2428
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2429
+	 * unless otherwise specified in the $query_params
2430
+	 *
2431
+	 * @param        int             /EE_Base_Class $id_or_obj
2432
+	 * @param string $model_name     like 'Event', or 'Registration'
2433
+	 * @param array  $query_params   like EEM_Base::get_all's
2434
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2435
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2436
+	 *                               that by the setting $distinct to TRUE;
2437
+	 * @return int
2438
+	 * @throws \EE_Error
2439
+	 */
2440
+	public function count_related(
2441
+		$id_or_obj,
2442
+		$model_name,
2443
+		$query_params = array(),
2444
+		$field_to_count = null,
2445
+		$distinct = false
2446
+	) {
2447
+		$related_model = $this->get_related_model_obj($model_name);
2448
+		//we're just going to use the query params on the related model's normal get_all query,
2449
+		//except add a condition to say to match the current mod
2450
+		if ( ! isset($query_params['default_where_conditions'])) {
2451
+			$query_params['default_where_conditions'] = 'none';
2452
+		}
2453
+		$this_model_name = $this->get_this_model_name();
2454
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2455
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2456
+		return $related_model->count($query_params, $field_to_count, $distinct);
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2463
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2464
+	 *
2465
+	 * @param        int           /EE_Base_Class $id_or_obj
2466
+	 * @param string $model_name   like 'Event', or 'Registration'
2467
+	 * @param array  $query_params like EEM_Base::get_all's
2468
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2469
+	 * @return float
2470
+	 * @throws \EE_Error
2471
+	 */
2472
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2473
+	{
2474
+		$related_model = $this->get_related_model_obj($model_name);
2475
+		if ( ! is_array($query_params)) {
2476
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2477
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2478
+					gettype($query_params)), '4.6.0');
2479
+			$query_params = array();
2480
+		}
2481
+		//we're just going to use the query params on the related model's normal get_all query,
2482
+		//except add a condition to say to match the current mod
2483
+		if ( ! isset($query_params['default_where_conditions'])) {
2484
+			$query_params['default_where_conditions'] = 'none';
2485
+		}
2486
+		$this_model_name = $this->get_this_model_name();
2487
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2488
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2489
+		return $related_model->sum($query_params, $field_to_sum);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2496
+	 * $modelObject
2497
+	 *
2498
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2499
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2500
+	 * @param array               $query_params     like EEM_Base::get_all's
2501
+	 * @return EE_Base_Class
2502
+	 * @throws \EE_Error
2503
+	 */
2504
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2505
+	{
2506
+		$query_params['limit'] = 1;
2507
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2508
+		if ($results) {
2509
+			return array_shift($results);
2510
+		} else {
2511
+			return null;
2512
+		}
2513
+	}
2514
+
2515
+
2516
+
2517
+	/**
2518
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2519
+	 *
2520
+	 * @return string
2521
+	 */
2522
+	public function get_this_model_name()
2523
+	{
2524
+		return str_replace("EEM_", "", get_class($this));
2525
+	}
2526
+
2527
+
2528
+
2529
+	/**
2530
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2531
+	 *
2532
+	 * @return EE_Any_Foreign_Model_Name_Field
2533
+	 * @throws EE_Error
2534
+	 */
2535
+	public function get_field_containing_related_model_name()
2536
+	{
2537
+		foreach ($this->field_settings(true) as $field) {
2538
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2539
+				$field_with_model_name = $field;
2540
+			}
2541
+		}
2542
+		if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2543
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2544
+				$this->get_this_model_name()));
2545
+		}
2546
+		return $field_with_model_name;
2547
+	}
2548
+
2549
+
2550
+
2551
+	/**
2552
+	 * Inserts a new entry into the database, for each table.
2553
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2554
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2555
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2556
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2557
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2558
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2559
+	 *
2560
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2561
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2562
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2563
+	 *                              of EEM_Base)
2564
+	 * @return int new primary key on main table that got inserted
2565
+	 * @throws EE_Error
2566
+	 */
2567
+	public function insert($field_n_values)
2568
+	{
2569
+		/**
2570
+		 * Filters the fields and their values before inserting an item using the models
2571
+		 *
2572
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2573
+		 * @param EEM_Base $model           the model used
2574
+		 */
2575
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2576
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2577
+			$main_table = $this->_get_main_table();
2578
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2579
+			if ($new_id !== false) {
2580
+				foreach ($this->_get_other_tables() as $other_table) {
2581
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2582
+				}
2583
+			}
2584
+			/**
2585
+			 * Done just after attempting to insert a new model object
2586
+			 *
2587
+			 * @param EEM_Base   $model           used
2588
+			 * @param array      $fields_n_values fields and their values
2589
+			 * @param int|string the              ID of the newly-inserted model object
2590
+			 */
2591
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2592
+			return $new_id;
2593
+		} else {
2594
+			return false;
2595
+		}
2596
+	}
2597
+
2598
+
2599
+
2600
+	/**
2601
+	 * Checks that the result would satisfy the unique indexes on this model
2602
+	 *
2603
+	 * @param array  $field_n_values
2604
+	 * @param string $action
2605
+	 * @return boolean
2606
+	 * @throws \EE_Error
2607
+	 */
2608
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2609
+	{
2610
+		foreach ($this->unique_indexes() as $index_name => $index) {
2611
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2612
+			if ($this->exists(array($uniqueness_where_params))) {
2613
+				EE_Error::add_error(
2614
+					sprintf(
2615
+						__(
2616
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2617
+							"event_espresso"
2618
+						),
2619
+						$action,
2620
+						$this->_get_class_name(),
2621
+						$index_name,
2622
+						implode(",", $index->field_names()),
2623
+						http_build_query($uniqueness_where_params)
2624
+					),
2625
+					__FILE__,
2626
+					__FUNCTION__,
2627
+					__LINE__
2628
+				);
2629
+				return false;
2630
+			}
2631
+		}
2632
+		return true;
2633
+	}
2634
+
2635
+
2636
+
2637
+	/**
2638
+	 * Checks the database for an item that conflicts (ie, if this item were
2639
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2640
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2641
+	 * can be either an EE_Base_Class or an array of fields n values
2642
+	 *
2643
+	 * @param EE_Base_Class|array $obj_or_fields_array
2644
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2645
+	 *                                                 when looking for conflicts
2646
+	 *                                                 (ie, if false, we ignore the model object's primary key
2647
+	 *                                                 when finding "conflicts". If true, it's also considered).
2648
+	 *                                                 Only works for INT primary key,
2649
+	 *                                                 STRING primary keys cannot be ignored
2650
+	 * @throws EE_Error
2651
+	 * @return EE_Base_Class|array
2652
+	 */
2653
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2654
+	{
2655
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2656
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2657
+		} elseif (is_array($obj_or_fields_array)) {
2658
+			$fields_n_values = $obj_or_fields_array;
2659
+		} else {
2660
+			throw new EE_Error(
2661
+				sprintf(
2662
+					__(
2663
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2664
+						"event_espresso"
2665
+					),
2666
+					get_class($this),
2667
+					$obj_or_fields_array
2668
+				)
2669
+			);
2670
+		}
2671
+		$query_params = array();
2672
+		if ($this->has_primary_key_field()
2673
+			&& ($include_primary_key
2674
+				|| $this->get_primary_key_field()
2675
+				   instanceof
2676
+				   EE_Primary_Key_String_Field)
2677
+			&& isset($fields_n_values[$this->primary_key_name()])
2678
+		) {
2679
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2680
+		}
2681
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2682
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2683
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2684
+		}
2685
+		//if there is nothing to base this search on, then we shouldn't find anything
2686
+		if (empty($query_params)) {
2687
+			return array();
2688
+		} else {
2689
+			return $this->get_one($query_params);
2690
+		}
2691
+	}
2692
+
2693
+
2694
+
2695
+	/**
2696
+	 * Like count, but is optimized and returns a boolean instead of an int
2697
+	 *
2698
+	 * @param array $query_params
2699
+	 * @return boolean
2700
+	 * @throws \EE_Error
2701
+	 */
2702
+	public function exists($query_params)
2703
+	{
2704
+		$query_params['limit'] = 1;
2705
+		return $this->count($query_params) > 0;
2706
+	}
2707
+
2708
+
2709
+
2710
+	/**
2711
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2712
+	 *
2713
+	 * @param int|string $id
2714
+	 * @return boolean
2715
+	 * @throws \EE_Error
2716
+	 */
2717
+	public function exists_by_ID($id)
2718
+	{
2719
+		return $this->exists(array('default_where_conditions' => 'none', array($this->primary_key_name() => $id)));
2720
+	}
2721
+
2722
+
2723
+
2724
+	/**
2725
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2726
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2727
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2728
+	 * on the main table)
2729
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2730
+	 * cases where we want to call it directly rather than via insert().
2731
+	 *
2732
+	 * @access   protected
2733
+	 * @param EE_Table_Base $table
2734
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2735
+	 *                                       float
2736
+	 * @param int           $new_id          for now we assume only int keys
2737
+	 * @throws EE_Error
2738
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2739
+	 * @return int ID of new row inserted, or FALSE on failure
2740
+	 */
2741
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2742
+	{
2743
+		global $wpdb;
2744
+		$insertion_col_n_values = array();
2745
+		$format_for_insertion = array();
2746
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2747
+		foreach ($fields_on_table as $field_name => $field_obj) {
2748
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2749
+			if ($field_obj->is_auto_increment()) {
2750
+				continue;
2751
+			}
2752
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2753
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2754
+			if ($prepared_value !== null) {
2755
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2756
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2757
+			}
2758
+		}
2759
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2760
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2761
+			//so add the fk to the main table as a column
2762
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2763
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2764
+		}
2765
+		//insert the new entry
2766
+		$result = $this->_do_wpdb_query('insert',
2767
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2768
+		if ($result === false) {
2769
+			return false;
2770
+		}
2771
+		//ok, now what do we return for the ID of the newly-inserted thing?
2772
+		if ($this->has_primary_key_field()) {
2773
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2774
+				return $wpdb->insert_id;
2775
+			} else {
2776
+				//it's not an auto-increment primary key, so
2777
+				//it must have been supplied
2778
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2779
+			}
2780
+		} else {
2781
+			//we can't return a  primary key because there is none. instead return
2782
+			//a unique string indicating this model
2783
+			return $this->get_index_primary_key_string($fields_n_values);
2784
+		}
2785
+	}
2786
+
2787
+
2788
+
2789
+	/**
2790
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2791
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2792
+	 * and there is no default, we pass it along. WPDB will take care of it)
2793
+	 *
2794
+	 * @param EE_Model_Field_Base $field_obj
2795
+	 * @param array               $fields_n_values
2796
+	 * @return mixed string|int|float depending on what the table column will be expecting
2797
+	 * @throws \EE_Error
2798
+	 */
2799
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2800
+	{
2801
+		//if this field doesn't allow nullable, don't allow it
2802
+		if ( ! $field_obj->is_nullable()
2803
+			 && (
2804
+				 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2805
+		) {
2806
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2807
+		}
2808
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2809
+			: null;
2810
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2811
+	}
2812
+
2813
+
2814
+
2815
+	/**
2816
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2817
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2818
+	 * the field's prepare_for_set() method.
2819
+	 *
2820
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2821
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2822
+	 *                                   top of file)
2823
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2824
+	 *                                   $value is a custom selection
2825
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2826
+	 */
2827
+	private function _prepare_value_for_use_in_db($value, $field)
2828
+	{
2829
+		if ($field && $field instanceof EE_Model_Field_Base) {
2830
+			switch ($this->_values_already_prepared_by_model_object) {
2831
+				/** @noinspection PhpMissingBreakStatementInspection */
2832
+				case self::not_prepared_by_model_object:
2833
+					$value = $field->prepare_for_set($value);
2834
+				//purposefully left out "return"
2835
+				case self::prepared_by_model_object:
2836
+					$value = $field->prepare_for_use_in_db($value);
2837
+				case self::prepared_for_use_in_db:
2838
+					//leave the value alone
2839
+			}
2840
+			return $value;
2841
+		} else {
2842
+			return $value;
2843
+		}
2844
+	}
2845
+
2846
+
2847
+
2848
+	/**
2849
+	 * Returns the main table on this model
2850
+	 *
2851
+	 * @return EE_Primary_Table
2852
+	 * @throws EE_Error
2853
+	 */
2854
+	protected function _get_main_table()
2855
+	{
2856
+		foreach ($this->_tables as $table) {
2857
+			if ($table instanceof EE_Primary_Table) {
2858
+				return $table;
2859
+			}
2860
+		}
2861
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2862
+			'event_espresso'), get_class($this)));
2863
+	}
2864
+
2865
+
2866
+
2867
+	/**
2868
+	 * table
2869
+	 * returns EE_Primary_Table table name
2870
+	 *
2871
+	 * @return string
2872
+	 * @throws \EE_Error
2873
+	 */
2874
+	public function table()
2875
+	{
2876
+		return $this->_get_main_table()->get_table_name();
2877
+	}
2878
+
2879
+
2880
+
2881
+	/**
2882
+	 * table
2883
+	 * returns first EE_Secondary_Table table name
2884
+	 *
2885
+	 * @return string
2886
+	 */
2887
+	public function second_table()
2888
+	{
2889
+		// grab second table from tables array
2890
+		$second_table = end($this->_tables);
2891
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
2892
+	}
2893
+
2894
+
2895
+
2896
+	/**
2897
+	 * get_table_obj_by_alias
2898
+	 * returns table name given it's alias
2899
+	 *
2900
+	 * @param string $table_alias
2901
+	 * @return EE_Primary_Table | EE_Secondary_Table
2902
+	 */
2903
+	public function get_table_obj_by_alias($table_alias = '')
2904
+	{
2905
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
2906
+	}
2907
+
2908
+
2909
+
2910
+	/**
2911
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
2912
+	 *
2913
+	 * @return EE_Secondary_Table[]
2914
+	 */
2915
+	protected function _get_other_tables()
2916
+	{
2917
+		$other_tables = array();
2918
+		foreach ($this->_tables as $table_alias => $table) {
2919
+			if ($table instanceof EE_Secondary_Table) {
2920
+				$other_tables[$table_alias] = $table;
2921
+			}
2922
+		}
2923
+		return $other_tables;
2924
+	}
2925
+
2926
+
2927
+
2928
+	/**
2929
+	 * Finds all the fields that correspond to the given table
2930
+	 *
2931
+	 * @param string $table_alias , array key in EEM_Base::_tables
2932
+	 * @return EE_Model_Field_Base[]
2933
+	 */
2934
+	public function _get_fields_for_table($table_alias)
2935
+	{
2936
+		return $this->_fields[$table_alias];
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Recurses through all the where parameters, and finds all the related models we'll need
2943
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
2944
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
2945
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
2946
+	 * related Registration, Transaction, and Payment models.
2947
+	 *
2948
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
2949
+	 * @return EE_Model_Query_Info_Carrier
2950
+	 * @throws \EE_Error
2951
+	 */
2952
+	public function _extract_related_models_from_query($query_params)
2953
+	{
2954
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
2955
+		if (array_key_exists(0, $query_params)) {
2956
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
2957
+		}
2958
+		if (array_key_exists('group_by', $query_params)) {
2959
+			if (is_array($query_params['group_by'])) {
2960
+				$this->_extract_related_models_from_sub_params_array_values(
2961
+					$query_params['group_by'],
2962
+					$query_info_carrier,
2963
+					'group_by'
2964
+				);
2965
+			} elseif ( ! empty ($query_params['group_by'])) {
2966
+				$this->_extract_related_model_info_from_query_param(
2967
+					$query_params['group_by'],
2968
+					$query_info_carrier,
2969
+					'group_by'
2970
+				);
2971
+			}
2972
+		}
2973
+		if (array_key_exists('having', $query_params)) {
2974
+			$this->_extract_related_models_from_sub_params_array_keys(
2975
+				$query_params[0],
2976
+				$query_info_carrier,
2977
+				'having'
2978
+			);
2979
+		}
2980
+		if (array_key_exists('order_by', $query_params)) {
2981
+			if (is_array($query_params['order_by'])) {
2982
+				$this->_extract_related_models_from_sub_params_array_keys(
2983
+					$query_params['order_by'],
2984
+					$query_info_carrier,
2985
+					'order_by'
2986
+				);
2987
+			} elseif ( ! empty($query_params['order_by'])) {
2988
+				$this->_extract_related_model_info_from_query_param(
2989
+					$query_params['order_by'],
2990
+					$query_info_carrier,
2991
+					'order_by'
2992
+				);
2993
+			}
2994
+		}
2995
+		if (array_key_exists('force_join', $query_params)) {
2996
+			$this->_extract_related_models_from_sub_params_array_values(
2997
+				$query_params['force_join'],
2998
+				$query_info_carrier,
2999
+				'force_join'
3000
+			);
3001
+		}
3002
+		return $query_info_carrier;
3003
+	}
3004
+
3005
+
3006
+
3007
+	/**
3008
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3009
+	 *
3010
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3011
+	 *                                                      $query_params['having']
3012
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3013
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3014
+	 * @throws EE_Error
3015
+	 * @return \EE_Model_Query_Info_Carrier
3016
+	 */
3017
+	private function _extract_related_models_from_sub_params_array_keys(
3018
+		$sub_query_params,
3019
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3020
+		$query_param_type
3021
+	) {
3022
+		if ( ! empty($sub_query_params)) {
3023
+			$sub_query_params = (array)$sub_query_params;
3024
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3025
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3026
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3027
+					$query_param_type);
3028
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3029
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3030
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3031
+				//of array('Registration.TXN_ID'=>23)
3032
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3033
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3034
+					if ( ! is_array($possibly_array_of_params)) {
3035
+						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'))",
3036
+							"event_espresso"),
3037
+							$param, $possibly_array_of_params));
3038
+					} else {
3039
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3040
+							$model_query_info_carrier, $query_param_type);
3041
+					}
3042
+				} elseif ($query_param_type === 0 //ie WHERE
3043
+						  && is_array($possibly_array_of_params)
3044
+						  && isset($possibly_array_of_params[2])
3045
+						  && $possibly_array_of_params[2] == true
3046
+				) {
3047
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3048
+					//indicating that $possible_array_of_params[1] is actually a field name,
3049
+					//from which we should extract query parameters!
3050
+					if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3051
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3052
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3053
+					}
3054
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3055
+						$model_query_info_carrier, $query_param_type);
3056
+				}
3057
+			}
3058
+		}
3059
+		return $model_query_info_carrier;
3060
+	}
3061
+
3062
+
3063
+
3064
+	/**
3065
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3066
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3067
+	 *
3068
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3069
+	 *                                                      $query_params['having']
3070
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3071
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3072
+	 * @throws EE_Error
3073
+	 * @return \EE_Model_Query_Info_Carrier
3074
+	 */
3075
+	private function _extract_related_models_from_sub_params_array_values(
3076
+		$sub_query_params,
3077
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3078
+		$query_param_type
3079
+	) {
3080
+		if ( ! empty($sub_query_params)) {
3081
+			if ( ! is_array($sub_query_params)) {
3082
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3083
+					$sub_query_params));
3084
+			}
3085
+			foreach ($sub_query_params as $param) {
3086
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3087
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3088
+					$query_param_type);
3089
+			}
3090
+		}
3091
+		return $model_query_info_carrier;
3092
+	}
3093
+
3094
+
3095
+
3096
+	/**
3097
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3098
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3099
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3100
+	 * but use them in a different order. Eg, we need to know what models we are querying
3101
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3102
+	 * other models before we can finalize the where clause SQL.
3103
+	 *
3104
+	 * @param array $query_params
3105
+	 * @throws EE_Error
3106
+	 * @return EE_Model_Query_Info_Carrier
3107
+	 */
3108
+	public function _create_model_query_info_carrier($query_params)
3109
+	{
3110
+		if ( ! is_array($query_params)) {
3111
+			EE_Error::doing_it_wrong(
3112
+				'EEM_Base::_create_model_query_info_carrier',
3113
+				sprintf(
3114
+					__(
3115
+						'$query_params should be an array, you passed a variable of type %s',
3116
+						'event_espresso'
3117
+					),
3118
+					gettype($query_params)
3119
+				),
3120
+				'4.6.0'
3121
+			);
3122
+			$query_params = array();
3123
+		}
3124
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3125
+		//first check if we should alter the query to account for caps or not
3126
+		//because the caps might require us to do extra joins
3127
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3128
+			$query_params[0] = $where_query_params = array_replace_recursive(
3129
+				$where_query_params,
3130
+				$this->caps_where_conditions(
3131
+					$query_params['caps']
3132
+				)
3133
+			);
3134
+		}
3135
+		$query_object = $this->_extract_related_models_from_query($query_params);
3136
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3137
+		foreach ($where_query_params as $key => $value) {
3138
+			if (is_int($key)) {
3139
+				throw new EE_Error(
3140
+					sprintf(
3141
+						__(
3142
+							"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.",
3143
+							"event_espresso"
3144
+						),
3145
+						$key,
3146
+						var_export($value, true),
3147
+						var_export($query_params, true),
3148
+						get_class($this)
3149
+					)
3150
+				);
3151
+			}
3152
+		}
3153
+		if (
3154
+			array_key_exists('default_where_conditions', $query_params)
3155
+			&& ! empty($query_params['default_where_conditions'])
3156
+		) {
3157
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3158
+		} else {
3159
+			$use_default_where_conditions = 'all';
3160
+		}
3161
+		$where_query_params = array_merge(
3162
+			$this->_get_default_where_conditions_for_models_in_query(
3163
+				$query_object,
3164
+				$use_default_where_conditions,
3165
+				$where_query_params
3166
+			),
3167
+			$where_query_params
3168
+		);
3169
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3170
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3171
+		// So we need to setup a subquery and use that for the main join.
3172
+		// Note for now this only works on the primary table for the model.
3173
+		// So for instance, you could set the limit array like this:
3174
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3175
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3176
+			$query_object->set_main_model_join_sql(
3177
+				$this->_construct_limit_join_select(
3178
+					$query_params['on_join_limit'][0],
3179
+					$query_params['on_join_limit'][1]
3180
+				)
3181
+			);
3182
+		}
3183
+		//set limit
3184
+		if (array_key_exists('limit', $query_params)) {
3185
+			if (is_array($query_params['limit'])) {
3186
+				if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3187
+					$e = sprintf(
3188
+						__(
3189
+							"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)",
3190
+							"event_espresso"
3191
+						),
3192
+						http_build_query($query_params['limit'])
3193
+					);
3194
+					throw new EE_Error($e . "|" . $e);
3195
+				}
3196
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3197
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3198
+			} elseif ( ! empty ($query_params['limit'])) {
3199
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3200
+			}
3201
+		}
3202
+		//set order by
3203
+		if (array_key_exists('order_by', $query_params)) {
3204
+			if (is_array($query_params['order_by'])) {
3205
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3206
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3207
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3208
+				if (array_key_exists('order', $query_params)) {
3209
+					throw new EE_Error(
3210
+						sprintf(
3211
+							__(
3212
+								"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 ",
3213
+								"event_espresso"
3214
+							),
3215
+							get_class($this),
3216
+							implode(", ", array_keys($query_params['order_by'])),
3217
+							implode(", ", $query_params['order_by']),
3218
+							$query_params['order']
3219
+						)
3220
+					);
3221
+				}
3222
+				$this->_extract_related_models_from_sub_params_array_keys(
3223
+					$query_params['order_by'],
3224
+					$query_object,
3225
+					'order_by'
3226
+				);
3227
+				//assume it's an array of fields to order by
3228
+				$order_array = array();
3229
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3230
+					$order = $this->_extract_order($order);
3231
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3232
+				}
3233
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3234
+			} elseif ( ! empty ($query_params['order_by'])) {
3235
+				$this->_extract_related_model_info_from_query_param(
3236
+					$query_params['order_by'],
3237
+					$query_object,
3238
+					'order',
3239
+					$query_params['order_by']
3240
+				);
3241
+				$order = isset($query_params['order'])
3242
+					? $this->_extract_order($query_params['order'])
3243
+					: 'DESC';
3244
+				$query_object->set_order_by_sql(
3245
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3246
+				);
3247
+			}
3248
+		}
3249
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3250
+		if ( ! array_key_exists('order_by', $query_params)
3251
+			 && array_key_exists('order', $query_params)
3252
+			 && ! empty($query_params['order'])
3253
+		) {
3254
+			$pk_field = $this->get_primary_key_field();
3255
+			$order = $this->_extract_order($query_params['order']);
3256
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3257
+		}
3258
+		//set group by
3259
+		if (array_key_exists('group_by', $query_params)) {
3260
+			if (is_array($query_params['group_by'])) {
3261
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3262
+				$group_by_array = array();
3263
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3264
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3265
+				}
3266
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3267
+			} elseif ( ! empty ($query_params['group_by'])) {
3268
+				$query_object->set_group_by_sql(
3269
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3270
+				);
3271
+			}
3272
+		}
3273
+		//set having
3274
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3275
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3276
+		}
3277
+		//now, just verify they didn't pass anything wack
3278
+		foreach ($query_params as $query_key => $query_value) {
3279
+			if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3280
+				throw new EE_Error(
3281
+					sprintf(
3282
+						__(
3283
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3284
+							'event_espresso'
3285
+						),
3286
+						$query_key,
3287
+						get_class($this),
3288
+						//						print_r( $this->_allowed_query_params, TRUE )
3289
+						implode(',', $this->_allowed_query_params)
3290
+					)
3291
+				);
3292
+			}
3293
+		}
3294
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3295
+		if (empty($main_model_join_sql)) {
3296
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3297
+		}
3298
+		return $query_object;
3299
+	}
3300
+
3301
+
3302
+
3303
+	/**
3304
+	 * Gets the where conditions that should be imposed on the query based on the
3305
+	 * context (eg reading frontend, backend, edit or delete).
3306
+	 *
3307
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3308
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3309
+	 * @throws \EE_Error
3310
+	 */
3311
+	public function caps_where_conditions($context = self::caps_read)
3312
+	{
3313
+		EEM_Base::verify_is_valid_cap_context($context);
3314
+		$cap_where_conditions = array();
3315
+		$cap_restrictions = $this->caps_missing($context);
3316
+		/**
3317
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3318
+		 */
3319
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3320
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3321
+				$restriction_if_no_cap->get_default_where_conditions());
3322
+		}
3323
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3324
+			$cap_restrictions);
3325
+	}
3326
+
3327
+
3328
+
3329
+	/**
3330
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3331
+	 * otherwise throws an exception
3332
+	 *
3333
+	 * @param string $should_be_order_string
3334
+	 * @return string either ASC, asc, DESC or desc
3335
+	 * @throws EE_Error
3336
+	 */
3337
+	private function _extract_order($should_be_order_string)
3338
+	{
3339
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3340
+			return $should_be_order_string;
3341
+		} else {
3342
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3343
+				"event_espresso"), get_class($this), $should_be_order_string));
3344
+		}
3345
+	}
3346
+
3347
+
3348
+
3349
+	/**
3350
+	 * Looks at all the models which are included in this query, and asks each
3351
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3352
+	 * so they can be merged
3353
+	 *
3354
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3355
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3356
+	 *                                                                  'none' means NO default where conditions will
3357
+	 *                                                                  be used AT ALL during this query.
3358
+	 *                                                                  'other_models_only' means default where
3359
+	 *                                                                  conditions from other models will be used, but
3360
+	 *                                                                  not for this primary model. 'all', the default,
3361
+	 *                                                                  means default where conditions will apply as
3362
+	 *                                                                  normal
3363
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3364
+	 * @throws EE_Error
3365
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3366
+	 */
3367
+	private function _get_default_where_conditions_for_models_in_query(
3368
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3369
+		$use_default_where_conditions = 'all',
3370
+		$where_query_params = array()
3371
+	) {
3372
+		$allowed_used_default_where_conditions_values = array(
3373
+			'all',
3374
+			'this_model_only',
3375
+			'other_models_only',
3376
+			'minimum',
3377
+			'none',
3378
+		);
3379
+		if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3380
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3381
+				"event_espresso"), $use_default_where_conditions,
3382
+				implode(", ", $allowed_used_default_where_conditions_values)));
3383
+		}
3384
+		$universal_query_params = array();
3385
+		if ($use_default_where_conditions === 'all' || $use_default_where_conditions === 'this_model_only') {
3386
+			$universal_query_params = $this->_get_default_where_conditions();
3387
+		} else if ($use_default_where_conditions === 'minimum') {
3388
+			$universal_query_params = $this->_get_minimum_where_conditions();
3389
+		}
3390
+		if (in_array($use_default_where_conditions, array('all', 'other_models_only'))) {
3391
+			foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3392
+				$related_model = $this->get_related_model_obj($model_name);
3393
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3394
+				$overrides = $this->_override_defaults_or_make_null_friendly(
3395
+					$related_model_universal_where_params,
3396
+					$where_query_params,
3397
+					$related_model,
3398
+					$model_relation_path
3399
+				);
3400
+				$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3401
+					$universal_query_params,
3402
+					$overrides
3403
+				);
3404
+			}
3405
+		}
3406
+		return $universal_query_params;
3407
+	}
3408
+
3409
+
3410
+
3411
+	/**
3412
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3413
+	 * then we also add a special where condition which allows for that model's primary key
3414
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3415
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3416
+	 *
3417
+	 * @param array    $default_where_conditions
3418
+	 * @param array    $provided_where_conditions
3419
+	 * @param EEM_Base $model
3420
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3421
+	 * @return array like EEM_Base::get_all's $query_params[0]
3422
+	 * @throws \EE_Error
3423
+	 */
3424
+	private function _override_defaults_or_make_null_friendly(
3425
+		$default_where_conditions,
3426
+		$provided_where_conditions,
3427
+		$model,
3428
+		$model_relation_path
3429
+	) {
3430
+		$null_friendly_where_conditions = array();
3431
+		$none_overridden = true;
3432
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3433
+		foreach ($default_where_conditions as $key => $val) {
3434
+			if (isset($provided_where_conditions[$key])) {
3435
+				$none_overridden = false;
3436
+			} else {
3437
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3438
+			}
3439
+		}
3440
+		if ($none_overridden && $default_where_conditions) {
3441
+			if ($model->has_primary_key_field()) {
3442
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3443
+																				. "."
3444
+																				. $model->primary_key_name()] = array('IS NULL');
3445
+			}/*else{
3446 3446
 				//@todo NO PK, use other defaults
3447 3447
 			}*/
3448
-        }
3449
-        return $null_friendly_where_conditions;
3450
-    }
3451
-
3452
-
3453
-
3454
-    /**
3455
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3456
-     * default where conditions on all get_all, update, and delete queries done by this model.
3457
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3459
-     *
3460
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
-     */
3463
-    private function _get_default_where_conditions($model_relation_path = null)
3464
-    {
3465
-        if ($this->_ignore_where_strategy) {
3466
-            return array();
3467
-        }
3468
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
-    }
3470
-
3471
-
3472
-
3473
-    /**
3474
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3478
-     * Similar to _get_default_where_conditions
3479
-     *
3480
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
-     */
3483
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3484
-    {
3485
-        if ($this->_ignore_where_strategy) {
3486
-            return array();
3487
-        }
3488
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
-    }
3490
-
3491
-
3492
-
3493
-    /**
3494
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
-     *
3497
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3498
-     * @return string
3499
-     * @throws \EE_Error
3500
-     */
3501
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
-    {
3503
-        $selects = $this->_get_columns_to_select_for_this_model();
3504
-        foreach (
3505
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3506
-            $name_of_other_model_included
3507
-        ) {
3508
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
-            foreach ($other_model_selects as $key => $value) {
3511
-                $selects[] = $value;
3512
-            }
3513
-        }
3514
-        return implode(", ", $selects);
3515
-    }
3516
-
3517
-
3518
-
3519
-    /**
3520
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
-     * So that's going to be the columns for all the fields on the model
3522
-     *
3523
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
-     */
3526
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
-    {
3528
-        $fields = $this->field_settings();
3529
-        $selects = array();
3530
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
-            $this->get_this_model_name());
3532
-        foreach ($fields as $field_obj) {
3533
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3534
-                         . $field_obj->get_table_alias()
3535
-                         . "."
3536
-                         . $field_obj->get_table_column()
3537
-                         . " AS '"
3538
-                         . $table_alias_with_model_relation_chain_prefix
3539
-                         . $field_obj->get_table_alias()
3540
-                         . "."
3541
-                         . $field_obj->get_table_column()
3542
-                         . "'";
3543
-        }
3544
-        //make sure we are also getting the PKs of each table
3545
-        $tables = $this->get_tables();
3546
-        if (count($tables) > 1) {
3547
-            foreach ($tables as $table_obj) {
3548
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
-                                       . $table_obj->get_fully_qualified_pk_column();
3550
-                if ( ! in_array($qualified_pk_column, $selects)) {
3551
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
-                }
3553
-            }
3554
-        }
3555
-        return $selects;
3556
-    }
3557
-
3558
-
3559
-
3560
-    /**
3561
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
-     * SQL for joining, and the data types
3565
-     *
3566
-     * @param null|string                 $original_query_param
3567
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3572
-     *                                                          or 'Registration's
3573
-     * @param string                      $original_query_param what it originally was (eg
3574
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
-     *                                                          matches $query_param
3576
-     * @throws EE_Error
3577
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
-     */
3579
-    private function _extract_related_model_info_from_query_param(
3580
-        $query_param,
3581
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
-        $query_param_type,
3583
-        $original_query_param = null
3584
-    ) {
3585
-        if ($original_query_param === null) {
3586
-            $original_query_param = $query_param;
3587
-        }
3588
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
-        //check to see if we have a field on this model
3593
-        $this_model_fields = $this->field_settings(true);
3594
-        if (array_key_exists($query_param, $this_model_fields)) {
3595
-            if ($allow_fields) {
3596
-                return;
3597
-            } else {
3598
-                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",
3599
-                    "event_espresso"),
3600
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3601
-            }
3602
-        } //check if this is a special logic query param
3603
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
-            if ($allow_logic_query_params) {
3605
-                return;
3606
-            } else {
3607
-                throw new EE_Error(
3608
-                    sprintf(
3609
-                        __('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',
3610
-                            'event_espresso'),
3611
-                        implode('", "', $this->_logic_query_param_keys),
3612
-                        $query_param,
3613
-                        get_class($this),
3614
-                        '<br />',
3615
-                        "\t"
3616
-                        . ' $passed_in_query_info = <pre>'
3617
-                        . print_r($passed_in_query_info, true)
3618
-                        . '</pre>'
3619
-                        . "\n\t"
3620
-                        . ' $query_param_type = '
3621
-                        . $query_param_type
3622
-                        . "\n\t"
3623
-                        . ' $original_query_param = '
3624
-                        . $original_query_param
3625
-                    )
3626
-                );
3627
-            }
3628
-        } //check if it's a custom selection
3629
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
-            return;
3631
-        }
3632
-        //check if has a model name at the beginning
3633
-        //and
3634
-        //check if it's a field on a related model
3635
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
-                if ($query_param === '') {
3640
-                    //nothing left to $query_param
3641
-                    //we should actually end in a field name, not a model like this!
3642
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
-                        "event_espresso"),
3644
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
-                } else {
3646
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3649
-                    return;
3650
-                }
3651
-            } elseif ($query_param === $valid_related_model_name) {
3652
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
-                return;
3654
-            }
3655
-        }
3656
-        //ok so $query_param didn't start with a model name
3657
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3658
-        //it's wack, that's what it is
3659
-        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",
3660
-            "event_espresso"),
3661
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3662
-    }
3663
-
3664
-
3665
-
3666
-    /**
3667
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
-     * and store it on $passed_in_query_info
3669
-     *
3670
-     * @param string                      $model_name
3671
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3673
-     *                                                          model and $model_name. Eg, if we are querying Event,
3674
-     *                                                          and are adding a join to 'Payment' with the original
3675
-     *                                                          query param key
3676
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3678
-     *                                                          Payment wants to add default query params so that it
3679
-     *                                                          will know what models to prepend onto its default query
3680
-     *                                                          params or in case it wants to rename tables (in case
3681
-     *                                                          there are multiple joins to the same table)
3682
-     * @return void
3683
-     * @throws \EE_Error
3684
-     */
3685
-    private function _add_join_to_model(
3686
-        $model_name,
3687
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
-        $original_query_param
3689
-    ) {
3690
-        $relation_obj = $this->related_settings_for($model_name);
3691
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
-        //check if the relation is HABTM, because then we're essentially doing two joins
3693
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3695
-            $join_model_obj = $relation_obj->get_join_model();
3696
-            //replace the model specified with the join model for this relation chain, whi
3697
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3699
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3700
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
-            $passed_in_query_info->merge($new_query_info);
3703
-        }
3704
-        //now just join to the other table pointed to by the relation object, and add its data types
3705
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3706
-            array($model_relation_chain => $model_name),
3707
-            $relation_obj->get_join_statement($model_relation_chain));
3708
-        $passed_in_query_info->merge($new_query_info);
3709
-    }
3710
-
3711
-
3712
-
3713
-    /**
3714
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
-     *
3716
-     * @param array $where_params like EEM_Base::get_all
3717
-     * @return string of SQL
3718
-     * @throws \EE_Error
3719
-     */
3720
-    private function _construct_where_clause($where_params)
3721
-    {
3722
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
-        if ($SQL) {
3724
-            return " WHERE " . $SQL;
3725
-        } else {
3726
-            return '';
3727
-        }
3728
-    }
3729
-
3730
-
3731
-
3732
-    /**
3733
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
-     * and should be passed HAVING parameters, not WHERE parameters
3735
-     *
3736
-     * @param array $having_params
3737
-     * @return string
3738
-     * @throws \EE_Error
3739
-     */
3740
-    private function _construct_having_clause($having_params)
3741
-    {
3742
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
-        if ($SQL) {
3744
-            return " HAVING " . $SQL;
3745
-        } else {
3746
-            return '';
3747
-        }
3748
-    }
3749
-
3750
-
3751
-
3752
-    /**
3753
-     * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
-     * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
-     * EEM_Attendee.
3756
-     *
3757
-     * @param string $field_name
3758
-     * @param string $model_name
3759
-     * @return EE_Model_Field_Base
3760
-     * @throws EE_Error
3761
-     */
3762
-    protected function _get_field_on_model($field_name, $model_name)
3763
-    {
3764
-        $model_class = 'EEM_' . $model_name;
3765
-        $model_filepath = $model_class . ".model.php";
3766
-        if (is_readable($model_filepath)) {
3767
-            require_once($model_filepath);
3768
-            $model_instance = call_user_func($model_name . "::instance");
3769
-            /* @var $model_instance EEM_Base */
3770
-            return $model_instance->field_settings_for($field_name);
3771
-        } else {
3772
-            throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
-                'event_espresso'), $model_name, $model_class, $model_filepath));
3774
-        }
3775
-    }
3776
-
3777
-
3778
-
3779
-    /**
3780
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
-     * Event_Meta.meta_value = 'foo'))"
3782
-     *
3783
-     * @param array  $where_params see EEM_Base::get_all for documentation
3784
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
-     * @throws EE_Error
3786
-     * @return string of SQL
3787
-     */
3788
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
-    {
3790
-        $where_clauses = array();
3791
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
-                switch ($query_param) {
3795
-                    case 'not':
3796
-                    case 'NOT':
3797
-                        $where_clauses[] = "! ("
3798
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
-                                $glue)
3800
-                                           . ")";
3801
-                        break;
3802
-                    case 'and':
3803
-                    case 'AND':
3804
-                        $where_clauses[] = " ("
3805
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
-                                ' AND ')
3807
-                                           . ")";
3808
-                        break;
3809
-                    case 'or':
3810
-                    case 'OR':
3811
-                        $where_clauses[] = " ("
3812
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
-                                ' OR ')
3814
-                                           . ")";
3815
-                        break;
3816
-                }
3817
-            } else {
3818
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3819
-                //if it's not a normal field, maybe it's a custom selection?
3820
-                if ( ! $field_obj) {
3821
-                    if (isset($this->_custom_selections[$query_param][1])) {
3822
-                        $field_obj = $this->_custom_selections[$query_param][1];
3823
-                    } else {
3824
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
-                            "event_espresso"), $query_param));
3826
-                    }
3827
-                }
3828
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
-            }
3831
-        }
3832
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3833
-    }
3834
-
3835
-
3836
-
3837
-    /**
3838
-     * Takes the input parameter and extract the table name (alias) and column name
3839
-     *
3840
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
-     * @throws EE_Error
3842
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
-     */
3844
-    private function _deduce_column_name_from_query_param($query_param)
3845
-    {
3846
-        $field = $this->_deduce_field_from_query_param($query_param);
3847
-        if ($field) {
3848
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
-                $query_param);
3850
-            return $table_alias_prefix . $field->get_qualified_column();
3851
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
-            //maybe it's custom selection item?
3853
-            //if so, just use it as the "column name"
3854
-            return $query_param;
3855
-        } else {
3856
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
-        }
3859
-    }
3860
-
3861
-
3862
-
3863
-    /**
3864
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
-     *
3869
-     * @param string $condition_query_param_key
3870
-     * @return string
3871
-     */
3872
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
-    {
3874
-        $pos_of_star = strpos($condition_query_param_key, '*');
3875
-        if ($pos_of_star === false) {
3876
-            return $condition_query_param_key;
3877
-        } else {
3878
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
-            return $condition_query_param_sans_star;
3880
-        }
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
-     *
3888
-     * @param                            mixed      array | string    $op_and_value
3889
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
-     * @throws EE_Error
3891
-     * @return string
3892
-     */
3893
-    private function _construct_op_and_value($op_and_value, $field_obj)
3894
-    {
3895
-        if (is_array($op_and_value)) {
3896
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
-            if ( ! $operator) {
3898
-                $php_array_like_string = array();
3899
-                foreach ($op_and_value as $key => $value) {
3900
-                    $php_array_like_string[] = "$key=>$value";
3901
-                }
3902
-                throw new EE_Error(
3903
-                    sprintf(
3904
-                        __(
3905
-                            "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))",
3906
-                            "event_espresso"
3907
-                        ),
3908
-                        implode(",", $php_array_like_string)
3909
-                    )
3910
-                );
3911
-            }
3912
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
-        } else {
3914
-            $operator = '=';
3915
-            $value = $op_and_value;
3916
-        }
3917
-        //check to see if the value is actually another field
3918
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
-        } elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
-            //in this case, the value should be an array, or at least a comma-separated list
3922
-            //it will need to handle a little differently
3923
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
-            //note: $cleaned_value has already been run through $wpdb->prepare()
3925
-            return $operator . SP . $cleaned_value;
3926
-        } elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
-            //the value should be an array with count of two.
3928
-            if (count($value) !== 2) {
3929
-                throw new EE_Error(
3930
-                    sprintf(
3931
-                        __(
3932
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
-                            'event_espresso'
3934
-                        ),
3935
-                        "BETWEEN"
3936
-                    )
3937
-                );
3938
-            }
3939
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
-            return $operator . SP . $cleaned_value;
3941
-        } elseif (in_array($operator, $this->_null_style_operators)) {
3942
-            if ($value !== null) {
3943
-                throw new EE_Error(
3944
-                    sprintf(
3945
-                        __(
3946
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
-                            "event_espresso"
3948
-                        ),
3949
-                        $value,
3950
-                        $operator
3951
-                    )
3952
-                );
3953
-            }
3954
-            return $operator;
3955
-        } elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
-            //remove other junk. So just treat it as a string.
3958
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
-        } elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
-            throw new EE_Error(
3963
-                sprintf(
3964
-                    __(
3965
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
-                        'event_espresso'
3967
-                    ),
3968
-                    $operator,
3969
-                    $operator
3970
-                )
3971
-            );
3972
-        } elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
-            throw new EE_Error(
3974
-                sprintf(
3975
-                    __(
3976
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
-                        'event_espresso'
3978
-                    ),
3979
-                    $operator,
3980
-                    $operator
3981
-                )
3982
-            );
3983
-        } else {
3984
-            throw new EE_Error(
3985
-                sprintf(
3986
-                    __(
3987
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
-                        "event_espresso"
3989
-                    ),
3990
-                    http_build_query($op_and_value)
3991
-                )
3992
-            );
3993
-        }
3994
-    }
3995
-
3996
-
3997
-
3998
-    /**
3999
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
-     *
4001
-     * @param array                      $values
4002
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
-     *                                              '%s'
4004
-     * @return string
4005
-     * @throws \EE_Error
4006
-     */
4007
-    public function _construct_between_value($values, $field_obj)
4008
-    {
4009
-        $cleaned_values = array();
4010
-        foreach ($values as $value) {
4011
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
-        }
4013
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
-    }
4015
-
4016
-
4017
-
4018
-    /**
4019
-     * Takes an array or a comma-separated list of $values and cleans them
4020
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4021
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
-     *
4025
-     * @param mixed                      $values    array or comma-separated string
4026
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
-     * @throws \EE_Error
4029
-     */
4030
-    public function _construct_in_value($values, $field_obj)
4031
-    {
4032
-        //check if the value is a CSV list
4033
-        if (is_string($values)) {
4034
-            //in which case, turn it into an array
4035
-            $values = explode(",", $values);
4036
-        }
4037
-        $cleaned_values = array();
4038
-        foreach ($values as $value) {
4039
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
-        }
4041
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
-        if (empty($cleaned_values)) {
4045
-            $all_fields = $this->field_settings();
4046
-            $a_field = array_shift($all_fields);
4047
-            $main_table = $this->_get_main_table();
4048
-            $cleaned_values[] = "SELECT "
4049
-                                . $a_field->get_table_column()
4050
-                                . " FROM "
4051
-                                . $main_table->get_table_name()
4052
-                                . " WHERE FALSE";
4053
-        }
4054
-        return "(" . implode(",", $cleaned_values) . ")";
4055
-    }
4056
-
4057
-
4058
-
4059
-    /**
4060
-     * @param mixed                      $value
4061
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
-     * @throws EE_Error
4063
-     * @return false|null|string
4064
-     */
4065
-    private function _wpdb_prepare_using_field($value, $field_obj)
4066
-    {
4067
-        /** @type WPDB $wpdb */
4068
-        global $wpdb;
4069
-        if ($field_obj instanceof EE_Model_Field_Base) {
4070
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4072
-        } else {//$field_obj should really just be a data type
4073
-            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
-            }
4077
-            return $wpdb->prepare($field_obj, $value);
4078
-        }
4079
-    }
4080
-
4081
-
4082
-
4083
-    /**
4084
-     * Takes the input parameter and finds the model field that it indicates.
4085
-     *
4086
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
-     * @throws EE_Error
4088
-     * @return EE_Model_Field_Base
4089
-     */
4090
-    protected function _deduce_field_from_query_param($query_param_name)
4091
-    {
4092
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
-        //which will help us find the database table and column
4094
-        $query_param_parts = explode(".", $query_param_name);
4095
-        if (empty($query_param_parts)) {
4096
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
-                'event_espresso'), $query_param_name));
4098
-        }
4099
-        $number_of_parts = count($query_param_parts);
4100
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
-        if ($number_of_parts === 1) {
4102
-            $field_name = $last_query_param_part;
4103
-            $model_obj = $this;
4104
-        } else {// $number_of_parts >= 2
4105
-            //the last part is the column name, and there are only 2parts. therefore...
4106
-            $field_name = $last_query_param_part;
4107
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
-        }
4109
-        try {
4110
-            return $model_obj->field_settings_for($field_name);
4111
-        } catch (EE_Error $e) {
4112
-            return null;
4113
-        }
4114
-    }
4115
-
4116
-
4117
-
4118
-    /**
4119
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
-     * alias and column which corresponds to it
4121
-     *
4122
-     * @param string $field_name
4123
-     * @throws EE_Error
4124
-     * @return string
4125
-     */
4126
-    public function _get_qualified_column_for_field($field_name)
4127
-    {
4128
-        $all_fields = $this->field_settings();
4129
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
-        if ($field) {
4131
-            return $field->get_qualified_column();
4132
-        } else {
4133
-            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.",
4134
-                'event_espresso'), $field_name, get_class($this)));
4135
-        }
4136
-    }
4137
-
4138
-
4139
-
4140
-    /**
4141
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4142
-     * Example usage:
4143
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4144
-     *      array(),
4145
-     *      ARRAY_A,
4146
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4147
-     *  );
4148
-     * is equivalent to
4149
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4150
-     * and
4151
-     *  EEM_Event::instance()->get_all_wpdb_results(
4152
-     *      array(
4153
-     *          array(
4154
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4155
-     *          ),
4156
-     *          ARRAY_A,
4157
-     *          implode(
4158
-     *              ', ',
4159
-     *              array_merge(
4160
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4161
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4162
-     *              )
4163
-     *          )
4164
-     *      )
4165
-     *  );
4166
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4167
-     *
4168
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4169
-     *                                            and the one whose fields you are selecting for example: when querying
4170
-     *                                            tickets model and selecting fields from the tickets model you would
4171
-     *                                            leave this parameter empty, because no models are needed to join
4172
-     *                                            between the queried model and the selected one. Likewise when
4173
-     *                                            querying the datetime model and selecting fields from the tickets
4174
-     *                                            model, it would also be left empty, because there is a direct
4175
-     *                                            relation from datetimes to tickets, so no model is needed to join
4176
-     *                                            them together. However, when querying from the event model and
4177
-     *                                            selecting fields from the ticket model, you should provide the string
4178
-     *                                            'Datetime', indicating that the event model must first join to the
4179
-     *                                            datetime model in order to find its relation to ticket model.
4180
-     *                                            Also, when querying from the venue model and selecting fields from
4181
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4182
-     *                                            indicating you need to join the venue model to the event model,
4183
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4184
-     *                                            This string is used to deduce the prefix that gets added onto the
4185
-     *                                            models' tables qualified columns
4186
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4187
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4188
-     *                                            qualified column names
4189
-     * @return array|string
4190
-     */
4191
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4192
-    {
4193
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4194
-        $qualified_columns = array();
4195
-        foreach ($this->field_settings() as $field_name => $field) {
4196
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4197
-        }
4198
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4199
-    }
4200
-
4201
-
4202
-
4203
-    /**
4204
-     * constructs the select use on special limit joins
4205
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4206
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4207
-     * (as that is typically where the limits would be set).
4208
-     *
4209
-     * @param  string       $table_alias The table the select is being built for
4210
-     * @param  mixed|string $limit       The limit for this select
4211
-     * @return string                The final select join element for the query.
4212
-     */
4213
-    public function _construct_limit_join_select($table_alias, $limit)
4214
-    {
4215
-        $SQL = '';
4216
-        foreach ($this->_tables as $table_obj) {
4217
-            if ($table_obj instanceof EE_Primary_Table) {
4218
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4219
-                    ? $table_obj->get_select_join_limit($limit)
4220
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4221
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4222
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4223
-                    ? $table_obj->get_select_join_limit_join($limit)
4224
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4225
-            }
4226
-        }
4227
-        return $SQL;
4228
-    }
4229
-
4230
-
4231
-
4232
-    /**
4233
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4234
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4235
-     *
4236
-     * @return string SQL
4237
-     * @throws \EE_Error
4238
-     */
4239
-    public function _construct_internal_join()
4240
-    {
4241
-        $SQL = $this->_get_main_table()->get_table_sql();
4242
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4243
-        return $SQL;
4244
-    }
4245
-
4246
-
4247
-
4248
-    /**
4249
-     * Constructs the SQL for joining all the tables on this model.
4250
-     * Normally $alias should be the primary table's alias, but in cases where
4251
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4252
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4253
-     * alias, this will construct SQL like:
4254
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4255
-     * With $alias being a secondary table's alias, this will construct SQL like:
4256
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4257
-     *
4258
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4259
-     * @return string
4260
-     */
4261
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4262
-    {
4263
-        $SQL = '';
4264
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4265
-        foreach ($this->_tables as $table_obj) {
4266
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4267
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4268
-                    //so we're joining to this table, meaning the table is already in
4269
-                    //the FROM statement, BUT the primary table isn't. So we want
4270
-                    //to add the inverse join sql
4271
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4272
-                } else {
4273
-                    //just add a regular JOIN to this table from the primary table
4274
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4275
-                }
4276
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4277
-        }
4278
-        return $SQL;
4279
-    }
4280
-
4281
-
4282
-
4283
-    /**
4284
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4285
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4286
-     * their data type (eg, '%s', '%d', etc)
4287
-     *
4288
-     * @return array
4289
-     */
4290
-    public function _get_data_types()
4291
-    {
4292
-        $data_types = array();
4293
-        foreach ($this->field_settings() as $field_obj) {
4294
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4295
-            /** @var $field_obj EE_Model_Field_Base */
4296
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4297
-        }
4298
-        return $data_types;
4299
-    }
4300
-
4301
-
4302
-
4303
-    /**
4304
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4305
-     *
4306
-     * @param string $model_name
4307
-     * @throws EE_Error
4308
-     * @return EEM_Base
4309
-     */
4310
-    public function get_related_model_obj($model_name)
4311
-    {
4312
-        $model_classname = "EEM_" . $model_name;
4313
-        if ( ! class_exists($model_classname)) {
4314
-            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",
4315
-                'event_espresso'), $model_name, $model_classname));
4316
-        }
4317
-        return call_user_func($model_classname . "::instance");
4318
-    }
4319
-
4320
-
4321
-
4322
-    /**
4323
-     * Returns the array of EE_ModelRelations for this model.
4324
-     *
4325
-     * @return EE_Model_Relation_Base[]
4326
-     */
4327
-    public function relation_settings()
4328
-    {
4329
-        return $this->_model_relations;
4330
-    }
4331
-
4332
-
4333
-
4334
-    /**
4335
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4336
-     * because without THOSE models, this model probably doesn't have much purpose.
4337
-     * (Eg, without an event, datetimes have little purpose.)
4338
-     *
4339
-     * @return EE_Belongs_To_Relation[]
4340
-     */
4341
-    public function belongs_to_relations()
4342
-    {
4343
-        $belongs_to_relations = array();
4344
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4345
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4346
-                $belongs_to_relations[$model_name] = $relation_obj;
4347
-            }
4348
-        }
4349
-        return $belongs_to_relations;
4350
-    }
4351
-
4352
-
4353
-
4354
-    /**
4355
-     * Returns the specified EE_Model_Relation, or throws an exception
4356
-     *
4357
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4358
-     * @throws EE_Error
4359
-     * @return EE_Model_Relation_Base
4360
-     */
4361
-    public function related_settings_for($relation_name)
4362
-    {
4363
-        $relatedModels = $this->relation_settings();
4364
-        if ( ! array_key_exists($relation_name, $relatedModels)) {
4365
-            throw new EE_Error(
4366
-                sprintf(
4367
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4368
-                        'event_espresso'),
4369
-                    $relation_name,
4370
-                    $this->_get_class_name(),
4371
-                    implode(', ', array_keys($relatedModels))
4372
-                )
4373
-            );
4374
-        }
4375
-        return $relatedModels[$relation_name];
4376
-    }
4377
-
4378
-
4379
-
4380
-    /**
4381
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4382
-     * fields
4383
-     *
4384
-     * @param string $fieldName
4385
-     * @throws EE_Error
4386
-     * @return EE_Model_Field_Base
4387
-     */
4388
-    public function field_settings_for($fieldName)
4389
-    {
4390
-        $fieldSettings = $this->field_settings(true);
4391
-        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4392
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4393
-                get_class($this)));
4394
-        }
4395
-        return $fieldSettings[$fieldName];
4396
-    }
4397
-
4398
-
4399
-
4400
-    /**
4401
-     * Checks if this field exists on this model
4402
-     *
4403
-     * @param string $fieldName a key in the model's _field_settings array
4404
-     * @return boolean
4405
-     */
4406
-    public function has_field($fieldName)
4407
-    {
4408
-        $fieldSettings = $this->field_settings(true);
4409
-        if (isset($fieldSettings[$fieldName])) {
4410
-            return true;
4411
-        } else {
4412
-            return false;
4413
-        }
4414
-    }
4415
-
4416
-
4417
-
4418
-    /**
4419
-     * Returns whether or not this model has a relation to the specified model
4420
-     *
4421
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4422
-     * @return boolean
4423
-     */
4424
-    public function has_relation($relation_name)
4425
-    {
4426
-        $relations = $this->relation_settings();
4427
-        if (isset($relations[$relation_name])) {
4428
-            return true;
4429
-        } else {
4430
-            return false;
4431
-        }
4432
-    }
4433
-
4434
-
4435
-
4436
-    /**
4437
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4438
-     * Eg, on EE_Answer that would be ANS_ID field object
4439
-     *
4440
-     * @param $field_obj
4441
-     * @return boolean
4442
-     */
4443
-    public function is_primary_key_field($field_obj)
4444
-    {
4445
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4446
-    }
4447
-
4448
-
4449
-
4450
-    /**
4451
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4452
-     * Eg, on EE_Answer that would be ANS_ID field object
4453
-     *
4454
-     * @return EE_Model_Field_Base
4455
-     * @throws EE_Error
4456
-     */
4457
-    public function get_primary_key_field()
4458
-    {
4459
-        if ($this->_primary_key_field === null) {
4460
-            foreach ($this->field_settings(true) as $field_obj) {
4461
-                if ($this->is_primary_key_field($field_obj)) {
4462
-                    $this->_primary_key_field = $field_obj;
4463
-                    break;
4464
-                }
4465
-            }
4466
-            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4467
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4468
-                    get_class($this)));
4469
-            }
4470
-        }
4471
-        return $this->_primary_key_field;
4472
-    }
4473
-
4474
-
4475
-
4476
-    /**
4477
-     * Returns whether or not not there is a primary key on this model.
4478
-     * Internally does some caching.
4479
-     *
4480
-     * @return boolean
4481
-     */
4482
-    public function has_primary_key_field()
4483
-    {
4484
-        if ($this->_has_primary_key_field === null) {
4485
-            try {
4486
-                $this->get_primary_key_field();
4487
-                $this->_has_primary_key_field = true;
4488
-            } catch (EE_Error $e) {
4489
-                $this->_has_primary_key_field = false;
4490
-            }
4491
-        }
4492
-        return $this->_has_primary_key_field;
4493
-    }
4494
-
4495
-
4496
-
4497
-    /**
4498
-     * Finds the first field of type $field_class_name.
4499
-     *
4500
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4501
-     *                                 EE_Foreign_Key_Field, etc
4502
-     * @return EE_Model_Field_Base or null if none is found
4503
-     */
4504
-    public function get_a_field_of_type($field_class_name)
4505
-    {
4506
-        foreach ($this->field_settings() as $field) {
4507
-            if ($field instanceof $field_class_name) {
4508
-                return $field;
4509
-            }
4510
-        }
4511
-        return null;
4512
-    }
4513
-
4514
-
4515
-
4516
-    /**
4517
-     * Gets a foreign key field pointing to model.
4518
-     *
4519
-     * @param string $model_name eg Event, Registration, not EEM_Event
4520
-     * @return EE_Foreign_Key_Field_Base
4521
-     * @throws EE_Error
4522
-     */
4523
-    public function get_foreign_key_to($model_name)
4524
-    {
4525
-        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4526
-            foreach ($this->field_settings() as $field) {
4527
-                if (
4528
-                    $field instanceof EE_Foreign_Key_Field_Base
4529
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4530
-                ) {
4531
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4532
-                    break;
4533
-                }
4534
-            }
4535
-            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4536
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4537
-                    'event_espresso'), $model_name, get_class($this)));
4538
-            }
4539
-        }
4540
-        return $this->_cache_foreign_key_to_fields[$model_name];
4541
-    }
4542
-
4543
-
4544
-
4545
-    /**
4546
-     * Gets the actual table for the table alias
4547
-     *
4548
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4549
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4550
-     *                            Either one works
4551
-     * @return EE_Table_Base
4552
-     */
4553
-    public function get_table_for_alias($table_alias)
4554
-    {
4555
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4556
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4557
-    }
4558
-
4559
-
4560
-
4561
-    /**
4562
-     * Returns a flat array of all field son this model, instead of organizing them
4563
-     * by table_alias as they are in the constructor.
4564
-     *
4565
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4566
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4567
-     */
4568
-    public function field_settings($include_db_only_fields = false)
4569
-    {
4570
-        if ($include_db_only_fields) {
4571
-            if ($this->_cached_fields === null) {
4572
-                $this->_cached_fields = array();
4573
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4574
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4575
-                        $this->_cached_fields[$field_name] = $field_obj;
4576
-                    }
4577
-                }
4578
-            }
4579
-            return $this->_cached_fields;
4580
-        } else {
4581
-            if ($this->_cached_fields_non_db_only === null) {
4582
-                $this->_cached_fields_non_db_only = array();
4583
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4584
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4585
-                        /** @var $field_obj EE_Model_Field_Base */
4586
-                        if ( ! $field_obj->is_db_only_field()) {
4587
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4588
-                        }
4589
-                    }
4590
-                }
4591
-            }
4592
-            return $this->_cached_fields_non_db_only;
4593
-        }
4594
-    }
4595
-
4596
-
4597
-
4598
-    /**
4599
-     *        cycle though array of attendees and create objects out of each item
4600
-     *
4601
-     * @access        private
4602
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4603
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4604
-     *                           numerically indexed)
4605
-     * @throws \EE_Error
4606
-     */
4607
-    protected function _create_objects($rows = array())
4608
-    {
4609
-        $array_of_objects = array();
4610
-        if (empty($rows)) {
4611
-            return array();
4612
-        }
4613
-        $count_if_model_has_no_primary_key = 0;
4614
-        $has_primary_key = $this->has_primary_key_field();
4615
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4616
-        foreach ((array)$rows as $row) {
4617
-            if (empty($row)) {
4618
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4619
-                return array();
4620
-            }
4621
-            //check if we've already set this object in the results array,
4622
-            //in which case there's no need to process it further (again)
4623
-            if ($has_primary_key) {
4624
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4625
-                    $row,
4626
-                    $primary_key_field->get_qualified_column(),
4627
-                    $primary_key_field->get_table_column()
4628
-                );
4629
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4630
-                    continue;
4631
-                }
4632
-            }
4633
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4634
-            if ( ! $classInstance) {
4635
-                throw new EE_Error(
4636
-                    sprintf(
4637
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4638
-                        $this->get_this_model_name(),
4639
-                        http_build_query($row)
4640
-                    )
4641
-                );
4642
-            }
4643
-            //set the timezone on the instantiated objects
4644
-            $classInstance->set_timezone($this->_timezone);
4645
-            //make sure if there is any timezone setting present that we set the timezone for the object
4646
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4647
-            $array_of_objects[$key] = $classInstance;
4648
-            //also, for all the relations of type BelongsTo, see if we can cache
4649
-            //those related models
4650
-            //(we could do this for other relations too, but if there are conditions
4651
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4652
-            //so it requires a little more thought than just caching them immediately...)
4653
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4654
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4655
-                    //check if this model's INFO is present. If so, cache it on the model
4656
-                    $other_model = $relation_obj->get_other_model();
4657
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4658
-                    //if we managed to make a model object from the results, cache it on the main model object
4659
-                    if ($other_model_obj_maybe) {
4660
-                        //set timezone on these other model objects if they are present
4661
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4662
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4663
-                    }
4664
-                }
4665
-            }
4666
-        }
4667
-        return $array_of_objects;
4668
-    }
4669
-
4670
-
4671
-
4672
-    /**
4673
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4674
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4675
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4676
-     * object (as set in the model_field!).
4677
-     *
4678
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4679
-     */
4680
-    public function create_default_object()
4681
-    {
4682
-        $this_model_fields_and_values = array();
4683
-        //setup the row using default values;
4684
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4685
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4686
-        }
4687
-        $className = $this->_get_class_name();
4688
-        $classInstance = EE_Registry::instance()
4689
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4690
-        return $classInstance;
4691
-    }
4692
-
4693
-
4694
-
4695
-    /**
4696
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4697
-     *                             or an stdClass where each property is the name of a column,
4698
-     * @return EE_Base_Class
4699
-     * @throws \EE_Error
4700
-     */
4701
-    public function instantiate_class_from_array_or_object($cols_n_values)
4702
-    {
4703
-        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4704
-            $cols_n_values = get_object_vars($cols_n_values);
4705
-        }
4706
-        $primary_key = null;
4707
-        //make sure the array only has keys that are fields/columns on this model
4708
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4709
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4710
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4711
-        }
4712
-        $className = $this->_get_class_name();
4713
-        //check we actually found results that we can use to build our model object
4714
-        //if not, return null
4715
-        if ($this->has_primary_key_field()) {
4716
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4717
-                return null;
4718
-            }
4719
-        } else if ($this->unique_indexes()) {
4720
-            $first_column = reset($this_model_fields_n_values);
4721
-            if (empty($first_column)) {
4722
-                return null;
4723
-            }
4724
-        }
4725
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4726
-        if ($primary_key) {
4727
-            $classInstance = $this->get_from_entity_map($primary_key);
4728
-            if ( ! $classInstance) {
4729
-                $classInstance = EE_Registry::instance()
4730
-                                            ->load_class($className,
4731
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4732
-                // add this new object to the entity map
4733
-                $classInstance = $this->add_to_entity_map($classInstance);
4734
-            }
4735
-        } else {
4736
-            $classInstance = EE_Registry::instance()
4737
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4738
-                                            true, false);
4739
-        }
4740
-        //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.
4741
-        $this->set_timezone($classInstance->get_timezone());
4742
-        return $classInstance;
4743
-    }
4744
-
4745
-
4746
-
4747
-    /**
4748
-     * Gets the model object from the  entity map if it exists
4749
-     *
4750
-     * @param int|string $id the ID of the model object
4751
-     * @return EE_Base_Class
4752
-     */
4753
-    public function get_from_entity_map($id)
4754
-    {
4755
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4756
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4757
-    }
4758
-
4759
-
4760
-
4761
-    /**
4762
-     * add_to_entity_map
4763
-     * Adds the object to the model's entity mappings
4764
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4765
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4766
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4767
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4768
-     *        then this method should be called immediately after the update query
4769
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4770
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4771
-     *
4772
-     * @param    EE_Base_Class $object
4773
-     * @throws EE_Error
4774
-     * @return \EE_Base_Class
4775
-     */
4776
-    public function add_to_entity_map(EE_Base_Class $object)
4777
-    {
4778
-        $className = $this->_get_class_name();
4779
-        if ( ! $object instanceof $className) {
4780
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4781
-                is_object($object) ? get_class($object) : $object, $className));
4782
-        }
4783
-        /** @var $object EE_Base_Class */
4784
-        if ( ! $object->ID()) {
4785
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4786
-                "event_espresso"), get_class($this)));
4787
-        }
4788
-        // double check it's not already there
4789
-        $classInstance = $this->get_from_entity_map($object->ID());
4790
-        if ($classInstance) {
4791
-            return $classInstance;
4792
-        } else {
4793
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4794
-            return $object;
4795
-        }
4796
-    }
4797
-
4798
-
4799
-
4800
-    /**
4801
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4802
-     * if no identifier is provided, then the entire entity map is emptied
4803
-     *
4804
-     * @param int|string $id the ID of the model object
4805
-     * @return boolean
4806
-     */
4807
-    public function clear_entity_map($id = null)
4808
-    {
4809
-        if (empty($id)) {
4810
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4811
-            return true;
4812
-        }
4813
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4814
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4815
-            return true;
4816
-        }
4817
-        return false;
4818
-    }
4819
-
4820
-
4821
-
4822
-    /**
4823
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4824
-     * Given an array where keys are column (or column alias) names and values,
4825
-     * returns an array of their corresponding field names and database values
4826
-     *
4827
-     * @param array $cols_n_values
4828
-     * @return array
4829
-     */
4830
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4831
-    {
4832
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4833
-    }
4834
-
4835
-
4836
-
4837
-    /**
4838
-     * _deduce_fields_n_values_from_cols_n_values
4839
-     * Given an array where keys are column (or column alias) names and values,
4840
-     * returns an array of their corresponding field names and database values
4841
-     *
4842
-     * @param string $cols_n_values
4843
-     * @return array
4844
-     */
4845
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4846
-    {
4847
-        $this_model_fields_n_values = array();
4848
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
4849
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4850
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4851
-            //there is a primary key on this table and its not set. Use defaults for all its columns
4852
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
4853
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4854
-                    if ( ! $field_obj->is_db_only_field()) {
4855
-                        //prepare field as if its coming from db
4856
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4857
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4858
-                    }
4859
-                }
4860
-            } else {
4861
-                //the table's rows existed. Use their values
4862
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4863
-                    if ( ! $field_obj->is_db_only_field()) {
4864
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4865
-                            $cols_n_values, $field_obj->get_qualified_column(),
4866
-                            $field_obj->get_table_column()
4867
-                        );
4868
-                    }
4869
-                }
4870
-            }
4871
-        }
4872
-        return $this_model_fields_n_values;
4873
-    }
4874
-
4875
-
4876
-
4877
-    /**
4878
-     * @param $cols_n_values
4879
-     * @param $qualified_column
4880
-     * @param $regular_column
4881
-     * @return null
4882
-     */
4883
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4884
-    {
4885
-        $value = null;
4886
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4887
-        //does the field on the model relate to this column retrieved from the db?
4888
-        //or is it a db-only field? (not relating to the model)
4889
-        if (isset($cols_n_values[$qualified_column])) {
4890
-            $value = $cols_n_values[$qualified_column];
4891
-        } elseif (isset($cols_n_values[$regular_column])) {
4892
-            $value = $cols_n_values[$regular_column];
4893
-        }
4894
-        return $value;
4895
-    }
4896
-
4897
-
4898
-
4899
-    /**
4900
-     * refresh_entity_map_from_db
4901
-     * Makes sure the model object in the entity map at $id assumes the values
4902
-     * of the database (opposite of EE_base_Class::save())
4903
-     *
4904
-     * @param int|string $id
4905
-     * @return EE_Base_Class
4906
-     * @throws \EE_Error
4907
-     */
4908
-    public function refresh_entity_map_from_db($id)
4909
-    {
4910
-        $obj_in_map = $this->get_from_entity_map($id);
4911
-        if ($obj_in_map) {
4912
-            $wpdb_results = $this->_get_all_wpdb_results(
4913
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4914
-            );
4915
-            if ($wpdb_results && is_array($wpdb_results)) {
4916
-                $one_row = reset($wpdb_results);
4917
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4918
-                    $obj_in_map->set_from_db($field_name, $db_value);
4919
-                }
4920
-                //clear the cache of related model objects
4921
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4922
-                    $obj_in_map->clear_cache($relation_name, null, true);
4923
-                }
4924
-            }
4925
-            return $obj_in_map;
4926
-        } else {
4927
-            return $this->get_one_by_ID($id);
4928
-        }
4929
-    }
4930
-
4931
-
4932
-
4933
-    /**
4934
-     * refresh_entity_map_with
4935
-     * Leaves the entry in the entity map alone, but updates it to match the provided
4936
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4937
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4938
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4939
-     *
4940
-     * @param int|string    $id
4941
-     * @param EE_Base_Class $replacing_model_obj
4942
-     * @return \EE_Base_Class
4943
-     * @throws \EE_Error
4944
-     */
4945
-    public function refresh_entity_map_with($id, $replacing_model_obj)
4946
-    {
4947
-        $obj_in_map = $this->get_from_entity_map($id);
4948
-        if ($obj_in_map) {
4949
-            if ($replacing_model_obj instanceof EE_Base_Class) {
4950
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4951
-                    $obj_in_map->set($field_name, $value);
4952
-                }
4953
-                //make the model object in the entity map's cache match the $replacing_model_obj
4954
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4955
-                    $obj_in_map->clear_cache($relation_name, null, true);
4956
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4957
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4958
-                    }
4959
-                }
4960
-            }
4961
-            return $obj_in_map;
4962
-        } else {
4963
-            $this->add_to_entity_map($replacing_model_obj);
4964
-            return $replacing_model_obj;
4965
-        }
4966
-    }
4967
-
4968
-
4969
-
4970
-    /**
4971
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4972
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4973
-     * require_once($this->_getClassName().".class.php");
4974
-     *
4975
-     * @return string
4976
-     */
4977
-    private function _get_class_name()
4978
-    {
4979
-        return "EE_" . $this->get_this_model_name();
4980
-    }
4981
-
4982
-
4983
-
4984
-    /**
4985
-     * Get the name of the items this model represents, for the quantity specified. Eg,
4986
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4987
-     * it would be 'Events'.
4988
-     *
4989
-     * @param int $quantity
4990
-     * @return string
4991
-     */
4992
-    public function item_name($quantity = 1)
4993
-    {
4994
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4995
-    }
4996
-
4997
-
4998
-
4999
-    /**
5000
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5001
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5002
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5003
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5004
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5005
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5006
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5007
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5008
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5009
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5010
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5011
-     *        return $previousReturnValue.$returnString;
5012
-     * }
5013
-     * require('EEM_Answer.model.php');
5014
-     * $answer=EEM_Answer::instance();
5015
-     * echo $answer->my_callback('monkeys',100);
5016
-     * //will output "you called my_callback! and passed args:monkeys,100"
5017
-     *
5018
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5019
-     * @param array  $args       array of original arguments passed to the function
5020
-     * @throws EE_Error
5021
-     * @return mixed whatever the plugin which calls add_filter decides
5022
-     */
5023
-    public function __call($methodName, $args)
5024
-    {
5025
-        $className = get_class($this);
5026
-        $tagName = "FHEE__{$className}__{$methodName}";
5027
-        if ( ! has_filter($tagName)) {
5028
-            throw new EE_Error(
5029
-                sprintf(
5030
-                    __('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 );',
5031
-                        'event_espresso'),
5032
-                    $methodName,
5033
-                    $className,
5034
-                    $tagName,
5035
-                    '<br />'
5036
-                )
5037
-            );
5038
-        }
5039
-        return apply_filters($tagName, null, $this, $args);
5040
-    }
5041
-
5042
-
5043
-
5044
-    /**
5045
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5046
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5047
-     *
5048
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5049
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5050
-     *                                                       the object's class name
5051
-     *                                                       or object's ID
5052
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5053
-     *                                                       exists in the database. If it does not, we add it
5054
-     * @throws EE_Error
5055
-     * @return EE_Base_Class
5056
-     */
5057
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5058
-    {
5059
-        $className = $this->_get_class_name();
5060
-        if ($base_class_obj_or_id instanceof $className) {
5061
-            $model_object = $base_class_obj_or_id;
5062
-        } else {
5063
-            $primary_key_field = $this->get_primary_key_field();
5064
-            if (
5065
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5066
-                && (
5067
-                    is_int($base_class_obj_or_id)
5068
-                    || is_string($base_class_obj_or_id)
5069
-                )
5070
-            ) {
5071
-                // assume it's an ID.
5072
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5073
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5074
-            } else if (
5075
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5076
-                && is_string($base_class_obj_or_id)
5077
-            ) {
5078
-                // assume its a string representation of the object
5079
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5080
-            } else {
5081
-                throw new EE_Error(
5082
-                    sprintf(
5083
-                        __(
5084
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5085
-                            'event_espresso'
5086
-                        ),
5087
-                        $base_class_obj_or_id,
5088
-                        $this->_get_class_name(),
5089
-                        print_r($base_class_obj_or_id, true)
5090
-                    )
5091
-                );
5092
-            }
5093
-        }
5094
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5095
-            $model_object->save();
5096
-        }
5097
-        return $model_object;
5098
-    }
5099
-
5100
-
5101
-
5102
-    /**
5103
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5104
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5105
-     * returns it ID.
5106
-     *
5107
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5108
-     * @return int|string depending on the type of this model object's ID
5109
-     * @throws EE_Error
5110
-     */
5111
-    public function ensure_is_ID($base_class_obj_or_id)
5112
-    {
5113
-        $className = $this->_get_class_name();
5114
-        if ($base_class_obj_or_id instanceof $className) {
5115
-            /** @var $base_class_obj_or_id EE_Base_Class */
5116
-            $id = $base_class_obj_or_id->ID();
5117
-        } elseif (is_int($base_class_obj_or_id)) {
5118
-            //assume it's an ID
5119
-            $id = $base_class_obj_or_id;
5120
-        } elseif (is_string($base_class_obj_or_id)) {
5121
-            //assume its a string representation of the object
5122
-            $id = $base_class_obj_or_id;
5123
-        } else {
5124
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5125
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5126
-                print_r($base_class_obj_or_id, true)));
5127
-        }
5128
-        return $id;
5129
-    }
5130
-
5131
-
5132
-
5133
-    /**
5134
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5135
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5136
-     * been sanitized and converted into the appropriate domain.
5137
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5138
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5139
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5140
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5141
-     * $EVT = EEM_Event::instance(); $old_setting =
5142
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5143
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5144
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5145
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5146
-     *
5147
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5148
-     * @return void
5149
-     */
5150
-    public function assume_values_already_prepared_by_model_object(
5151
-        $values_already_prepared = self::not_prepared_by_model_object
5152
-    ) {
5153
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5154
-    }
5155
-
5156
-
5157
-
5158
-    /**
5159
-     * Read comments for assume_values_already_prepared_by_model_object()
5160
-     *
5161
-     * @return int
5162
-     */
5163
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5164
-    {
5165
-        return $this->_values_already_prepared_by_model_object;
5166
-    }
5167
-
5168
-
5169
-
5170
-    /**
5171
-     * Gets all the indexes on this model
5172
-     *
5173
-     * @return EE_Index[]
5174
-     */
5175
-    public function indexes()
5176
-    {
5177
-        return $this->_indexes;
5178
-    }
5179
-
5180
-
5181
-
5182
-    /**
5183
-     * Gets all the Unique Indexes on this model
5184
-     *
5185
-     * @return EE_Unique_Index[]
5186
-     */
5187
-    public function unique_indexes()
5188
-    {
5189
-        $unique_indexes = array();
5190
-        foreach ($this->_indexes as $name => $index) {
5191
-            if ($index instanceof EE_Unique_Index) {
5192
-                $unique_indexes [$name] = $index;
5193
-            }
5194
-        }
5195
-        return $unique_indexes;
5196
-    }
5197
-
5198
-
5199
-
5200
-    /**
5201
-     * Gets all the fields which, when combined, make the primary key.
5202
-     * This is usually just an array with 1 element (the primary key), but in cases
5203
-     * where there is no primary key, it's a combination of fields as defined
5204
-     * on a primary index
5205
-     *
5206
-     * @return EE_Model_Field_Base[] indexed by the field's name
5207
-     * @throws \EE_Error
5208
-     */
5209
-    public function get_combined_primary_key_fields()
5210
-    {
5211
-        foreach ($this->indexes() as $index) {
5212
-            if ($index instanceof EE_Primary_Key_Index) {
5213
-                return $index->fields();
5214
-            }
5215
-        }
5216
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5217
-    }
5218
-
5219
-
5220
-
5221
-    /**
5222
-     * Used to build a primary key string (when the model has no primary key),
5223
-     * which can be used a unique string to identify this model object.
5224
-     *
5225
-     * @param array $cols_n_values keys are field names, values are their values
5226
-     * @return string
5227
-     * @throws \EE_Error
5228
-     */
5229
-    public function get_index_primary_key_string($cols_n_values)
5230
-    {
5231
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5232
-            $this->get_combined_primary_key_fields());
5233
-        return http_build_query($cols_n_values_for_primary_key_index);
5234
-    }
5235
-
5236
-
5237
-
5238
-    /**
5239
-     * Gets the field values from the primary key string
5240
-     *
5241
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5242
-     * @param string $index_primary_key_string
5243
-     * @return null|array
5244
-     * @throws \EE_Error
5245
-     */
5246
-    public function parse_index_primary_key_string($index_primary_key_string)
5247
-    {
5248
-        $key_fields = $this->get_combined_primary_key_fields();
5249
-        //check all of them are in the $id
5250
-        $key_vals_in_combined_pk = array();
5251
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5252
-        foreach ($key_fields as $key_field_name => $field_obj) {
5253
-            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5254
-                return null;
5255
-            }
5256
-        }
5257
-        return $key_vals_in_combined_pk;
5258
-    }
5259
-
5260
-
5261
-
5262
-    /**
5263
-     * verifies that an array of key-value pairs for model fields has a key
5264
-     * for each field comprising the primary key index
5265
-     *
5266
-     * @param array $key_vals
5267
-     * @return boolean
5268
-     * @throws \EE_Error
5269
-     */
5270
-    public function has_all_combined_primary_key_fields($key_vals)
5271
-    {
5272
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5273
-        foreach ($keys_it_should_have as $key) {
5274
-            if ( ! isset($key_vals[$key])) {
5275
-                return false;
5276
-            }
5277
-        }
5278
-        return true;
5279
-    }
5280
-
5281
-
5282
-
5283
-    /**
5284
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5285
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5286
-     *
5287
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5288
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5289
-     * @throws EE_Error
5290
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5291
-     *                                                              indexed)
5292
-     */
5293
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5294
-    {
5295
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5296
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5297
-        } elseif (is_array($model_object_or_attributes_array)) {
5298
-            $attributes_array = $model_object_or_attributes_array;
5299
-        } else {
5300
-            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",
5301
-                "event_espresso"), $model_object_or_attributes_array));
5302
-        }
5303
-        //even copies obviously won't have the same ID, so remove the primary key
5304
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5305
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5306
-            unset($attributes_array[$this->primary_key_name()]);
5307
-        }
5308
-        if (isset($query_params[0])) {
5309
-            $query_params[0] = array_merge($attributes_array, $query_params);
5310
-        } else {
5311
-            $query_params[0] = $attributes_array;
5312
-        }
5313
-        return $this->get_all($query_params);
5314
-    }
5315
-
5316
-
5317
-
5318
-    /**
5319
-     * Gets the first copy we find. See get_all_copies for more details
5320
-     *
5321
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5322
-     * @param array $query_params
5323
-     * @return EE_Base_Class
5324
-     * @throws \EE_Error
5325
-     */
5326
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5327
-    {
5328
-        if ( ! is_array($query_params)) {
5329
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5330
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5331
-                    gettype($query_params)), '4.6.0');
5332
-            $query_params = array();
5333
-        }
5334
-        $query_params['limit'] = 1;
5335
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5336
-        if (is_array($copies)) {
5337
-            return array_shift($copies);
5338
-        } else {
5339
-            return null;
5340
-        }
5341
-    }
5342
-
5343
-
5344
-
5345
-    /**
5346
-     * Updates the item with the specified id. Ignores default query parameters because
5347
-     * we have specified the ID, and its assumed we KNOW what we're doing
5348
-     *
5349
-     * @param array      $fields_n_values keys are field names, values are their new values
5350
-     * @param int|string $id              the value of the primary key to update
5351
-     * @return int number of rows updated
5352
-     * @throws \EE_Error
5353
-     */
5354
-    public function update_by_ID($fields_n_values, $id)
5355
-    {
5356
-        $query_params = array(
5357
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5358
-            'default_where_conditions' => 'other_models_only',
5359
-        );
5360
-        return $this->update($fields_n_values, $query_params);
5361
-    }
5362
-
5363
-
5364
-
5365
-    /**
5366
-     * Changes an operator which was supplied to the models into one usable in SQL
5367
-     *
5368
-     * @param string $operator_supplied
5369
-     * @return string an operator which can be used in SQL
5370
-     * @throws EE_Error
5371
-     */
5372
-    private function _prepare_operator_for_sql($operator_supplied)
5373
-    {
5374
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5375
-            : null;
5376
-        if ($sql_operator) {
5377
-            return $sql_operator;
5378
-        } else {
5379
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5380
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5381
-        }
5382
-    }
5383
-
5384
-
5385
-
5386
-    /**
5387
-     * Gets an array where keys are the primary keys and values are their 'names'
5388
-     * (as determined by the model object's name() function, which is often overridden)
5389
-     *
5390
-     * @param array $query_params like get_all's
5391
-     * @return string[]
5392
-     * @throws \EE_Error
5393
-     */
5394
-    public function get_all_names($query_params = array())
5395
-    {
5396
-        $objs = $this->get_all($query_params);
5397
-        $names = array();
5398
-        foreach ($objs as $obj) {
5399
-            $names[$obj->ID()] = $obj->name();
5400
-        }
5401
-        return $names;
5402
-    }
5403
-
5404
-
5405
-
5406
-    /**
5407
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5408
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5409
-     * this is duplicated effort and reduces efficiency) you would be better to use
5410
-     * array_keys() on $model_objects.
5411
-     *
5412
-     * @param \EE_Base_Class[] $model_objects
5413
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5414
-     *                                               in the returned array
5415
-     * @return array
5416
-     * @throws \EE_Error
5417
-     */
5418
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5419
-    {
5420
-        if ( ! $this->has_primary_key_field()) {
5421
-            if (WP_DEBUG) {
5422
-                EE_Error::add_error(
5423
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5424
-                    __FILE__,
5425
-                    __FUNCTION__,
5426
-                    __LINE__
5427
-                );
5428
-            }
5429
-        }
5430
-        $IDs = array();
5431
-        foreach ($model_objects as $model_object) {
5432
-            $id = $model_object->ID();
5433
-            if ( ! $id) {
5434
-                if ($filter_out_empty_ids) {
5435
-                    continue;
5436
-                }
5437
-                if (WP_DEBUG) {
5438
-                    EE_Error::add_error(
5439
-                        __(
5440
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5441
-                            'event_espresso'
5442
-                        ),
5443
-                        __FILE__,
5444
-                        __FUNCTION__,
5445
-                        __LINE__
5446
-                    );
5447
-                }
5448
-            }
5449
-            $IDs[] = $id;
5450
-        }
5451
-        return $IDs;
5452
-    }
5453
-
5454
-
5455
-
5456
-    /**
5457
-     * Returns the string used in capabilities relating to this model. If there
5458
-     * are no capabilities that relate to this model returns false
5459
-     *
5460
-     * @return string|false
5461
-     */
5462
-    public function cap_slug()
5463
-    {
5464
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5465
-    }
5466
-
5467
-
5468
-
5469
-    /**
5470
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5471
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5472
-     * only returns the cap restrictions array in that context (ie, the array
5473
-     * at that key)
5474
-     *
5475
-     * @param string $context
5476
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5477
-     * @throws \EE_Error
5478
-     */
5479
-    public function cap_restrictions($context = EEM_Base::caps_read)
5480
-    {
5481
-        EEM_Base::verify_is_valid_cap_context($context);
5482
-        //check if we ought to run the restriction generator first
5483
-        if (
5484
-            isset($this->_cap_restriction_generators[$context])
5485
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5486
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5487
-        ) {
5488
-            $this->_cap_restrictions[$context] = array_merge(
5489
-                $this->_cap_restrictions[$context],
5490
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5491
-            );
5492
-        }
5493
-        //and make sure we've finalized the construction of each restriction
5494
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5495
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5496
-                $where_conditions_obj->_finalize_construct($this);
5497
-            }
5498
-        }
5499
-        return $this->_cap_restrictions[$context];
5500
-    }
5501
-
5502
-
5503
-
5504
-    /**
5505
-     * Indicating whether or not this model thinks its a wp core model
5506
-     *
5507
-     * @return boolean
5508
-     */
5509
-    public function is_wp_core_model()
5510
-    {
5511
-        return $this->_wp_core_model;
5512
-    }
5513
-
5514
-
5515
-
5516
-    /**
5517
-     * Gets all the caps that are missing which impose a restriction on
5518
-     * queries made in this context
5519
-     *
5520
-     * @param string $context one of EEM_Base::caps_ constants
5521
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5522
-     * @throws \EE_Error
5523
-     */
5524
-    public function caps_missing($context = EEM_Base::caps_read)
5525
-    {
5526
-        $missing_caps = array();
5527
-        $cap_restrictions = $this->cap_restrictions($context);
5528
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5529
-            if ( ! EE_Capabilities::instance()
5530
-                                  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5531
-            ) {
5532
-                $missing_caps[$cap] = $restriction_if_no_cap;
5533
-            }
5534
-        }
5535
-        return $missing_caps;
5536
-    }
5537
-
5538
-
5539
-
5540
-    /**
5541
-     * Gets the mapping from capability contexts to action strings used in capability names
5542
-     *
5543
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5544
-     * one of 'read', 'edit', or 'delete'
5545
-     */
5546
-    public function cap_contexts_to_cap_action_map()
5547
-    {
5548
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5549
-            $this);
5550
-    }
5551
-
5552
-
5553
-
5554
-    /**
5555
-     * Gets the action string for the specified capability context
5556
-     *
5557
-     * @param string $context
5558
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5559
-     * @throws \EE_Error
5560
-     */
5561
-    public function cap_action_for_context($context)
5562
-    {
5563
-        $mapping = $this->cap_contexts_to_cap_action_map();
5564
-        if (isset($mapping[$context])) {
5565
-            return $mapping[$context];
5566
-        }
5567
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5568
-            return $action;
5569
-        }
5570
-        throw new EE_Error(
5571
-            sprintf(
5572
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5573
-                $context,
5574
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5575
-            )
5576
-        );
5577
-    }
5578
-
5579
-
5580
-
5581
-    /**
5582
-     * Returns all the capability contexts which are valid when querying models
5583
-     *
5584
-     * @return array
5585
-     */
5586
-    static public function valid_cap_contexts()
5587
-    {
5588
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5589
-            self::caps_read,
5590
-            self::caps_read_admin,
5591
-            self::caps_edit,
5592
-            self::caps_delete,
5593
-        ));
5594
-    }
5595
-
5596
-
5597
-
5598
-    /**
5599
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5600
-     *
5601
-     * @param string $context
5602
-     * @return bool
5603
-     * @throws \EE_Error
5604
-     */
5605
-    static public function verify_is_valid_cap_context($context)
5606
-    {
5607
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5608
-        if (in_array($context, $valid_cap_contexts)) {
5609
-            return true;
5610
-        } else {
5611
-            throw new EE_Error(
5612
-                sprintf(
5613
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5614
-                        'event_espresso'),
5615
-                    $context,
5616
-                    'EEM_Base',
5617
-                    implode(',', $valid_cap_contexts)
5618
-                )
5619
-            );
5620
-        }
5621
-    }
5622
-
5623
-
5624
-
5625
-    /**
5626
-     * Clears all the models field caches. This is only useful when a sub-class
5627
-     * might have added a field or something and these caches might be invalidated
5628
-     */
5629
-    protected function _invalidate_field_caches()
5630
-    {
5631
-        $this->_cache_foreign_key_to_fields = array();
5632
-        $this->_cached_fields = null;
5633
-        $this->_cached_fields_non_db_only = null;
5634
-    }
3448
+		}
3449
+		return $null_friendly_where_conditions;
3450
+	}
3451
+
3452
+
3453
+
3454
+	/**
3455
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3456
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3457
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3458
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3459
+	 *
3460
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3461
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3462
+	 */
3463
+	private function _get_default_where_conditions($model_relation_path = null)
3464
+	{
3465
+		if ($this->_ignore_where_strategy) {
3466
+			return array();
3467
+		}
3468
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3469
+	}
3470
+
3471
+
3472
+
3473
+	/**
3474
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3475
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3476
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3477
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3478
+	 * Similar to _get_default_where_conditions
3479
+	 *
3480
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3481
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3482
+	 */
3483
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3484
+	{
3485
+		if ($this->_ignore_where_strategy) {
3486
+			return array();
3487
+		}
3488
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3489
+	}
3490
+
3491
+
3492
+
3493
+	/**
3494
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3495
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3496
+	 *
3497
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3498
+	 * @return string
3499
+	 * @throws \EE_Error
3500
+	 */
3501
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3502
+	{
3503
+		$selects = $this->_get_columns_to_select_for_this_model();
3504
+		foreach (
3505
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3506
+			$name_of_other_model_included
3507
+		) {
3508
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3509
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3510
+			foreach ($other_model_selects as $key => $value) {
3511
+				$selects[] = $value;
3512
+			}
3513
+		}
3514
+		return implode(", ", $selects);
3515
+	}
3516
+
3517
+
3518
+
3519
+	/**
3520
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3521
+	 * So that's going to be the columns for all the fields on the model
3522
+	 *
3523
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3524
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3525
+	 */
3526
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3527
+	{
3528
+		$fields = $this->field_settings();
3529
+		$selects = array();
3530
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3531
+			$this->get_this_model_name());
3532
+		foreach ($fields as $field_obj) {
3533
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3534
+						 . $field_obj->get_table_alias()
3535
+						 . "."
3536
+						 . $field_obj->get_table_column()
3537
+						 . " AS '"
3538
+						 . $table_alias_with_model_relation_chain_prefix
3539
+						 . $field_obj->get_table_alias()
3540
+						 . "."
3541
+						 . $field_obj->get_table_column()
3542
+						 . "'";
3543
+		}
3544
+		//make sure we are also getting the PKs of each table
3545
+		$tables = $this->get_tables();
3546
+		if (count($tables) > 1) {
3547
+			foreach ($tables as $table_obj) {
3548
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3549
+									   . $table_obj->get_fully_qualified_pk_column();
3550
+				if ( ! in_array($qualified_pk_column, $selects)) {
3551
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3552
+				}
3553
+			}
3554
+		}
3555
+		return $selects;
3556
+	}
3557
+
3558
+
3559
+
3560
+	/**
3561
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3562
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3563
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3564
+	 * SQL for joining, and the data types
3565
+	 *
3566
+	 * @param null|string                 $original_query_param
3567
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3568
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3569
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3570
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3571
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3572
+	 *                                                          or 'Registration's
3573
+	 * @param string                      $original_query_param what it originally was (eg
3574
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3575
+	 *                                                          matches $query_param
3576
+	 * @throws EE_Error
3577
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3578
+	 */
3579
+	private function _extract_related_model_info_from_query_param(
3580
+		$query_param,
3581
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3582
+		$query_param_type,
3583
+		$original_query_param = null
3584
+	) {
3585
+		if ($original_query_param === null) {
3586
+			$original_query_param = $query_param;
3587
+		}
3588
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3589
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3590
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3591
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3592
+		//check to see if we have a field on this model
3593
+		$this_model_fields = $this->field_settings(true);
3594
+		if (array_key_exists($query_param, $this_model_fields)) {
3595
+			if ($allow_fields) {
3596
+				return;
3597
+			} else {
3598
+				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",
3599
+					"event_espresso"),
3600
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3601
+			}
3602
+		} //check if this is a special logic query param
3603
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3604
+			if ($allow_logic_query_params) {
3605
+				return;
3606
+			} else {
3607
+				throw new EE_Error(
3608
+					sprintf(
3609
+						__('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',
3610
+							'event_espresso'),
3611
+						implode('", "', $this->_logic_query_param_keys),
3612
+						$query_param,
3613
+						get_class($this),
3614
+						'<br />',
3615
+						"\t"
3616
+						. ' $passed_in_query_info = <pre>'
3617
+						. print_r($passed_in_query_info, true)
3618
+						. '</pre>'
3619
+						. "\n\t"
3620
+						. ' $query_param_type = '
3621
+						. $query_param_type
3622
+						. "\n\t"
3623
+						. ' $original_query_param = '
3624
+						. $original_query_param
3625
+					)
3626
+				);
3627
+			}
3628
+		} //check if it's a custom selection
3629
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3630
+			return;
3631
+		}
3632
+		//check if has a model name at the beginning
3633
+		//and
3634
+		//check if it's a field on a related model
3635
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3636
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3637
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3638
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3639
+				if ($query_param === '') {
3640
+					//nothing left to $query_param
3641
+					//we should actually end in a field name, not a model like this!
3642
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3643
+						"event_espresso"),
3644
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3645
+				} else {
3646
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3647
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3648
+						$passed_in_query_info, $query_param_type, $original_query_param);
3649
+					return;
3650
+				}
3651
+			} elseif ($query_param === $valid_related_model_name) {
3652
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3653
+				return;
3654
+			}
3655
+		}
3656
+		//ok so $query_param didn't start with a model name
3657
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3658
+		//it's wack, that's what it is
3659
+		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",
3660
+			"event_espresso"),
3661
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3662
+	}
3663
+
3664
+
3665
+
3666
+	/**
3667
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3668
+	 * and store it on $passed_in_query_info
3669
+	 *
3670
+	 * @param string                      $model_name
3671
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3672
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3673
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3674
+	 *                                                          and are adding a join to 'Payment' with the original
3675
+	 *                                                          query param key
3676
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3677
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3678
+	 *                                                          Payment wants to add default query params so that it
3679
+	 *                                                          will know what models to prepend onto its default query
3680
+	 *                                                          params or in case it wants to rename tables (in case
3681
+	 *                                                          there are multiple joins to the same table)
3682
+	 * @return void
3683
+	 * @throws \EE_Error
3684
+	 */
3685
+	private function _add_join_to_model(
3686
+		$model_name,
3687
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3688
+		$original_query_param
3689
+	) {
3690
+		$relation_obj = $this->related_settings_for($model_name);
3691
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3692
+		//check if the relation is HABTM, because then we're essentially doing two joins
3693
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3694
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3695
+			$join_model_obj = $relation_obj->get_join_model();
3696
+			//replace the model specified with the join model for this relation chain, whi
3697
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3698
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3699
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3700
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3701
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3702
+			$passed_in_query_info->merge($new_query_info);
3703
+		}
3704
+		//now just join to the other table pointed to by the relation object, and add its data types
3705
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3706
+			array($model_relation_chain => $model_name),
3707
+			$relation_obj->get_join_statement($model_relation_chain));
3708
+		$passed_in_query_info->merge($new_query_info);
3709
+	}
3710
+
3711
+
3712
+
3713
+	/**
3714
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3715
+	 *
3716
+	 * @param array $where_params like EEM_Base::get_all
3717
+	 * @return string of SQL
3718
+	 * @throws \EE_Error
3719
+	 */
3720
+	private function _construct_where_clause($where_params)
3721
+	{
3722
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3723
+		if ($SQL) {
3724
+			return " WHERE " . $SQL;
3725
+		} else {
3726
+			return '';
3727
+		}
3728
+	}
3729
+
3730
+
3731
+
3732
+	/**
3733
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3734
+	 * and should be passed HAVING parameters, not WHERE parameters
3735
+	 *
3736
+	 * @param array $having_params
3737
+	 * @return string
3738
+	 * @throws \EE_Error
3739
+	 */
3740
+	private function _construct_having_clause($having_params)
3741
+	{
3742
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3743
+		if ($SQL) {
3744
+			return " HAVING " . $SQL;
3745
+		} else {
3746
+			return '';
3747
+		}
3748
+	}
3749
+
3750
+
3751
+
3752
+	/**
3753
+	 * Gets the EE_Model_Field on the model indicated by $model_name and the $field_name.
3754
+	 * Eg, if called with _get_field_on_model('ATT_ID','Attendee'), it will return the EE_Primary_Key_Field on
3755
+	 * EEM_Attendee.
3756
+	 *
3757
+	 * @param string $field_name
3758
+	 * @param string $model_name
3759
+	 * @return EE_Model_Field_Base
3760
+	 * @throws EE_Error
3761
+	 */
3762
+	protected function _get_field_on_model($field_name, $model_name)
3763
+	{
3764
+		$model_class = 'EEM_' . $model_name;
3765
+		$model_filepath = $model_class . ".model.php";
3766
+		if (is_readable($model_filepath)) {
3767
+			require_once($model_filepath);
3768
+			$model_instance = call_user_func($model_name . "::instance");
3769
+			/* @var $model_instance EEM_Base */
3770
+			return $model_instance->field_settings_for($field_name);
3771
+		} else {
3772
+			throw new EE_Error(sprintf(__('No model named %s exists, with classname %s and filepath %s',
3773
+				'event_espresso'), $model_name, $model_class, $model_filepath));
3774
+		}
3775
+	}
3776
+
3777
+
3778
+
3779
+	/**
3780
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3781
+	 * Event_Meta.meta_value = 'foo'))"
3782
+	 *
3783
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3784
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3785
+	 * @throws EE_Error
3786
+	 * @return string of SQL
3787
+	 */
3788
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3789
+	{
3790
+		$where_clauses = array();
3791
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3792
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3793
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3794
+				switch ($query_param) {
3795
+					case 'not':
3796
+					case 'NOT':
3797
+						$where_clauses[] = "! ("
3798
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3799
+								$glue)
3800
+										   . ")";
3801
+						break;
3802
+					case 'and':
3803
+					case 'AND':
3804
+						$where_clauses[] = " ("
3805
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3806
+								' AND ')
3807
+										   . ")";
3808
+						break;
3809
+					case 'or':
3810
+					case 'OR':
3811
+						$where_clauses[] = " ("
3812
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3813
+								' OR ')
3814
+										   . ")";
3815
+						break;
3816
+				}
3817
+			} else {
3818
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3819
+				//if it's not a normal field, maybe it's a custom selection?
3820
+				if ( ! $field_obj) {
3821
+					if (isset($this->_custom_selections[$query_param][1])) {
3822
+						$field_obj = $this->_custom_selections[$query_param][1];
3823
+					} else {
3824
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3825
+							"event_espresso"), $query_param));
3826
+					}
3827
+				}
3828
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3829
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3830
+			}
3831
+		}
3832
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3833
+	}
3834
+
3835
+
3836
+
3837
+	/**
3838
+	 * Takes the input parameter and extract the table name (alias) and column name
3839
+	 *
3840
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3841
+	 * @throws EE_Error
3842
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3843
+	 */
3844
+	private function _deduce_column_name_from_query_param($query_param)
3845
+	{
3846
+		$field = $this->_deduce_field_from_query_param($query_param);
3847
+		if ($field) {
3848
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
3849
+				$query_param);
3850
+			return $table_alias_prefix . $field->get_qualified_column();
3851
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
3852
+			//maybe it's custom selection item?
3853
+			//if so, just use it as the "column name"
3854
+			return $query_param;
3855
+		} else {
3856
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
3857
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
3858
+		}
3859
+	}
3860
+
3861
+
3862
+
3863
+	/**
3864
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
3865
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
3866
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
3867
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
3868
+	 *
3869
+	 * @param string $condition_query_param_key
3870
+	 * @return string
3871
+	 */
3872
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
3873
+	{
3874
+		$pos_of_star = strpos($condition_query_param_key, '*');
3875
+		if ($pos_of_star === false) {
3876
+			return $condition_query_param_key;
3877
+		} else {
3878
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
3879
+			return $condition_query_param_sans_star;
3880
+		}
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
3887
+	 *
3888
+	 * @param                            mixed      array | string    $op_and_value
3889
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
3890
+	 * @throws EE_Error
3891
+	 * @return string
3892
+	 */
3893
+	private function _construct_op_and_value($op_and_value, $field_obj)
3894
+	{
3895
+		if (is_array($op_and_value)) {
3896
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
3897
+			if ( ! $operator) {
3898
+				$php_array_like_string = array();
3899
+				foreach ($op_and_value as $key => $value) {
3900
+					$php_array_like_string[] = "$key=>$value";
3901
+				}
3902
+				throw new EE_Error(
3903
+					sprintf(
3904
+						__(
3905
+							"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))",
3906
+							"event_espresso"
3907
+						),
3908
+						implode(",", $php_array_like_string)
3909
+					)
3910
+				);
3911
+			}
3912
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
3913
+		} else {
3914
+			$operator = '=';
3915
+			$value = $op_and_value;
3916
+		}
3917
+		//check to see if the value is actually another field
3918
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
3919
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
3920
+		} elseif (in_array($operator, $this->_in_style_operators) && is_array($value)) {
3921
+			//in this case, the value should be an array, or at least a comma-separated list
3922
+			//it will need to handle a little differently
3923
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
3924
+			//note: $cleaned_value has already been run through $wpdb->prepare()
3925
+			return $operator . SP . $cleaned_value;
3926
+		} elseif (in_array($operator, $this->_between_style_operators) && is_array($value)) {
3927
+			//the value should be an array with count of two.
3928
+			if (count($value) !== 2) {
3929
+				throw new EE_Error(
3930
+					sprintf(
3931
+						__(
3932
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
3933
+							'event_espresso'
3934
+						),
3935
+						"BETWEEN"
3936
+					)
3937
+				);
3938
+			}
3939
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
3940
+			return $operator . SP . $cleaned_value;
3941
+		} elseif (in_array($operator, $this->_null_style_operators)) {
3942
+			if ($value !== null) {
3943
+				throw new EE_Error(
3944
+					sprintf(
3945
+						__(
3946
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
3947
+							"event_espresso"
3948
+						),
3949
+						$value,
3950
+						$operator
3951
+					)
3952
+				);
3953
+			}
3954
+			return $operator;
3955
+		} elseif ($operator === 'LIKE' && ! is_array($value)) {
3956
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
3957
+			//remove other junk. So just treat it as a string.
3958
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
3959
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3960
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
3961
+		} elseif (in_array($operator, $this->_in_style_operators) && ! is_array($value)) {
3962
+			throw new EE_Error(
3963
+				sprintf(
3964
+					__(
3965
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
3966
+						'event_espresso'
3967
+					),
3968
+					$operator,
3969
+					$operator
3970
+				)
3971
+			);
3972
+		} elseif ( ! in_array($operator, $this->_in_style_operators) && is_array($value)) {
3973
+			throw new EE_Error(
3974
+				sprintf(
3975
+					__(
3976
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
3977
+						'event_espresso'
3978
+					),
3979
+					$operator,
3980
+					$operator
3981
+				)
3982
+			);
3983
+		} else {
3984
+			throw new EE_Error(
3985
+				sprintf(
3986
+					__(
3987
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
3988
+						"event_espresso"
3989
+					),
3990
+					http_build_query($op_and_value)
3991
+				)
3992
+			);
3993
+		}
3994
+	}
3995
+
3996
+
3997
+
3998
+	/**
3999
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4000
+	 *
4001
+	 * @param array                      $values
4002
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4003
+	 *                                              '%s'
4004
+	 * @return string
4005
+	 * @throws \EE_Error
4006
+	 */
4007
+	public function _construct_between_value($values, $field_obj)
4008
+	{
4009
+		$cleaned_values = array();
4010
+		foreach ($values as $value) {
4011
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4012
+		}
4013
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4014
+	}
4015
+
4016
+
4017
+
4018
+	/**
4019
+	 * Takes an array or a comma-separated list of $values and cleans them
4020
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4021
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4022
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4023
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4024
+	 *
4025
+	 * @param mixed                      $values    array or comma-separated string
4026
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4027
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4028
+	 * @throws \EE_Error
4029
+	 */
4030
+	public function _construct_in_value($values, $field_obj)
4031
+	{
4032
+		//check if the value is a CSV list
4033
+		if (is_string($values)) {
4034
+			//in which case, turn it into an array
4035
+			$values = explode(",", $values);
4036
+		}
4037
+		$cleaned_values = array();
4038
+		foreach ($values as $value) {
4039
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4040
+		}
4041
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4042
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4043
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4044
+		if (empty($cleaned_values)) {
4045
+			$all_fields = $this->field_settings();
4046
+			$a_field = array_shift($all_fields);
4047
+			$main_table = $this->_get_main_table();
4048
+			$cleaned_values[] = "SELECT "
4049
+								. $a_field->get_table_column()
4050
+								. " FROM "
4051
+								. $main_table->get_table_name()
4052
+								. " WHERE FALSE";
4053
+		}
4054
+		return "(" . implode(",", $cleaned_values) . ")";
4055
+	}
4056
+
4057
+
4058
+
4059
+	/**
4060
+	 * @param mixed                      $value
4061
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4062
+	 * @throws EE_Error
4063
+	 * @return false|null|string
4064
+	 */
4065
+	private function _wpdb_prepare_using_field($value, $field_obj)
4066
+	{
4067
+		/** @type WPDB $wpdb */
4068
+		global $wpdb;
4069
+		if ($field_obj instanceof EE_Model_Field_Base) {
4070
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4071
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4072
+		} else {//$field_obj should really just be a data type
4073
+			if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4074
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4075
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4076
+			}
4077
+			return $wpdb->prepare($field_obj, $value);
4078
+		}
4079
+	}
4080
+
4081
+
4082
+
4083
+	/**
4084
+	 * Takes the input parameter and finds the model field that it indicates.
4085
+	 *
4086
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4087
+	 * @throws EE_Error
4088
+	 * @return EE_Model_Field_Base
4089
+	 */
4090
+	protected function _deduce_field_from_query_param($query_param_name)
4091
+	{
4092
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4093
+		//which will help us find the database table and column
4094
+		$query_param_parts = explode(".", $query_param_name);
4095
+		if (empty($query_param_parts)) {
4096
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4097
+				'event_espresso'), $query_param_name));
4098
+		}
4099
+		$number_of_parts = count($query_param_parts);
4100
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4101
+		if ($number_of_parts === 1) {
4102
+			$field_name = $last_query_param_part;
4103
+			$model_obj = $this;
4104
+		} else {// $number_of_parts >= 2
4105
+			//the last part is the column name, and there are only 2parts. therefore...
4106
+			$field_name = $last_query_param_part;
4107
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4108
+		}
4109
+		try {
4110
+			return $model_obj->field_settings_for($field_name);
4111
+		} catch (EE_Error $e) {
4112
+			return null;
4113
+		}
4114
+	}
4115
+
4116
+
4117
+
4118
+	/**
4119
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4120
+	 * alias and column which corresponds to it
4121
+	 *
4122
+	 * @param string $field_name
4123
+	 * @throws EE_Error
4124
+	 * @return string
4125
+	 */
4126
+	public function _get_qualified_column_for_field($field_name)
4127
+	{
4128
+		$all_fields = $this->field_settings();
4129
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4130
+		if ($field) {
4131
+			return $field->get_qualified_column();
4132
+		} else {
4133
+			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.",
4134
+				'event_espresso'), $field_name, get_class($this)));
4135
+		}
4136
+	}
4137
+
4138
+
4139
+
4140
+	/**
4141
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4142
+	 * Example usage:
4143
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4144
+	 *      array(),
4145
+	 *      ARRAY_A,
4146
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4147
+	 *  );
4148
+	 * is equivalent to
4149
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4150
+	 * and
4151
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4152
+	 *      array(
4153
+	 *          array(
4154
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4155
+	 *          ),
4156
+	 *          ARRAY_A,
4157
+	 *          implode(
4158
+	 *              ', ',
4159
+	 *              array_merge(
4160
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4161
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4162
+	 *              )
4163
+	 *          )
4164
+	 *      )
4165
+	 *  );
4166
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4167
+	 *
4168
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4169
+	 *                                            and the one whose fields you are selecting for example: when querying
4170
+	 *                                            tickets model and selecting fields from the tickets model you would
4171
+	 *                                            leave this parameter empty, because no models are needed to join
4172
+	 *                                            between the queried model and the selected one. Likewise when
4173
+	 *                                            querying the datetime model and selecting fields from the tickets
4174
+	 *                                            model, it would also be left empty, because there is a direct
4175
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4176
+	 *                                            them together. However, when querying from the event model and
4177
+	 *                                            selecting fields from the ticket model, you should provide the string
4178
+	 *                                            'Datetime', indicating that the event model must first join to the
4179
+	 *                                            datetime model in order to find its relation to ticket model.
4180
+	 *                                            Also, when querying from the venue model and selecting fields from
4181
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4182
+	 *                                            indicating you need to join the venue model to the event model,
4183
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4184
+	 *                                            This string is used to deduce the prefix that gets added onto the
4185
+	 *                                            models' tables qualified columns
4186
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4187
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4188
+	 *                                            qualified column names
4189
+	 * @return array|string
4190
+	 */
4191
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4192
+	{
4193
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4194
+		$qualified_columns = array();
4195
+		foreach ($this->field_settings() as $field_name => $field) {
4196
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4197
+		}
4198
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4199
+	}
4200
+
4201
+
4202
+
4203
+	/**
4204
+	 * constructs the select use on special limit joins
4205
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4206
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4207
+	 * (as that is typically where the limits would be set).
4208
+	 *
4209
+	 * @param  string       $table_alias The table the select is being built for
4210
+	 * @param  mixed|string $limit       The limit for this select
4211
+	 * @return string                The final select join element for the query.
4212
+	 */
4213
+	public function _construct_limit_join_select($table_alias, $limit)
4214
+	{
4215
+		$SQL = '';
4216
+		foreach ($this->_tables as $table_obj) {
4217
+			if ($table_obj instanceof EE_Primary_Table) {
4218
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4219
+					? $table_obj->get_select_join_limit($limit)
4220
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4221
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4222
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4223
+					? $table_obj->get_select_join_limit_join($limit)
4224
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4225
+			}
4226
+		}
4227
+		return $SQL;
4228
+	}
4229
+
4230
+
4231
+
4232
+	/**
4233
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4234
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4235
+	 *
4236
+	 * @return string SQL
4237
+	 * @throws \EE_Error
4238
+	 */
4239
+	public function _construct_internal_join()
4240
+	{
4241
+		$SQL = $this->_get_main_table()->get_table_sql();
4242
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4243
+		return $SQL;
4244
+	}
4245
+
4246
+
4247
+
4248
+	/**
4249
+	 * Constructs the SQL for joining all the tables on this model.
4250
+	 * Normally $alias should be the primary table's alias, but in cases where
4251
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4252
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4253
+	 * alias, this will construct SQL like:
4254
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4255
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4256
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4257
+	 *
4258
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4259
+	 * @return string
4260
+	 */
4261
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4262
+	{
4263
+		$SQL = '';
4264
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4265
+		foreach ($this->_tables as $table_obj) {
4266
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4267
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4268
+					//so we're joining to this table, meaning the table is already in
4269
+					//the FROM statement, BUT the primary table isn't. So we want
4270
+					//to add the inverse join sql
4271
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4272
+				} else {
4273
+					//just add a regular JOIN to this table from the primary table
4274
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4275
+				}
4276
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4277
+		}
4278
+		return $SQL;
4279
+	}
4280
+
4281
+
4282
+
4283
+	/**
4284
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4285
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4286
+	 * their data type (eg, '%s', '%d', etc)
4287
+	 *
4288
+	 * @return array
4289
+	 */
4290
+	public function _get_data_types()
4291
+	{
4292
+		$data_types = array();
4293
+		foreach ($this->field_settings() as $field_obj) {
4294
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4295
+			/** @var $field_obj EE_Model_Field_Base */
4296
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4297
+		}
4298
+		return $data_types;
4299
+	}
4300
+
4301
+
4302
+
4303
+	/**
4304
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4305
+	 *
4306
+	 * @param string $model_name
4307
+	 * @throws EE_Error
4308
+	 * @return EEM_Base
4309
+	 */
4310
+	public function get_related_model_obj($model_name)
4311
+	{
4312
+		$model_classname = "EEM_" . $model_name;
4313
+		if ( ! class_exists($model_classname)) {
4314
+			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",
4315
+				'event_espresso'), $model_name, $model_classname));
4316
+		}
4317
+		return call_user_func($model_classname . "::instance");
4318
+	}
4319
+
4320
+
4321
+
4322
+	/**
4323
+	 * Returns the array of EE_ModelRelations for this model.
4324
+	 *
4325
+	 * @return EE_Model_Relation_Base[]
4326
+	 */
4327
+	public function relation_settings()
4328
+	{
4329
+		return $this->_model_relations;
4330
+	}
4331
+
4332
+
4333
+
4334
+	/**
4335
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4336
+	 * because without THOSE models, this model probably doesn't have much purpose.
4337
+	 * (Eg, without an event, datetimes have little purpose.)
4338
+	 *
4339
+	 * @return EE_Belongs_To_Relation[]
4340
+	 */
4341
+	public function belongs_to_relations()
4342
+	{
4343
+		$belongs_to_relations = array();
4344
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4345
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4346
+				$belongs_to_relations[$model_name] = $relation_obj;
4347
+			}
4348
+		}
4349
+		return $belongs_to_relations;
4350
+	}
4351
+
4352
+
4353
+
4354
+	/**
4355
+	 * Returns the specified EE_Model_Relation, or throws an exception
4356
+	 *
4357
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4358
+	 * @throws EE_Error
4359
+	 * @return EE_Model_Relation_Base
4360
+	 */
4361
+	public function related_settings_for($relation_name)
4362
+	{
4363
+		$relatedModels = $this->relation_settings();
4364
+		if ( ! array_key_exists($relation_name, $relatedModels)) {
4365
+			throw new EE_Error(
4366
+				sprintf(
4367
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4368
+						'event_espresso'),
4369
+					$relation_name,
4370
+					$this->_get_class_name(),
4371
+					implode(', ', array_keys($relatedModels))
4372
+				)
4373
+			);
4374
+		}
4375
+		return $relatedModels[$relation_name];
4376
+	}
4377
+
4378
+
4379
+
4380
+	/**
4381
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4382
+	 * fields
4383
+	 *
4384
+	 * @param string $fieldName
4385
+	 * @throws EE_Error
4386
+	 * @return EE_Model_Field_Base
4387
+	 */
4388
+	public function field_settings_for($fieldName)
4389
+	{
4390
+		$fieldSettings = $this->field_settings(true);
4391
+		if ( ! array_key_exists($fieldName, $fieldSettings)) {
4392
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4393
+				get_class($this)));
4394
+		}
4395
+		return $fieldSettings[$fieldName];
4396
+	}
4397
+
4398
+
4399
+
4400
+	/**
4401
+	 * Checks if this field exists on this model
4402
+	 *
4403
+	 * @param string $fieldName a key in the model's _field_settings array
4404
+	 * @return boolean
4405
+	 */
4406
+	public function has_field($fieldName)
4407
+	{
4408
+		$fieldSettings = $this->field_settings(true);
4409
+		if (isset($fieldSettings[$fieldName])) {
4410
+			return true;
4411
+		} else {
4412
+			return false;
4413
+		}
4414
+	}
4415
+
4416
+
4417
+
4418
+	/**
4419
+	 * Returns whether or not this model has a relation to the specified model
4420
+	 *
4421
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4422
+	 * @return boolean
4423
+	 */
4424
+	public function has_relation($relation_name)
4425
+	{
4426
+		$relations = $this->relation_settings();
4427
+		if (isset($relations[$relation_name])) {
4428
+			return true;
4429
+		} else {
4430
+			return false;
4431
+		}
4432
+	}
4433
+
4434
+
4435
+
4436
+	/**
4437
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4438
+	 * Eg, on EE_Answer that would be ANS_ID field object
4439
+	 *
4440
+	 * @param $field_obj
4441
+	 * @return boolean
4442
+	 */
4443
+	public function is_primary_key_field($field_obj)
4444
+	{
4445
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4446
+	}
4447
+
4448
+
4449
+
4450
+	/**
4451
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4452
+	 * Eg, on EE_Answer that would be ANS_ID field object
4453
+	 *
4454
+	 * @return EE_Model_Field_Base
4455
+	 * @throws EE_Error
4456
+	 */
4457
+	public function get_primary_key_field()
4458
+	{
4459
+		if ($this->_primary_key_field === null) {
4460
+			foreach ($this->field_settings(true) as $field_obj) {
4461
+				if ($this->is_primary_key_field($field_obj)) {
4462
+					$this->_primary_key_field = $field_obj;
4463
+					break;
4464
+				}
4465
+			}
4466
+			if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4467
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4468
+					get_class($this)));
4469
+			}
4470
+		}
4471
+		return $this->_primary_key_field;
4472
+	}
4473
+
4474
+
4475
+
4476
+	/**
4477
+	 * Returns whether or not not there is a primary key on this model.
4478
+	 * Internally does some caching.
4479
+	 *
4480
+	 * @return boolean
4481
+	 */
4482
+	public function has_primary_key_field()
4483
+	{
4484
+		if ($this->_has_primary_key_field === null) {
4485
+			try {
4486
+				$this->get_primary_key_field();
4487
+				$this->_has_primary_key_field = true;
4488
+			} catch (EE_Error $e) {
4489
+				$this->_has_primary_key_field = false;
4490
+			}
4491
+		}
4492
+		return $this->_has_primary_key_field;
4493
+	}
4494
+
4495
+
4496
+
4497
+	/**
4498
+	 * Finds the first field of type $field_class_name.
4499
+	 *
4500
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4501
+	 *                                 EE_Foreign_Key_Field, etc
4502
+	 * @return EE_Model_Field_Base or null if none is found
4503
+	 */
4504
+	public function get_a_field_of_type($field_class_name)
4505
+	{
4506
+		foreach ($this->field_settings() as $field) {
4507
+			if ($field instanceof $field_class_name) {
4508
+				return $field;
4509
+			}
4510
+		}
4511
+		return null;
4512
+	}
4513
+
4514
+
4515
+
4516
+	/**
4517
+	 * Gets a foreign key field pointing to model.
4518
+	 *
4519
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4520
+	 * @return EE_Foreign_Key_Field_Base
4521
+	 * @throws EE_Error
4522
+	 */
4523
+	public function get_foreign_key_to($model_name)
4524
+	{
4525
+		if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4526
+			foreach ($this->field_settings() as $field) {
4527
+				if (
4528
+					$field instanceof EE_Foreign_Key_Field_Base
4529
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4530
+				) {
4531
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4532
+					break;
4533
+				}
4534
+			}
4535
+			if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4536
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4537
+					'event_espresso'), $model_name, get_class($this)));
4538
+			}
4539
+		}
4540
+		return $this->_cache_foreign_key_to_fields[$model_name];
4541
+	}
4542
+
4543
+
4544
+
4545
+	/**
4546
+	 * Gets the actual table for the table alias
4547
+	 *
4548
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4549
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4550
+	 *                            Either one works
4551
+	 * @return EE_Table_Base
4552
+	 */
4553
+	public function get_table_for_alias($table_alias)
4554
+	{
4555
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4556
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4557
+	}
4558
+
4559
+
4560
+
4561
+	/**
4562
+	 * Returns a flat array of all field son this model, instead of organizing them
4563
+	 * by table_alias as they are in the constructor.
4564
+	 *
4565
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4566
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4567
+	 */
4568
+	public function field_settings($include_db_only_fields = false)
4569
+	{
4570
+		if ($include_db_only_fields) {
4571
+			if ($this->_cached_fields === null) {
4572
+				$this->_cached_fields = array();
4573
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4574
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4575
+						$this->_cached_fields[$field_name] = $field_obj;
4576
+					}
4577
+				}
4578
+			}
4579
+			return $this->_cached_fields;
4580
+		} else {
4581
+			if ($this->_cached_fields_non_db_only === null) {
4582
+				$this->_cached_fields_non_db_only = array();
4583
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4584
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4585
+						/** @var $field_obj EE_Model_Field_Base */
4586
+						if ( ! $field_obj->is_db_only_field()) {
4587
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4588
+						}
4589
+					}
4590
+				}
4591
+			}
4592
+			return $this->_cached_fields_non_db_only;
4593
+		}
4594
+	}
4595
+
4596
+
4597
+
4598
+	/**
4599
+	 *        cycle though array of attendees and create objects out of each item
4600
+	 *
4601
+	 * @access        private
4602
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4603
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4604
+	 *                           numerically indexed)
4605
+	 * @throws \EE_Error
4606
+	 */
4607
+	protected function _create_objects($rows = array())
4608
+	{
4609
+		$array_of_objects = array();
4610
+		if (empty($rows)) {
4611
+			return array();
4612
+		}
4613
+		$count_if_model_has_no_primary_key = 0;
4614
+		$has_primary_key = $this->has_primary_key_field();
4615
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4616
+		foreach ((array)$rows as $row) {
4617
+			if (empty($row)) {
4618
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4619
+				return array();
4620
+			}
4621
+			//check if we've already set this object in the results array,
4622
+			//in which case there's no need to process it further (again)
4623
+			if ($has_primary_key) {
4624
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4625
+					$row,
4626
+					$primary_key_field->get_qualified_column(),
4627
+					$primary_key_field->get_table_column()
4628
+				);
4629
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4630
+					continue;
4631
+				}
4632
+			}
4633
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4634
+			if ( ! $classInstance) {
4635
+				throw new EE_Error(
4636
+					sprintf(
4637
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4638
+						$this->get_this_model_name(),
4639
+						http_build_query($row)
4640
+					)
4641
+				);
4642
+			}
4643
+			//set the timezone on the instantiated objects
4644
+			$classInstance->set_timezone($this->_timezone);
4645
+			//make sure if there is any timezone setting present that we set the timezone for the object
4646
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4647
+			$array_of_objects[$key] = $classInstance;
4648
+			//also, for all the relations of type BelongsTo, see if we can cache
4649
+			//those related models
4650
+			//(we could do this for other relations too, but if there are conditions
4651
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4652
+			//so it requires a little more thought than just caching them immediately...)
4653
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4654
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4655
+					//check if this model's INFO is present. If so, cache it on the model
4656
+					$other_model = $relation_obj->get_other_model();
4657
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4658
+					//if we managed to make a model object from the results, cache it on the main model object
4659
+					if ($other_model_obj_maybe) {
4660
+						//set timezone on these other model objects if they are present
4661
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4662
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4663
+					}
4664
+				}
4665
+			}
4666
+		}
4667
+		return $array_of_objects;
4668
+	}
4669
+
4670
+
4671
+
4672
+	/**
4673
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4674
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4675
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4676
+	 * object (as set in the model_field!).
4677
+	 *
4678
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4679
+	 */
4680
+	public function create_default_object()
4681
+	{
4682
+		$this_model_fields_and_values = array();
4683
+		//setup the row using default values;
4684
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4685
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4686
+		}
4687
+		$className = $this->_get_class_name();
4688
+		$classInstance = EE_Registry::instance()
4689
+									->load_class($className, array($this_model_fields_and_values), false, false);
4690
+		return $classInstance;
4691
+	}
4692
+
4693
+
4694
+
4695
+	/**
4696
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4697
+	 *                             or an stdClass where each property is the name of a column,
4698
+	 * @return EE_Base_Class
4699
+	 * @throws \EE_Error
4700
+	 */
4701
+	public function instantiate_class_from_array_or_object($cols_n_values)
4702
+	{
4703
+		if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4704
+			$cols_n_values = get_object_vars($cols_n_values);
4705
+		}
4706
+		$primary_key = null;
4707
+		//make sure the array only has keys that are fields/columns on this model
4708
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4709
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4710
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4711
+		}
4712
+		$className = $this->_get_class_name();
4713
+		//check we actually found results that we can use to build our model object
4714
+		//if not, return null
4715
+		if ($this->has_primary_key_field()) {
4716
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4717
+				return null;
4718
+			}
4719
+		} else if ($this->unique_indexes()) {
4720
+			$first_column = reset($this_model_fields_n_values);
4721
+			if (empty($first_column)) {
4722
+				return null;
4723
+			}
4724
+		}
4725
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4726
+		if ($primary_key) {
4727
+			$classInstance = $this->get_from_entity_map($primary_key);
4728
+			if ( ! $classInstance) {
4729
+				$classInstance = EE_Registry::instance()
4730
+											->load_class($className,
4731
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4732
+				// add this new object to the entity map
4733
+				$classInstance = $this->add_to_entity_map($classInstance);
4734
+			}
4735
+		} else {
4736
+			$classInstance = EE_Registry::instance()
4737
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4738
+											true, false);
4739
+		}
4740
+		//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.
4741
+		$this->set_timezone($classInstance->get_timezone());
4742
+		return $classInstance;
4743
+	}
4744
+
4745
+
4746
+
4747
+	/**
4748
+	 * Gets the model object from the  entity map if it exists
4749
+	 *
4750
+	 * @param int|string $id the ID of the model object
4751
+	 * @return EE_Base_Class
4752
+	 */
4753
+	public function get_from_entity_map($id)
4754
+	{
4755
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4756
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4757
+	}
4758
+
4759
+
4760
+
4761
+	/**
4762
+	 * add_to_entity_map
4763
+	 * Adds the object to the model's entity mappings
4764
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4765
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4766
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4767
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4768
+	 *        then this method should be called immediately after the update query
4769
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4770
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4771
+	 *
4772
+	 * @param    EE_Base_Class $object
4773
+	 * @throws EE_Error
4774
+	 * @return \EE_Base_Class
4775
+	 */
4776
+	public function add_to_entity_map(EE_Base_Class $object)
4777
+	{
4778
+		$className = $this->_get_class_name();
4779
+		if ( ! $object instanceof $className) {
4780
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4781
+				is_object($object) ? get_class($object) : $object, $className));
4782
+		}
4783
+		/** @var $object EE_Base_Class */
4784
+		if ( ! $object->ID()) {
4785
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4786
+				"event_espresso"), get_class($this)));
4787
+		}
4788
+		// double check it's not already there
4789
+		$classInstance = $this->get_from_entity_map($object->ID());
4790
+		if ($classInstance) {
4791
+			return $classInstance;
4792
+		} else {
4793
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4794
+			return $object;
4795
+		}
4796
+	}
4797
+
4798
+
4799
+
4800
+	/**
4801
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4802
+	 * if no identifier is provided, then the entire entity map is emptied
4803
+	 *
4804
+	 * @param int|string $id the ID of the model object
4805
+	 * @return boolean
4806
+	 */
4807
+	public function clear_entity_map($id = null)
4808
+	{
4809
+		if (empty($id)) {
4810
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4811
+			return true;
4812
+		}
4813
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4814
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4815
+			return true;
4816
+		}
4817
+		return false;
4818
+	}
4819
+
4820
+
4821
+
4822
+	/**
4823
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4824
+	 * Given an array where keys are column (or column alias) names and values,
4825
+	 * returns an array of their corresponding field names and database values
4826
+	 *
4827
+	 * @param array $cols_n_values
4828
+	 * @return array
4829
+	 */
4830
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4831
+	{
4832
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4833
+	}
4834
+
4835
+
4836
+
4837
+	/**
4838
+	 * _deduce_fields_n_values_from_cols_n_values
4839
+	 * Given an array where keys are column (or column alias) names and values,
4840
+	 * returns an array of their corresponding field names and database values
4841
+	 *
4842
+	 * @param string $cols_n_values
4843
+	 * @return array
4844
+	 */
4845
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
4846
+	{
4847
+		$this_model_fields_n_values = array();
4848
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
4849
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
4850
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
4851
+			//there is a primary key on this table and its not set. Use defaults for all its columns
4852
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
4853
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4854
+					if ( ! $field_obj->is_db_only_field()) {
4855
+						//prepare field as if its coming from db
4856
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
4857
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
4858
+					}
4859
+				}
4860
+			} else {
4861
+				//the table's rows existed. Use their values
4862
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
4863
+					if ( ! $field_obj->is_db_only_field()) {
4864
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
4865
+							$cols_n_values, $field_obj->get_qualified_column(),
4866
+							$field_obj->get_table_column()
4867
+						);
4868
+					}
4869
+				}
4870
+			}
4871
+		}
4872
+		return $this_model_fields_n_values;
4873
+	}
4874
+
4875
+
4876
+
4877
+	/**
4878
+	 * @param $cols_n_values
4879
+	 * @param $qualified_column
4880
+	 * @param $regular_column
4881
+	 * @return null
4882
+	 */
4883
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
4884
+	{
4885
+		$value = null;
4886
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
4887
+		//does the field on the model relate to this column retrieved from the db?
4888
+		//or is it a db-only field? (not relating to the model)
4889
+		if (isset($cols_n_values[$qualified_column])) {
4890
+			$value = $cols_n_values[$qualified_column];
4891
+		} elseif (isset($cols_n_values[$regular_column])) {
4892
+			$value = $cols_n_values[$regular_column];
4893
+		}
4894
+		return $value;
4895
+	}
4896
+
4897
+
4898
+
4899
+	/**
4900
+	 * refresh_entity_map_from_db
4901
+	 * Makes sure the model object in the entity map at $id assumes the values
4902
+	 * of the database (opposite of EE_base_Class::save())
4903
+	 *
4904
+	 * @param int|string $id
4905
+	 * @return EE_Base_Class
4906
+	 * @throws \EE_Error
4907
+	 */
4908
+	public function refresh_entity_map_from_db($id)
4909
+	{
4910
+		$obj_in_map = $this->get_from_entity_map($id);
4911
+		if ($obj_in_map) {
4912
+			$wpdb_results = $this->_get_all_wpdb_results(
4913
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
4914
+			);
4915
+			if ($wpdb_results && is_array($wpdb_results)) {
4916
+				$one_row = reset($wpdb_results);
4917
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
4918
+					$obj_in_map->set_from_db($field_name, $db_value);
4919
+				}
4920
+				//clear the cache of related model objects
4921
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4922
+					$obj_in_map->clear_cache($relation_name, null, true);
4923
+				}
4924
+			}
4925
+			return $obj_in_map;
4926
+		} else {
4927
+			return $this->get_one_by_ID($id);
4928
+		}
4929
+	}
4930
+
4931
+
4932
+
4933
+	/**
4934
+	 * refresh_entity_map_with
4935
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
4936
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
4937
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
4938
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
4939
+	 *
4940
+	 * @param int|string    $id
4941
+	 * @param EE_Base_Class $replacing_model_obj
4942
+	 * @return \EE_Base_Class
4943
+	 * @throws \EE_Error
4944
+	 */
4945
+	public function refresh_entity_map_with($id, $replacing_model_obj)
4946
+	{
4947
+		$obj_in_map = $this->get_from_entity_map($id);
4948
+		if ($obj_in_map) {
4949
+			if ($replacing_model_obj instanceof EE_Base_Class) {
4950
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
4951
+					$obj_in_map->set($field_name, $value);
4952
+				}
4953
+				//make the model object in the entity map's cache match the $replacing_model_obj
4954
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
4955
+					$obj_in_map->clear_cache($relation_name, null, true);
4956
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
4957
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
4958
+					}
4959
+				}
4960
+			}
4961
+			return $obj_in_map;
4962
+		} else {
4963
+			$this->add_to_entity_map($replacing_model_obj);
4964
+			return $replacing_model_obj;
4965
+		}
4966
+	}
4967
+
4968
+
4969
+
4970
+	/**
4971
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
4972
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
4973
+	 * require_once($this->_getClassName().".class.php");
4974
+	 *
4975
+	 * @return string
4976
+	 */
4977
+	private function _get_class_name()
4978
+	{
4979
+		return "EE_" . $this->get_this_model_name();
4980
+	}
4981
+
4982
+
4983
+
4984
+	/**
4985
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
4986
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
4987
+	 * it would be 'Events'.
4988
+	 *
4989
+	 * @param int $quantity
4990
+	 * @return string
4991
+	 */
4992
+	public function item_name($quantity = 1)
4993
+	{
4994
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
4995
+	}
4996
+
4997
+
4998
+
4999
+	/**
5000
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5001
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5002
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5003
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5004
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5005
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5006
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5007
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5008
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5009
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5010
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5011
+	 *        return $previousReturnValue.$returnString;
5012
+	 * }
5013
+	 * require('EEM_Answer.model.php');
5014
+	 * $answer=EEM_Answer::instance();
5015
+	 * echo $answer->my_callback('monkeys',100);
5016
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5017
+	 *
5018
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5019
+	 * @param array  $args       array of original arguments passed to the function
5020
+	 * @throws EE_Error
5021
+	 * @return mixed whatever the plugin which calls add_filter decides
5022
+	 */
5023
+	public function __call($methodName, $args)
5024
+	{
5025
+		$className = get_class($this);
5026
+		$tagName = "FHEE__{$className}__{$methodName}";
5027
+		if ( ! has_filter($tagName)) {
5028
+			throw new EE_Error(
5029
+				sprintf(
5030
+					__('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 );',
5031
+						'event_espresso'),
5032
+					$methodName,
5033
+					$className,
5034
+					$tagName,
5035
+					'<br />'
5036
+				)
5037
+			);
5038
+		}
5039
+		return apply_filters($tagName, null, $this, $args);
5040
+	}
5041
+
5042
+
5043
+
5044
+	/**
5045
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5046
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5047
+	 *
5048
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5049
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5050
+	 *                                                       the object's class name
5051
+	 *                                                       or object's ID
5052
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5053
+	 *                                                       exists in the database. If it does not, we add it
5054
+	 * @throws EE_Error
5055
+	 * @return EE_Base_Class
5056
+	 */
5057
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5058
+	{
5059
+		$className = $this->_get_class_name();
5060
+		if ($base_class_obj_or_id instanceof $className) {
5061
+			$model_object = $base_class_obj_or_id;
5062
+		} else {
5063
+			$primary_key_field = $this->get_primary_key_field();
5064
+			if (
5065
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5066
+				&& (
5067
+					is_int($base_class_obj_or_id)
5068
+					|| is_string($base_class_obj_or_id)
5069
+				)
5070
+			) {
5071
+				// assume it's an ID.
5072
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5073
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5074
+			} else if (
5075
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5076
+				&& is_string($base_class_obj_or_id)
5077
+			) {
5078
+				// assume its a string representation of the object
5079
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5080
+			} else {
5081
+				throw new EE_Error(
5082
+					sprintf(
5083
+						__(
5084
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5085
+							'event_espresso'
5086
+						),
5087
+						$base_class_obj_or_id,
5088
+						$this->_get_class_name(),
5089
+						print_r($base_class_obj_or_id, true)
5090
+					)
5091
+				);
5092
+			}
5093
+		}
5094
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5095
+			$model_object->save();
5096
+		}
5097
+		return $model_object;
5098
+	}
5099
+
5100
+
5101
+
5102
+	/**
5103
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5104
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5105
+	 * returns it ID.
5106
+	 *
5107
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5108
+	 * @return int|string depending on the type of this model object's ID
5109
+	 * @throws EE_Error
5110
+	 */
5111
+	public function ensure_is_ID($base_class_obj_or_id)
5112
+	{
5113
+		$className = $this->_get_class_name();
5114
+		if ($base_class_obj_or_id instanceof $className) {
5115
+			/** @var $base_class_obj_or_id EE_Base_Class */
5116
+			$id = $base_class_obj_or_id->ID();
5117
+		} elseif (is_int($base_class_obj_or_id)) {
5118
+			//assume it's an ID
5119
+			$id = $base_class_obj_or_id;
5120
+		} elseif (is_string($base_class_obj_or_id)) {
5121
+			//assume its a string representation of the object
5122
+			$id = $base_class_obj_or_id;
5123
+		} else {
5124
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5125
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5126
+				print_r($base_class_obj_or_id, true)));
5127
+		}
5128
+		return $id;
5129
+	}
5130
+
5131
+
5132
+
5133
+	/**
5134
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5135
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5136
+	 * been sanitized and converted into the appropriate domain.
5137
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5138
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5139
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5140
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5141
+	 * $EVT = EEM_Event::instance(); $old_setting =
5142
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5143
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5144
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5145
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5146
+	 *
5147
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5148
+	 * @return void
5149
+	 */
5150
+	public function assume_values_already_prepared_by_model_object(
5151
+		$values_already_prepared = self::not_prepared_by_model_object
5152
+	) {
5153
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5154
+	}
5155
+
5156
+
5157
+
5158
+	/**
5159
+	 * Read comments for assume_values_already_prepared_by_model_object()
5160
+	 *
5161
+	 * @return int
5162
+	 */
5163
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5164
+	{
5165
+		return $this->_values_already_prepared_by_model_object;
5166
+	}
5167
+
5168
+
5169
+
5170
+	/**
5171
+	 * Gets all the indexes on this model
5172
+	 *
5173
+	 * @return EE_Index[]
5174
+	 */
5175
+	public function indexes()
5176
+	{
5177
+		return $this->_indexes;
5178
+	}
5179
+
5180
+
5181
+
5182
+	/**
5183
+	 * Gets all the Unique Indexes on this model
5184
+	 *
5185
+	 * @return EE_Unique_Index[]
5186
+	 */
5187
+	public function unique_indexes()
5188
+	{
5189
+		$unique_indexes = array();
5190
+		foreach ($this->_indexes as $name => $index) {
5191
+			if ($index instanceof EE_Unique_Index) {
5192
+				$unique_indexes [$name] = $index;
5193
+			}
5194
+		}
5195
+		return $unique_indexes;
5196
+	}
5197
+
5198
+
5199
+
5200
+	/**
5201
+	 * Gets all the fields which, when combined, make the primary key.
5202
+	 * This is usually just an array with 1 element (the primary key), but in cases
5203
+	 * where there is no primary key, it's a combination of fields as defined
5204
+	 * on a primary index
5205
+	 *
5206
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5207
+	 * @throws \EE_Error
5208
+	 */
5209
+	public function get_combined_primary_key_fields()
5210
+	{
5211
+		foreach ($this->indexes() as $index) {
5212
+			if ($index instanceof EE_Primary_Key_Index) {
5213
+				return $index->fields();
5214
+			}
5215
+		}
5216
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5217
+	}
5218
+
5219
+
5220
+
5221
+	/**
5222
+	 * Used to build a primary key string (when the model has no primary key),
5223
+	 * which can be used a unique string to identify this model object.
5224
+	 *
5225
+	 * @param array $cols_n_values keys are field names, values are their values
5226
+	 * @return string
5227
+	 * @throws \EE_Error
5228
+	 */
5229
+	public function get_index_primary_key_string($cols_n_values)
5230
+	{
5231
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5232
+			$this->get_combined_primary_key_fields());
5233
+		return http_build_query($cols_n_values_for_primary_key_index);
5234
+	}
5235
+
5236
+
5237
+
5238
+	/**
5239
+	 * Gets the field values from the primary key string
5240
+	 *
5241
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5242
+	 * @param string $index_primary_key_string
5243
+	 * @return null|array
5244
+	 * @throws \EE_Error
5245
+	 */
5246
+	public function parse_index_primary_key_string($index_primary_key_string)
5247
+	{
5248
+		$key_fields = $this->get_combined_primary_key_fields();
5249
+		//check all of them are in the $id
5250
+		$key_vals_in_combined_pk = array();
5251
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5252
+		foreach ($key_fields as $key_field_name => $field_obj) {
5253
+			if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5254
+				return null;
5255
+			}
5256
+		}
5257
+		return $key_vals_in_combined_pk;
5258
+	}
5259
+
5260
+
5261
+
5262
+	/**
5263
+	 * verifies that an array of key-value pairs for model fields has a key
5264
+	 * for each field comprising the primary key index
5265
+	 *
5266
+	 * @param array $key_vals
5267
+	 * @return boolean
5268
+	 * @throws \EE_Error
5269
+	 */
5270
+	public function has_all_combined_primary_key_fields($key_vals)
5271
+	{
5272
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5273
+		foreach ($keys_it_should_have as $key) {
5274
+			if ( ! isset($key_vals[$key])) {
5275
+				return false;
5276
+			}
5277
+		}
5278
+		return true;
5279
+	}
5280
+
5281
+
5282
+
5283
+	/**
5284
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5285
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5286
+	 *
5287
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5288
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5289
+	 * @throws EE_Error
5290
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5291
+	 *                                                              indexed)
5292
+	 */
5293
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5294
+	{
5295
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5296
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5297
+		} elseif (is_array($model_object_or_attributes_array)) {
5298
+			$attributes_array = $model_object_or_attributes_array;
5299
+		} else {
5300
+			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",
5301
+				"event_espresso"), $model_object_or_attributes_array));
5302
+		}
5303
+		//even copies obviously won't have the same ID, so remove the primary key
5304
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5305
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5306
+			unset($attributes_array[$this->primary_key_name()]);
5307
+		}
5308
+		if (isset($query_params[0])) {
5309
+			$query_params[0] = array_merge($attributes_array, $query_params);
5310
+		} else {
5311
+			$query_params[0] = $attributes_array;
5312
+		}
5313
+		return $this->get_all($query_params);
5314
+	}
5315
+
5316
+
5317
+
5318
+	/**
5319
+	 * Gets the first copy we find. See get_all_copies for more details
5320
+	 *
5321
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5322
+	 * @param array $query_params
5323
+	 * @return EE_Base_Class
5324
+	 * @throws \EE_Error
5325
+	 */
5326
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5327
+	{
5328
+		if ( ! is_array($query_params)) {
5329
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5330
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5331
+					gettype($query_params)), '4.6.0');
5332
+			$query_params = array();
5333
+		}
5334
+		$query_params['limit'] = 1;
5335
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5336
+		if (is_array($copies)) {
5337
+			return array_shift($copies);
5338
+		} else {
5339
+			return null;
5340
+		}
5341
+	}
5342
+
5343
+
5344
+
5345
+	/**
5346
+	 * Updates the item with the specified id. Ignores default query parameters because
5347
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5348
+	 *
5349
+	 * @param array      $fields_n_values keys are field names, values are their new values
5350
+	 * @param int|string $id              the value of the primary key to update
5351
+	 * @return int number of rows updated
5352
+	 * @throws \EE_Error
5353
+	 */
5354
+	public function update_by_ID($fields_n_values, $id)
5355
+	{
5356
+		$query_params = array(
5357
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5358
+			'default_where_conditions' => 'other_models_only',
5359
+		);
5360
+		return $this->update($fields_n_values, $query_params);
5361
+	}
5362
+
5363
+
5364
+
5365
+	/**
5366
+	 * Changes an operator which was supplied to the models into one usable in SQL
5367
+	 *
5368
+	 * @param string $operator_supplied
5369
+	 * @return string an operator which can be used in SQL
5370
+	 * @throws EE_Error
5371
+	 */
5372
+	private function _prepare_operator_for_sql($operator_supplied)
5373
+	{
5374
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5375
+			: null;
5376
+		if ($sql_operator) {
5377
+			return $sql_operator;
5378
+		} else {
5379
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5380
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5381
+		}
5382
+	}
5383
+
5384
+
5385
+
5386
+	/**
5387
+	 * Gets an array where keys are the primary keys and values are their 'names'
5388
+	 * (as determined by the model object's name() function, which is often overridden)
5389
+	 *
5390
+	 * @param array $query_params like get_all's
5391
+	 * @return string[]
5392
+	 * @throws \EE_Error
5393
+	 */
5394
+	public function get_all_names($query_params = array())
5395
+	{
5396
+		$objs = $this->get_all($query_params);
5397
+		$names = array();
5398
+		foreach ($objs as $obj) {
5399
+			$names[$obj->ID()] = $obj->name();
5400
+		}
5401
+		return $names;
5402
+	}
5403
+
5404
+
5405
+
5406
+	/**
5407
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5408
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5409
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5410
+	 * array_keys() on $model_objects.
5411
+	 *
5412
+	 * @param \EE_Base_Class[] $model_objects
5413
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5414
+	 *                                               in the returned array
5415
+	 * @return array
5416
+	 * @throws \EE_Error
5417
+	 */
5418
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5419
+	{
5420
+		if ( ! $this->has_primary_key_field()) {
5421
+			if (WP_DEBUG) {
5422
+				EE_Error::add_error(
5423
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5424
+					__FILE__,
5425
+					__FUNCTION__,
5426
+					__LINE__
5427
+				);
5428
+			}
5429
+		}
5430
+		$IDs = array();
5431
+		foreach ($model_objects as $model_object) {
5432
+			$id = $model_object->ID();
5433
+			if ( ! $id) {
5434
+				if ($filter_out_empty_ids) {
5435
+					continue;
5436
+				}
5437
+				if (WP_DEBUG) {
5438
+					EE_Error::add_error(
5439
+						__(
5440
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5441
+							'event_espresso'
5442
+						),
5443
+						__FILE__,
5444
+						__FUNCTION__,
5445
+						__LINE__
5446
+					);
5447
+				}
5448
+			}
5449
+			$IDs[] = $id;
5450
+		}
5451
+		return $IDs;
5452
+	}
5453
+
5454
+
5455
+
5456
+	/**
5457
+	 * Returns the string used in capabilities relating to this model. If there
5458
+	 * are no capabilities that relate to this model returns false
5459
+	 *
5460
+	 * @return string|false
5461
+	 */
5462
+	public function cap_slug()
5463
+	{
5464
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5465
+	}
5466
+
5467
+
5468
+
5469
+	/**
5470
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5471
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5472
+	 * only returns the cap restrictions array in that context (ie, the array
5473
+	 * at that key)
5474
+	 *
5475
+	 * @param string $context
5476
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5477
+	 * @throws \EE_Error
5478
+	 */
5479
+	public function cap_restrictions($context = EEM_Base::caps_read)
5480
+	{
5481
+		EEM_Base::verify_is_valid_cap_context($context);
5482
+		//check if we ought to run the restriction generator first
5483
+		if (
5484
+			isset($this->_cap_restriction_generators[$context])
5485
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5486
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5487
+		) {
5488
+			$this->_cap_restrictions[$context] = array_merge(
5489
+				$this->_cap_restrictions[$context],
5490
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5491
+			);
5492
+		}
5493
+		//and make sure we've finalized the construction of each restriction
5494
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5495
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5496
+				$where_conditions_obj->_finalize_construct($this);
5497
+			}
5498
+		}
5499
+		return $this->_cap_restrictions[$context];
5500
+	}
5501
+
5502
+
5503
+
5504
+	/**
5505
+	 * Indicating whether or not this model thinks its a wp core model
5506
+	 *
5507
+	 * @return boolean
5508
+	 */
5509
+	public function is_wp_core_model()
5510
+	{
5511
+		return $this->_wp_core_model;
5512
+	}
5513
+
5514
+
5515
+
5516
+	/**
5517
+	 * Gets all the caps that are missing which impose a restriction on
5518
+	 * queries made in this context
5519
+	 *
5520
+	 * @param string $context one of EEM_Base::caps_ constants
5521
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5522
+	 * @throws \EE_Error
5523
+	 */
5524
+	public function caps_missing($context = EEM_Base::caps_read)
5525
+	{
5526
+		$missing_caps = array();
5527
+		$cap_restrictions = $this->cap_restrictions($context);
5528
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5529
+			if ( ! EE_Capabilities::instance()
5530
+								  ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5531
+			) {
5532
+				$missing_caps[$cap] = $restriction_if_no_cap;
5533
+			}
5534
+		}
5535
+		return $missing_caps;
5536
+	}
5537
+
5538
+
5539
+
5540
+	/**
5541
+	 * Gets the mapping from capability contexts to action strings used in capability names
5542
+	 *
5543
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5544
+	 * one of 'read', 'edit', or 'delete'
5545
+	 */
5546
+	public function cap_contexts_to_cap_action_map()
5547
+	{
5548
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5549
+			$this);
5550
+	}
5551
+
5552
+
5553
+
5554
+	/**
5555
+	 * Gets the action string for the specified capability context
5556
+	 *
5557
+	 * @param string $context
5558
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5559
+	 * @throws \EE_Error
5560
+	 */
5561
+	public function cap_action_for_context($context)
5562
+	{
5563
+		$mapping = $this->cap_contexts_to_cap_action_map();
5564
+		if (isset($mapping[$context])) {
5565
+			return $mapping[$context];
5566
+		}
5567
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5568
+			return $action;
5569
+		}
5570
+		throw new EE_Error(
5571
+			sprintf(
5572
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5573
+				$context,
5574
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5575
+			)
5576
+		);
5577
+	}
5578
+
5579
+
5580
+
5581
+	/**
5582
+	 * Returns all the capability contexts which are valid when querying models
5583
+	 *
5584
+	 * @return array
5585
+	 */
5586
+	static public function valid_cap_contexts()
5587
+	{
5588
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5589
+			self::caps_read,
5590
+			self::caps_read_admin,
5591
+			self::caps_edit,
5592
+			self::caps_delete,
5593
+		));
5594
+	}
5595
+
5596
+
5597
+
5598
+	/**
5599
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5600
+	 *
5601
+	 * @param string $context
5602
+	 * @return bool
5603
+	 * @throws \EE_Error
5604
+	 */
5605
+	static public function verify_is_valid_cap_context($context)
5606
+	{
5607
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5608
+		if (in_array($context, $valid_cap_contexts)) {
5609
+			return true;
5610
+		} else {
5611
+			throw new EE_Error(
5612
+				sprintf(
5613
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5614
+						'event_espresso'),
5615
+					$context,
5616
+					'EEM_Base',
5617
+					implode(',', $valid_cap_contexts)
5618
+				)
5619
+			);
5620
+		}
5621
+	}
5622
+
5623
+
5624
+
5625
+	/**
5626
+	 * Clears all the models field caches. This is only useful when a sub-class
5627
+	 * might have added a field or something and these caches might be invalidated
5628
+	 */
5629
+	protected function _invalidate_field_caches()
5630
+	{
5631
+		$this->_cache_foreign_key_to_fields = array();
5632
+		$this->_cached_fields = null;
5633
+		$this->_cached_fields_non_db_only = null;
5634
+	}
5635 5635
 
5636 5636
 
5637 5637
 
Please login to merge, or discard this patch.