Completed
Branch FET-9222-rest-api-writes (4eb34b)
by
unknown
141:37 queued 128:36
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +5870 added lines, -5870 removed lines patch added patch discarded remove patch
@@ -29,5878 +29,5878 @@
 block discarded – undo
29 29
 abstract class EEM_Base extends EE_Base
30 30
 {
31 31
 
32
-    /**
33
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
34
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
35
-     * They almost always WILL NOT, but it's not necessarily a requirement.
36
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
37
-     *
38
-     * @var boolean
39
-     */
40
-    private $_values_already_prepared_by_model_object = 0;
41
-
42
-    /**
43
-     * when $_values_already_prepared_by_model_object equals this, we assume
44
-     * the data is just like form input that needs to have the model fields'
45
-     * prepare_for_set and prepare_for_use_in_db called on it
46
-     */
47
-    const not_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we
51
-     * assume this value is coming from a model object and doesn't need to have
52
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
53
-     */
54
-    const prepared_by_model_object = 1;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we assume
58
-     * the values are already to be used in the database (ie no processing is done
59
-     * on them by the model's fields)
60
-     */
61
-    const prepared_for_use_in_db = 2;
62
-
63
-
64
-    protected $singular_item = 'Item';
65
-
66
-    protected $plural_item   = 'Items';
67
-
68
-    /**
69
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
70
-     */
71
-    protected $_tables;
72
-
73
-    /**
74
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
75
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
76
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
77
-     *
78
-     * @var \EE_Model_Field_Base[][] $_fields
79
-     */
80
-    protected $_fields;
81
-
82
-    /**
83
-     * array of different kinds of relations
84
-     *
85
-     * @var \EE_Model_Relation_Base[] $_model_relations
86
-     */
87
-    protected $_model_relations;
88
-
89
-    /**
90
-     * @var \EE_Index[] $_indexes
91
-     */
92
-    protected $_indexes = array();
93
-
94
-    /**
95
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
96
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
97
-     * by setting the same columns as used in these queries in the query yourself.
98
-     *
99
-     * @var EE_Default_Where_Conditions
100
-     */
101
-    protected $_default_where_conditions_strategy;
102
-
103
-    /**
104
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
105
-     * This is particularly useful when you want something between 'none' and 'default'
106
-     *
107
-     * @var EE_Default_Where_Conditions
108
-     */
109
-    protected $_minimum_where_conditions_strategy;
110
-
111
-    /**
112
-     * String describing how to find the "owner" of this model's objects.
113
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
114
-     * But when there isn't, this indicates which related model, or transiently-related model,
115
-     * has the foreign key to the wp_users table.
116
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
117
-     * related to events, and events have a foreign key to wp_users.
118
-     * On EEM_Transaction, this would be 'Transaction.Event'
119
-     *
120
-     * @var string
121
-     */
122
-    protected $_model_chain_to_wp_user = '';
123
-
124
-    /**
125
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
126
-     * don't need it (particularly CPT models)
127
-     *
128
-     * @var bool
129
-     */
130
-    protected $_ignore_where_strategy = false;
131
-
132
-    /**
133
-     * String used in caps relating to this model. Eg, if the caps relating to this
134
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
135
-     *
136
-     * @var string. If null it hasn't been initialized yet. If false then we
137
-     * have indicated capabilities don't apply to this
138
-     */
139
-    protected $_caps_slug = null;
140
-
141
-    /**
142
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
143
-     * and next-level keys are capability names, and each's value is a
144
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
145
-     * they specify which context to use (ie, frontend, backend, edit or delete)
146
-     * and then each capability in the corresponding sub-array that they're missing
147
-     * adds the where conditions onto the query.
148
-     *
149
-     * @var array
150
-     */
151
-    protected $_cap_restrictions = array(
152
-        self::caps_read       => array(),
153
-        self::caps_read_admin => array(),
154
-        self::caps_edit       => array(),
155
-        self::caps_delete     => array(),
156
-    );
157
-
158
-    /**
159
-     * Array defining which cap restriction generators to use to create default
160
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
161
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
162
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
163
-     * automatically set this to false (not just null).
164
-     *
165
-     * @var EE_Restriction_Generator_Base[]
166
-     */
167
-    protected $_cap_restriction_generators = array();
168
-
169
-    /**
170
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
171
-     */
172
-    const caps_read       = 'read';
173
-
174
-    const caps_read_admin = 'read_admin';
175
-
176
-    const caps_edit       = 'edit';
177
-
178
-    const caps_delete     = 'delete';
179
-
180
-    /**
181
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
182
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
183
-     * maps to 'read' because when looking for relevant permissions we're going to use
184
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
185
-     *
186
-     * @var array
187
-     */
188
-    protected $_cap_contexts_to_cap_action_map = array(
189
-        self::caps_read       => 'read',
190
-        self::caps_read_admin => 'read',
191
-        self::caps_edit       => 'edit',
192
-        self::caps_delete     => 'delete',
193
-    );
194
-
195
-    /**
196
-     * Timezone
197
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
198
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
199
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
200
-     * EE_Datetime_Field data type will have access to it.
201
-     *
202
-     * @var string
203
-     */
204
-    protected $_timezone;
205
-
206
-
207
-    /**
208
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
209
-     * multisite.
210
-     *
211
-     * @var int
212
-     */
213
-    protected static $_model_query_blog_id;
214
-
215
-    /**
216
-     * A copy of _fields, except the array keys are the model names pointed to by
217
-     * the field
218
-     *
219
-     * @var EE_Model_Field_Base[]
220
-     */
221
-    private $_cache_foreign_key_to_fields = array();
222
-
223
-    /**
224
-     * Cached list of all the fields on the model, indexed by their name
225
-     *
226
-     * @var EE_Model_Field_Base[]
227
-     */
228
-    private $_cached_fields = null;
229
-
230
-    /**
231
-     * Cached list of all the fields on the model, except those that are
232
-     * marked as only pertinent to the database
233
-     *
234
-     * @var EE_Model_Field_Base[]
235
-     */
236
-    private $_cached_fields_non_db_only = null;
237
-
238
-    /**
239
-     * A cached reference to the primary key for quick lookup
240
-     *
241
-     * @var EE_Model_Field_Base
242
-     */
243
-    private $_primary_key_field = null;
244
-
245
-    /**
246
-     * Flag indicating whether this model has a primary key or not
247
-     *
248
-     * @var boolean
249
-     */
250
-    protected $_has_primary_key_field = null;
251
-
252
-    /**
253
-     * Whether or not this model is based off a table in WP core only (CPTs should set
254
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
255
-     * This should be true for models that deal with data that should exist independent of EE.
256
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
257
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
258
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
259
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
260
-     * @var boolean
261
-     */
262
-    protected $_wp_core_model = false;
263
-
264
-    /**
265
-     *    List of valid operators that can be used for querying.
266
-     * The keys are all operators we'll accept, the values are the real SQL
267
-     * operators used
268
-     *
269
-     * @var array
270
-     */
271
-    protected $_valid_operators = array(
272
-        '='           => '=',
273
-        '<='          => '<=',
274
-        '<'           => '<',
275
-        '>='          => '>=',
276
-        '>'           => '>',
277
-        '!='          => '!=',
278
-        'LIKE'        => 'LIKE',
279
-        'like'        => 'LIKE',
280
-        'NOT_LIKE'    => 'NOT LIKE',
281
-        'not_like'    => 'NOT LIKE',
282
-        'NOT LIKE'    => 'NOT LIKE',
283
-        'not like'    => 'NOT LIKE',
284
-        'IN'          => 'IN',
285
-        'in'          => 'IN',
286
-        'NOT_IN'      => 'NOT IN',
287
-        'not_in'      => 'NOT IN',
288
-        'NOT IN'      => 'NOT IN',
289
-        'not in'      => 'NOT IN',
290
-        'between'     => 'BETWEEN',
291
-        'BETWEEN'     => 'BETWEEN',
292
-        'IS_NOT_NULL' => 'IS NOT NULL',
293
-        'is_not_null' => 'IS NOT NULL',
294
-        'IS NOT NULL' => 'IS NOT NULL',
295
-        'is not null' => 'IS NOT NULL',
296
-        'IS_NULL'     => 'IS NULL',
297
-        'is_null'     => 'IS NULL',
298
-        'IS NULL'     => 'IS NULL',
299
-        'is null'     => 'IS NULL',
300
-        'REGEXP'      => 'REGEXP',
301
-        'regexp'      => 'REGEXP',
302
-        'NOT_REGEXP'  => 'NOT REGEXP',
303
-        'not_regexp'  => 'NOT REGEXP',
304
-        'NOT REGEXP'  => 'NOT REGEXP',
305
-        'not regexp'  => 'NOT REGEXP',
306
-    );
307
-
308
-    /**
309
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
310
-     *
311
-     * @var array
312
-     */
313
-    protected $_in_style_operators = array('IN', 'NOT IN');
314
-
315
-    /**
316
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
317
-     * '12-31-2012'"
318
-     *
319
-     * @var array
320
-     */
321
-    protected $_between_style_operators = array('BETWEEN');
322
-
323
-    /**
324
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
325
-     * @var array
326
-     */
327
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
328
-    /**
329
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
330
-     * on a join table.
331
-     *
332
-     * @var array
333
-     */
334
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
335
-
336
-    /**
337
-     * Allowed values for $query_params['order'] for ordering in queries
338
-     *
339
-     * @var array
340
-     */
341
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
342
-
343
-    /**
344
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
345
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
346
-     *
347
-     * @var array
348
-     */
349
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
350
-
351
-    /**
352
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
353
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
354
-     *
355
-     * @var array
356
-     */
357
-    private $_allowed_query_params = array(
358
-        0,
359
-        'limit',
360
-        'order_by',
361
-        'group_by',
362
-        'having',
363
-        'force_join',
364
-        'order',
365
-        'on_join_limit',
366
-        'default_where_conditions',
367
-        'caps',
368
-    );
369
-
370
-    /**
371
-     * All the data types that can be used in $wpdb->prepare statements.
372
-     *
373
-     * @var array
374
-     */
375
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
376
-
377
-    /**
378
-     *    EE_Registry Object
379
-     *
380
-     * @var    object
381
-     * @access    protected
382
-     */
383
-    protected $EE = null;
384
-
385
-
386
-    /**
387
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
-     *
389
-     * @var int
390
-     */
391
-    protected $_show_next_x_db_queries = 0;
392
-
393
-    /**
394
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
-     *
397
-     * @var array
398
-     */
399
-    protected $_custom_selections = array();
400
-
401
-    /**
402
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
-     * caches every model object we've fetched from the DB on this request
404
-     *
405
-     * @var array
406
-     */
407
-    protected $_entity_map;
408
-
409
-    /**
410
-     * constant used to show EEM_Base has not yet verified the db on this http request
411
-     */
412
-    const db_verified_none = 0;
413
-
414
-    /**
415
-     * constant used to show EEM_Base has verified the EE core db on this http request,
416
-     * but not the addons' dbs
417
-     */
418
-    const db_verified_core = 1;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
422
-     * the EE core db too)
423
-     */
424
-    const db_verified_addons = 2;
425
-
426
-    /**
427
-     * indicates whether an EEM_Base child has already re-verified the DB
428
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
429
-     * looking like EEM_Base::db_verified_*
430
-     *
431
-     * @var int - 0 = none, 1 = core, 2 = addons
432
-     */
433
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
434
-
435
-    /**
436
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
437
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
438
-     *        registrations for non-trashed tickets for non-trashed datetimes)
439
-     */
440
-    const default_where_conditions_all = 'all';
441
-
442
-    /**
443
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
444
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
445
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
446
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
447
-     *        models which share tables with other models, this can return data for the wrong model.
448
-     */
449
-    const default_where_conditions_this_only = 'this_model_only';
450
-
451
-    /**
452
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
453
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
454
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
455
-     */
456
-    const default_where_conditions_others_only = 'other_models_only';
457
-
458
-    /**
459
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
460
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
461
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
462
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
463
-     *        (regardless of whether those events and venues are trashed)
464
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
465
-     *        events.
466
-     */
467
-    const default_where_conditions_minimum_all = 'minimum';
468
-
469
-    /**
470
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
471
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
472
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
473
-     *        not)
474
-     */
475
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
476
-
477
-    /**
478
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
479
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
480
-     *        it's possible it will return table entries for other models. You should use
481
-     *        EEM_Base::default_where_conditions_minimum_all instead.
482
-     */
483
-    const default_where_conditions_none = 'none';
484
-
485
-
486
-
487
-    /**
488
-     * About all child constructors:
489
-     * they should define the _tables, _fields and _model_relations arrays.
490
-     * Should ALWAYS be called after child constructor.
491
-     * In order to make the child constructors to be as simple as possible, this parent constructor
492
-     * finalizes constructing all the object's attributes.
493
-     * Generally, rather than requiring a child to code
494
-     * $this->_tables = array(
495
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
496
-     *        ...);
497
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
498
-     * each EE_Table has a function to set the table's alias after the constructor, using
499
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
500
-     * do something similar.
501
-     *
502
-     * @param null $timezone
503
-     * @throws \EE_Error
504
-     */
505
-    protected function __construct($timezone = null)
506
-    {
507
-        // check that the model has not been loaded too soon
508
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
-            throw new EE_Error (
510
-                sprintf(
511
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
512
-                        'event_espresso'),
513
-                    get_class($this)
514
-                )
515
-            );
516
-        }
517
-        /**
518
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
519
-         */
520
-        if (empty(EEM_Base::$_model_query_blog_id)) {
521
-            EEM_Base::set_model_query_blog_id();
522
-        }
523
-        /**
524
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
525
-         * just use EE_Register_Model_Extension
526
-         *
527
-         * @var EE_Table_Base[] $_tables
528
-         */
529
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
530
-        foreach ($this->_tables as $table_alias => $table_obj) {
531
-            /** @var $table_obj EE_Table_Base */
532
-            $table_obj->_construct_finalize_with_alias($table_alias);
533
-            if ($table_obj instanceof EE_Secondary_Table) {
534
-                /** @var $table_obj EE_Secondary_Table */
535
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
536
-            }
537
-        }
538
-        /**
539
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
540
-         * EE_Register_Model_Extension
541
-         *
542
-         * @param EE_Model_Field_Base[] $_fields
543
-         */
544
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
545
-        $this->_invalidate_field_caches();
546
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
547
-            if (! array_key_exists($table_alias, $this->_tables)) {
548
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
550
-            }
551
-            foreach ($fields_for_table as $field_name => $field_obj) {
552
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
553
-                //primary key field base has a slightly different _construct_finalize
554
-                /** @var $field_obj EE_Model_Field_Base */
555
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
556
-            }
557
-        }
558
-        // everything is related to Extra_Meta
559
-        if (get_class($this) !== 'EEM_Extra_Meta') {
560
-            //make extra meta related to everything, but don't block deleting things just
561
-            //because they have related extra meta info. For now just orphan those extra meta
562
-            //in the future we should automatically delete them
563
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
564
-        }
565
-        //and change logs
566
-        if (get_class($this) !== 'EEM_Change_Log') {
567
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
568
-        }
569
-        /**
570
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
571
-         * EE_Register_Model_Extension
572
-         *
573
-         * @param EE_Model_Relation_Base[] $_model_relations
574
-         */
575
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
576
-            $this->_model_relations);
577
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
578
-            /** @var $relation_obj EE_Model_Relation_Base */
579
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
580
-        }
581
-        foreach ($this->_indexes as $index_name => $index_obj) {
582
-            /** @var $index_obj EE_Index */
583
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
584
-        }
585
-        $this->set_timezone($timezone);
586
-        //finalize default where condition strategy, or set default
587
-        if (! $this->_default_where_conditions_strategy) {
588
-            //nothing was set during child constructor, so set default
589
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590
-        }
591
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
592
-        if (! $this->_minimum_where_conditions_strategy) {
593
-            //nothing was set during child constructor, so set default
594
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595
-        }
596
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
597
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
598
-        //to indicate to NOT set it, set it to the logical default
599
-        if ($this->_caps_slug === null) {
600
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
601
-        }
602
-        //initialize the standard cap restriction generators if none were specified by the child constructor
603
-        if ($this->_cap_restriction_generators !== false) {
604
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
606
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
607
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608
-                        new EE_Restriction_Generator_Protected(),
609
-                        $cap_context,
610
-                        $this
611
-                    );
612
-                }
613
-            }
614
-        }
615
-        //if there are cap restriction generators, use them to make the default cap restrictions
616
-        if ($this->_cap_restriction_generators !== false) {
617
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
-                if (! $generator_object) {
619
-                    continue;
620
-                }
621
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
622
-                    throw new EE_Error(
623
-                        sprintf(
624
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
625
-                                'event_espresso'),
626
-                            $context,
627
-                            $this->get_this_model_name()
628
-                        )
629
-                    );
630
-                }
631
-                $action = $this->cap_action_for_context($context);
632
-                if (! $generator_object->construction_finalized()) {
633
-                    $generator_object->_construct_finalize($this, $action);
634
-                }
635
-            }
636
-        }
637
-        do_action('AHEE__' . get_class($this) . '__construct__end');
638
-    }
639
-
640
-
641
-
642
-    /**
643
-     * Used to set the $_model_query_blog_id static property.
644
-     *
645
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
646
-     *                      value for get_current_blog_id() will be used.
647
-     */
648
-    public static function set_model_query_blog_id($blog_id = 0)
649
-    {
650
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
651
-    }
652
-
653
-
654
-
655
-    /**
656
-     * Returns whatever is set as the internal $model_query_blog_id.
657
-     *
658
-     * @return int
659
-     */
660
-    public static function get_model_query_blog_id()
661
-    {
662
-        return EEM_Base::$_model_query_blog_id;
663
-    }
664
-
665
-
666
-
667
-    /**
668
-     *        This function is a singleton method used to instantiate the Espresso_model object
669
-     *
670
-     * @access public
671
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
672
-     *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
673
-     *                         date time model field objects.  Default is NULL (and will be assumed using the set
674
-     *                         timezone in the 'timezone_string' wp option)
675
-     * @return static (as in the concrete child class)
676
-     */
677
-    public static function instance($timezone = null)
678
-    {
679
-        // check if instance of Espresso_model already exists
680
-        if (! static::$_instance instanceof static) {
681
-            // instantiate Espresso_model
682
-            static::$_instance = new static($timezone);
683
-        }
684
-        //we might have a timezone set, let set_timezone decide what to do with it
685
-        static::$_instance->set_timezone($timezone);
686
-        // Espresso_model object
687
-        return static::$_instance;
688
-    }
689
-
690
-
691
-
692
-    /**
693
-     * resets the model and returns it
694
-     *
695
-     * @param null | string $timezone
696
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
697
-     * all its properties reset; if it wasn't instantiated, returns null)
698
-     */
699
-    public static function reset($timezone = null)
700
-    {
701
-        if (static::$_instance instanceof EEM_Base) {
702
-            //let's try to NOT swap out the current instance for a new one
703
-            //because if someone has a reference to it, we can't remove their reference
704
-            //so it's best to keep using the same reference, but change the original object
705
-            //reset all its properties to their original values as defined in the class
706
-            $r = new ReflectionClass(get_class(static::$_instance));
707
-            $static_properties = $r->getStaticProperties();
708
-            foreach ($r->getDefaultProperties() as $property => $value) {
709
-                //don't set instance to null like it was originally,
710
-                //but it's static anyways, and we're ignoring static properties (for now at least)
711
-                if (! isset($static_properties[$property])) {
712
-                    static::$_instance->{$property} = $value;
713
-                }
714
-            }
715
-            //and then directly call its constructor again, like we would if we
716
-            //were creating a new one
717
-            static::$_instance->__construct($timezone);
718
-            return self::instance();
719
-        }
720
-        return null;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
727
-     *
728
-     * @param  boolean $translated return localized strings or JUST the array.
729
-     * @return array
730
-     * @throws \EE_Error
731
-     */
732
-    public function status_array($translated = false)
733
-    {
734
-        if (! array_key_exists('Status', $this->_model_relations)) {
735
-            return array();
736
-        }
737
-        $model_name = $this->get_this_model_name();
738
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
739
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
740
-        $status_array = array();
741
-        foreach ($stati as $status) {
742
-            $status_array[$status->ID()] = $status->get('STS_code');
743
-        }
744
-        return $translated
745
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
746
-            : $status_array;
747
-    }
748
-
749
-
750
-
751
-    /**
752
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
753
-     *
754
-     * @param array $query_params             {
755
-     * @var array $0 (where) array {
756
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
757
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
758
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
759
-     *                                        conditions based on related models (and even
760
-     *                                        models-related-to-related-models) prepend the model's name onto the field
761
-     *                                        name. Eg,
762
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
763
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
764
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
765
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
766
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
767
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
768
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
769
-     *                                        to Venues (even when each of those models actually consisted of two
770
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
771
-     *                                        just having
772
-     *                                        "Venue.VNU_ID", you could have
773
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
774
-     *                                        events are related to Registrations, which are related to Attendees). You
775
-     *                                        can take it even further with
776
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
777
-     *                                        (from the default of '='), change the value to an numerically-indexed
778
-     *                                        array, where the first item in the list is the operator. eg: array(
779
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
780
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
781
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
782
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
783
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
784
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
785
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
786
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
787
-     *                                        the value is a field, simply provide a third array item (true) to the
788
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
789
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
790
-     *                                        Note: you can also use related model field names like you would any other
791
-     *                                        field name. eg:
792
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
793
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
794
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
795
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
796
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
797
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
798
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
799
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
800
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
801
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
802
-     *                                        "stick" until you specify an AND. eg
803
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
804
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
805
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
806
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
807
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
808
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
809
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
810
-     *                                        too, eg:
811
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
812
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
813
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
814
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
815
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
816
-     *                                        the OFFSET, the 2nd is the LIMIT
817
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
818
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
819
-     *                                        following format array('on_join_limit'
820
-     *                                        => array( 'table_alias', array(1,2) ) ).
821
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
822
-     *                                        values are either 'ASC' or 'DESC'.
823
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
824
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
825
-     *                                        DESC..." respectively. Like the
826
-     *                                        'where' conditions, these fields can be on related models. Eg
827
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
828
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
829
-     *                                        Attendee, Price, Datetime, etc.)
830
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
831
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
832
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
833
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
834
-     *                                        order by the primary key. Eg,
835
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
836
-     *                                        //(will join with the Datetime model's table(s) and order by its field
837
-     *                                        DTT_EVT_start) or
838
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
839
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
840
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
841
-     *                                        'group_by'=>'VNU_ID', or
842
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
843
-     *                                        if no
844
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
845
-     *                                        model's primary key (or combined primary keys). This avoids some
846
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
847
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
848
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
849
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
850
-     *                                        results)
851
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
852
-     *                                        array where values are models to be joined in the query.Eg
853
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
854
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
855
-     *                                        probably only want to do this in hopes of increasing efficiency, as
856
-     *                                        related models which belongs to the current model
857
-     *                                        (ie, the current model has a foreign key to them, like how Registration
858
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
859
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
860
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
861
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
862
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
863
-     *                                        default where conditions set it to 'other_models_only'. If you only want
864
-     *                                        this model's default where conditions added to the query, use
865
-     *                                        'this_model_only'. If you want to use all default where conditions
866
-     *                                        (default), set to 'all'.
867
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
868
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
869
-     *                                        everything? Or should we only show the current user items they should be
870
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
871
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
872
-     *                                        }
873
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
874
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
875
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
876
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
877
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
878
-     *                                        array( array(
879
-     *                                        'OR'=>array(
880
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
881
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
882
-     *                                        )
883
-     *                                        ),
884
-     *                                        'limit'=>10,
885
-     *                                        'group_by'=>'TXN_ID'
886
-     *                                        ));
887
-     *                                        get all the answers to the question titled "shirt size" for event with id
888
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
889
-     *                                        'Question.QST_display_text'=>'shirt size',
890
-     *                                        'Registration.Event.EVT_ID'=>12
891
-     *                                        ),
892
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
893
-     *                                        ));
894
-     * @throws \EE_Error
895
-     */
896
-    public function get_all($query_params = array())
897
-    {
898
-        if (isset($query_params['limit'])
899
-            && ! isset($query_params['group_by'])
900
-        ) {
901
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
902
-        }
903
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
904
-    }
905
-
906
-
907
-
908
-    /**
909
-     * Modifies the query parameters so we only get back model objects
910
-     * that "belong" to the current user
911
-     *
912
-     * @param array $query_params @see EEM_Base::get_all()
913
-     * @return array like EEM_Base::get_all
914
-     */
915
-    public function alter_query_params_to_only_include_mine($query_params = array())
916
-    {
917
-        $wp_user_field_name = $this->wp_user_field_name();
918
-        if ($wp_user_field_name) {
919
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
920
-        }
921
-        return $query_params;
922
-    }
923
-
924
-
925
-
926
-    /**
927
-     * Returns the name of the field's name that points to the WP_User table
928
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
929
-     * foreign key to the WP_User table)
930
-     *
931
-     * @return string|boolean string on success, boolean false when there is no
932
-     * foreign key to the WP_User table
933
-     */
934
-    public function wp_user_field_name()
935
-    {
936
-        try {
937
-            if (! empty($this->_model_chain_to_wp_user)) {
938
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
939
-                $last_model_name = end($models_to_follow_to_wp_users);
940
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
941
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
942
-            } else {
943
-                $model_with_fk_to_wp_users = $this;
944
-                $model_chain_to_wp_user = '';
945
-            }
946
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
947
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
948
-        } catch (EE_Error $e) {
949
-            return false;
950
-        }
951
-    }
952
-
953
-
954
-
955
-    /**
956
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
957
-     * (or transiently-related model) has a foreign key to the wp_users table;
958
-     * useful for finding if model objects of this type are 'owned' by the current user.
959
-     * This is an empty string when the foreign key is on this model and when it isn't,
960
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
961
-     * (or transiently-related model)
962
-     *
963
-     * @return string
964
-     */
965
-    public function model_chain_to_wp_user()
966
-    {
967
-        return $this->_model_chain_to_wp_user;
968
-    }
969
-
970
-
971
-
972
-    /**
973
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
974
-     * like how registrations don't have a foreign key to wp_users, but the
975
-     * events they are for are), or is unrelated to wp users.
976
-     * generally available
977
-     *
978
-     * @return boolean
979
-     */
980
-    public function is_owned()
981
-    {
982
-        if ($this->model_chain_to_wp_user()) {
983
-            return true;
984
-        } else {
985
-            try {
986
-                $this->get_foreign_key_to('WP_User');
987
-                return true;
988
-            } catch (EE_Error $e) {
989
-                return false;
990
-            }
991
-        }
992
-    }
993
-
994
-
995
-
996
-    /**
997
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
998
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
999
-     * the model)
1000
-     *
1001
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1002
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1003
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1004
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1005
-     *                                  override this and set the select to "*", or a specific column name, like
1006
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1007
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1008
-     *                                  the aliases used to refer to this selection, and values are to be
1009
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1010
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1011
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1012
-     * @throws \EE_Error
1013
-     */
1014
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1015
-    {
1016
-        // remember the custom selections, if any, and type cast as array
1017
-        // (unless $columns_to_select is an object, then just set as an empty array)
1018
-        // Note: (array) 'some string' === array( 'some string' )
1019
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1020
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1021
-        $select_expressions = $columns_to_select !== null
1022
-            ? $this->_construct_select_from_input($columns_to_select)
1023
-            : $this->_construct_default_select_sql($model_query_info);
1024
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1025
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1026
-    }
1027
-
1028
-
1029
-
1030
-    /**
1031
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1032
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1033
-     * take care of joins, field preparation etc.
1034
-     *
1035
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1036
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1039
-     *                                  override this and set the select to "*", or a specific column name, like
1040
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
-     *                                  the aliases used to refer to this selection, and values are to be
1043
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
-     * @throws \EE_Error
1047
-     */
1048
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
-    {
1050
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
-    }
1052
-
1053
-
1054
-
1055
-    /**
1056
-     * For creating a custom select statement
1057
-     *
1058
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
-     *                                 SQL, and 1=>is the datatype
1061
-     * @throws EE_Error
1062
-     * @return string
1063
-     */
1064
-    private function _construct_select_from_input($columns_to_select)
1065
-    {
1066
-        if (is_array($columns_to_select)) {
1067
-            $select_sql_array = array();
1068
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
-                    throw new EE_Error(
1071
-                        sprintf(
1072
-                            __(
1073
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
-                                "event_espresso"
1075
-                            ),
1076
-                            $selection_and_datatype,
1077
-                            $alias
1078
-                        )
1079
-                    );
1080
-                }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1082
-                    throw new EE_Error(
1083
-                        sprintf(
1084
-                            __(
1085
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
-                                "event_espresso"
1087
-                            ),
1088
-                            $selection_and_datatype[1],
1089
-                            $selection_and_datatype[0],
1090
-                            $alias,
1091
-                            implode(",", $this->_valid_wpdb_data_types)
1092
-                        )
1093
-                    );
1094
-                }
1095
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
-            }
1097
-            $columns_to_select_string = implode(", ", $select_sql_array);
1098
-        } else {
1099
-            $columns_to_select_string = $columns_to_select;
1100
-        }
1101
-        return $columns_to_select_string;
1102
-    }
1103
-
1104
-
1105
-
1106
-    /**
1107
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
-     *
1109
-     * @return string
1110
-     * @throws \EE_Error
1111
-     */
1112
-    public function primary_key_name()
1113
-    {
1114
-        return $this->get_primary_key_field()->get_name();
1115
-    }
1116
-
1117
-
1118
-
1119
-    /**
1120
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1121
-     * If there is no primary key on this model, $id is treated as primary key string
1122
-     *
1123
-     * @param mixed $id int or string, depending on the type of the model's primary key
1124
-     * @return EE_Base_Class
1125
-     */
1126
-    public function get_one_by_ID($id)
1127
-    {
1128
-        if ($this->get_from_entity_map($id)) {
1129
-            return $this->get_from_entity_map($id);
1130
-        }
1131
-        return $this->get_one(
1132
-            $this->alter_query_params_to_restrict_by_ID(
1133
-                $id,
1134
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
-            )
1136
-        );
1137
-    }
1138
-
1139
-
1140
-
1141
-    /**
1142
-     * Alters query parameters to only get items with this ID are returned.
1143
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1144
-     * or could just be a simple primary key ID
1145
-     *
1146
-     * @param int   $id
1147
-     * @param array $query_params
1148
-     * @return array of normal query params, @see EEM_Base::get_all
1149
-     * @throws \EE_Error
1150
-     */
1151
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1152
-    {
1153
-        if (! isset($query_params[0])) {
1154
-            $query_params[0] = array();
1155
-        }
1156
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1157
-        if ($conditions_from_id === null) {
1158
-            $query_params[0][$this->primary_key_name()] = $id;
1159
-        } else {
1160
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1161
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1162
-        }
1163
-        return $query_params;
1164
-    }
1165
-
1166
-
1167
-
1168
-    /**
1169
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1170
-     * array. If no item is found, null is returned.
1171
-     *
1172
-     * @param array $query_params like EEM_Base's $query_params variable.
1173
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1174
-     * @throws \EE_Error
1175
-     */
1176
-    public function get_one($query_params = array())
1177
-    {
1178
-        if (! is_array($query_params)) {
1179
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1180
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1181
-                    gettype($query_params)), '4.6.0');
1182
-            $query_params = array();
1183
-        }
1184
-        $query_params['limit'] = 1;
1185
-        $items = $this->get_all($query_params);
1186
-        if (empty($items)) {
1187
-            return null;
1188
-        } else {
1189
-            return array_shift($items);
1190
-        }
1191
-    }
1192
-
1193
-
1194
-
1195
-    /**
1196
-     * Returns the next x number of items in sequence from the given value as
1197
-     * found in the database matching the given query conditions.
1198
-     *
1199
-     * @param mixed $current_field_value    Value used for the reference point.
1200
-     * @param null  $field_to_order_by      What field is used for the
1201
-     *                                      reference point.
1202
-     * @param int   $limit                  How many to return.
1203
-     * @param array $query_params           Extra conditions on the query.
1204
-     * @param null  $columns_to_select      If left null, then an array of
1205
-     *                                      EE_Base_Class objects is returned,
1206
-     *                                      otherwise you can indicate just the
1207
-     *                                      columns you want returned.
1208
-     * @return EE_Base_Class[]|array
1209
-     * @throws \EE_Error
1210
-     */
1211
-    public function next_x(
1212
-        $current_field_value,
1213
-        $field_to_order_by = null,
1214
-        $limit = 1,
1215
-        $query_params = array(),
1216
-        $columns_to_select = null
1217
-    ) {
1218
-        return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1219
-            $columns_to_select);
1220
-    }
1221
-
1222
-
1223
-
1224
-    /**
1225
-     * Returns the previous x number of items in sequence from the given value
1226
-     * as found in the database matching the given query conditions.
1227
-     *
1228
-     * @param mixed $current_field_value    Value used for the reference point.
1229
-     * @param null  $field_to_order_by      What field is used for the
1230
-     *                                      reference point.
1231
-     * @param int   $limit                  How many to return.
1232
-     * @param array $query_params           Extra conditions on the query.
1233
-     * @param null  $columns_to_select      If left null, then an array of
1234
-     *                                      EE_Base_Class objects is returned,
1235
-     *                                      otherwise you can indicate just the
1236
-     *                                      columns you want returned.
1237
-     * @return EE_Base_Class[]|array
1238
-     * @throws \EE_Error
1239
-     */
1240
-    public function previous_x(
1241
-        $current_field_value,
1242
-        $field_to_order_by = null,
1243
-        $limit = 1,
1244
-        $query_params = array(),
1245
-        $columns_to_select = null
1246
-    ) {
1247
-        return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1248
-            $columns_to_select);
1249
-    }
1250
-
1251
-
1252
-
1253
-    /**
1254
-     * Returns the next item in sequence from the given value as found in the
1255
-     * database matching the given query conditions.
1256
-     *
1257
-     * @param mixed $current_field_value    Value used for the reference point.
1258
-     * @param null  $field_to_order_by      What field is used for the
1259
-     *                                      reference point.
1260
-     * @param array $query_params           Extra conditions on the query.
1261
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1262
-     *                                      object is returned, otherwise you
1263
-     *                                      can indicate just the columns you
1264
-     *                                      want and a single array indexed by
1265
-     *                                      the columns will be returned.
1266
-     * @return EE_Base_Class|null|array()
1267
-     * @throws \EE_Error
1268
-     */
1269
-    public function next(
1270
-        $current_field_value,
1271
-        $field_to_order_by = null,
1272
-        $query_params = array(),
1273
-        $columns_to_select = null
1274
-    ) {
1275
-        $results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1276
-            $columns_to_select);
1277
-        return empty($results) ? null : reset($results);
1278
-    }
1279
-
1280
-
1281
-
1282
-    /**
1283
-     * Returns the previous item in sequence from the given value as found in
1284
-     * the database matching the given query conditions.
1285
-     *
1286
-     * @param mixed $current_field_value    Value used for the reference point.
1287
-     * @param null  $field_to_order_by      What field is used for the
1288
-     *                                      reference point.
1289
-     * @param array $query_params           Extra conditions on the query.
1290
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1291
-     *                                      object is returned, otherwise you
1292
-     *                                      can indicate just the columns you
1293
-     *                                      want and a single array indexed by
1294
-     *                                      the columns will be returned.
1295
-     * @return EE_Base_Class|null|array()
1296
-     * @throws EE_Error
1297
-     */
1298
-    public function previous(
1299
-        $current_field_value,
1300
-        $field_to_order_by = null,
1301
-        $query_params = array(),
1302
-        $columns_to_select = null
1303
-    ) {
1304
-        $results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1305
-            $columns_to_select);
1306
-        return empty($results) ? null : reset($results);
1307
-    }
1308
-
1309
-
1310
-
1311
-    /**
1312
-     * Returns the a consecutive number of items in sequence from the given
1313
-     * value as found in the database matching the given query conditions.
1314
-     *
1315
-     * @param mixed  $current_field_value   Value used for the reference point.
1316
-     * @param string $operand               What operand is used for the sequence.
1317
-     * @param string $field_to_order_by     What field is used for the reference point.
1318
-     * @param int    $limit                 How many to return.
1319
-     * @param array  $query_params          Extra conditions on the query.
1320
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1321
-     *                                      otherwise you can indicate just the columns you want returned.
1322
-     * @return EE_Base_Class[]|array
1323
-     * @throws EE_Error
1324
-     */
1325
-    protected function _get_consecutive(
1326
-        $current_field_value,
1327
-        $operand = '>',
1328
-        $field_to_order_by = null,
1329
-        $limit = 1,
1330
-        $query_params = array(),
1331
-        $columns_to_select = null
1332
-    ) {
1333
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1334
-        if (empty($field_to_order_by)) {
1335
-            if ($this->has_primary_key_field()) {
1336
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1337
-            } else {
1338
-                if (WP_DEBUG) {
1339
-                    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).',
1340
-                        'event_espresso'));
1341
-                }
1342
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1343
-                return array();
1344
-            }
1345
-        }
1346
-        if (! is_array($query_params)) {
1347
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1348
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1349
-                    gettype($query_params)), '4.6.0');
1350
-            $query_params = array();
1351
-        }
1352
-        //let's add the where query param for consecutive look up.
1353
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1354
-        $query_params['limit'] = $limit;
1355
-        //set direction
1356
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1357
-        $query_params['order_by'] = $operand === '>'
1358
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1359
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1360
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1361
-        if (empty($columns_to_select)) {
1362
-            return $this->get_all($query_params);
1363
-        } else {
1364
-            //getting just the fields
1365
-            return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1366
-        }
1367
-    }
1368
-
1369
-
1370
-
1371
-    /**
1372
-     * This sets the _timezone property after model object has been instantiated.
1373
-     *
1374
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1375
-     */
1376
-    public function set_timezone($timezone)
1377
-    {
1378
-        if ($timezone !== null) {
1379
-            $this->_timezone = $timezone;
1380
-        }
1381
-        //note we need to loop through relations and set the timezone on those objects as well.
1382
-        foreach ($this->_model_relations as $relation) {
1383
-            $relation->set_timezone($timezone);
1384
-        }
1385
-        //and finally we do the same for any datetime fields
1386
-        foreach ($this->_fields as $field) {
1387
-            if ($field instanceof EE_Datetime_Field) {
1388
-                $field->set_timezone($timezone);
1389
-            }
1390
-        }
1391
-    }
1392
-
1393
-
1394
-
1395
-    /**
1396
-     * This just returns whatever is set for the current timezone.
1397
-     *
1398
-     * @access public
1399
-     * @return string
1400
-     */
1401
-    public function get_timezone()
1402
-    {
1403
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1404
-        if (empty($this->_timezone)) {
1405
-            foreach ($this->_fields as $field) {
1406
-                if ($field instanceof EE_Datetime_Field) {
1407
-                    $this->set_timezone($field->get_timezone());
1408
-                    break;
1409
-                }
1410
-            }
1411
-        }
1412
-        //if timezone STILL empty then return the default timezone for the site.
1413
-        if (empty($this->_timezone)) {
1414
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1415
-        }
1416
-        return $this->_timezone;
1417
-    }
1418
-
1419
-
1420
-
1421
-    /**
1422
-     * This returns the date formats set for the given field name and also ensures that
1423
-     * $this->_timezone property is set correctly.
1424
-     *
1425
-     * @since 4.6.x
1426
-     * @param string $field_name The name of the field the formats are being retrieved for.
1427
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1428
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1429
-     * @return array formats in an array with the date format first, and the time format last.
1430
-     */
1431
-    public function get_formats_for($field_name, $pretty = false)
1432
-    {
1433
-        $field_settings = $this->field_settings_for($field_name);
1434
-        //if not a valid EE_Datetime_Field then throw error
1435
-        if (! $field_settings instanceof EE_Datetime_Field) {
1436
-            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.',
1437
-                'event_espresso'), $field_name));
1438
-        }
1439
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1440
-        //the field.
1441
-        $this->_timezone = $field_settings->get_timezone();
1442
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1443
-    }
1444
-
1445
-
1446
-
1447
-    /**
1448
-     * This returns the current time in a format setup for a query on this model.
1449
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1450
-     * it will return:
1451
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1452
-     *  NOW
1453
-     *  - or a unix timestamp (equivalent to time())
1454
-     *
1455
-     * @since 4.6.x
1456
-     * @param string $field_name       The field the current time is needed for.
1457
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1458
-     *                                 formatted string matching the set format for the field in the set timezone will
1459
-     *                                 be returned.
1460
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1461
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1462
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1463
-     *                                 exception is triggered.
1464
-     */
1465
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1466
-    {
1467
-        $formats = $this->get_formats_for($field_name);
1468
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1469
-        if ($timestamp) {
1470
-            return $DateTime->format('U');
1471
-        }
1472
-        //not returning timestamp, so return formatted string in timezone.
1473
-        switch ($what) {
1474
-            case 'time' :
1475
-                return $DateTime->format($formats[1]);
1476
-                break;
1477
-            case 'date' :
1478
-                return $DateTime->format($formats[0]);
1479
-                break;
1480
-            default :
1481
-                return $DateTime->format(implode(' ', $formats));
1482
-                break;
1483
-        }
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1490
-     * for the model are.  Returns a DateTime object.
1491
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1492
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1493
-     * ignored.
1494
-     *
1495
-     * @param string $field_name      The field being setup.
1496
-     * @param string $timestring      The date time string being used.
1497
-     * @param string $incoming_format The format for the time string.
1498
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1499
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1500
-     *                                format is
1501
-     *                                'U', this is ignored.
1502
-     * @return DateTime
1503
-     * @throws \EE_Error
1504
-     */
1505
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1506
-    {
1507
-        //just using this to ensure the timezone is set correctly internally
1508
-        $this->get_formats_for($field_name);
1509
-        //load EEH_DTT_Helper
1510
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1511
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1512
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1513
-    }
1514
-
1515
-
1516
-
1517
-    /**
1518
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1519
-     *
1520
-     * @return EE_Table_Base[]
1521
-     */
1522
-    public function get_tables()
1523
-    {
1524
-        return $this->_tables;
1525
-    }
1526
-
1527
-
1528
-
1529
-    /**
1530
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1531
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1532
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1533
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1534
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1535
-     * model object with EVT_ID = 1
1536
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1537
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1538
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1539
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1540
-     * are not specified)
1541
-     *
1542
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1543
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1544
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1545
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1546
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1547
-     *                                         ID=34, we'd use this method as follows:
1548
-     *                                         EEM_Transaction::instance()->update(
1549
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1550
-     *                                         array(array('TXN_ID'=>34)));
1551
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1552
-     *                                         in client code into what's expected to be stored on each field. Eg,
1553
-     *                                         consider updating Question's QST_admin_label field is of type
1554
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1555
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1556
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1557
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1558
-     *                                         TRUE, it is assumed that you've already called
1559
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1560
-     *                                         malicious javascript. However, if
1561
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1562
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1563
-     *                                         and every other field, before insertion. We provide this parameter
1564
-     *                                         because model objects perform their prepare_for_set function on all
1565
-     *                                         their values, and so don't need to be called again (and in many cases,
1566
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1567
-     *                                         prepare_for_set method...)
1568
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1569
-     *                                         in this model's entity map according to $fields_n_values that match
1570
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1571
-     *                                         by setting this to FALSE, but be aware that model objects being used
1572
-     *                                         could get out-of-sync with the database
1573
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1574
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1575
-     *                                         bad)
1576
-     * @throws \EE_Error
1577
-     */
1578
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1579
-    {
1580
-        if (! is_array($query_params)) {
1581
-            EE_Error::doing_it_wrong('EEM_Base::update',
1582
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1583
-                    gettype($query_params)), '4.6.0');
1584
-            $query_params = array();
1585
-        }
1586
-        /**
1587
-         * Action called before a model update call has been made.
1588
-         *
1589
-         * @param EEM_Base $model
1590
-         * @param array    $fields_n_values the updated fields and their new values
1591
-         * @param array    $query_params    @see EEM_Base::get_all()
1592
-         */
1593
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1594
-        /**
1595
-         * Filters the fields about to be updated given the query parameters. You can provide the
1596
-         * $query_params to $this->get_all() to find exactly which records will be updated
1597
-         *
1598
-         * @param array    $fields_n_values fields and their new values
1599
-         * @param EEM_Base $model           the model being queried
1600
-         * @param array    $query_params    see EEM_Base::get_all()
1601
-         */
1602
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1603
-            $query_params);
1604
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1605
-        //to do that, for each table, verify that it's PK isn't null.
1606
-        $tables = $this->get_tables();
1607
-        //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
1608
-        //NOTE: we should make this code more efficient by NOT querying twice
1609
-        //before the real update, but that needs to first go through ALPHA testing
1610
-        //as it's dangerous. says Mike August 8 2014
1611
-        //we want to make sure the default_where strategy is ignored
1612
-        $this->_ignore_where_strategy = true;
1613
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1614
-        foreach ($wpdb_select_results as $wpdb_result) {
1615
-            // type cast stdClass as array
1616
-            $wpdb_result = (array)$wpdb_result;
1617
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1618
-            if ($this->has_primary_key_field()) {
1619
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1620
-            } else {
1621
-                //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)
1622
-                $main_table_pk_value = null;
1623
-            }
1624
-            //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
1625
-            //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
1626
-            if (count($tables) > 1) {
1627
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1628
-                //in that table, and so we'll want to insert one
1629
-                foreach ($tables as $table_obj) {
1630
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1631
-                    //if there is no private key for this table on the results, it means there's no entry
1632
-                    //in this table, right? so insert a row in the current table, using any fields available
1633
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1634
-                           && $wpdb_result[$this_table_pk_column])
1635
-                    ) {
1636
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1637
-                            $main_table_pk_value);
1638
-                        //if we died here, report the error
1639
-                        if (! $success) {
1640
-                            return false;
1641
-                        }
1642
-                    }
1643
-                }
1644
-            }
1645
-            //				//and now check that if we have cached any models by that ID on the model, that
1646
-            //				//they also get updated properly
1647
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1648
-            //				if( $model_object ){
1649
-            //					foreach( $fields_n_values as $field => $value ){
1650
-            //						$model_object->set($field, $value);
1651
-            //let's make sure default_where strategy is followed now
1652
-            $this->_ignore_where_strategy = false;
1653
-        }
1654
-        //if we want to keep model objects in sync, AND
1655
-        //if this wasn't called from a model object (to update itself)
1656
-        //then we want to make sure we keep all the existing
1657
-        //model objects in sync with the db
1658
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1659
-            if ($this->has_primary_key_field()) {
1660
-                $model_objs_affected_ids = $this->get_col($query_params);
1661
-            } else {
1662
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1663
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1664
-                $model_objs_affected_ids = array();
1665
-                foreach ($models_affected_key_columns as $row) {
1666
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1667
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1668
-                }
1669
-            }
1670
-            if (! $model_objs_affected_ids) {
1671
-                //wait wait wait- if nothing was affected let's stop here
1672
-                return 0;
1673
-            }
1674
-            foreach ($model_objs_affected_ids as $id) {
1675
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1676
-                if ($model_obj_in_entity_map) {
1677
-                    foreach ($fields_n_values as $field => $new_value) {
1678
-                        $model_obj_in_entity_map->set($field, $new_value);
1679
-                    }
1680
-                }
1681
-            }
1682
-            //if there is a primary key on this model, we can now do a slight optimization
1683
-            if ($this->has_primary_key_field()) {
1684
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1685
-                $query_params = array(
1686
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1687
-                    'limit'                    => count($model_objs_affected_ids),
1688
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1689
-                );
1690
-            }
1691
-        }
1692
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1693
-        $SQL = "UPDATE "
1694
-               . $model_query_info->get_full_join_sql()
1695
-               . " SET "
1696
-               . $this->_construct_update_sql($fields_n_values)
1697
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1698
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1699
-        /**
1700
-         * Action called after a model update call has been made.
1701
-         *
1702
-         * @param EEM_Base $model
1703
-         * @param array    $fields_n_values the updated fields and their new values
1704
-         * @param array    $query_params    @see EEM_Base::get_all()
1705
-         * @param int      $rows_affected
1706
-         */
1707
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1708
-        return $rows_affected;//how many supposedly got updated
1709
-    }
1710
-
1711
-
1712
-
1713
-    /**
1714
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1715
-     * are teh values of the field specified (or by default the primary key field)
1716
-     * that matched the query params. Note that you should pass the name of the
1717
-     * model FIELD, not the database table's column name.
1718
-     *
1719
-     * @param array  $query_params @see EEM_Base::get_all()
1720
-     * @param string $field_to_select
1721
-     * @return array just like $wpdb->get_col()
1722
-     * @throws \EE_Error
1723
-     */
1724
-    public function get_col($query_params = array(), $field_to_select = null)
1725
-    {
1726
-        if ($field_to_select) {
1727
-            $field = $this->field_settings_for($field_to_select);
1728
-        } elseif ($this->has_primary_key_field()) {
1729
-            $field = $this->get_primary_key_field();
1730
-        } else {
1731
-            //no primary key, just grab the first column
1732
-            $field = reset($this->field_settings());
1733
-        }
1734
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1735
-        $select_expressions = $field->get_qualified_column();
1736
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1737
-        return $this->_do_wpdb_query('get_col', array($SQL));
1738
-    }
1739
-
1740
-
1741
-
1742
-    /**
1743
-     * Returns a single column value for a single row from the database
1744
-     *
1745
-     * @param array  $query_params    @see EEM_Base::get_all()
1746
-     * @param string $field_to_select @see EEM_Base::get_col()
1747
-     * @return string
1748
-     * @throws \EE_Error
1749
-     */
1750
-    public function get_var($query_params = array(), $field_to_select = null)
1751
-    {
1752
-        $query_params['limit'] = 1;
1753
-        $col = $this->get_col($query_params, $field_to_select);
1754
-        if (! empty($col)) {
1755
-            return reset($col);
1756
-        } else {
1757
-            return null;
1758
-        }
1759
-    }
1760
-
1761
-
1762
-
1763
-    /**
1764
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1765
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1766
-     * injection, but currently no further filtering is done
1767
-     *
1768
-     * @global      $wpdb
1769
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1770
-     *                               be updated to in the DB
1771
-     * @return string of SQL
1772
-     * @throws \EE_Error
1773
-     */
1774
-    public function _construct_update_sql($fields_n_values)
1775
-    {
1776
-        /** @type WPDB $wpdb */
1777
-        global $wpdb;
1778
-        $cols_n_values = array();
1779
-        foreach ($fields_n_values as $field_name => $value) {
1780
-            $field_obj = $this->field_settings_for($field_name);
1781
-            //if the value is NULL, we want to assign the value to that.
1782
-            //wpdb->prepare doesn't really handle that properly
1783
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1784
-            $value_sql = $prepared_value === null ? 'NULL'
1785
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1786
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1787
-        }
1788
-        return implode(",", $cols_n_values);
1789
-    }
1790
-
1791
-
1792
-
1793
-    /**
1794
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1795
-     * Performs a HARD delete, meaning the database row should always be removed,
1796
-     * not just have a flag field on it switched
1797
-     * Wrapper for EEM_Base::delete_permanently()
1798
-     *
1799
-     * @param mixed $id
1800
-     * @param boolean $allow_blocking
1801
-     * @return int the number of rows deleted
1802
-     * @throws \EE_Error
1803
-     */
1804
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1805
-    {
1806
-        return $this->delete_permanently(
1807
-            array(
1808
-                array($this->get_primary_key_field()->get_name() => $id),
1809
-                'limit' => 1,
1810
-            ),
1811
-            $allow_blocking
1812
-        );
1813
-    }
1814
-
1815
-
1816
-
1817
-    /**
1818
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1819
-     * Wrapper for EEM_Base::delete()
1820
-     *
1821
-     * @param mixed $id
1822
-     * @param boolean $allow_blocking
1823
-     * @return int the number of rows deleted
1824
-     * @throws \EE_Error
1825
-     */
1826
-    public function delete_by_ID($id, $allow_blocking = true)
1827
-    {
1828
-        return $this->delete(
1829
-            array(
1830
-                array($this->get_primary_key_field()->get_name() => $id),
1831
-                'limit' => 1,
1832
-            ),
1833
-            $allow_blocking
1834
-        );
1835
-    }
1836
-
1837
-
1838
-
1839
-    /**
1840
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1841
-     * meaning if the model has a field that indicates its been "trashed" or
1842
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1843
-     *
1844
-     * @see EEM_Base::delete_permanently
1845
-     * @param array   $query_params
1846
-     * @param boolean $allow_blocking
1847
-     * @return int how many rows got deleted
1848
-     * @throws \EE_Error
1849
-     */
1850
-    public function delete($query_params, $allow_blocking = true)
1851
-    {
1852
-        return $this->delete_permanently($query_params, $allow_blocking);
1853
-    }
1854
-
1855
-
1856
-
1857
-    /**
1858
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1859
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1860
-     * as archived, not actually deleted
1861
-     *
1862
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1863
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1864
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1865
-     *                                deletes regardless of other objects which may depend on it. Its generally
1866
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1867
-     *                                DB
1868
-     * @return int how many rows got deleted
1869
-     * @throws \EE_Error
1870
-     */
1871
-    public function delete_permanently($query_params, $allow_blocking = true)
1872
-    {
1873
-        /**
1874
-         * Action called just before performing a real deletion query. You can use the
1875
-         * model and its $query_params to find exactly which items will be deleted
1876
-         *
1877
-         * @param EEM_Base $model
1878
-         * @param array    $query_params   @see EEM_Base::get_all()
1879
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1880
-         *                                 to block (prevent) this deletion
1881
-         */
1882
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1883
-        //some MySQL databases may be running safe mode, which may restrict
1884
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1885
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1886
-        //to delete them
1887
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1888
-        $deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1889
-        if ($deletion_where) {
1890
-            //echo "objects for deletion:";var_dump($objects_for_deletion);
1891
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1892
-            $table_aliases = array_keys($this->_tables);
1893
-            $SQL = "DELETE "
1894
-                   . implode(", ", $table_aliases)
1895
-                   . " FROM "
1896
-                   . $model_query_info->get_full_join_sql()
1897
-                   . " WHERE "
1898
-                   . $deletion_where;
1899
-            //		/echo "delete sql:$SQL";
1900
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1901
-        } else {
1902
-            $rows_deleted = 0;
1903
-        }
1904
-        //and lastly make sure those items are removed from the entity map; if they could be put into it at all
1905
-        if ($this->has_primary_key_field()) {
1906
-            foreach ($items_for_deletion as $item_for_deletion_row) {
1907
-                $pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1908
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1909
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1910
-                }
1911
-            }
1912
-        }
1913
-        /**
1914
-         * Action called just after performing a real deletion query. Although at this point the
1915
-         * items should have been deleted
1916
-         *
1917
-         * @param EEM_Base $model
1918
-         * @param array    $query_params @see EEM_Base::get_all()
1919
-         * @param int      $rows_deleted
1920
-         */
1921
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1922
-        return $rows_deleted;//how many supposedly got deleted
1923
-    }
1924
-
1925
-
1926
-
1927
-    /**
1928
-     * Checks all the relations that throw error messages when there are blocking related objects
1929
-     * for related model objects. If there are any related model objects on those relations,
1930
-     * adds an EE_Error, and return true
1931
-     *
1932
-     * @param EE_Base_Class|int $this_model_obj_or_id
1933
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1934
-     *                                                 should be ignored when determining whether there are related
1935
-     *                                                 model objects which block this model object's deletion. Useful
1936
-     *                                                 if you know A is related to B and are considering deleting A,
1937
-     *                                                 but want to see if A has any other objects blocking its deletion
1938
-     *                                                 before removing the relation between A and B
1939
-     * @return boolean
1940
-     * @throws \EE_Error
1941
-     */
1942
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1943
-    {
1944
-        //first, if $ignore_this_model_obj was supplied, get its model
1945
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1946
-            $ignored_model = $ignore_this_model_obj->get_model();
1947
-        } else {
1948
-            $ignored_model = null;
1949
-        }
1950
-        //now check all the relations of $this_model_obj_or_id and see if there
1951
-        //are any related model objects blocking it?
1952
-        $is_blocked = false;
1953
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
1954
-            if ($relation_obj->block_delete_if_related_models_exist()) {
1955
-                //if $ignore_this_model_obj was supplied, then for the query
1956
-                //on that model needs to be told to ignore $ignore_this_model_obj
1957
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1958
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1959
-                        array(
1960
-                            $ignored_model->get_primary_key_field()->get_name() => array(
1961
-                                '!=',
1962
-                                $ignore_this_model_obj->ID(),
1963
-                            ),
1964
-                        ),
1965
-                    ));
1966
-                } else {
1967
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1968
-                }
1969
-                if ($related_model_objects) {
1970
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1971
-                    $is_blocked = true;
1972
-                }
1973
-            }
1974
-        }
1975
-        return $is_blocked;
1976
-    }
1977
-
1978
-
1979
-
1980
-    /**
1981
-     * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1982
-     * well.
1983
-     *
1984
-     * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1985
-     * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1986
-     *                                      info that blocks it (ie, there' sno other data that depends on this data);
1987
-     *                                      if false, deletes regardless of other objects which may depend on it. Its
1988
-     *                                      generally advisable to always leave this as TRUE, otherwise you could
1989
-     *                                      easily corrupt your DB
1990
-     * @throws EE_Error
1991
-     * @return string    everything that comes after the WHERE statement.
1992
-     */
1993
-    protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1994
-    {
1995
-        if ($this->has_primary_key_field()) {
1996
-            $primary_table = $this->_get_main_table();
1997
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
1998
-            $other_tables = $this->_get_other_tables();
1999
-            /**
2000
-             * @var EE_Primary_Key_Field_Base[] $other_tables_pk_fields  keys are table aliases
2001
-             */
2002
-            $other_tables_pk_fields = array();
2003
-            /**
2004
-             * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2005
-             */
2006
-            $other_tables_fk_fields = array();
2007
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2008
-                $other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2009
-                $other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2010
-            }
2011
-            $deletes = $query = array();
2012
-            foreach ($objects_for_deletion as $delete_object) {
2013
-                //before we mark this object for deletion,
2014
-                //make sure there's no related objects blocking its deletion (if we're checking)
2015
-                if (
2016
-                    $allow_blocking
2017
-                    && $this->delete_is_blocked_by_related_models(
2018
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()]
2019
-                    )
2020
-                ) {
2021
-                    continue;
2022
-                }
2023
-                //primary table deletes
2024
-                if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2025
-
2026
-                    $deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2027
-                        $delete_object[$primary_table->get_fully_qualified_pk_column()],
2028
-                        $primary_table_pk_field
2029
-                    );
2030
-                }
2031
-                //other tables
2032
-                if (! empty($other_tables)) {
2033
-                    foreach ($other_tables as $other_table_alias => $other_table_obj) {
2034
-                        $other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2035
-                        $other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
2036
-                        //first check if we've got the foreign key column here.
2037
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_fk_column()])) {
2038
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2039
-                                $delete_object[$other_table_obj->get_fully_qualified_fk_column()],
2040
-                                $other_table_fk_field
2041
-                            );
2042
-                        }
2043
-                        // wait! it's entirely possible that we'll have a the primary key
2044
-                        // for this table in here, if it's a foreign key for one of the other secondary tables
2045
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_column()])) {
2046
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2047
-                                $delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2048
-                                $other_table_pk_field
2049
-                            );
2050
-                        }
2051
-                        // finally, it is possible that the fk for this table is found
2052
-                        // in the fully qualified pk column for the fk table, so let's see if that's there!
2053
-                        if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_on_fk_table()])) {
2054
-                            $deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2055
-                                $delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2056
-                                $other_table_pk_field
2057
-                            );
2058
-                        }
2059
-                    }
2060
-                }
2061
-            }
2062
-            //we should have deletes now, so let's just go through and setup the where statement
2063
-            foreach ($deletes as $column => $values) {
2064
-                //make sure we have unique $values;
2065
-                $values = array_unique($values);
2066
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
-            }
2068
-            return ! empty($query) ? implode(' AND ', $query) : '';
2069
-        }
2070
-        $combined_primary_key_fields = $this->get_combined_primary_key_fields();
2071
-        if (count($combined_primary_key_fields) > 1) {
2072
-            $ways_to_identify_a_row = array();
2073
-            //note: because there's no primary key, that means nothing else  can be pointing to this model, right?
2074
-            foreach ($objects_for_deletion as $delete_object) {
2075
-                $combined_primary_key_row_values = array();
2076
-                foreach ($combined_primary_key_fields as $field_in_combined_primary_key) {
2077
-                    if ($field_in_combined_primary_key instanceof EE_Model_Field_Base) {
2078
-                        $combined_primary_key_row_values[] = $field_in_combined_primary_key->get_qualified_column()
2079
-                                                           . "="
2080
-                                                           . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2081
-                    }
2082
-                }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2084
-            }
2085
-            return implode(" OR ", $ways_to_identify_a_row);
2086
-        } else {
2087
-            //so there's no primary key and no combined key...
2088
-            //sorry, can't help you
2089
-            throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
-                "event_espresso"), get_class($this)));
2091
-        }
2092
-    }
2093
-
2094
-
2095
-    /**
2096
-     * Gets the model field by the fully qualified name
2097
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2098
-     * @return EE_Model_Field_Base
2099
-     */
2100
-    public function get_field_by_column($qualified_column_name)
2101
-    {
2102
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2103
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2104
-               return $field_obj;
2105
-           }
2106
-       }
2107
-        throw new EE_Error(
2108
-            sprintf(
2109
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2110
-                $this->get_this_model_name(),
2111
-                $qualified_column_name
2112
-            )
2113
-        );
2114
-    }
2115
-
2116
-
2117
-
2118
-    /**
2119
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2120
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2121
-     * column
2122
-     *
2123
-     * @param array  $query_params   like EEM_Base::get_all's
2124
-     * @param string $field_to_count field on model to count by (not column name)
2125
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2126
-     *                               that by the setting $distinct to TRUE;
2127
-     * @return int
2128
-     * @throws \EE_Error
2129
-     */
2130
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2131
-    {
2132
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2133
-        if ($field_to_count) {
2134
-            $field_obj = $this->field_settings_for($field_to_count);
2135
-            $column_to_count = $field_obj->get_qualified_column();
2136
-        } elseif ($this->has_primary_key_field()) {
2137
-            $pk_field_obj = $this->get_primary_key_field();
2138
-            $column_to_count = $pk_field_obj->get_qualified_column();
2139
-        } else {
2140
-            //there's no primary key
2141
-            //if we're counting distinct items, and there's no primary key,
2142
-            //we need to list out the columns for distinction;
2143
-            //otherwise we can just use star
2144
-            if ($distinct) {
2145
-                $columns_to_use = array();
2146
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2147
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2148
-                }
2149
-                $column_to_count = implode(',', $columns_to_use);
2150
-            } else {
2151
-                $column_to_count = '*';
2152
-            }
2153
-        }
2154
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2155
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2157
-    }
2158
-
2159
-
2160
-
2161
-    /**
2162
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2163
-     *
2164
-     * @param array  $query_params like EEM_Base::get_all
2165
-     * @param string $field_to_sum name of field (array key in $_fields array)
2166
-     * @return float
2167
-     * @throws \EE_Error
2168
-     */
2169
-    public function sum($query_params, $field_to_sum = null)
2170
-    {
2171
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2172
-        if ($field_to_sum) {
2173
-            $field_obj = $this->field_settings_for($field_to_sum);
2174
-        } else {
2175
-            $field_obj = $this->get_primary_key_field();
2176
-        }
2177
-        $column_to_count = $field_obj->get_qualified_column();
2178
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2179
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2180
-        $data_type = $field_obj->get_wpdb_data_type();
2181
-        if ($data_type === '%d' || $data_type === '%s') {
2182
-            return (float)$return_value;
2183
-        } else {//must be %f
2184
-            return (float)$return_value;
2185
-        }
2186
-    }
2187
-
2188
-
2189
-
2190
-    /**
2191
-     * Just calls the specified method on $wpdb with the given arguments
2192
-     * Consolidates a little extra error handling code
2193
-     *
2194
-     * @param string $wpdb_method
2195
-     * @param array  $arguments_to_provide
2196
-     * @throws EE_Error
2197
-     * @global wpdb  $wpdb
2198
-     * @return mixed
2199
-     */
2200
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2201
-    {
2202
-        //if we're in maintenance mode level 2, DON'T run any queries
2203
-        //because level 2 indicates the database needs updating and
2204
-        //is probably out of sync with the code
2205
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2206
-            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.",
2207
-                "event_espresso")));
2208
-        }
2209
-        /** @type WPDB $wpdb */
2210
-        global $wpdb;
2211
-        if (! method_exists($wpdb, $wpdb_method)) {
2212
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2213
-                'event_espresso'), $wpdb_method));
2214
-        }
2215
-        if (WP_DEBUG) {
2216
-            $old_show_errors_value = $wpdb->show_errors;
2217
-            $wpdb->show_errors(false);
2218
-        }
2219
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2220
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2221
-        if (WP_DEBUG) {
2222
-            $wpdb->show_errors($old_show_errors_value);
2223
-            if (! empty($wpdb->last_error)) {
2224
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2225
-            } elseif ($result === false) {
2226
-                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"',
2227
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2228
-            }
2229
-        } elseif ($result === false) {
2230
-            EE_Error::add_error(
2231
-                sprintf(
2232
-                    __('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"',
2233
-                        'event_espresso'),
2234
-                    $wpdb_method,
2235
-                    var_export($arguments_to_provide, true),
2236
-                    $wpdb->last_error
2237
-                ),
2238
-                __FILE__,
2239
-                __FUNCTION__,
2240
-                __LINE__
2241
-            );
2242
-        }
2243
-        return $result;
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Attempts to run the indicated WPDB method with the provided arguments,
2250
-     * and if there's an error tries to verify the DB is correct. Uses
2251
-     * the static property EEM_Base::$_db_verification_level to determine whether
2252
-     * we should try to fix the EE core db, the addons, or just give up
2253
-     *
2254
-     * @param string $wpdb_method
2255
-     * @param array  $arguments_to_provide
2256
-     * @return mixed
2257
-     */
2258
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2259
-    {
2260
-        /** @type WPDB $wpdb */
2261
-        global $wpdb;
2262
-        $wpdb->last_error = null;
2263
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2264
-        // was there an error running the query? but we don't care on new activations
2265
-        // (we're going to setup the DB anyway on new activations)
2266
-        if (($result === false || ! empty($wpdb->last_error))
2267
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2268
-        ) {
2269
-            switch (EEM_Base::$_db_verification_level) {
2270
-                case EEM_Base::db_verified_none :
2271
-                    // let's double-check core's DB
2272
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2273
-                    break;
2274
-                case EEM_Base::db_verified_core :
2275
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2276
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2277
-                    break;
2278
-                case EEM_Base::db_verified_addons :
2279
-                    // ummmm... you in trouble
2280
-                    return $result;
2281
-                    break;
2282
-            }
2283
-            if (! empty($error_message)) {
2284
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2285
-                trigger_error($error_message);
2286
-            }
2287
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2288
-        }
2289
-        return $result;
2290
-    }
2291
-
2292
-
2293
-
2294
-    /**
2295
-     * Verifies the EE core database is up-to-date and records that we've done it on
2296
-     * EEM_Base::$_db_verification_level
2297
-     *
2298
-     * @param string $wpdb_method
2299
-     * @param array  $arguments_to_provide
2300
-     * @return string
2301
-     */
2302
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2303
-    {
2304
-        /** @type WPDB $wpdb */
2305
-        global $wpdb;
2306
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2307
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2308
-        $error_message = sprintf(
2309
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2310
-                'event_espresso'),
2311
-            $wpdb->last_error,
2312
-            $wpdb_method,
2313
-            wp_json_encode($arguments_to_provide)
2314
-        );
2315
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2316
-        return $error_message;
2317
-    }
2318
-
2319
-
2320
-
2321
-    /**
2322
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2323
-     * EEM_Base::$_db_verification_level
2324
-     *
2325
-     * @param $wpdb_method
2326
-     * @param $arguments_to_provide
2327
-     * @return string
2328
-     */
2329
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2330
-    {
2331
-        /** @type WPDB $wpdb */
2332
-        global $wpdb;
2333
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2334
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2335
-        $error_message = sprintf(
2336
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2337
-                'event_espresso'),
2338
-            $wpdb->last_error,
2339
-            $wpdb_method,
2340
-            wp_json_encode($arguments_to_provide)
2341
-        );
2342
-        EE_System::instance()->initialize_addons();
2343
-        return $error_message;
2344
-    }
2345
-
2346
-
2347
-
2348
-    /**
2349
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2350
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2351
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2352
-     * ..."
2353
-     *
2354
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2355
-     * @return string
2356
-     */
2357
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2358
-    {
2359
-        return " FROM " . $model_query_info->get_full_join_sql() .
2360
-               $model_query_info->get_where_sql() .
2361
-               $model_query_info->get_group_by_sql() .
2362
-               $model_query_info->get_having_sql() .
2363
-               $model_query_info->get_order_by_sql() .
2364
-               $model_query_info->get_limit_sql();
2365
-    }
2366
-
2367
-
2368
-
2369
-    /**
2370
-     * Set to easily debug the next X queries ran from this model.
2371
-     *
2372
-     * @param int $count
2373
-     */
2374
-    public function show_next_x_db_queries($count = 1)
2375
-    {
2376
-        $this->_show_next_x_db_queries = $count;
2377
-    }
2378
-
2379
-
2380
-
2381
-    /**
2382
-     * @param $sql_query
2383
-     */
2384
-    public function show_db_query_if_previously_requested($sql_query)
2385
-    {
2386
-        if ($this->_show_next_x_db_queries > 0) {
2387
-            echo $sql_query;
2388
-            $this->_show_next_x_db_queries--;
2389
-        }
2390
-    }
2391
-
2392
-
2393
-
2394
-    /**
2395
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2396
-     * There are the 3 cases:
2397
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2398
-     * $otherModelObject has no ID, it is first saved.
2399
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2400
-     * has no ID, it is first saved.
2401
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2402
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2403
-     * join table
2404
-     *
2405
-     * @param        EE_Base_Class                     /int $thisModelObject
2406
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2407
-     * @param string $relationName                     , key in EEM_Base::_relations
2408
-     *                                                 an attendee to a group, you also want to specify which role they
2409
-     *                                                 will have in that group. So you would use this parameter to
2410
-     *                                                 specify array('role-column-name'=>'role-id')
2411
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2412
-     *                                                 to for relation to methods that allow you to further specify
2413
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2414
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2415
-     *                                                 because these will be inserted in any new rows created as well.
2416
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2417
-     * @throws \EE_Error
2418
-     */
2419
-    public function add_relationship_to(
2420
-        $id_or_obj,
2421
-        $other_model_id_or_obj,
2422
-        $relationName,
2423
-        $extra_join_model_fields_n_values = array()
2424
-    ) {
2425
-        $relation_obj = $this->related_settings_for($relationName);
2426
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2427
-    }
2428
-
2429
-
2430
-
2431
-    /**
2432
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2433
-     * There are the 3 cases:
2434
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2435
-     * error
2436
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2437
-     * an error
2438
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2439
-     *
2440
-     * @param        EE_Base_Class /int $id_or_obj
2441
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2442
-     * @param string $relationName key in EEM_Base::_relations
2443
-     * @return boolean of success
2444
-     * @throws \EE_Error
2445
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2446
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2447
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2448
-     *                             because these will be inserted in any new rows created as well.
2449
-     */
2450
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2451
-    {
2452
-        $relation_obj = $this->related_settings_for($relationName);
2453
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2454
-    }
2455
-
2456
-
2457
-
2458
-    /**
2459
-     * @param mixed           $id_or_obj
2460
-     * @param string          $relationName
2461
-     * @param array           $where_query_params
2462
-     * @param EE_Base_Class[] objects to which relations were removed
2463
-     * @return \EE_Base_Class[]
2464
-     * @throws \EE_Error
2465
-     */
2466
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2467
-    {
2468
-        $relation_obj = $this->related_settings_for($relationName);
2469
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2470
-    }
2471
-
2472
-
2473
-
2474
-    /**
2475
-     * Gets all the related items of the specified $model_name, using $query_params.
2476
-     * Note: by default, we remove the "default query params"
2477
-     * because we want to get even deleted items etc.
2478
-     *
2479
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2480
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2481
-     * @param array  $query_params like EEM_Base::get_all
2482
-     * @return EE_Base_Class[]
2483
-     * @throws \EE_Error
2484
-     */
2485
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2486
-    {
2487
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2488
-        $relation_settings = $this->related_settings_for($model_name);
2489
-        return $relation_settings->get_all_related($model_obj, $query_params);
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * Deletes all the model objects across the relation indicated by $model_name
2496
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2497
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2498
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2499
-     *
2500
-     * @param EE_Base_Class|int|string $id_or_obj
2501
-     * @param string                   $model_name
2502
-     * @param array                    $query_params
2503
-     * @return int how many deleted
2504
-     * @throws \EE_Error
2505
-     */
2506
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2507
-    {
2508
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2509
-        $relation_settings = $this->related_settings_for($model_name);
2510
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2511
-    }
2512
-
2513
-
2514
-
2515
-    /**
2516
-     * Hard deletes all the model objects across the relation indicated by $model_name
2517
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2518
-     * the model objects can't be hard deleted because of blocking related model objects,
2519
-     * just does a soft-delete on them instead.
2520
-     *
2521
-     * @param EE_Base_Class|int|string $id_or_obj
2522
-     * @param string                   $model_name
2523
-     * @param array                    $query_params
2524
-     * @return int how many deleted
2525
-     * @throws \EE_Error
2526
-     */
2527
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2528
-    {
2529
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2530
-        $relation_settings = $this->related_settings_for($model_name);
2531
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2532
-    }
2533
-
2534
-
2535
-
2536
-    /**
2537
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2538
-     * unless otherwise specified in the $query_params
2539
-     *
2540
-     * @param        int             /EE_Base_Class $id_or_obj
2541
-     * @param string $model_name     like 'Event', or 'Registration'
2542
-     * @param array  $query_params   like EEM_Base::get_all's
2543
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2544
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2545
-     *                               that by the setting $distinct to TRUE;
2546
-     * @return int
2547
-     * @throws \EE_Error
2548
-     */
2549
-    public function count_related(
2550
-        $id_or_obj,
2551
-        $model_name,
2552
-        $query_params = array(),
2553
-        $field_to_count = null,
2554
-        $distinct = false
2555
-    ) {
2556
-        $related_model = $this->get_related_model_obj($model_name);
2557
-        //we're just going to use the query params on the related model's normal get_all query,
2558
-        //except add a condition to say to match the current mod
2559
-        if (! isset($query_params['default_where_conditions'])) {
2560
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2561
-        }
2562
-        $this_model_name = $this->get_this_model_name();
2563
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2564
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2565
-        return $related_model->count($query_params, $field_to_count, $distinct);
2566
-    }
2567
-
2568
-
2569
-
2570
-    /**
2571
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2572
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2573
-     *
2574
-     * @param        int           /EE_Base_Class $id_or_obj
2575
-     * @param string $model_name   like 'Event', or 'Registration'
2576
-     * @param array  $query_params like EEM_Base::get_all's
2577
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2578
-     * @return float
2579
-     * @throws \EE_Error
2580
-     */
2581
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2582
-    {
2583
-        $related_model = $this->get_related_model_obj($model_name);
2584
-        if (! is_array($query_params)) {
2585
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2586
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2587
-                    gettype($query_params)), '4.6.0');
2588
-            $query_params = array();
2589
-        }
2590
-        //we're just going to use the query params on the related model's normal get_all query,
2591
-        //except add a condition to say to match the current mod
2592
-        if (! isset($query_params['default_where_conditions'])) {
2593
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2594
-        }
2595
-        $this_model_name = $this->get_this_model_name();
2596
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2597
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2598
-        return $related_model->sum($query_params, $field_to_sum);
2599
-    }
2600
-
2601
-
2602
-
2603
-    /**
2604
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2605
-     * $modelObject
2606
-     *
2607
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2608
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2609
-     * @param array               $query_params     like EEM_Base::get_all's
2610
-     * @return EE_Base_Class
2611
-     * @throws \EE_Error
2612
-     */
2613
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2614
-    {
2615
-        $query_params['limit'] = 1;
2616
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2617
-        if ($results) {
2618
-            return array_shift($results);
2619
-        } else {
2620
-            return null;
2621
-        }
2622
-    }
2623
-
2624
-
2625
-
2626
-    /**
2627
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2628
-     *
2629
-     * @return string
2630
-     */
2631
-    public function get_this_model_name()
2632
-    {
2633
-        return str_replace("EEM_", "", get_class($this));
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2640
-     *
2641
-     * @return EE_Any_Foreign_Model_Name_Field
2642
-     * @throws EE_Error
2643
-     */
2644
-    public function get_field_containing_related_model_name()
2645
-    {
2646
-        foreach ($this->field_settings(true) as $field) {
2647
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2648
-                $field_with_model_name = $field;
2649
-            }
2650
-        }
2651
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2652
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2653
-                $this->get_this_model_name()));
2654
-        }
2655
-        return $field_with_model_name;
2656
-    }
2657
-
2658
-
2659
-
2660
-    /**
2661
-     * Inserts a new entry into the database, for each table.
2662
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2663
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2664
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2665
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2666
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2667
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2668
-     *
2669
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2670
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2671
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2672
-     *                              of EEM_Base)
2673
-     * @return int new primary key on main table that got inserted
2674
-     * @throws EE_Error
2675
-     */
2676
-    public function insert($field_n_values)
2677
-    {
2678
-        /**
2679
-         * Filters the fields and their values before inserting an item using the models
2680
-         *
2681
-         * @param array    $fields_n_values keys are the fields and values are their new values
2682
-         * @param EEM_Base $model           the model used
2683
-         */
2684
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2685
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2686
-            $main_table = $this->_get_main_table();
2687
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2688
-            if ($new_id !== false) {
2689
-                foreach ($this->_get_other_tables() as $other_table) {
2690
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2691
-                }
2692
-            }
2693
-            /**
2694
-             * Done just after attempting to insert a new model object
2695
-             *
2696
-             * @param EEM_Base   $model           used
2697
-             * @param array      $fields_n_values fields and their values
2698
-             * @param int|string the              ID of the newly-inserted model object
2699
-             */
2700
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2701
-            return $new_id;
2702
-        } else {
2703
-            return false;
2704
-        }
2705
-    }
2706
-
2707
-
2708
-
2709
-    /**
2710
-     * Checks that the result would satisfy the unique indexes on this model
2711
-     *
2712
-     * @param array  $field_n_values
2713
-     * @param string $action
2714
-     * @return boolean
2715
-     * @throws \EE_Error
2716
-     */
2717
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2718
-    {
2719
-        foreach ($this->unique_indexes() as $index_name => $index) {
2720
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2721
-            if ($this->exists(array($uniqueness_where_params))) {
2722
-                EE_Error::add_error(
2723
-                    sprintf(
2724
-                        __(
2725
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2726
-                            "event_espresso"
2727
-                        ),
2728
-                        $action,
2729
-                        $this->_get_class_name(),
2730
-                        $index_name,
2731
-                        implode(",", $index->field_names()),
2732
-                        http_build_query($uniqueness_where_params)
2733
-                    ),
2734
-                    __FILE__,
2735
-                    __FUNCTION__,
2736
-                    __LINE__
2737
-                );
2738
-                return false;
2739
-            }
2740
-        }
2741
-        return true;
2742
-    }
2743
-
2744
-
2745
-
2746
-    /**
2747
-     * Checks the database for an item that conflicts (ie, if this item were
2748
-     * saved to the DB would break some uniqueness requirement, like a primary key
2749
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2750
-     * can be either an EE_Base_Class or an array of fields n values
2751
-     *
2752
-     * @param EE_Base_Class|array $obj_or_fields_array
2753
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2754
-     *                                                 when looking for conflicts
2755
-     *                                                 (ie, if false, we ignore the model object's primary key
2756
-     *                                                 when finding "conflicts". If true, it's also considered).
2757
-     *                                                 Only works for INT primary key,
2758
-     *                                                 STRING primary keys cannot be ignored
2759
-     * @throws EE_Error
2760
-     * @return EE_Base_Class|array
2761
-     */
2762
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2763
-    {
2764
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2765
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2766
-        } elseif (is_array($obj_or_fields_array)) {
2767
-            $fields_n_values = $obj_or_fields_array;
2768
-        } else {
2769
-            throw new EE_Error(
2770
-                sprintf(
2771
-                    __(
2772
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2773
-                        "event_espresso"
2774
-                    ),
2775
-                    get_class($this),
2776
-                    $obj_or_fields_array
2777
-                )
2778
-            );
2779
-        }
2780
-        $query_params = array();
2781
-        if ($this->has_primary_key_field()
2782
-            && ($include_primary_key
2783
-                || $this->get_primary_key_field()
2784
-                   instanceof
2785
-                   EE_Primary_Key_String_Field)
2786
-            && isset($fields_n_values[$this->primary_key_name()])
2787
-        ) {
2788
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2789
-        }
2790
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2791
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2792
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2793
-        }
2794
-        //if there is nothing to base this search on, then we shouldn't find anything
2795
-        if (empty($query_params)) {
2796
-            return array();
2797
-        } else {
2798
-            return $this->get_one($query_params);
2799
-        }
2800
-    }
2801
-
2802
-
2803
-
2804
-    /**
2805
-     * Like count, but is optimized and returns a boolean instead of an int
2806
-     *
2807
-     * @param array $query_params
2808
-     * @return boolean
2809
-     * @throws \EE_Error
2810
-     */
2811
-    public function exists($query_params)
2812
-    {
2813
-        $query_params['limit'] = 1;
2814
-        return $this->count($query_params) > 0;
2815
-    }
2816
-
2817
-
2818
-
2819
-    /**
2820
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2821
-     *
2822
-     * @param int|string $id
2823
-     * @return boolean
2824
-     * @throws \EE_Error
2825
-     */
2826
-    public function exists_by_ID($id)
2827
-    {
2828
-        return $this->exists(
2829
-            array(
2830
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2831
-                array(
2832
-                    $this->primary_key_name() => $id,
2833
-                ),
2834
-            )
2835
-        );
2836
-    }
2837
-
2838
-
2839
-
2840
-    /**
2841
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2842
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2843
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2844
-     * on the main table)
2845
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2846
-     * cases where we want to call it directly rather than via insert().
2847
-     *
2848
-     * @access   protected
2849
-     * @param EE_Table_Base $table
2850
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2851
-     *                                       float
2852
-     * @param int           $new_id          for now we assume only int keys
2853
-     * @throws EE_Error
2854
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2855
-     * @return int ID of new row inserted, or FALSE on failure
2856
-     */
2857
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2858
-    {
2859
-        global $wpdb;
2860
-        $insertion_col_n_values = array();
2861
-        $format_for_insertion = array();
2862
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2863
-        foreach ($fields_on_table as $field_name => $field_obj) {
2864
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2865
-            if ($field_obj->is_auto_increment()) {
2866
-                continue;
2867
-            }
2868
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2869
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2870
-            if ($prepared_value !== null) {
2871
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2872
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2873
-            }
2874
-        }
2875
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2876
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2877
-            //so add the fk to the main table as a column
2878
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2879
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2880
-        }
2881
-        //insert the new entry
2882
-        $result = $this->_do_wpdb_query('insert',
2883
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2884
-        if ($result === false) {
2885
-            return false;
2886
-        }
2887
-        //ok, now what do we return for the ID of the newly-inserted thing?
2888
-        if ($this->has_primary_key_field()) {
2889
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2890
-                return $wpdb->insert_id;
2891
-            } else {
2892
-                //it's not an auto-increment primary key, so
2893
-                //it must have been supplied
2894
-                return $fields_n_values[$this->get_primary_key_field()->get_name()];
2895
-            }
2896
-        } else {
2897
-            //we can't return a  primary key because there is none. instead return
2898
-            //a unique string indicating this model
2899
-            return $this->get_index_primary_key_string($fields_n_values);
2900
-        }
2901
-    }
2902
-
2903
-
2904
-
2905
-    /**
2906
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2907
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2908
-     * and there is no default, we pass it along. WPDB will take care of it)
2909
-     *
2910
-     * @param EE_Model_Field_Base $field_obj
2911
-     * @param array               $fields_n_values
2912
-     * @return mixed string|int|float depending on what the table column will be expecting
2913
-     * @throws \EE_Error
2914
-     */
2915
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2916
-    {
2917
-        //if this field doesn't allow nullable, don't allow it
2918
-        if (! $field_obj->is_nullable()
2919
-            && (
2920
-                ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2921
-        ) {
2922
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2923
-        }
2924
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2925
-            : null;
2926
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2927
-    }
2928
-
2929
-
2930
-
2931
-    /**
2932
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2933
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2934
-     * the field's prepare_for_set() method.
2935
-     *
2936
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2937
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2938
-     *                                   top of file)
2939
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2940
-     *                                   $value is a custom selection
2941
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2942
-     */
2943
-    private function _prepare_value_for_use_in_db($value, $field)
2944
-    {
2945
-        if ($field && $field instanceof EE_Model_Field_Base) {
2946
-            switch ($this->_values_already_prepared_by_model_object) {
2947
-                /** @noinspection PhpMissingBreakStatementInspection */
2948
-                case self::not_prepared_by_model_object:
2949
-                    $value = $field->prepare_for_set($value);
2950
-                //purposefully left out "return"
2951
-                case self::prepared_by_model_object:
2952
-                    $value = $field->prepare_for_use_in_db($value);
2953
-                case self::prepared_for_use_in_db:
2954
-                    //leave the value alone
2955
-            }
2956
-            return $value;
2957
-        } else {
2958
-            return $value;
2959
-        }
2960
-    }
2961
-
2962
-
2963
-
2964
-    /**
2965
-     * Returns the main table on this model
2966
-     *
2967
-     * @return EE_Primary_Table
2968
-     * @throws EE_Error
2969
-     */
2970
-    protected function _get_main_table()
2971
-    {
2972
-        foreach ($this->_tables as $table) {
2973
-            if ($table instanceof EE_Primary_Table) {
2974
-                return $table;
2975
-            }
2976
-        }
2977
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2978
-            'event_espresso'), get_class($this)));
2979
-    }
2980
-
2981
-
2982
-
2983
-    /**
2984
-     * table
2985
-     * returns EE_Primary_Table table name
2986
-     *
2987
-     * @return string
2988
-     * @throws \EE_Error
2989
-     */
2990
-    public function table()
2991
-    {
2992
-        return $this->_get_main_table()->get_table_name();
2993
-    }
2994
-
2995
-
2996
-
2997
-    /**
2998
-     * table
2999
-     * returns first EE_Secondary_Table table name
3000
-     *
3001
-     * @return string
3002
-     */
3003
-    public function second_table()
3004
-    {
3005
-        // grab second table from tables array
3006
-        $second_table = end($this->_tables);
3007
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3008
-    }
3009
-
3010
-
3011
-
3012
-    /**
3013
-     * get_table_obj_by_alias
3014
-     * returns table name given it's alias
3015
-     *
3016
-     * @param string $table_alias
3017
-     * @return EE_Primary_Table | EE_Secondary_Table
3018
-     */
3019
-    public function get_table_obj_by_alias($table_alias = '')
3020
-    {
3021
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3022
-    }
3023
-
3024
-
3025
-
3026
-    /**
3027
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3028
-     *
3029
-     * @return EE_Secondary_Table[]
3030
-     */
3031
-    protected function _get_other_tables()
3032
-    {
3033
-        $other_tables = array();
3034
-        foreach ($this->_tables as $table_alias => $table) {
3035
-            if ($table instanceof EE_Secondary_Table) {
3036
-                $other_tables[$table_alias] = $table;
3037
-            }
3038
-        }
3039
-        return $other_tables;
3040
-    }
3041
-
3042
-
3043
-
3044
-    /**
3045
-     * Finds all the fields that correspond to the given table
3046
-     *
3047
-     * @param string $table_alias , array key in EEM_Base::_tables
3048
-     * @return EE_Model_Field_Base[]
3049
-     */
3050
-    public function _get_fields_for_table($table_alias)
3051
-    {
3052
-        return $this->_fields[$table_alias];
3053
-    }
3054
-
3055
-
3056
-
3057
-    /**
3058
-     * Recurses through all the where parameters, and finds all the related models we'll need
3059
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3060
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3061
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3062
-     * related Registration, Transaction, and Payment models.
3063
-     *
3064
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3065
-     * @return EE_Model_Query_Info_Carrier
3066
-     * @throws \EE_Error
3067
-     */
3068
-    public function _extract_related_models_from_query($query_params)
3069
-    {
3070
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3071
-        if (array_key_exists(0, $query_params)) {
3072
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3073
-        }
3074
-        if (array_key_exists('group_by', $query_params)) {
3075
-            if (is_array($query_params['group_by'])) {
3076
-                $this->_extract_related_models_from_sub_params_array_values(
3077
-                    $query_params['group_by'],
3078
-                    $query_info_carrier,
3079
-                    'group_by'
3080
-                );
3081
-            } elseif (! empty ($query_params['group_by'])) {
3082
-                $this->_extract_related_model_info_from_query_param(
3083
-                    $query_params['group_by'],
3084
-                    $query_info_carrier,
3085
-                    'group_by'
3086
-                );
3087
-            }
3088
-        }
3089
-        if (array_key_exists('having', $query_params)) {
3090
-            $this->_extract_related_models_from_sub_params_array_keys(
3091
-                $query_params[0],
3092
-                $query_info_carrier,
3093
-                'having'
3094
-            );
3095
-        }
3096
-        if (array_key_exists('order_by', $query_params)) {
3097
-            if (is_array($query_params['order_by'])) {
3098
-                $this->_extract_related_models_from_sub_params_array_keys(
3099
-                    $query_params['order_by'],
3100
-                    $query_info_carrier,
3101
-                    'order_by'
3102
-                );
3103
-            } elseif (! empty($query_params['order_by'])) {
3104
-                $this->_extract_related_model_info_from_query_param(
3105
-                    $query_params['order_by'],
3106
-                    $query_info_carrier,
3107
-                    'order_by'
3108
-                );
3109
-            }
3110
-        }
3111
-        if (array_key_exists('force_join', $query_params)) {
3112
-            $this->_extract_related_models_from_sub_params_array_values(
3113
-                $query_params['force_join'],
3114
-                $query_info_carrier,
3115
-                'force_join'
3116
-            );
3117
-        }
3118
-        return $query_info_carrier;
3119
-    }
3120
-
3121
-
3122
-
3123
-    /**
3124
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3125
-     *
3126
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3127
-     *                                                      $query_params['having']
3128
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3129
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3130
-     * @throws EE_Error
3131
-     * @return \EE_Model_Query_Info_Carrier
3132
-     */
3133
-    private function _extract_related_models_from_sub_params_array_keys(
3134
-        $sub_query_params,
3135
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3136
-        $query_param_type
3137
-    ) {
3138
-        if (! empty($sub_query_params)) {
3139
-            $sub_query_params = (array)$sub_query_params;
3140
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3141
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3142
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3143
-                    $query_param_type);
3144
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3145
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3146
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3147
-                //of array('Registration.TXN_ID'=>23)
3148
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3149
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3150
-                    if (! is_array($possibly_array_of_params)) {
3151
-                        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'))",
3152
-                            "event_espresso"),
3153
-                            $param, $possibly_array_of_params));
3154
-                    } else {
3155
-                        $this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3156
-                            $model_query_info_carrier, $query_param_type);
3157
-                    }
3158
-                } elseif ($query_param_type === 0 //ie WHERE
3159
-                          && is_array($possibly_array_of_params)
3160
-                          && isset($possibly_array_of_params[2])
3161
-                          && $possibly_array_of_params[2] == true
3162
-                ) {
3163
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3164
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3165
-                    //from which we should extract query parameters!
3166
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3167
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3168
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3169
-                    }
3170
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3171
-                        $model_query_info_carrier, $query_param_type);
3172
-                }
3173
-            }
3174
-        }
3175
-        return $model_query_info_carrier;
3176
-    }
3177
-
3178
-
3179
-
3180
-    /**
3181
-     * For extracting related models from forced_joins, where the array values contain the info about what
3182
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3183
-     *
3184
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3185
-     *                                                      $query_params['having']
3186
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3187
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3188
-     * @throws EE_Error
3189
-     * @return \EE_Model_Query_Info_Carrier
3190
-     */
3191
-    private function _extract_related_models_from_sub_params_array_values(
3192
-        $sub_query_params,
3193
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3194
-        $query_param_type
3195
-    ) {
3196
-        if (! empty($sub_query_params)) {
3197
-            if (! is_array($sub_query_params)) {
3198
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3199
-                    $sub_query_params));
3200
-            }
3201
-            foreach ($sub_query_params as $param) {
3202
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3203
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3204
-                    $query_param_type);
3205
-            }
3206
-        }
3207
-        return $model_query_info_carrier;
3208
-    }
3209
-
3210
-
3211
-
3212
-    /**
3213
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3214
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3215
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3216
-     * but use them in a different order. Eg, we need to know what models we are querying
3217
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3218
-     * other models before we can finalize the where clause SQL.
3219
-     *
3220
-     * @param array $query_params
3221
-     * @throws EE_Error
3222
-     * @return EE_Model_Query_Info_Carrier
3223
-     */
3224
-    public function _create_model_query_info_carrier($query_params)
3225
-    {
3226
-        if (! is_array($query_params)) {
3227
-            EE_Error::doing_it_wrong(
3228
-                'EEM_Base::_create_model_query_info_carrier',
3229
-                sprintf(
3230
-                    __(
3231
-                        '$query_params should be an array, you passed a variable of type %s',
3232
-                        'event_espresso'
3233
-                    ),
3234
-                    gettype($query_params)
3235
-                ),
3236
-                '4.6.0'
3237
-            );
3238
-            $query_params = array();
3239
-        }
3240
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3241
-        //first check if we should alter the query to account for caps or not
3242
-        //because the caps might require us to do extra joins
3243
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3244
-            $query_params[0] = $where_query_params = array_replace_recursive(
3245
-                $where_query_params,
3246
-                $this->caps_where_conditions(
3247
-                    $query_params['caps']
3248
-                )
3249
-            );
3250
-        }
3251
-        $query_object = $this->_extract_related_models_from_query($query_params);
3252
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3253
-        foreach ($where_query_params as $key => $value) {
3254
-            if (is_int($key)) {
3255
-                throw new EE_Error(
3256
-                    sprintf(
3257
-                        __(
3258
-                            "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.",
3259
-                            "event_espresso"
3260
-                        ),
3261
-                        $key,
3262
-                        var_export($value, true),
3263
-                        var_export($query_params, true),
3264
-                        get_class($this)
3265
-                    )
3266
-                );
3267
-            }
3268
-        }
3269
-        if (
3270
-            array_key_exists('default_where_conditions', $query_params)
3271
-            && ! empty($query_params['default_where_conditions'])
3272
-        ) {
3273
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3274
-        } else {
3275
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3276
-        }
3277
-        $where_query_params = array_merge(
3278
-            $this->_get_default_where_conditions_for_models_in_query(
3279
-                $query_object,
3280
-                $use_default_where_conditions,
3281
-                $where_query_params
3282
-            ),
3283
-            $where_query_params
3284
-        );
3285
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3286
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3287
-        // So we need to setup a subquery and use that for the main join.
3288
-        // Note for now this only works on the primary table for the model.
3289
-        // So for instance, you could set the limit array like this:
3290
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3291
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3292
-            $query_object->set_main_model_join_sql(
3293
-                $this->_construct_limit_join_select(
3294
-                    $query_params['on_join_limit'][0],
3295
-                    $query_params['on_join_limit'][1]
3296
-                )
3297
-            );
3298
-        }
3299
-        //set limit
3300
-        if (array_key_exists('limit', $query_params)) {
3301
-            if (is_array($query_params['limit'])) {
3302
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3303
-                    $e = sprintf(
3304
-                        __(
3305
-                            "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)",
3306
-                            "event_espresso"
3307
-                        ),
3308
-                        http_build_query($query_params['limit'])
3309
-                    );
3310
-                    throw new EE_Error($e . "|" . $e);
3311
-                }
3312
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3313
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3314
-            } elseif (! empty ($query_params['limit'])) {
3315
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3316
-            }
3317
-        }
3318
-        //set order by
3319
-        if (array_key_exists('order_by', $query_params)) {
3320
-            if (is_array($query_params['order_by'])) {
3321
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3322
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3323
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3324
-                if (array_key_exists('order', $query_params)) {
3325
-                    throw new EE_Error(
3326
-                        sprintf(
3327
-                            __(
3328
-                                "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 ",
3329
-                                "event_espresso"
3330
-                            ),
3331
-                            get_class($this),
3332
-                            implode(", ", array_keys($query_params['order_by'])),
3333
-                            implode(", ", $query_params['order_by']),
3334
-                            $query_params['order']
3335
-                        )
3336
-                    );
3337
-                }
3338
-                $this->_extract_related_models_from_sub_params_array_keys(
3339
-                    $query_params['order_by'],
3340
-                    $query_object,
3341
-                    'order_by'
3342
-                );
3343
-                //assume it's an array of fields to order by
3344
-                $order_array = array();
3345
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3346
-                    $order = $this->_extract_order($order);
3347
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3348
-                }
3349
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3350
-            } elseif (! empty ($query_params['order_by'])) {
3351
-                $this->_extract_related_model_info_from_query_param(
3352
-                    $query_params['order_by'],
3353
-                    $query_object,
3354
-                    'order',
3355
-                    $query_params['order_by']
3356
-                );
3357
-                $order = isset($query_params['order'])
3358
-                    ? $this->_extract_order($query_params['order'])
3359
-                    : 'DESC';
3360
-                $query_object->set_order_by_sql(
3361
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3362
-                );
3363
-            }
3364
-        }
3365
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3366
-        if (! array_key_exists('order_by', $query_params)
3367
-            && array_key_exists('order', $query_params)
3368
-            && ! empty($query_params['order'])
3369
-        ) {
3370
-            $pk_field = $this->get_primary_key_field();
3371
-            $order = $this->_extract_order($query_params['order']);
3372
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3373
-        }
3374
-        //set group by
3375
-        if (array_key_exists('group_by', $query_params)) {
3376
-            if (is_array($query_params['group_by'])) {
3377
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3378
-                $group_by_array = array();
3379
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3380
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3381
-                }
3382
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3383
-            } elseif (! empty ($query_params['group_by'])) {
3384
-                $query_object->set_group_by_sql(
3385
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3386
-                );
3387
-            }
3388
-        }
3389
-        //set having
3390
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3391
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3392
-        }
3393
-        //now, just verify they didn't pass anything wack
3394
-        foreach ($query_params as $query_key => $query_value) {
3395
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3396
-                throw new EE_Error(
3397
-                    sprintf(
3398
-                        __(
3399
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3400
-                            'event_espresso'
3401
-                        ),
3402
-                        $query_key,
3403
-                        get_class($this),
3404
-                        //						print_r( $this->_allowed_query_params, TRUE )
3405
-                        implode(',', $this->_allowed_query_params)
3406
-                    )
3407
-                );
3408
-            }
3409
-        }
3410
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3411
-        if (empty($main_model_join_sql)) {
3412
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3413
-        }
3414
-        return $query_object;
3415
-    }
3416
-
3417
-
3418
-
3419
-    /**
3420
-     * Gets the where conditions that should be imposed on the query based on the
3421
-     * context (eg reading frontend, backend, edit or delete).
3422
-     *
3423
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3424
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3425
-     * @throws \EE_Error
3426
-     */
3427
-    public function caps_where_conditions($context = self::caps_read)
3428
-    {
3429
-        EEM_Base::verify_is_valid_cap_context($context);
3430
-        $cap_where_conditions = array();
3431
-        $cap_restrictions = $this->caps_missing($context);
3432
-        /**
3433
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3434
-         */
3435
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3436
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3437
-                $restriction_if_no_cap->get_default_where_conditions());
3438
-        }
3439
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3440
-            $cap_restrictions);
3441
-    }
3442
-
3443
-
3444
-
3445
-    /**
3446
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3447
-     * otherwise throws an exception
3448
-     *
3449
-     * @param string $should_be_order_string
3450
-     * @return string either ASC, asc, DESC or desc
3451
-     * @throws EE_Error
3452
-     */
3453
-    private function _extract_order($should_be_order_string)
3454
-    {
3455
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3456
-            return $should_be_order_string;
3457
-        } else {
3458
-            throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3459
-                "event_espresso"), get_class($this), $should_be_order_string));
3460
-        }
3461
-    }
3462
-
3463
-
3464
-
3465
-    /**
3466
-     * Looks at all the models which are included in this query, and asks each
3467
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3468
-     * so they can be merged
3469
-     *
3470
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3471
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3472
-     *                                                                  'none' means NO default where conditions will
3473
-     *                                                                  be used AT ALL during this query.
3474
-     *                                                                  'other_models_only' means default where
3475
-     *                                                                  conditions from other models will be used, but
3476
-     *                                                                  not for this primary model. 'all', the default,
3477
-     *                                                                  means default where conditions will apply as
3478
-     *                                                                  normal
3479
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3480
-     * @throws EE_Error
3481
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3482
-     */
3483
-    private function _get_default_where_conditions_for_models_in_query(
3484
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3485
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3486
-        $where_query_params = array()
3487
-    ) {
3488
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3489
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3490
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3491
-                "event_espresso"), $use_default_where_conditions,
3492
-                implode(", ", $allowed_used_default_where_conditions_values)));
3493
-        }
3494
-        $universal_query_params = array();
3495
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3496
-            $universal_query_params = $this->_get_default_where_conditions();
3497
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3498
-            $universal_query_params = $this->_get_minimum_where_conditions();
3499
-        }
3500
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3501
-            $related_model = $this->get_related_model_obj($model_name);
3502
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3503
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3504
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3505
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3506
-            } else {
3507
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3508
-                continue;
3509
-            }
3510
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3511
-                $related_model_universal_where_params,
3512
-                $where_query_params,
3513
-                $related_model,
3514
-                $model_relation_path
3515
-            );
3516
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3517
-                $universal_query_params,
3518
-                $overrides
3519
-            );
3520
-        }
3521
-        return $universal_query_params;
3522
-    }
3523
-
3524
-
3525
-
3526
-    /**
3527
-     * Determines whether or not we should use default where conditions for the model in question
3528
-     * (this model, or other related models).
3529
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3530
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3531
-     * We should use default where conditions on related models when they requested to use default where conditions
3532
-     * on all models, or specifically just on other related models
3533
-     * @param      $default_where_conditions_value
3534
-     * @param bool $for_this_model false means this is for OTHER related models
3535
-     * @return bool
3536
-     */
3537
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3538
-    {
3539
-        return (
3540
-                   $for_this_model
3541
-                   && in_array(
3542
-                       $default_where_conditions_value,
3543
-                       array(
3544
-                           EEM_Base::default_where_conditions_all,
3545
-                           EEM_Base::default_where_conditions_this_only,
3546
-                           EEM_Base::default_where_conditions_minimum_others,
3547
-                       ),
3548
-                       true
3549
-                   )
3550
-               )
3551
-               || (
3552
-                   ! $for_this_model
3553
-                   && in_array(
3554
-                       $default_where_conditions_value,
3555
-                       array(
3556
-                           EEM_Base::default_where_conditions_all,
3557
-                           EEM_Base::default_where_conditions_others_only,
3558
-                       ),
3559
-                       true
3560
-                   )
3561
-               );
3562
-    }
3563
-
3564
-    /**
3565
-     * Determines whether or not we should use default minimum conditions for the model in question
3566
-     * (this model, or other related models).
3567
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3568
-     * where conditions.
3569
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3570
-     * on this model or others
3571
-     * @param      $default_where_conditions_value
3572
-     * @param bool $for_this_model false means this is for OTHER related models
3573
-     * @return bool
3574
-     */
3575
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3576
-    {
3577
-        return (
3578
-                   $for_this_model
3579
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3580
-               )
3581
-               || (
3582
-                   ! $for_this_model
3583
-                   && in_array(
3584
-                       $default_where_conditions_value,
3585
-                       array(
3586
-                           EEM_Base::default_where_conditions_minimum_others,
3587
-                           EEM_Base::default_where_conditions_minimum_all,
3588
-                       ),
3589
-                       true
3590
-                   )
3591
-               );
3592
-    }
3593
-
3594
-
3595
-    /**
3596
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3597
-     * then we also add a special where condition which allows for that model's primary key
3598
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3599
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3600
-     *
3601
-     * @param array    $default_where_conditions
3602
-     * @param array    $provided_where_conditions
3603
-     * @param EEM_Base $model
3604
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3605
-     * @return array like EEM_Base::get_all's $query_params[0]
3606
-     * @throws \EE_Error
3607
-     */
3608
-    private function _override_defaults_or_make_null_friendly(
3609
-        $default_where_conditions,
3610
-        $provided_where_conditions,
3611
-        $model,
3612
-        $model_relation_path
3613
-    ) {
3614
-        $null_friendly_where_conditions = array();
3615
-        $none_overridden = true;
3616
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3617
-        foreach ($default_where_conditions as $key => $val) {
3618
-            if (isset($provided_where_conditions[$key])) {
3619
-                $none_overridden = false;
3620
-            } else {
3621
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3622
-            }
3623
-        }
3624
-        if ($none_overridden && $default_where_conditions) {
3625
-            if ($model->has_primary_key_field()) {
3626
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3627
-                                                                                . "."
3628
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3629
-            }/*else{
32
+	/**
33
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
34
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
35
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
36
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
37
+	 *
38
+	 * @var boolean
39
+	 */
40
+	private $_values_already_prepared_by_model_object = 0;
41
+
42
+	/**
43
+	 * when $_values_already_prepared_by_model_object equals this, we assume
44
+	 * the data is just like form input that needs to have the model fields'
45
+	 * prepare_for_set and prepare_for_use_in_db called on it
46
+	 */
47
+	const not_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we
51
+	 * assume this value is coming from a model object and doesn't need to have
52
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
53
+	 */
54
+	const prepared_by_model_object = 1;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we assume
58
+	 * the values are already to be used in the database (ie no processing is done
59
+	 * on them by the model's fields)
60
+	 */
61
+	const prepared_for_use_in_db = 2;
62
+
63
+
64
+	protected $singular_item = 'Item';
65
+
66
+	protected $plural_item   = 'Items';
67
+
68
+	/**
69
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
70
+	 */
71
+	protected $_tables;
72
+
73
+	/**
74
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
75
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
76
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
77
+	 *
78
+	 * @var \EE_Model_Field_Base[][] $_fields
79
+	 */
80
+	protected $_fields;
81
+
82
+	/**
83
+	 * array of different kinds of relations
84
+	 *
85
+	 * @var \EE_Model_Relation_Base[] $_model_relations
86
+	 */
87
+	protected $_model_relations;
88
+
89
+	/**
90
+	 * @var \EE_Index[] $_indexes
91
+	 */
92
+	protected $_indexes = array();
93
+
94
+	/**
95
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
96
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
97
+	 * by setting the same columns as used in these queries in the query yourself.
98
+	 *
99
+	 * @var EE_Default_Where_Conditions
100
+	 */
101
+	protected $_default_where_conditions_strategy;
102
+
103
+	/**
104
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
105
+	 * This is particularly useful when you want something between 'none' and 'default'
106
+	 *
107
+	 * @var EE_Default_Where_Conditions
108
+	 */
109
+	protected $_minimum_where_conditions_strategy;
110
+
111
+	/**
112
+	 * String describing how to find the "owner" of this model's objects.
113
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
114
+	 * But when there isn't, this indicates which related model, or transiently-related model,
115
+	 * has the foreign key to the wp_users table.
116
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
117
+	 * related to events, and events have a foreign key to wp_users.
118
+	 * On EEM_Transaction, this would be 'Transaction.Event'
119
+	 *
120
+	 * @var string
121
+	 */
122
+	protected $_model_chain_to_wp_user = '';
123
+
124
+	/**
125
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
126
+	 * don't need it (particularly CPT models)
127
+	 *
128
+	 * @var bool
129
+	 */
130
+	protected $_ignore_where_strategy = false;
131
+
132
+	/**
133
+	 * String used in caps relating to this model. Eg, if the caps relating to this
134
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
135
+	 *
136
+	 * @var string. If null it hasn't been initialized yet. If false then we
137
+	 * have indicated capabilities don't apply to this
138
+	 */
139
+	protected $_caps_slug = null;
140
+
141
+	/**
142
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
143
+	 * and next-level keys are capability names, and each's value is a
144
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
145
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
146
+	 * and then each capability in the corresponding sub-array that they're missing
147
+	 * adds the where conditions onto the query.
148
+	 *
149
+	 * @var array
150
+	 */
151
+	protected $_cap_restrictions = array(
152
+		self::caps_read       => array(),
153
+		self::caps_read_admin => array(),
154
+		self::caps_edit       => array(),
155
+		self::caps_delete     => array(),
156
+	);
157
+
158
+	/**
159
+	 * Array defining which cap restriction generators to use to create default
160
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
161
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
162
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
163
+	 * automatically set this to false (not just null).
164
+	 *
165
+	 * @var EE_Restriction_Generator_Base[]
166
+	 */
167
+	protected $_cap_restriction_generators = array();
168
+
169
+	/**
170
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
171
+	 */
172
+	const caps_read       = 'read';
173
+
174
+	const caps_read_admin = 'read_admin';
175
+
176
+	const caps_edit       = 'edit';
177
+
178
+	const caps_delete     = 'delete';
179
+
180
+	/**
181
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
182
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
183
+	 * maps to 'read' because when looking for relevant permissions we're going to use
184
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
185
+	 *
186
+	 * @var array
187
+	 */
188
+	protected $_cap_contexts_to_cap_action_map = array(
189
+		self::caps_read       => 'read',
190
+		self::caps_read_admin => 'read',
191
+		self::caps_edit       => 'edit',
192
+		self::caps_delete     => 'delete',
193
+	);
194
+
195
+	/**
196
+	 * Timezone
197
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
198
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
199
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
200
+	 * EE_Datetime_Field data type will have access to it.
201
+	 *
202
+	 * @var string
203
+	 */
204
+	protected $_timezone;
205
+
206
+
207
+	/**
208
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
209
+	 * multisite.
210
+	 *
211
+	 * @var int
212
+	 */
213
+	protected static $_model_query_blog_id;
214
+
215
+	/**
216
+	 * A copy of _fields, except the array keys are the model names pointed to by
217
+	 * the field
218
+	 *
219
+	 * @var EE_Model_Field_Base[]
220
+	 */
221
+	private $_cache_foreign_key_to_fields = array();
222
+
223
+	/**
224
+	 * Cached list of all the fields on the model, indexed by their name
225
+	 *
226
+	 * @var EE_Model_Field_Base[]
227
+	 */
228
+	private $_cached_fields = null;
229
+
230
+	/**
231
+	 * Cached list of all the fields on the model, except those that are
232
+	 * marked as only pertinent to the database
233
+	 *
234
+	 * @var EE_Model_Field_Base[]
235
+	 */
236
+	private $_cached_fields_non_db_only = null;
237
+
238
+	/**
239
+	 * A cached reference to the primary key for quick lookup
240
+	 *
241
+	 * @var EE_Model_Field_Base
242
+	 */
243
+	private $_primary_key_field = null;
244
+
245
+	/**
246
+	 * Flag indicating whether this model has a primary key or not
247
+	 *
248
+	 * @var boolean
249
+	 */
250
+	protected $_has_primary_key_field = null;
251
+
252
+	/**
253
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
254
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
255
+	 * This should be true for models that deal with data that should exist independent of EE.
256
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
257
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
258
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
259
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
260
+	 * @var boolean
261
+	 */
262
+	protected $_wp_core_model = false;
263
+
264
+	/**
265
+	 *    List of valid operators that can be used for querying.
266
+	 * The keys are all operators we'll accept, the values are the real SQL
267
+	 * operators used
268
+	 *
269
+	 * @var array
270
+	 */
271
+	protected $_valid_operators = array(
272
+		'='           => '=',
273
+		'<='          => '<=',
274
+		'<'           => '<',
275
+		'>='          => '>=',
276
+		'>'           => '>',
277
+		'!='          => '!=',
278
+		'LIKE'        => 'LIKE',
279
+		'like'        => 'LIKE',
280
+		'NOT_LIKE'    => 'NOT LIKE',
281
+		'not_like'    => 'NOT LIKE',
282
+		'NOT LIKE'    => 'NOT LIKE',
283
+		'not like'    => 'NOT LIKE',
284
+		'IN'          => 'IN',
285
+		'in'          => 'IN',
286
+		'NOT_IN'      => 'NOT IN',
287
+		'not_in'      => 'NOT IN',
288
+		'NOT IN'      => 'NOT IN',
289
+		'not in'      => 'NOT IN',
290
+		'between'     => 'BETWEEN',
291
+		'BETWEEN'     => 'BETWEEN',
292
+		'IS_NOT_NULL' => 'IS NOT NULL',
293
+		'is_not_null' => 'IS NOT NULL',
294
+		'IS NOT NULL' => 'IS NOT NULL',
295
+		'is not null' => 'IS NOT NULL',
296
+		'IS_NULL'     => 'IS NULL',
297
+		'is_null'     => 'IS NULL',
298
+		'IS NULL'     => 'IS NULL',
299
+		'is null'     => 'IS NULL',
300
+		'REGEXP'      => 'REGEXP',
301
+		'regexp'      => 'REGEXP',
302
+		'NOT_REGEXP'  => 'NOT REGEXP',
303
+		'not_regexp'  => 'NOT REGEXP',
304
+		'NOT REGEXP'  => 'NOT REGEXP',
305
+		'not regexp'  => 'NOT REGEXP',
306
+	);
307
+
308
+	/**
309
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
310
+	 *
311
+	 * @var array
312
+	 */
313
+	protected $_in_style_operators = array('IN', 'NOT IN');
314
+
315
+	/**
316
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
317
+	 * '12-31-2012'"
318
+	 *
319
+	 * @var array
320
+	 */
321
+	protected $_between_style_operators = array('BETWEEN');
322
+
323
+	/**
324
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
325
+	 * @var array
326
+	 */
327
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
328
+	/**
329
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
330
+	 * on a join table.
331
+	 *
332
+	 * @var array
333
+	 */
334
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
335
+
336
+	/**
337
+	 * Allowed values for $query_params['order'] for ordering in queries
338
+	 *
339
+	 * @var array
340
+	 */
341
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
342
+
343
+	/**
344
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
345
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
346
+	 *
347
+	 * @var array
348
+	 */
349
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
350
+
351
+	/**
352
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
353
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
354
+	 *
355
+	 * @var array
356
+	 */
357
+	private $_allowed_query_params = array(
358
+		0,
359
+		'limit',
360
+		'order_by',
361
+		'group_by',
362
+		'having',
363
+		'force_join',
364
+		'order',
365
+		'on_join_limit',
366
+		'default_where_conditions',
367
+		'caps',
368
+	);
369
+
370
+	/**
371
+	 * All the data types that can be used in $wpdb->prepare statements.
372
+	 *
373
+	 * @var array
374
+	 */
375
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
376
+
377
+	/**
378
+	 *    EE_Registry Object
379
+	 *
380
+	 * @var    object
381
+	 * @access    protected
382
+	 */
383
+	protected $EE = null;
384
+
385
+
386
+	/**
387
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
+	 *
389
+	 * @var int
390
+	 */
391
+	protected $_show_next_x_db_queries = 0;
392
+
393
+	/**
394
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
+	 *
397
+	 * @var array
398
+	 */
399
+	protected $_custom_selections = array();
400
+
401
+	/**
402
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
+	 * caches every model object we've fetched from the DB on this request
404
+	 *
405
+	 * @var array
406
+	 */
407
+	protected $_entity_map;
408
+
409
+	/**
410
+	 * constant used to show EEM_Base has not yet verified the db on this http request
411
+	 */
412
+	const db_verified_none = 0;
413
+
414
+	/**
415
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
416
+	 * but not the addons' dbs
417
+	 */
418
+	const db_verified_core = 1;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
422
+	 * the EE core db too)
423
+	 */
424
+	const db_verified_addons = 2;
425
+
426
+	/**
427
+	 * indicates whether an EEM_Base child has already re-verified the DB
428
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
429
+	 * looking like EEM_Base::db_verified_*
430
+	 *
431
+	 * @var int - 0 = none, 1 = core, 2 = addons
432
+	 */
433
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
434
+
435
+	/**
436
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
437
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
438
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
439
+	 */
440
+	const default_where_conditions_all = 'all';
441
+
442
+	/**
443
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
444
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
445
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
446
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
447
+	 *        models which share tables with other models, this can return data for the wrong model.
448
+	 */
449
+	const default_where_conditions_this_only = 'this_model_only';
450
+
451
+	/**
452
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
453
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
454
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
455
+	 */
456
+	const default_where_conditions_others_only = 'other_models_only';
457
+
458
+	/**
459
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
460
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
461
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
462
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
463
+	 *        (regardless of whether those events and venues are trashed)
464
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
465
+	 *        events.
466
+	 */
467
+	const default_where_conditions_minimum_all = 'minimum';
468
+
469
+	/**
470
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
471
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
472
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
473
+	 *        not)
474
+	 */
475
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
476
+
477
+	/**
478
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
479
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
480
+	 *        it's possible it will return table entries for other models. You should use
481
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
482
+	 */
483
+	const default_where_conditions_none = 'none';
484
+
485
+
486
+
487
+	/**
488
+	 * About all child constructors:
489
+	 * they should define the _tables, _fields and _model_relations arrays.
490
+	 * Should ALWAYS be called after child constructor.
491
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
492
+	 * finalizes constructing all the object's attributes.
493
+	 * Generally, rather than requiring a child to code
494
+	 * $this->_tables = array(
495
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
496
+	 *        ...);
497
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
498
+	 * each EE_Table has a function to set the table's alias after the constructor, using
499
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
500
+	 * do something similar.
501
+	 *
502
+	 * @param null $timezone
503
+	 * @throws \EE_Error
504
+	 */
505
+	protected function __construct($timezone = null)
506
+	{
507
+		// check that the model has not been loaded too soon
508
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
+			throw new EE_Error (
510
+				sprintf(
511
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
512
+						'event_espresso'),
513
+					get_class($this)
514
+				)
515
+			);
516
+		}
517
+		/**
518
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
519
+		 */
520
+		if (empty(EEM_Base::$_model_query_blog_id)) {
521
+			EEM_Base::set_model_query_blog_id();
522
+		}
523
+		/**
524
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
525
+		 * just use EE_Register_Model_Extension
526
+		 *
527
+		 * @var EE_Table_Base[] $_tables
528
+		 */
529
+		$this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
530
+		foreach ($this->_tables as $table_alias => $table_obj) {
531
+			/** @var $table_obj EE_Table_Base */
532
+			$table_obj->_construct_finalize_with_alias($table_alias);
533
+			if ($table_obj instanceof EE_Secondary_Table) {
534
+				/** @var $table_obj EE_Secondary_Table */
535
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
536
+			}
537
+		}
538
+		/**
539
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
540
+		 * EE_Register_Model_Extension
541
+		 *
542
+		 * @param EE_Model_Field_Base[] $_fields
543
+		 */
544
+		$this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
545
+		$this->_invalidate_field_caches();
546
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
547
+			if (! array_key_exists($table_alias, $this->_tables)) {
548
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
550
+			}
551
+			foreach ($fields_for_table as $field_name => $field_obj) {
552
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
553
+				//primary key field base has a slightly different _construct_finalize
554
+				/** @var $field_obj EE_Model_Field_Base */
555
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
556
+			}
557
+		}
558
+		// everything is related to Extra_Meta
559
+		if (get_class($this) !== 'EEM_Extra_Meta') {
560
+			//make extra meta related to everything, but don't block deleting things just
561
+			//because they have related extra meta info. For now just orphan those extra meta
562
+			//in the future we should automatically delete them
563
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
564
+		}
565
+		//and change logs
566
+		if (get_class($this) !== 'EEM_Change_Log') {
567
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
568
+		}
569
+		/**
570
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
571
+		 * EE_Register_Model_Extension
572
+		 *
573
+		 * @param EE_Model_Relation_Base[] $_model_relations
574
+		 */
575
+		$this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
576
+			$this->_model_relations);
577
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
578
+			/** @var $relation_obj EE_Model_Relation_Base */
579
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
580
+		}
581
+		foreach ($this->_indexes as $index_name => $index_obj) {
582
+			/** @var $index_obj EE_Index */
583
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
584
+		}
585
+		$this->set_timezone($timezone);
586
+		//finalize default where condition strategy, or set default
587
+		if (! $this->_default_where_conditions_strategy) {
588
+			//nothing was set during child constructor, so set default
589
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590
+		}
591
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
592
+		if (! $this->_minimum_where_conditions_strategy) {
593
+			//nothing was set during child constructor, so set default
594
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595
+		}
596
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
597
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
598
+		//to indicate to NOT set it, set it to the logical default
599
+		if ($this->_caps_slug === null) {
600
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
601
+		}
602
+		//initialize the standard cap restriction generators if none were specified by the child constructor
603
+		if ($this->_cap_restriction_generators !== false) {
604
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
606
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
607
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608
+						new EE_Restriction_Generator_Protected(),
609
+						$cap_context,
610
+						$this
611
+					);
612
+				}
613
+			}
614
+		}
615
+		//if there are cap restriction generators, use them to make the default cap restrictions
616
+		if ($this->_cap_restriction_generators !== false) {
617
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
+				if (! $generator_object) {
619
+					continue;
620
+				}
621
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
622
+					throw new EE_Error(
623
+						sprintf(
624
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
625
+								'event_espresso'),
626
+							$context,
627
+							$this->get_this_model_name()
628
+						)
629
+					);
630
+				}
631
+				$action = $this->cap_action_for_context($context);
632
+				if (! $generator_object->construction_finalized()) {
633
+					$generator_object->_construct_finalize($this, $action);
634
+				}
635
+			}
636
+		}
637
+		do_action('AHEE__' . get_class($this) . '__construct__end');
638
+	}
639
+
640
+
641
+
642
+	/**
643
+	 * Used to set the $_model_query_blog_id static property.
644
+	 *
645
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
646
+	 *                      value for get_current_blog_id() will be used.
647
+	 */
648
+	public static function set_model_query_blog_id($blog_id = 0)
649
+	{
650
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
651
+	}
652
+
653
+
654
+
655
+	/**
656
+	 * Returns whatever is set as the internal $model_query_blog_id.
657
+	 *
658
+	 * @return int
659
+	 */
660
+	public static function get_model_query_blog_id()
661
+	{
662
+		return EEM_Base::$_model_query_blog_id;
663
+	}
664
+
665
+
666
+
667
+	/**
668
+	 *        This function is a singleton method used to instantiate the Espresso_model object
669
+	 *
670
+	 * @access public
671
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings (and any
672
+	 *                         incoming timezone data that gets saved).  Note this just sends the timezone info to the
673
+	 *                         date time model field objects.  Default is NULL (and will be assumed using the set
674
+	 *                         timezone in the 'timezone_string' wp option)
675
+	 * @return static (as in the concrete child class)
676
+	 */
677
+	public static function instance($timezone = null)
678
+	{
679
+		// check if instance of Espresso_model already exists
680
+		if (! static::$_instance instanceof static) {
681
+			// instantiate Espresso_model
682
+			static::$_instance = new static($timezone);
683
+		}
684
+		//we might have a timezone set, let set_timezone decide what to do with it
685
+		static::$_instance->set_timezone($timezone);
686
+		// Espresso_model object
687
+		return static::$_instance;
688
+	}
689
+
690
+
691
+
692
+	/**
693
+	 * resets the model and returns it
694
+	 *
695
+	 * @param null | string $timezone
696
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
697
+	 * all its properties reset; if it wasn't instantiated, returns null)
698
+	 */
699
+	public static function reset($timezone = null)
700
+	{
701
+		if (static::$_instance instanceof EEM_Base) {
702
+			//let's try to NOT swap out the current instance for a new one
703
+			//because if someone has a reference to it, we can't remove their reference
704
+			//so it's best to keep using the same reference, but change the original object
705
+			//reset all its properties to their original values as defined in the class
706
+			$r = new ReflectionClass(get_class(static::$_instance));
707
+			$static_properties = $r->getStaticProperties();
708
+			foreach ($r->getDefaultProperties() as $property => $value) {
709
+				//don't set instance to null like it was originally,
710
+				//but it's static anyways, and we're ignoring static properties (for now at least)
711
+				if (! isset($static_properties[$property])) {
712
+					static::$_instance->{$property} = $value;
713
+				}
714
+			}
715
+			//and then directly call its constructor again, like we would if we
716
+			//were creating a new one
717
+			static::$_instance->__construct($timezone);
718
+			return self::instance();
719
+		}
720
+		return null;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
727
+	 *
728
+	 * @param  boolean $translated return localized strings or JUST the array.
729
+	 * @return array
730
+	 * @throws \EE_Error
731
+	 */
732
+	public function status_array($translated = false)
733
+	{
734
+		if (! array_key_exists('Status', $this->_model_relations)) {
735
+			return array();
736
+		}
737
+		$model_name = $this->get_this_model_name();
738
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
739
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
740
+		$status_array = array();
741
+		foreach ($stati as $status) {
742
+			$status_array[$status->ID()] = $status->get('STS_code');
743
+		}
744
+		return $translated
745
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
746
+			: $status_array;
747
+	}
748
+
749
+
750
+
751
+	/**
752
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
753
+	 *
754
+	 * @param array $query_params             {
755
+	 * @var array $0 (where) array {
756
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
757
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
758
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
759
+	 *                                        conditions based on related models (and even
760
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
761
+	 *                                        name. Eg,
762
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
763
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
764
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
765
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
766
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
767
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
768
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
769
+	 *                                        to Venues (even when each of those models actually consisted of two
770
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
771
+	 *                                        just having
772
+	 *                                        "Venue.VNU_ID", you could have
773
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
774
+	 *                                        events are related to Registrations, which are related to Attendees). You
775
+	 *                                        can take it even further with
776
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
777
+	 *                                        (from the default of '='), change the value to an numerically-indexed
778
+	 *                                        array, where the first item in the list is the operator. eg: array(
779
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
780
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
781
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
782
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
783
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
784
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
785
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
786
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
787
+	 *                                        the value is a field, simply provide a third array item (true) to the
788
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
789
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
790
+	 *                                        Note: you can also use related model field names like you would any other
791
+	 *                                        field name. eg:
792
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
793
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
794
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
795
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
796
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
797
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
798
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
799
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
800
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
801
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
802
+	 *                                        "stick" until you specify an AND. eg
803
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
804
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
805
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
806
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
807
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
808
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
809
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
810
+	 *                                        too, eg:
811
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
812
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
813
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
814
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
815
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
816
+	 *                                        the OFFSET, the 2nd is the LIMIT
817
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
818
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
819
+	 *                                        following format array('on_join_limit'
820
+	 *                                        => array( 'table_alias', array(1,2) ) ).
821
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
822
+	 *                                        values are either 'ASC' or 'DESC'.
823
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
824
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
825
+	 *                                        DESC..." respectively. Like the
826
+	 *                                        'where' conditions, these fields can be on related models. Eg
827
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
828
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
829
+	 *                                        Attendee, Price, Datetime, etc.)
830
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
831
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
832
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
833
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
834
+	 *                                        order by the primary key. Eg,
835
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
836
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
837
+	 *                                        DTT_EVT_start) or
838
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
839
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
840
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
841
+	 *                                        'group_by'=>'VNU_ID', or
842
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
843
+	 *                                        if no
844
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
845
+	 *                                        model's primary key (or combined primary keys). This avoids some
846
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
847
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
848
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
849
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
850
+	 *                                        results)
851
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
852
+	 *                                        array where values are models to be joined in the query.Eg
853
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
854
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
855
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
856
+	 *                                        related models which belongs to the current model
857
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
858
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
859
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
860
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
861
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
862
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
863
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
864
+	 *                                        this model's default where conditions added to the query, use
865
+	 *                                        'this_model_only'. If you want to use all default where conditions
866
+	 *                                        (default), set to 'all'.
867
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
868
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
869
+	 *                                        everything? Or should we only show the current user items they should be
870
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
871
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
872
+	 *                                        }
873
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
874
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
875
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
876
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
877
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
878
+	 *                                        array( array(
879
+	 *                                        'OR'=>array(
880
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
881
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
882
+	 *                                        )
883
+	 *                                        ),
884
+	 *                                        'limit'=>10,
885
+	 *                                        'group_by'=>'TXN_ID'
886
+	 *                                        ));
887
+	 *                                        get all the answers to the question titled "shirt size" for event with id
888
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
889
+	 *                                        'Question.QST_display_text'=>'shirt size',
890
+	 *                                        'Registration.Event.EVT_ID'=>12
891
+	 *                                        ),
892
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
893
+	 *                                        ));
894
+	 * @throws \EE_Error
895
+	 */
896
+	public function get_all($query_params = array())
897
+	{
898
+		if (isset($query_params['limit'])
899
+			&& ! isset($query_params['group_by'])
900
+		) {
901
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
902
+		}
903
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
904
+	}
905
+
906
+
907
+
908
+	/**
909
+	 * Modifies the query parameters so we only get back model objects
910
+	 * that "belong" to the current user
911
+	 *
912
+	 * @param array $query_params @see EEM_Base::get_all()
913
+	 * @return array like EEM_Base::get_all
914
+	 */
915
+	public function alter_query_params_to_only_include_mine($query_params = array())
916
+	{
917
+		$wp_user_field_name = $this->wp_user_field_name();
918
+		if ($wp_user_field_name) {
919
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
920
+		}
921
+		return $query_params;
922
+	}
923
+
924
+
925
+
926
+	/**
927
+	 * Returns the name of the field's name that points to the WP_User table
928
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
929
+	 * foreign key to the WP_User table)
930
+	 *
931
+	 * @return string|boolean string on success, boolean false when there is no
932
+	 * foreign key to the WP_User table
933
+	 */
934
+	public function wp_user_field_name()
935
+	{
936
+		try {
937
+			if (! empty($this->_model_chain_to_wp_user)) {
938
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
939
+				$last_model_name = end($models_to_follow_to_wp_users);
940
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
941
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
942
+			} else {
943
+				$model_with_fk_to_wp_users = $this;
944
+				$model_chain_to_wp_user = '';
945
+			}
946
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
947
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
948
+		} catch (EE_Error $e) {
949
+			return false;
950
+		}
951
+	}
952
+
953
+
954
+
955
+	/**
956
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
957
+	 * (or transiently-related model) has a foreign key to the wp_users table;
958
+	 * useful for finding if model objects of this type are 'owned' by the current user.
959
+	 * This is an empty string when the foreign key is on this model and when it isn't,
960
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
961
+	 * (or transiently-related model)
962
+	 *
963
+	 * @return string
964
+	 */
965
+	public function model_chain_to_wp_user()
966
+	{
967
+		return $this->_model_chain_to_wp_user;
968
+	}
969
+
970
+
971
+
972
+	/**
973
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
974
+	 * like how registrations don't have a foreign key to wp_users, but the
975
+	 * events they are for are), or is unrelated to wp users.
976
+	 * generally available
977
+	 *
978
+	 * @return boolean
979
+	 */
980
+	public function is_owned()
981
+	{
982
+		if ($this->model_chain_to_wp_user()) {
983
+			return true;
984
+		} else {
985
+			try {
986
+				$this->get_foreign_key_to('WP_User');
987
+				return true;
988
+			} catch (EE_Error $e) {
989
+				return false;
990
+			}
991
+		}
992
+	}
993
+
994
+
995
+
996
+	/**
997
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
998
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
999
+	 * the model)
1000
+	 *
1001
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1002
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1003
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1004
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1005
+	 *                                  override this and set the select to "*", or a specific column name, like
1006
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1007
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1008
+	 *                                  the aliases used to refer to this selection, and values are to be
1009
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1010
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1011
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1012
+	 * @throws \EE_Error
1013
+	 */
1014
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1015
+	{
1016
+		// remember the custom selections, if any, and type cast as array
1017
+		// (unless $columns_to_select is an object, then just set as an empty array)
1018
+		// Note: (array) 'some string' === array( 'some string' )
1019
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1020
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1021
+		$select_expressions = $columns_to_select !== null
1022
+			? $this->_construct_select_from_input($columns_to_select)
1023
+			: $this->_construct_default_select_sql($model_query_info);
1024
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1025
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1026
+	}
1027
+
1028
+
1029
+
1030
+	/**
1031
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1032
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1033
+	 * take care of joins, field preparation etc.
1034
+	 *
1035
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1036
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1037
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1038
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1039
+	 *                                  override this and set the select to "*", or a specific column name, like
1040
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1041
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1042
+	 *                                  the aliases used to refer to this selection, and values are to be
1043
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1044
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1045
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1046
+	 * @throws \EE_Error
1047
+	 */
1048
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1049
+	{
1050
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1051
+	}
1052
+
1053
+
1054
+
1055
+	/**
1056
+	 * For creating a custom select statement
1057
+	 *
1058
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1059
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1060
+	 *                                 SQL, and 1=>is the datatype
1061
+	 * @throws EE_Error
1062
+	 * @return string
1063
+	 */
1064
+	private function _construct_select_from_input($columns_to_select)
1065
+	{
1066
+		if (is_array($columns_to_select)) {
1067
+			$select_sql_array = array();
1068
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070
+					throw new EE_Error(
1071
+						sprintf(
1072
+							__(
1073
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1074
+								"event_espresso"
1075
+							),
1076
+							$selection_and_datatype,
1077
+							$alias
1078
+						)
1079
+					);
1080
+				}
1081
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1082
+					throw new EE_Error(
1083
+						sprintf(
1084
+							__(
1085
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1086
+								"event_espresso"
1087
+							),
1088
+							$selection_and_datatype[1],
1089
+							$selection_and_datatype[0],
1090
+							$alias,
1091
+							implode(",", $this->_valid_wpdb_data_types)
1092
+						)
1093
+					);
1094
+				}
1095
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1096
+			}
1097
+			$columns_to_select_string = implode(", ", $select_sql_array);
1098
+		} else {
1099
+			$columns_to_select_string = $columns_to_select;
1100
+		}
1101
+		return $columns_to_select_string;
1102
+	}
1103
+
1104
+
1105
+
1106
+	/**
1107
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1108
+	 *
1109
+	 * @return string
1110
+	 * @throws \EE_Error
1111
+	 */
1112
+	public function primary_key_name()
1113
+	{
1114
+		return $this->get_primary_key_field()->get_name();
1115
+	}
1116
+
1117
+
1118
+
1119
+	/**
1120
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1121
+	 * If there is no primary key on this model, $id is treated as primary key string
1122
+	 *
1123
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1124
+	 * @return EE_Base_Class
1125
+	 */
1126
+	public function get_one_by_ID($id)
1127
+	{
1128
+		if ($this->get_from_entity_map($id)) {
1129
+			return $this->get_from_entity_map($id);
1130
+		}
1131
+		return $this->get_one(
1132
+			$this->alter_query_params_to_restrict_by_ID(
1133
+				$id,
1134
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1135
+			)
1136
+		);
1137
+	}
1138
+
1139
+
1140
+
1141
+	/**
1142
+	 * Alters query parameters to only get items with this ID are returned.
1143
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1144
+	 * or could just be a simple primary key ID
1145
+	 *
1146
+	 * @param int   $id
1147
+	 * @param array $query_params
1148
+	 * @return array of normal query params, @see EEM_Base::get_all
1149
+	 * @throws \EE_Error
1150
+	 */
1151
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1152
+	{
1153
+		if (! isset($query_params[0])) {
1154
+			$query_params[0] = array();
1155
+		}
1156
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1157
+		if ($conditions_from_id === null) {
1158
+			$query_params[0][$this->primary_key_name()] = $id;
1159
+		} else {
1160
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1161
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1162
+		}
1163
+		return $query_params;
1164
+	}
1165
+
1166
+
1167
+
1168
+	/**
1169
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1170
+	 * array. If no item is found, null is returned.
1171
+	 *
1172
+	 * @param array $query_params like EEM_Base's $query_params variable.
1173
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1174
+	 * @throws \EE_Error
1175
+	 */
1176
+	public function get_one($query_params = array())
1177
+	{
1178
+		if (! is_array($query_params)) {
1179
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1180
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1181
+					gettype($query_params)), '4.6.0');
1182
+			$query_params = array();
1183
+		}
1184
+		$query_params['limit'] = 1;
1185
+		$items = $this->get_all($query_params);
1186
+		if (empty($items)) {
1187
+			return null;
1188
+		} else {
1189
+			return array_shift($items);
1190
+		}
1191
+	}
1192
+
1193
+
1194
+
1195
+	/**
1196
+	 * Returns the next x number of items in sequence from the given value as
1197
+	 * found in the database matching the given query conditions.
1198
+	 *
1199
+	 * @param mixed $current_field_value    Value used for the reference point.
1200
+	 * @param null  $field_to_order_by      What field is used for the
1201
+	 *                                      reference point.
1202
+	 * @param int   $limit                  How many to return.
1203
+	 * @param array $query_params           Extra conditions on the query.
1204
+	 * @param null  $columns_to_select      If left null, then an array of
1205
+	 *                                      EE_Base_Class objects is returned,
1206
+	 *                                      otherwise you can indicate just the
1207
+	 *                                      columns you want returned.
1208
+	 * @return EE_Base_Class[]|array
1209
+	 * @throws \EE_Error
1210
+	 */
1211
+	public function next_x(
1212
+		$current_field_value,
1213
+		$field_to_order_by = null,
1214
+		$limit = 1,
1215
+		$query_params = array(),
1216
+		$columns_to_select = null
1217
+	) {
1218
+		return $this->_get_consecutive($current_field_value, '>', $field_to_order_by, $limit, $query_params,
1219
+			$columns_to_select);
1220
+	}
1221
+
1222
+
1223
+
1224
+	/**
1225
+	 * Returns the previous x number of items in sequence from the given value
1226
+	 * as found in the database matching the given query conditions.
1227
+	 *
1228
+	 * @param mixed $current_field_value    Value used for the reference point.
1229
+	 * @param null  $field_to_order_by      What field is used for the
1230
+	 *                                      reference point.
1231
+	 * @param int   $limit                  How many to return.
1232
+	 * @param array $query_params           Extra conditions on the query.
1233
+	 * @param null  $columns_to_select      If left null, then an array of
1234
+	 *                                      EE_Base_Class objects is returned,
1235
+	 *                                      otherwise you can indicate just the
1236
+	 *                                      columns you want returned.
1237
+	 * @return EE_Base_Class[]|array
1238
+	 * @throws \EE_Error
1239
+	 */
1240
+	public function previous_x(
1241
+		$current_field_value,
1242
+		$field_to_order_by = null,
1243
+		$limit = 1,
1244
+		$query_params = array(),
1245
+		$columns_to_select = null
1246
+	) {
1247
+		return $this->_get_consecutive($current_field_value, '<', $field_to_order_by, $limit, $query_params,
1248
+			$columns_to_select);
1249
+	}
1250
+
1251
+
1252
+
1253
+	/**
1254
+	 * Returns the next item in sequence from the given value as found in the
1255
+	 * database matching the given query conditions.
1256
+	 *
1257
+	 * @param mixed $current_field_value    Value used for the reference point.
1258
+	 * @param null  $field_to_order_by      What field is used for the
1259
+	 *                                      reference point.
1260
+	 * @param array $query_params           Extra conditions on the query.
1261
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1262
+	 *                                      object is returned, otherwise you
1263
+	 *                                      can indicate just the columns you
1264
+	 *                                      want and a single array indexed by
1265
+	 *                                      the columns will be returned.
1266
+	 * @return EE_Base_Class|null|array()
1267
+	 * @throws \EE_Error
1268
+	 */
1269
+	public function next(
1270
+		$current_field_value,
1271
+		$field_to_order_by = null,
1272
+		$query_params = array(),
1273
+		$columns_to_select = null
1274
+	) {
1275
+		$results = $this->_get_consecutive($current_field_value, '>', $field_to_order_by, 1, $query_params,
1276
+			$columns_to_select);
1277
+		return empty($results) ? null : reset($results);
1278
+	}
1279
+
1280
+
1281
+
1282
+	/**
1283
+	 * Returns the previous item in sequence from the given value as found in
1284
+	 * the database matching the given query conditions.
1285
+	 *
1286
+	 * @param mixed $current_field_value    Value used for the reference point.
1287
+	 * @param null  $field_to_order_by      What field is used for the
1288
+	 *                                      reference point.
1289
+	 * @param array $query_params           Extra conditions on the query.
1290
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1291
+	 *                                      object is returned, otherwise you
1292
+	 *                                      can indicate just the columns you
1293
+	 *                                      want and a single array indexed by
1294
+	 *                                      the columns will be returned.
1295
+	 * @return EE_Base_Class|null|array()
1296
+	 * @throws EE_Error
1297
+	 */
1298
+	public function previous(
1299
+		$current_field_value,
1300
+		$field_to_order_by = null,
1301
+		$query_params = array(),
1302
+		$columns_to_select = null
1303
+	) {
1304
+		$results = $this->_get_consecutive($current_field_value, '<', $field_to_order_by, 1, $query_params,
1305
+			$columns_to_select);
1306
+		return empty($results) ? null : reset($results);
1307
+	}
1308
+
1309
+
1310
+
1311
+	/**
1312
+	 * Returns the a consecutive number of items in sequence from the given
1313
+	 * value as found in the database matching the given query conditions.
1314
+	 *
1315
+	 * @param mixed  $current_field_value   Value used for the reference point.
1316
+	 * @param string $operand               What operand is used for the sequence.
1317
+	 * @param string $field_to_order_by     What field is used for the reference point.
1318
+	 * @param int    $limit                 How many to return.
1319
+	 * @param array  $query_params          Extra conditions on the query.
1320
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1321
+	 *                                      otherwise you can indicate just the columns you want returned.
1322
+	 * @return EE_Base_Class[]|array
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	protected function _get_consecutive(
1326
+		$current_field_value,
1327
+		$operand = '>',
1328
+		$field_to_order_by = null,
1329
+		$limit = 1,
1330
+		$query_params = array(),
1331
+		$columns_to_select = null
1332
+	) {
1333
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1334
+		if (empty($field_to_order_by)) {
1335
+			if ($this->has_primary_key_field()) {
1336
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1337
+			} else {
1338
+				if (WP_DEBUG) {
1339
+					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).',
1340
+						'event_espresso'));
1341
+				}
1342
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1343
+				return array();
1344
+			}
1345
+		}
1346
+		if (! is_array($query_params)) {
1347
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1348
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1349
+					gettype($query_params)), '4.6.0');
1350
+			$query_params = array();
1351
+		}
1352
+		//let's add the where query param for consecutive look up.
1353
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1354
+		$query_params['limit'] = $limit;
1355
+		//set direction
1356
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1357
+		$query_params['order_by'] = $operand === '>'
1358
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1359
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1360
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1361
+		if (empty($columns_to_select)) {
1362
+			return $this->get_all($query_params);
1363
+		} else {
1364
+			//getting just the fields
1365
+			return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1366
+		}
1367
+	}
1368
+
1369
+
1370
+
1371
+	/**
1372
+	 * This sets the _timezone property after model object has been instantiated.
1373
+	 *
1374
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1375
+	 */
1376
+	public function set_timezone($timezone)
1377
+	{
1378
+		if ($timezone !== null) {
1379
+			$this->_timezone = $timezone;
1380
+		}
1381
+		//note we need to loop through relations and set the timezone on those objects as well.
1382
+		foreach ($this->_model_relations as $relation) {
1383
+			$relation->set_timezone($timezone);
1384
+		}
1385
+		//and finally we do the same for any datetime fields
1386
+		foreach ($this->_fields as $field) {
1387
+			if ($field instanceof EE_Datetime_Field) {
1388
+				$field->set_timezone($timezone);
1389
+			}
1390
+		}
1391
+	}
1392
+
1393
+
1394
+
1395
+	/**
1396
+	 * This just returns whatever is set for the current timezone.
1397
+	 *
1398
+	 * @access public
1399
+	 * @return string
1400
+	 */
1401
+	public function get_timezone()
1402
+	{
1403
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1404
+		if (empty($this->_timezone)) {
1405
+			foreach ($this->_fields as $field) {
1406
+				if ($field instanceof EE_Datetime_Field) {
1407
+					$this->set_timezone($field->get_timezone());
1408
+					break;
1409
+				}
1410
+			}
1411
+		}
1412
+		//if timezone STILL empty then return the default timezone for the site.
1413
+		if (empty($this->_timezone)) {
1414
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1415
+		}
1416
+		return $this->_timezone;
1417
+	}
1418
+
1419
+
1420
+
1421
+	/**
1422
+	 * This returns the date formats set for the given field name and also ensures that
1423
+	 * $this->_timezone property is set correctly.
1424
+	 *
1425
+	 * @since 4.6.x
1426
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1427
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1428
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1429
+	 * @return array formats in an array with the date format first, and the time format last.
1430
+	 */
1431
+	public function get_formats_for($field_name, $pretty = false)
1432
+	{
1433
+		$field_settings = $this->field_settings_for($field_name);
1434
+		//if not a valid EE_Datetime_Field then throw error
1435
+		if (! $field_settings instanceof EE_Datetime_Field) {
1436
+			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.',
1437
+				'event_espresso'), $field_name));
1438
+		}
1439
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1440
+		//the field.
1441
+		$this->_timezone = $field_settings->get_timezone();
1442
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1443
+	}
1444
+
1445
+
1446
+
1447
+	/**
1448
+	 * This returns the current time in a format setup for a query on this model.
1449
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1450
+	 * it will return:
1451
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1452
+	 *  NOW
1453
+	 *  - or a unix timestamp (equivalent to time())
1454
+	 *
1455
+	 * @since 4.6.x
1456
+	 * @param string $field_name       The field the current time is needed for.
1457
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1458
+	 *                                 formatted string matching the set format for the field in the set timezone will
1459
+	 *                                 be returned.
1460
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1461
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1462
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1463
+	 *                                 exception is triggered.
1464
+	 */
1465
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1466
+	{
1467
+		$formats = $this->get_formats_for($field_name);
1468
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1469
+		if ($timestamp) {
1470
+			return $DateTime->format('U');
1471
+		}
1472
+		//not returning timestamp, so return formatted string in timezone.
1473
+		switch ($what) {
1474
+			case 'time' :
1475
+				return $DateTime->format($formats[1]);
1476
+				break;
1477
+			case 'date' :
1478
+				return $DateTime->format($formats[0]);
1479
+				break;
1480
+			default :
1481
+				return $DateTime->format(implode(' ', $formats));
1482
+				break;
1483
+		}
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1490
+	 * for the model are.  Returns a DateTime object.
1491
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1492
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1493
+	 * ignored.
1494
+	 *
1495
+	 * @param string $field_name      The field being setup.
1496
+	 * @param string $timestring      The date time string being used.
1497
+	 * @param string $incoming_format The format for the time string.
1498
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1499
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1500
+	 *                                format is
1501
+	 *                                'U', this is ignored.
1502
+	 * @return DateTime
1503
+	 * @throws \EE_Error
1504
+	 */
1505
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1506
+	{
1507
+		//just using this to ensure the timezone is set correctly internally
1508
+		$this->get_formats_for($field_name);
1509
+		//load EEH_DTT_Helper
1510
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1511
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1512
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1513
+	}
1514
+
1515
+
1516
+
1517
+	/**
1518
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1519
+	 *
1520
+	 * @return EE_Table_Base[]
1521
+	 */
1522
+	public function get_tables()
1523
+	{
1524
+		return $this->_tables;
1525
+	}
1526
+
1527
+
1528
+
1529
+	/**
1530
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1531
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1532
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1533
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1534
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1535
+	 * model object with EVT_ID = 1
1536
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1537
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1538
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1539
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1540
+	 * are not specified)
1541
+	 *
1542
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1543
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1544
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1545
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1546
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1547
+	 *                                         ID=34, we'd use this method as follows:
1548
+	 *                                         EEM_Transaction::instance()->update(
1549
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1550
+	 *                                         array(array('TXN_ID'=>34)));
1551
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1552
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1553
+	 *                                         consider updating Question's QST_admin_label field is of type
1554
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1555
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1556
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1557
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1558
+	 *                                         TRUE, it is assumed that you've already called
1559
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1560
+	 *                                         malicious javascript. However, if
1561
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1562
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1563
+	 *                                         and every other field, before insertion. We provide this parameter
1564
+	 *                                         because model objects perform their prepare_for_set function on all
1565
+	 *                                         their values, and so don't need to be called again (and in many cases,
1566
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1567
+	 *                                         prepare_for_set method...)
1568
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1569
+	 *                                         in this model's entity map according to $fields_n_values that match
1570
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1571
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1572
+	 *                                         could get out-of-sync with the database
1573
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1574
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1575
+	 *                                         bad)
1576
+	 * @throws \EE_Error
1577
+	 */
1578
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1579
+	{
1580
+		if (! is_array($query_params)) {
1581
+			EE_Error::doing_it_wrong('EEM_Base::update',
1582
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1583
+					gettype($query_params)), '4.6.0');
1584
+			$query_params = array();
1585
+		}
1586
+		/**
1587
+		 * Action called before a model update call has been made.
1588
+		 *
1589
+		 * @param EEM_Base $model
1590
+		 * @param array    $fields_n_values the updated fields and their new values
1591
+		 * @param array    $query_params    @see EEM_Base::get_all()
1592
+		 */
1593
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1594
+		/**
1595
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1596
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1597
+		 *
1598
+		 * @param array    $fields_n_values fields and their new values
1599
+		 * @param EEM_Base $model           the model being queried
1600
+		 * @param array    $query_params    see EEM_Base::get_all()
1601
+		 */
1602
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1603
+			$query_params);
1604
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1605
+		//to do that, for each table, verify that it's PK isn't null.
1606
+		$tables = $this->get_tables();
1607
+		//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
1608
+		//NOTE: we should make this code more efficient by NOT querying twice
1609
+		//before the real update, but that needs to first go through ALPHA testing
1610
+		//as it's dangerous. says Mike August 8 2014
1611
+		//we want to make sure the default_where strategy is ignored
1612
+		$this->_ignore_where_strategy = true;
1613
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1614
+		foreach ($wpdb_select_results as $wpdb_result) {
1615
+			// type cast stdClass as array
1616
+			$wpdb_result = (array)$wpdb_result;
1617
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1618
+			if ($this->has_primary_key_field()) {
1619
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1620
+			} else {
1621
+				//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)
1622
+				$main_table_pk_value = null;
1623
+			}
1624
+			//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
1625
+			//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
1626
+			if (count($tables) > 1) {
1627
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1628
+				//in that table, and so we'll want to insert one
1629
+				foreach ($tables as $table_obj) {
1630
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1631
+					//if there is no private key for this table on the results, it means there's no entry
1632
+					//in this table, right? so insert a row in the current table, using any fields available
1633
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1634
+						   && $wpdb_result[$this_table_pk_column])
1635
+					) {
1636
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1637
+							$main_table_pk_value);
1638
+						//if we died here, report the error
1639
+						if (! $success) {
1640
+							return false;
1641
+						}
1642
+					}
1643
+				}
1644
+			}
1645
+			//				//and now check that if we have cached any models by that ID on the model, that
1646
+			//				//they also get updated properly
1647
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1648
+			//				if( $model_object ){
1649
+			//					foreach( $fields_n_values as $field => $value ){
1650
+			//						$model_object->set($field, $value);
1651
+			//let's make sure default_where strategy is followed now
1652
+			$this->_ignore_where_strategy = false;
1653
+		}
1654
+		//if we want to keep model objects in sync, AND
1655
+		//if this wasn't called from a model object (to update itself)
1656
+		//then we want to make sure we keep all the existing
1657
+		//model objects in sync with the db
1658
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1659
+			if ($this->has_primary_key_field()) {
1660
+				$model_objs_affected_ids = $this->get_col($query_params);
1661
+			} else {
1662
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1663
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1664
+				$model_objs_affected_ids = array();
1665
+				foreach ($models_affected_key_columns as $row) {
1666
+					$combined_index_key = $this->get_index_primary_key_string($row);
1667
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1668
+				}
1669
+			}
1670
+			if (! $model_objs_affected_ids) {
1671
+				//wait wait wait- if nothing was affected let's stop here
1672
+				return 0;
1673
+			}
1674
+			foreach ($model_objs_affected_ids as $id) {
1675
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1676
+				if ($model_obj_in_entity_map) {
1677
+					foreach ($fields_n_values as $field => $new_value) {
1678
+						$model_obj_in_entity_map->set($field, $new_value);
1679
+					}
1680
+				}
1681
+			}
1682
+			//if there is a primary key on this model, we can now do a slight optimization
1683
+			if ($this->has_primary_key_field()) {
1684
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1685
+				$query_params = array(
1686
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1687
+					'limit'                    => count($model_objs_affected_ids),
1688
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1689
+				);
1690
+			}
1691
+		}
1692
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1693
+		$SQL = "UPDATE "
1694
+			   . $model_query_info->get_full_join_sql()
1695
+			   . " SET "
1696
+			   . $this->_construct_update_sql($fields_n_values)
1697
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1698
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1699
+		/**
1700
+		 * Action called after a model update call has been made.
1701
+		 *
1702
+		 * @param EEM_Base $model
1703
+		 * @param array    $fields_n_values the updated fields and their new values
1704
+		 * @param array    $query_params    @see EEM_Base::get_all()
1705
+		 * @param int      $rows_affected
1706
+		 */
1707
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1708
+		return $rows_affected;//how many supposedly got updated
1709
+	}
1710
+
1711
+
1712
+
1713
+	/**
1714
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1715
+	 * are teh values of the field specified (or by default the primary key field)
1716
+	 * that matched the query params. Note that you should pass the name of the
1717
+	 * model FIELD, not the database table's column name.
1718
+	 *
1719
+	 * @param array  $query_params @see EEM_Base::get_all()
1720
+	 * @param string $field_to_select
1721
+	 * @return array just like $wpdb->get_col()
1722
+	 * @throws \EE_Error
1723
+	 */
1724
+	public function get_col($query_params = array(), $field_to_select = null)
1725
+	{
1726
+		if ($field_to_select) {
1727
+			$field = $this->field_settings_for($field_to_select);
1728
+		} elseif ($this->has_primary_key_field()) {
1729
+			$field = $this->get_primary_key_field();
1730
+		} else {
1731
+			//no primary key, just grab the first column
1732
+			$field = reset($this->field_settings());
1733
+		}
1734
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1735
+		$select_expressions = $field->get_qualified_column();
1736
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1737
+		return $this->_do_wpdb_query('get_col', array($SQL));
1738
+	}
1739
+
1740
+
1741
+
1742
+	/**
1743
+	 * Returns a single column value for a single row from the database
1744
+	 *
1745
+	 * @param array  $query_params    @see EEM_Base::get_all()
1746
+	 * @param string $field_to_select @see EEM_Base::get_col()
1747
+	 * @return string
1748
+	 * @throws \EE_Error
1749
+	 */
1750
+	public function get_var($query_params = array(), $field_to_select = null)
1751
+	{
1752
+		$query_params['limit'] = 1;
1753
+		$col = $this->get_col($query_params, $field_to_select);
1754
+		if (! empty($col)) {
1755
+			return reset($col);
1756
+		} else {
1757
+			return null;
1758
+		}
1759
+	}
1760
+
1761
+
1762
+
1763
+	/**
1764
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1765
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1766
+	 * injection, but currently no further filtering is done
1767
+	 *
1768
+	 * @global      $wpdb
1769
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1770
+	 *                               be updated to in the DB
1771
+	 * @return string of SQL
1772
+	 * @throws \EE_Error
1773
+	 */
1774
+	public function _construct_update_sql($fields_n_values)
1775
+	{
1776
+		/** @type WPDB $wpdb */
1777
+		global $wpdb;
1778
+		$cols_n_values = array();
1779
+		foreach ($fields_n_values as $field_name => $value) {
1780
+			$field_obj = $this->field_settings_for($field_name);
1781
+			//if the value is NULL, we want to assign the value to that.
1782
+			//wpdb->prepare doesn't really handle that properly
1783
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1784
+			$value_sql = $prepared_value === null ? 'NULL'
1785
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1786
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1787
+		}
1788
+		return implode(",", $cols_n_values);
1789
+	}
1790
+
1791
+
1792
+
1793
+	/**
1794
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1795
+	 * Performs a HARD delete, meaning the database row should always be removed,
1796
+	 * not just have a flag field on it switched
1797
+	 * Wrapper for EEM_Base::delete_permanently()
1798
+	 *
1799
+	 * @param mixed $id
1800
+	 * @param boolean $allow_blocking
1801
+	 * @return int the number of rows deleted
1802
+	 * @throws \EE_Error
1803
+	 */
1804
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1805
+	{
1806
+		return $this->delete_permanently(
1807
+			array(
1808
+				array($this->get_primary_key_field()->get_name() => $id),
1809
+				'limit' => 1,
1810
+			),
1811
+			$allow_blocking
1812
+		);
1813
+	}
1814
+
1815
+
1816
+
1817
+	/**
1818
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1819
+	 * Wrapper for EEM_Base::delete()
1820
+	 *
1821
+	 * @param mixed $id
1822
+	 * @param boolean $allow_blocking
1823
+	 * @return int the number of rows deleted
1824
+	 * @throws \EE_Error
1825
+	 */
1826
+	public function delete_by_ID($id, $allow_blocking = true)
1827
+	{
1828
+		return $this->delete(
1829
+			array(
1830
+				array($this->get_primary_key_field()->get_name() => $id),
1831
+				'limit' => 1,
1832
+			),
1833
+			$allow_blocking
1834
+		);
1835
+	}
1836
+
1837
+
1838
+
1839
+	/**
1840
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1841
+	 * meaning if the model has a field that indicates its been "trashed" or
1842
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1843
+	 *
1844
+	 * @see EEM_Base::delete_permanently
1845
+	 * @param array   $query_params
1846
+	 * @param boolean $allow_blocking
1847
+	 * @return int how many rows got deleted
1848
+	 * @throws \EE_Error
1849
+	 */
1850
+	public function delete($query_params, $allow_blocking = true)
1851
+	{
1852
+		return $this->delete_permanently($query_params, $allow_blocking);
1853
+	}
1854
+
1855
+
1856
+
1857
+	/**
1858
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1859
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1860
+	 * as archived, not actually deleted
1861
+	 *
1862
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1863
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1864
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1865
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1866
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1867
+	 *                                DB
1868
+	 * @return int how many rows got deleted
1869
+	 * @throws \EE_Error
1870
+	 */
1871
+	public function delete_permanently($query_params, $allow_blocking = true)
1872
+	{
1873
+		/**
1874
+		 * Action called just before performing a real deletion query. You can use the
1875
+		 * model and its $query_params to find exactly which items will be deleted
1876
+		 *
1877
+		 * @param EEM_Base $model
1878
+		 * @param array    $query_params   @see EEM_Base::get_all()
1879
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1880
+		 *                                 to block (prevent) this deletion
1881
+		 */
1882
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1883
+		//some MySQL databases may be running safe mode, which may restrict
1884
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1885
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1886
+		//to delete them
1887
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1888
+		$deletion_where = $this->_setup_ids_for_delete($items_for_deletion, $allow_blocking);
1889
+		if ($deletion_where) {
1890
+			//echo "objects for deletion:";var_dump($objects_for_deletion);
1891
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1892
+			$table_aliases = array_keys($this->_tables);
1893
+			$SQL = "DELETE "
1894
+				   . implode(", ", $table_aliases)
1895
+				   . " FROM "
1896
+				   . $model_query_info->get_full_join_sql()
1897
+				   . " WHERE "
1898
+				   . $deletion_where;
1899
+			//		/echo "delete sql:$SQL";
1900
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1901
+		} else {
1902
+			$rows_deleted = 0;
1903
+		}
1904
+		//and lastly make sure those items are removed from the entity map; if they could be put into it at all
1905
+		if ($this->has_primary_key_field()) {
1906
+			foreach ($items_for_deletion as $item_for_deletion_row) {
1907
+				$pk_value = $item_for_deletion_row[$this->get_primary_key_field()->get_qualified_column()];
1908
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value])) {
1909
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$pk_value]);
1910
+				}
1911
+			}
1912
+		}
1913
+		/**
1914
+		 * Action called just after performing a real deletion query. Although at this point the
1915
+		 * items should have been deleted
1916
+		 *
1917
+		 * @param EEM_Base $model
1918
+		 * @param array    $query_params @see EEM_Base::get_all()
1919
+		 * @param int      $rows_deleted
1920
+		 */
1921
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1922
+		return $rows_deleted;//how many supposedly got deleted
1923
+	}
1924
+
1925
+
1926
+
1927
+	/**
1928
+	 * Checks all the relations that throw error messages when there are blocking related objects
1929
+	 * for related model objects. If there are any related model objects on those relations,
1930
+	 * adds an EE_Error, and return true
1931
+	 *
1932
+	 * @param EE_Base_Class|int $this_model_obj_or_id
1933
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
1934
+	 *                                                 should be ignored when determining whether there are related
1935
+	 *                                                 model objects which block this model object's deletion. Useful
1936
+	 *                                                 if you know A is related to B and are considering deleting A,
1937
+	 *                                                 but want to see if A has any other objects blocking its deletion
1938
+	 *                                                 before removing the relation between A and B
1939
+	 * @return boolean
1940
+	 * @throws \EE_Error
1941
+	 */
1942
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
1943
+	{
1944
+		//first, if $ignore_this_model_obj was supplied, get its model
1945
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
1946
+			$ignored_model = $ignore_this_model_obj->get_model();
1947
+		} else {
1948
+			$ignored_model = null;
1949
+		}
1950
+		//now check all the relations of $this_model_obj_or_id and see if there
1951
+		//are any related model objects blocking it?
1952
+		$is_blocked = false;
1953
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
1954
+			if ($relation_obj->block_delete_if_related_models_exist()) {
1955
+				//if $ignore_this_model_obj was supplied, then for the query
1956
+				//on that model needs to be told to ignore $ignore_this_model_obj
1957
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
1958
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
1959
+						array(
1960
+							$ignored_model->get_primary_key_field()->get_name() => array(
1961
+								'!=',
1962
+								$ignore_this_model_obj->ID(),
1963
+							),
1964
+						),
1965
+					));
1966
+				} else {
1967
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
1968
+				}
1969
+				if ($related_model_objects) {
1970
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
1971
+					$is_blocked = true;
1972
+				}
1973
+			}
1974
+		}
1975
+		return $is_blocked;
1976
+	}
1977
+
1978
+
1979
+
1980
+	/**
1981
+	 * This sets up our delete where sql and accounts for if we have secondary tables that will have rows deleted as
1982
+	 * well.
1983
+	 *
1984
+	 * @param  array  $objects_for_deletion This should be the values returned by $this->_get_all_wpdb_results()
1985
+	 * @param boolean $allow_blocking       if TRUE, matched objects will only be deleted if there is no related model
1986
+	 *                                      info that blocks it (ie, there' sno other data that depends on this data);
1987
+	 *                                      if false, deletes regardless of other objects which may depend on it. Its
1988
+	 *                                      generally advisable to always leave this as TRUE, otherwise you could
1989
+	 *                                      easily corrupt your DB
1990
+	 * @throws EE_Error
1991
+	 * @return string    everything that comes after the WHERE statement.
1992
+	 */
1993
+	protected function _setup_ids_for_delete($objects_for_deletion, $allow_blocking = true)
1994
+	{
1995
+		if ($this->has_primary_key_field()) {
1996
+			$primary_table = $this->_get_main_table();
1997
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
1998
+			$other_tables = $this->_get_other_tables();
1999
+			/**
2000
+			 * @var EE_Primary_Key_Field_Base[] $other_tables_pk_fields  keys are table aliases
2001
+			 */
2002
+			$other_tables_pk_fields = array();
2003
+			/**
2004
+			 * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2005
+			 */
2006
+			$other_tables_fk_fields = array();
2007
+			foreach($other_tables as $other_table_alias => $other_table_obj){
2008
+				$other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2009
+				$other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2010
+			}
2011
+			$deletes = $query = array();
2012
+			foreach ($objects_for_deletion as $delete_object) {
2013
+				//before we mark this object for deletion,
2014
+				//make sure there's no related objects blocking its deletion (if we're checking)
2015
+				if (
2016
+					$allow_blocking
2017
+					&& $this->delete_is_blocked_by_related_models(
2018
+						$delete_object[$primary_table->get_fully_qualified_pk_column()]
2019
+					)
2020
+				) {
2021
+					continue;
2022
+				}
2023
+				//primary table deletes
2024
+				if (isset($delete_object[$primary_table->get_fully_qualified_pk_column()])) {
2025
+
2026
+					$deletes[$primary_table->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2027
+						$delete_object[$primary_table->get_fully_qualified_pk_column()],
2028
+						$primary_table_pk_field
2029
+					);
2030
+				}
2031
+				//other tables
2032
+				if (! empty($other_tables)) {
2033
+					foreach ($other_tables as $other_table_alias => $other_table_obj) {
2034
+						$other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2035
+						$other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
2036
+						//first check if we've got the foreign key column here.
2037
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_fk_column()])) {
2038
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2039
+								$delete_object[$other_table_obj->get_fully_qualified_fk_column()],
2040
+								$other_table_fk_field
2041
+							);
2042
+						}
2043
+						// wait! it's entirely possible that we'll have a the primary key
2044
+						// for this table in here, if it's a foreign key for one of the other secondary tables
2045
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_column()])) {
2046
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2047
+								$delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2048
+								$other_table_pk_field
2049
+							);
2050
+						}
2051
+						// finally, it is possible that the fk for this table is found
2052
+						// in the fully qualified pk column for the fk table, so let's see if that's there!
2053
+						if (isset($delete_object[$other_table_obj->get_fully_qualified_pk_on_fk_table()])) {
2054
+							$deletes[$other_table_obj->get_fully_qualified_pk_column()][] = $this->_wpdb_prepare_using_field(
2055
+								$delete_object[$other_table_obj->get_fully_qualified_pk_column()],
2056
+								$other_table_pk_field
2057
+							);
2058
+						}
2059
+					}
2060
+				}
2061
+			}
2062
+			//we should have deletes now, so let's just go through and setup the where statement
2063
+			foreach ($deletes as $column => $values) {
2064
+				//make sure we have unique $values;
2065
+				$values = array_unique($values);
2066
+				$query[] = $column . ' IN(' . implode(",", $values) . ')';
2067
+			}
2068
+			return ! empty($query) ? implode(' AND ', $query) : '';
2069
+		}
2070
+		$combined_primary_key_fields = $this->get_combined_primary_key_fields();
2071
+		if (count($combined_primary_key_fields) > 1) {
2072
+			$ways_to_identify_a_row = array();
2073
+			//note: because there's no primary key, that means nothing else  can be pointing to this model, right?
2074
+			foreach ($objects_for_deletion as $delete_object) {
2075
+				$combined_primary_key_row_values = array();
2076
+				foreach ($combined_primary_key_fields as $field_in_combined_primary_key) {
2077
+					if ($field_in_combined_primary_key instanceof EE_Model_Field_Base) {
2078
+						$combined_primary_key_row_values[] = $field_in_combined_primary_key->get_qualified_column()
2079
+														   . "="
2080
+														   . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2081
+					}
2082
+				}
2083
+				$ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2084
+			}
2085
+			return implode(" OR ", $ways_to_identify_a_row);
2086
+		} else {
2087
+			//so there's no primary key and no combined key...
2088
+			//sorry, can't help you
2089
+			throw new EE_Error(sprintf(__("Cannot delete objects of type %s because there is no primary key NOR combined key",
2090
+				"event_espresso"), get_class($this)));
2091
+		}
2092
+	}
2093
+
2094
+
2095
+	/**
2096
+	 * Gets the model field by the fully qualified name
2097
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2098
+	 * @return EE_Model_Field_Base
2099
+	 */
2100
+	public function get_field_by_column($qualified_column_name)
2101
+	{
2102
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2103
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2104
+			   return $field_obj;
2105
+		   }
2106
+	   }
2107
+		throw new EE_Error(
2108
+			sprintf(
2109
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2110
+				$this->get_this_model_name(),
2111
+				$qualified_column_name
2112
+			)
2113
+		);
2114
+	}
2115
+
2116
+
2117
+
2118
+	/**
2119
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2120
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2121
+	 * column
2122
+	 *
2123
+	 * @param array  $query_params   like EEM_Base::get_all's
2124
+	 * @param string $field_to_count field on model to count by (not column name)
2125
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2126
+	 *                               that by the setting $distinct to TRUE;
2127
+	 * @return int
2128
+	 * @throws \EE_Error
2129
+	 */
2130
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2131
+	{
2132
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2133
+		if ($field_to_count) {
2134
+			$field_obj = $this->field_settings_for($field_to_count);
2135
+			$column_to_count = $field_obj->get_qualified_column();
2136
+		} elseif ($this->has_primary_key_field()) {
2137
+			$pk_field_obj = $this->get_primary_key_field();
2138
+			$column_to_count = $pk_field_obj->get_qualified_column();
2139
+		} else {
2140
+			//there's no primary key
2141
+			//if we're counting distinct items, and there's no primary key,
2142
+			//we need to list out the columns for distinction;
2143
+			//otherwise we can just use star
2144
+			if ($distinct) {
2145
+				$columns_to_use = array();
2146
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2147
+					$columns_to_use[] = $field_obj->get_qualified_column();
2148
+				}
2149
+				$column_to_count = implode(',', $columns_to_use);
2150
+			} else {
2151
+				$column_to_count = '*';
2152
+			}
2153
+		}
2154
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2155
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2157
+	}
2158
+
2159
+
2160
+
2161
+	/**
2162
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2163
+	 *
2164
+	 * @param array  $query_params like EEM_Base::get_all
2165
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2166
+	 * @return float
2167
+	 * @throws \EE_Error
2168
+	 */
2169
+	public function sum($query_params, $field_to_sum = null)
2170
+	{
2171
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2172
+		if ($field_to_sum) {
2173
+			$field_obj = $this->field_settings_for($field_to_sum);
2174
+		} else {
2175
+			$field_obj = $this->get_primary_key_field();
2176
+		}
2177
+		$column_to_count = $field_obj->get_qualified_column();
2178
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2179
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2180
+		$data_type = $field_obj->get_wpdb_data_type();
2181
+		if ($data_type === '%d' || $data_type === '%s') {
2182
+			return (float)$return_value;
2183
+		} else {//must be %f
2184
+			return (float)$return_value;
2185
+		}
2186
+	}
2187
+
2188
+
2189
+
2190
+	/**
2191
+	 * Just calls the specified method on $wpdb with the given arguments
2192
+	 * Consolidates a little extra error handling code
2193
+	 *
2194
+	 * @param string $wpdb_method
2195
+	 * @param array  $arguments_to_provide
2196
+	 * @throws EE_Error
2197
+	 * @global wpdb  $wpdb
2198
+	 * @return mixed
2199
+	 */
2200
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2201
+	{
2202
+		//if we're in maintenance mode level 2, DON'T run any queries
2203
+		//because level 2 indicates the database needs updating and
2204
+		//is probably out of sync with the code
2205
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2206
+			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.",
2207
+				"event_espresso")));
2208
+		}
2209
+		/** @type WPDB $wpdb */
2210
+		global $wpdb;
2211
+		if (! method_exists($wpdb, $wpdb_method)) {
2212
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2213
+				'event_espresso'), $wpdb_method));
2214
+		}
2215
+		if (WP_DEBUG) {
2216
+			$old_show_errors_value = $wpdb->show_errors;
2217
+			$wpdb->show_errors(false);
2218
+		}
2219
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2220
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2221
+		if (WP_DEBUG) {
2222
+			$wpdb->show_errors($old_show_errors_value);
2223
+			if (! empty($wpdb->last_error)) {
2224
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2225
+			} elseif ($result === false) {
2226
+				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"',
2227
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2228
+			}
2229
+		} elseif ($result === false) {
2230
+			EE_Error::add_error(
2231
+				sprintf(
2232
+					__('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"',
2233
+						'event_espresso'),
2234
+					$wpdb_method,
2235
+					var_export($arguments_to_provide, true),
2236
+					$wpdb->last_error
2237
+				),
2238
+				__FILE__,
2239
+				__FUNCTION__,
2240
+				__LINE__
2241
+			);
2242
+		}
2243
+		return $result;
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2250
+	 * and if there's an error tries to verify the DB is correct. Uses
2251
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2252
+	 * we should try to fix the EE core db, the addons, or just give up
2253
+	 *
2254
+	 * @param string $wpdb_method
2255
+	 * @param array  $arguments_to_provide
2256
+	 * @return mixed
2257
+	 */
2258
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2259
+	{
2260
+		/** @type WPDB $wpdb */
2261
+		global $wpdb;
2262
+		$wpdb->last_error = null;
2263
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2264
+		// was there an error running the query? but we don't care on new activations
2265
+		// (we're going to setup the DB anyway on new activations)
2266
+		if (($result === false || ! empty($wpdb->last_error))
2267
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2268
+		) {
2269
+			switch (EEM_Base::$_db_verification_level) {
2270
+				case EEM_Base::db_verified_none :
2271
+					// let's double-check core's DB
2272
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2273
+					break;
2274
+				case EEM_Base::db_verified_core :
2275
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2276
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2277
+					break;
2278
+				case EEM_Base::db_verified_addons :
2279
+					// ummmm... you in trouble
2280
+					return $result;
2281
+					break;
2282
+			}
2283
+			if (! empty($error_message)) {
2284
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2285
+				trigger_error($error_message);
2286
+			}
2287
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2288
+		}
2289
+		return $result;
2290
+	}
2291
+
2292
+
2293
+
2294
+	/**
2295
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2296
+	 * EEM_Base::$_db_verification_level
2297
+	 *
2298
+	 * @param string $wpdb_method
2299
+	 * @param array  $arguments_to_provide
2300
+	 * @return string
2301
+	 */
2302
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2303
+	{
2304
+		/** @type WPDB $wpdb */
2305
+		global $wpdb;
2306
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2307
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2308
+		$error_message = sprintf(
2309
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2310
+				'event_espresso'),
2311
+			$wpdb->last_error,
2312
+			$wpdb_method,
2313
+			wp_json_encode($arguments_to_provide)
2314
+		);
2315
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2316
+		return $error_message;
2317
+	}
2318
+
2319
+
2320
+
2321
+	/**
2322
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2323
+	 * EEM_Base::$_db_verification_level
2324
+	 *
2325
+	 * @param $wpdb_method
2326
+	 * @param $arguments_to_provide
2327
+	 * @return string
2328
+	 */
2329
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2330
+	{
2331
+		/** @type WPDB $wpdb */
2332
+		global $wpdb;
2333
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2334
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2335
+		$error_message = sprintf(
2336
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2337
+				'event_espresso'),
2338
+			$wpdb->last_error,
2339
+			$wpdb_method,
2340
+			wp_json_encode($arguments_to_provide)
2341
+		);
2342
+		EE_System::instance()->initialize_addons();
2343
+		return $error_message;
2344
+	}
2345
+
2346
+
2347
+
2348
+	/**
2349
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2350
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2351
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2352
+	 * ..."
2353
+	 *
2354
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2355
+	 * @return string
2356
+	 */
2357
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2358
+	{
2359
+		return " FROM " . $model_query_info->get_full_join_sql() .
2360
+			   $model_query_info->get_where_sql() .
2361
+			   $model_query_info->get_group_by_sql() .
2362
+			   $model_query_info->get_having_sql() .
2363
+			   $model_query_info->get_order_by_sql() .
2364
+			   $model_query_info->get_limit_sql();
2365
+	}
2366
+
2367
+
2368
+
2369
+	/**
2370
+	 * Set to easily debug the next X queries ran from this model.
2371
+	 *
2372
+	 * @param int $count
2373
+	 */
2374
+	public function show_next_x_db_queries($count = 1)
2375
+	{
2376
+		$this->_show_next_x_db_queries = $count;
2377
+	}
2378
+
2379
+
2380
+
2381
+	/**
2382
+	 * @param $sql_query
2383
+	 */
2384
+	public function show_db_query_if_previously_requested($sql_query)
2385
+	{
2386
+		if ($this->_show_next_x_db_queries > 0) {
2387
+			echo $sql_query;
2388
+			$this->_show_next_x_db_queries--;
2389
+		}
2390
+	}
2391
+
2392
+
2393
+
2394
+	/**
2395
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2396
+	 * There are the 3 cases:
2397
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2398
+	 * $otherModelObject has no ID, it is first saved.
2399
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2400
+	 * has no ID, it is first saved.
2401
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2402
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2403
+	 * join table
2404
+	 *
2405
+	 * @param        EE_Base_Class                     /int $thisModelObject
2406
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2407
+	 * @param string $relationName                     , key in EEM_Base::_relations
2408
+	 *                                                 an attendee to a group, you also want to specify which role they
2409
+	 *                                                 will have in that group. So you would use this parameter to
2410
+	 *                                                 specify array('role-column-name'=>'role-id')
2411
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2412
+	 *                                                 to for relation to methods that allow you to further specify
2413
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2414
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2415
+	 *                                                 because these will be inserted in any new rows created as well.
2416
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2417
+	 * @throws \EE_Error
2418
+	 */
2419
+	public function add_relationship_to(
2420
+		$id_or_obj,
2421
+		$other_model_id_or_obj,
2422
+		$relationName,
2423
+		$extra_join_model_fields_n_values = array()
2424
+	) {
2425
+		$relation_obj = $this->related_settings_for($relationName);
2426
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2427
+	}
2428
+
2429
+
2430
+
2431
+	/**
2432
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2433
+	 * There are the 3 cases:
2434
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2435
+	 * error
2436
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2437
+	 * an error
2438
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2439
+	 *
2440
+	 * @param        EE_Base_Class /int $id_or_obj
2441
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2442
+	 * @param string $relationName key in EEM_Base::_relations
2443
+	 * @return boolean of success
2444
+	 * @throws \EE_Error
2445
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2446
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2447
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2448
+	 *                             because these will be inserted in any new rows created as well.
2449
+	 */
2450
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2451
+	{
2452
+		$relation_obj = $this->related_settings_for($relationName);
2453
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2454
+	}
2455
+
2456
+
2457
+
2458
+	/**
2459
+	 * @param mixed           $id_or_obj
2460
+	 * @param string          $relationName
2461
+	 * @param array           $where_query_params
2462
+	 * @param EE_Base_Class[] objects to which relations were removed
2463
+	 * @return \EE_Base_Class[]
2464
+	 * @throws \EE_Error
2465
+	 */
2466
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2467
+	{
2468
+		$relation_obj = $this->related_settings_for($relationName);
2469
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2470
+	}
2471
+
2472
+
2473
+
2474
+	/**
2475
+	 * Gets all the related items of the specified $model_name, using $query_params.
2476
+	 * Note: by default, we remove the "default query params"
2477
+	 * because we want to get even deleted items etc.
2478
+	 *
2479
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2480
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2481
+	 * @param array  $query_params like EEM_Base::get_all
2482
+	 * @return EE_Base_Class[]
2483
+	 * @throws \EE_Error
2484
+	 */
2485
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2486
+	{
2487
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2488
+		$relation_settings = $this->related_settings_for($model_name);
2489
+		return $relation_settings->get_all_related($model_obj, $query_params);
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * Deletes all the model objects across the relation indicated by $model_name
2496
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2497
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2498
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2499
+	 *
2500
+	 * @param EE_Base_Class|int|string $id_or_obj
2501
+	 * @param string                   $model_name
2502
+	 * @param array                    $query_params
2503
+	 * @return int how many deleted
2504
+	 * @throws \EE_Error
2505
+	 */
2506
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2507
+	{
2508
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2509
+		$relation_settings = $this->related_settings_for($model_name);
2510
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2511
+	}
2512
+
2513
+
2514
+
2515
+	/**
2516
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2517
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2518
+	 * the model objects can't be hard deleted because of blocking related model objects,
2519
+	 * just does a soft-delete on them instead.
2520
+	 *
2521
+	 * @param EE_Base_Class|int|string $id_or_obj
2522
+	 * @param string                   $model_name
2523
+	 * @param array                    $query_params
2524
+	 * @return int how many deleted
2525
+	 * @throws \EE_Error
2526
+	 */
2527
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2528
+	{
2529
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2530
+		$relation_settings = $this->related_settings_for($model_name);
2531
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2532
+	}
2533
+
2534
+
2535
+
2536
+	/**
2537
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2538
+	 * unless otherwise specified in the $query_params
2539
+	 *
2540
+	 * @param        int             /EE_Base_Class $id_or_obj
2541
+	 * @param string $model_name     like 'Event', or 'Registration'
2542
+	 * @param array  $query_params   like EEM_Base::get_all's
2543
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2544
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2545
+	 *                               that by the setting $distinct to TRUE;
2546
+	 * @return int
2547
+	 * @throws \EE_Error
2548
+	 */
2549
+	public function count_related(
2550
+		$id_or_obj,
2551
+		$model_name,
2552
+		$query_params = array(),
2553
+		$field_to_count = null,
2554
+		$distinct = false
2555
+	) {
2556
+		$related_model = $this->get_related_model_obj($model_name);
2557
+		//we're just going to use the query params on the related model's normal get_all query,
2558
+		//except add a condition to say to match the current mod
2559
+		if (! isset($query_params['default_where_conditions'])) {
2560
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2561
+		}
2562
+		$this_model_name = $this->get_this_model_name();
2563
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2564
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2565
+		return $related_model->count($query_params, $field_to_count, $distinct);
2566
+	}
2567
+
2568
+
2569
+
2570
+	/**
2571
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2572
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2573
+	 *
2574
+	 * @param        int           /EE_Base_Class $id_or_obj
2575
+	 * @param string $model_name   like 'Event', or 'Registration'
2576
+	 * @param array  $query_params like EEM_Base::get_all's
2577
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2578
+	 * @return float
2579
+	 * @throws \EE_Error
2580
+	 */
2581
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2582
+	{
2583
+		$related_model = $this->get_related_model_obj($model_name);
2584
+		if (! is_array($query_params)) {
2585
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2586
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2587
+					gettype($query_params)), '4.6.0');
2588
+			$query_params = array();
2589
+		}
2590
+		//we're just going to use the query params on the related model's normal get_all query,
2591
+		//except add a condition to say to match the current mod
2592
+		if (! isset($query_params['default_where_conditions'])) {
2593
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2594
+		}
2595
+		$this_model_name = $this->get_this_model_name();
2596
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2597
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2598
+		return $related_model->sum($query_params, $field_to_sum);
2599
+	}
2600
+
2601
+
2602
+
2603
+	/**
2604
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2605
+	 * $modelObject
2606
+	 *
2607
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2608
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2609
+	 * @param array               $query_params     like EEM_Base::get_all's
2610
+	 * @return EE_Base_Class
2611
+	 * @throws \EE_Error
2612
+	 */
2613
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2614
+	{
2615
+		$query_params['limit'] = 1;
2616
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2617
+		if ($results) {
2618
+			return array_shift($results);
2619
+		} else {
2620
+			return null;
2621
+		}
2622
+	}
2623
+
2624
+
2625
+
2626
+	/**
2627
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2628
+	 *
2629
+	 * @return string
2630
+	 */
2631
+	public function get_this_model_name()
2632
+	{
2633
+		return str_replace("EEM_", "", get_class($this));
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2640
+	 *
2641
+	 * @return EE_Any_Foreign_Model_Name_Field
2642
+	 * @throws EE_Error
2643
+	 */
2644
+	public function get_field_containing_related_model_name()
2645
+	{
2646
+		foreach ($this->field_settings(true) as $field) {
2647
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2648
+				$field_with_model_name = $field;
2649
+			}
2650
+		}
2651
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2652
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2653
+				$this->get_this_model_name()));
2654
+		}
2655
+		return $field_with_model_name;
2656
+	}
2657
+
2658
+
2659
+
2660
+	/**
2661
+	 * Inserts a new entry into the database, for each table.
2662
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2663
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2664
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2665
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2666
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2667
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2668
+	 *
2669
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2670
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2671
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2672
+	 *                              of EEM_Base)
2673
+	 * @return int new primary key on main table that got inserted
2674
+	 * @throws EE_Error
2675
+	 */
2676
+	public function insert($field_n_values)
2677
+	{
2678
+		/**
2679
+		 * Filters the fields and their values before inserting an item using the models
2680
+		 *
2681
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2682
+		 * @param EEM_Base $model           the model used
2683
+		 */
2684
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2685
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2686
+			$main_table = $this->_get_main_table();
2687
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2688
+			if ($new_id !== false) {
2689
+				foreach ($this->_get_other_tables() as $other_table) {
2690
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2691
+				}
2692
+			}
2693
+			/**
2694
+			 * Done just after attempting to insert a new model object
2695
+			 *
2696
+			 * @param EEM_Base   $model           used
2697
+			 * @param array      $fields_n_values fields and their values
2698
+			 * @param int|string the              ID of the newly-inserted model object
2699
+			 */
2700
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2701
+			return $new_id;
2702
+		} else {
2703
+			return false;
2704
+		}
2705
+	}
2706
+
2707
+
2708
+
2709
+	/**
2710
+	 * Checks that the result would satisfy the unique indexes on this model
2711
+	 *
2712
+	 * @param array  $field_n_values
2713
+	 * @param string $action
2714
+	 * @return boolean
2715
+	 * @throws \EE_Error
2716
+	 */
2717
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2718
+	{
2719
+		foreach ($this->unique_indexes() as $index_name => $index) {
2720
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2721
+			if ($this->exists(array($uniqueness_where_params))) {
2722
+				EE_Error::add_error(
2723
+					sprintf(
2724
+						__(
2725
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2726
+							"event_espresso"
2727
+						),
2728
+						$action,
2729
+						$this->_get_class_name(),
2730
+						$index_name,
2731
+						implode(",", $index->field_names()),
2732
+						http_build_query($uniqueness_where_params)
2733
+					),
2734
+					__FILE__,
2735
+					__FUNCTION__,
2736
+					__LINE__
2737
+				);
2738
+				return false;
2739
+			}
2740
+		}
2741
+		return true;
2742
+	}
2743
+
2744
+
2745
+
2746
+	/**
2747
+	 * Checks the database for an item that conflicts (ie, if this item were
2748
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2749
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2750
+	 * can be either an EE_Base_Class or an array of fields n values
2751
+	 *
2752
+	 * @param EE_Base_Class|array $obj_or_fields_array
2753
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2754
+	 *                                                 when looking for conflicts
2755
+	 *                                                 (ie, if false, we ignore the model object's primary key
2756
+	 *                                                 when finding "conflicts". If true, it's also considered).
2757
+	 *                                                 Only works for INT primary key,
2758
+	 *                                                 STRING primary keys cannot be ignored
2759
+	 * @throws EE_Error
2760
+	 * @return EE_Base_Class|array
2761
+	 */
2762
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2763
+	{
2764
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2765
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2766
+		} elseif (is_array($obj_or_fields_array)) {
2767
+			$fields_n_values = $obj_or_fields_array;
2768
+		} else {
2769
+			throw new EE_Error(
2770
+				sprintf(
2771
+					__(
2772
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2773
+						"event_espresso"
2774
+					),
2775
+					get_class($this),
2776
+					$obj_or_fields_array
2777
+				)
2778
+			);
2779
+		}
2780
+		$query_params = array();
2781
+		if ($this->has_primary_key_field()
2782
+			&& ($include_primary_key
2783
+				|| $this->get_primary_key_field()
2784
+				   instanceof
2785
+				   EE_Primary_Key_String_Field)
2786
+			&& isset($fields_n_values[$this->primary_key_name()])
2787
+		) {
2788
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2789
+		}
2790
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2791
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2792
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2793
+		}
2794
+		//if there is nothing to base this search on, then we shouldn't find anything
2795
+		if (empty($query_params)) {
2796
+			return array();
2797
+		} else {
2798
+			return $this->get_one($query_params);
2799
+		}
2800
+	}
2801
+
2802
+
2803
+
2804
+	/**
2805
+	 * Like count, but is optimized and returns a boolean instead of an int
2806
+	 *
2807
+	 * @param array $query_params
2808
+	 * @return boolean
2809
+	 * @throws \EE_Error
2810
+	 */
2811
+	public function exists($query_params)
2812
+	{
2813
+		$query_params['limit'] = 1;
2814
+		return $this->count($query_params) > 0;
2815
+	}
2816
+
2817
+
2818
+
2819
+	/**
2820
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2821
+	 *
2822
+	 * @param int|string $id
2823
+	 * @return boolean
2824
+	 * @throws \EE_Error
2825
+	 */
2826
+	public function exists_by_ID($id)
2827
+	{
2828
+		return $this->exists(
2829
+			array(
2830
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2831
+				array(
2832
+					$this->primary_key_name() => $id,
2833
+				),
2834
+			)
2835
+		);
2836
+	}
2837
+
2838
+
2839
+
2840
+	/**
2841
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2842
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2843
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2844
+	 * on the main table)
2845
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2846
+	 * cases where we want to call it directly rather than via insert().
2847
+	 *
2848
+	 * @access   protected
2849
+	 * @param EE_Table_Base $table
2850
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2851
+	 *                                       float
2852
+	 * @param int           $new_id          for now we assume only int keys
2853
+	 * @throws EE_Error
2854
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2855
+	 * @return int ID of new row inserted, or FALSE on failure
2856
+	 */
2857
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2858
+	{
2859
+		global $wpdb;
2860
+		$insertion_col_n_values = array();
2861
+		$format_for_insertion = array();
2862
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2863
+		foreach ($fields_on_table as $field_name => $field_obj) {
2864
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2865
+			if ($field_obj->is_auto_increment()) {
2866
+				continue;
2867
+			}
2868
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2869
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2870
+			if ($prepared_value !== null) {
2871
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2872
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2873
+			}
2874
+		}
2875
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2876
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2877
+			//so add the fk to the main table as a column
2878
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2879
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2880
+		}
2881
+		//insert the new entry
2882
+		$result = $this->_do_wpdb_query('insert',
2883
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2884
+		if ($result === false) {
2885
+			return false;
2886
+		}
2887
+		//ok, now what do we return for the ID of the newly-inserted thing?
2888
+		if ($this->has_primary_key_field()) {
2889
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2890
+				return $wpdb->insert_id;
2891
+			} else {
2892
+				//it's not an auto-increment primary key, so
2893
+				//it must have been supplied
2894
+				return $fields_n_values[$this->get_primary_key_field()->get_name()];
2895
+			}
2896
+		} else {
2897
+			//we can't return a  primary key because there is none. instead return
2898
+			//a unique string indicating this model
2899
+			return $this->get_index_primary_key_string($fields_n_values);
2900
+		}
2901
+	}
2902
+
2903
+
2904
+
2905
+	/**
2906
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
2907
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
2908
+	 * and there is no default, we pass it along. WPDB will take care of it)
2909
+	 *
2910
+	 * @param EE_Model_Field_Base $field_obj
2911
+	 * @param array               $fields_n_values
2912
+	 * @return mixed string|int|float depending on what the table column will be expecting
2913
+	 * @throws \EE_Error
2914
+	 */
2915
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2916
+	{
2917
+		//if this field doesn't allow nullable, don't allow it
2918
+		if (! $field_obj->is_nullable()
2919
+			&& (
2920
+				! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2921
+		) {
2922
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
2923
+		}
2924
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()]) ? $fields_n_values[$field_obj->get_name()]
2925
+			: null;
2926
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
2927
+	}
2928
+
2929
+
2930
+
2931
+	/**
2932
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
2933
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
2934
+	 * the field's prepare_for_set() method.
2935
+	 *
2936
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
2937
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
2938
+	 *                                   top of file)
2939
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
2940
+	 *                                   $value is a custom selection
2941
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
2942
+	 */
2943
+	private function _prepare_value_for_use_in_db($value, $field)
2944
+	{
2945
+		if ($field && $field instanceof EE_Model_Field_Base) {
2946
+			switch ($this->_values_already_prepared_by_model_object) {
2947
+				/** @noinspection PhpMissingBreakStatementInspection */
2948
+				case self::not_prepared_by_model_object:
2949
+					$value = $field->prepare_for_set($value);
2950
+				//purposefully left out "return"
2951
+				case self::prepared_by_model_object:
2952
+					$value = $field->prepare_for_use_in_db($value);
2953
+				case self::prepared_for_use_in_db:
2954
+					//leave the value alone
2955
+			}
2956
+			return $value;
2957
+		} else {
2958
+			return $value;
2959
+		}
2960
+	}
2961
+
2962
+
2963
+
2964
+	/**
2965
+	 * Returns the main table on this model
2966
+	 *
2967
+	 * @return EE_Primary_Table
2968
+	 * @throws EE_Error
2969
+	 */
2970
+	protected function _get_main_table()
2971
+	{
2972
+		foreach ($this->_tables as $table) {
2973
+			if ($table instanceof EE_Primary_Table) {
2974
+				return $table;
2975
+			}
2976
+		}
2977
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
2978
+			'event_espresso'), get_class($this)));
2979
+	}
2980
+
2981
+
2982
+
2983
+	/**
2984
+	 * table
2985
+	 * returns EE_Primary_Table table name
2986
+	 *
2987
+	 * @return string
2988
+	 * @throws \EE_Error
2989
+	 */
2990
+	public function table()
2991
+	{
2992
+		return $this->_get_main_table()->get_table_name();
2993
+	}
2994
+
2995
+
2996
+
2997
+	/**
2998
+	 * table
2999
+	 * returns first EE_Secondary_Table table name
3000
+	 *
3001
+	 * @return string
3002
+	 */
3003
+	public function second_table()
3004
+	{
3005
+		// grab second table from tables array
3006
+		$second_table = end($this->_tables);
3007
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3008
+	}
3009
+
3010
+
3011
+
3012
+	/**
3013
+	 * get_table_obj_by_alias
3014
+	 * returns table name given it's alias
3015
+	 *
3016
+	 * @param string $table_alias
3017
+	 * @return EE_Primary_Table | EE_Secondary_Table
3018
+	 */
3019
+	public function get_table_obj_by_alias($table_alias = '')
3020
+	{
3021
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3022
+	}
3023
+
3024
+
3025
+
3026
+	/**
3027
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3028
+	 *
3029
+	 * @return EE_Secondary_Table[]
3030
+	 */
3031
+	protected function _get_other_tables()
3032
+	{
3033
+		$other_tables = array();
3034
+		foreach ($this->_tables as $table_alias => $table) {
3035
+			if ($table instanceof EE_Secondary_Table) {
3036
+				$other_tables[$table_alias] = $table;
3037
+			}
3038
+		}
3039
+		return $other_tables;
3040
+	}
3041
+
3042
+
3043
+
3044
+	/**
3045
+	 * Finds all the fields that correspond to the given table
3046
+	 *
3047
+	 * @param string $table_alias , array key in EEM_Base::_tables
3048
+	 * @return EE_Model_Field_Base[]
3049
+	 */
3050
+	public function _get_fields_for_table($table_alias)
3051
+	{
3052
+		return $this->_fields[$table_alias];
3053
+	}
3054
+
3055
+
3056
+
3057
+	/**
3058
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3059
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3060
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3061
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3062
+	 * related Registration, Transaction, and Payment models.
3063
+	 *
3064
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3065
+	 * @return EE_Model_Query_Info_Carrier
3066
+	 * @throws \EE_Error
3067
+	 */
3068
+	public function _extract_related_models_from_query($query_params)
3069
+	{
3070
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3071
+		if (array_key_exists(0, $query_params)) {
3072
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3073
+		}
3074
+		if (array_key_exists('group_by', $query_params)) {
3075
+			if (is_array($query_params['group_by'])) {
3076
+				$this->_extract_related_models_from_sub_params_array_values(
3077
+					$query_params['group_by'],
3078
+					$query_info_carrier,
3079
+					'group_by'
3080
+				);
3081
+			} elseif (! empty ($query_params['group_by'])) {
3082
+				$this->_extract_related_model_info_from_query_param(
3083
+					$query_params['group_by'],
3084
+					$query_info_carrier,
3085
+					'group_by'
3086
+				);
3087
+			}
3088
+		}
3089
+		if (array_key_exists('having', $query_params)) {
3090
+			$this->_extract_related_models_from_sub_params_array_keys(
3091
+				$query_params[0],
3092
+				$query_info_carrier,
3093
+				'having'
3094
+			);
3095
+		}
3096
+		if (array_key_exists('order_by', $query_params)) {
3097
+			if (is_array($query_params['order_by'])) {
3098
+				$this->_extract_related_models_from_sub_params_array_keys(
3099
+					$query_params['order_by'],
3100
+					$query_info_carrier,
3101
+					'order_by'
3102
+				);
3103
+			} elseif (! empty($query_params['order_by'])) {
3104
+				$this->_extract_related_model_info_from_query_param(
3105
+					$query_params['order_by'],
3106
+					$query_info_carrier,
3107
+					'order_by'
3108
+				);
3109
+			}
3110
+		}
3111
+		if (array_key_exists('force_join', $query_params)) {
3112
+			$this->_extract_related_models_from_sub_params_array_values(
3113
+				$query_params['force_join'],
3114
+				$query_info_carrier,
3115
+				'force_join'
3116
+			);
3117
+		}
3118
+		return $query_info_carrier;
3119
+	}
3120
+
3121
+
3122
+
3123
+	/**
3124
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3125
+	 *
3126
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3127
+	 *                                                      $query_params['having']
3128
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3129
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3130
+	 * @throws EE_Error
3131
+	 * @return \EE_Model_Query_Info_Carrier
3132
+	 */
3133
+	private function _extract_related_models_from_sub_params_array_keys(
3134
+		$sub_query_params,
3135
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3136
+		$query_param_type
3137
+	) {
3138
+		if (! empty($sub_query_params)) {
3139
+			$sub_query_params = (array)$sub_query_params;
3140
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3141
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3142
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3143
+					$query_param_type);
3144
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3145
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3146
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3147
+				//of array('Registration.TXN_ID'=>23)
3148
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3149
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3150
+					if (! is_array($possibly_array_of_params)) {
3151
+						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'))",
3152
+							"event_espresso"),
3153
+							$param, $possibly_array_of_params));
3154
+					} else {
3155
+						$this->_extract_related_models_from_sub_params_array_keys($possibly_array_of_params,
3156
+							$model_query_info_carrier, $query_param_type);
3157
+					}
3158
+				} elseif ($query_param_type === 0 //ie WHERE
3159
+						  && is_array($possibly_array_of_params)
3160
+						  && isset($possibly_array_of_params[2])
3161
+						  && $possibly_array_of_params[2] == true
3162
+				) {
3163
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3164
+					//indicating that $possible_array_of_params[1] is actually a field name,
3165
+					//from which we should extract query parameters!
3166
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3167
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3168
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3169
+					}
3170
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3171
+						$model_query_info_carrier, $query_param_type);
3172
+				}
3173
+			}
3174
+		}
3175
+		return $model_query_info_carrier;
3176
+	}
3177
+
3178
+
3179
+
3180
+	/**
3181
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3182
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3183
+	 *
3184
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3185
+	 *                                                      $query_params['having']
3186
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3187
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3188
+	 * @throws EE_Error
3189
+	 * @return \EE_Model_Query_Info_Carrier
3190
+	 */
3191
+	private function _extract_related_models_from_sub_params_array_values(
3192
+		$sub_query_params,
3193
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3194
+		$query_param_type
3195
+	) {
3196
+		if (! empty($sub_query_params)) {
3197
+			if (! is_array($sub_query_params)) {
3198
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3199
+					$sub_query_params));
3200
+			}
3201
+			foreach ($sub_query_params as $param) {
3202
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3203
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3204
+					$query_param_type);
3205
+			}
3206
+		}
3207
+		return $model_query_info_carrier;
3208
+	}
3209
+
3210
+
3211
+
3212
+	/**
3213
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3214
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3215
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3216
+	 * but use them in a different order. Eg, we need to know what models we are querying
3217
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3218
+	 * other models before we can finalize the where clause SQL.
3219
+	 *
3220
+	 * @param array $query_params
3221
+	 * @throws EE_Error
3222
+	 * @return EE_Model_Query_Info_Carrier
3223
+	 */
3224
+	public function _create_model_query_info_carrier($query_params)
3225
+	{
3226
+		if (! is_array($query_params)) {
3227
+			EE_Error::doing_it_wrong(
3228
+				'EEM_Base::_create_model_query_info_carrier',
3229
+				sprintf(
3230
+					__(
3231
+						'$query_params should be an array, you passed a variable of type %s',
3232
+						'event_espresso'
3233
+					),
3234
+					gettype($query_params)
3235
+				),
3236
+				'4.6.0'
3237
+			);
3238
+			$query_params = array();
3239
+		}
3240
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3241
+		//first check if we should alter the query to account for caps or not
3242
+		//because the caps might require us to do extra joins
3243
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3244
+			$query_params[0] = $where_query_params = array_replace_recursive(
3245
+				$where_query_params,
3246
+				$this->caps_where_conditions(
3247
+					$query_params['caps']
3248
+				)
3249
+			);
3250
+		}
3251
+		$query_object = $this->_extract_related_models_from_query($query_params);
3252
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3253
+		foreach ($where_query_params as $key => $value) {
3254
+			if (is_int($key)) {
3255
+				throw new EE_Error(
3256
+					sprintf(
3257
+						__(
3258
+							"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.",
3259
+							"event_espresso"
3260
+						),
3261
+						$key,
3262
+						var_export($value, true),
3263
+						var_export($query_params, true),
3264
+						get_class($this)
3265
+					)
3266
+				);
3267
+			}
3268
+		}
3269
+		if (
3270
+			array_key_exists('default_where_conditions', $query_params)
3271
+			&& ! empty($query_params['default_where_conditions'])
3272
+		) {
3273
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3274
+		} else {
3275
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3276
+		}
3277
+		$where_query_params = array_merge(
3278
+			$this->_get_default_where_conditions_for_models_in_query(
3279
+				$query_object,
3280
+				$use_default_where_conditions,
3281
+				$where_query_params
3282
+			),
3283
+			$where_query_params
3284
+		);
3285
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3286
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3287
+		// So we need to setup a subquery and use that for the main join.
3288
+		// Note for now this only works on the primary table for the model.
3289
+		// So for instance, you could set the limit array like this:
3290
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3291
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3292
+			$query_object->set_main_model_join_sql(
3293
+				$this->_construct_limit_join_select(
3294
+					$query_params['on_join_limit'][0],
3295
+					$query_params['on_join_limit'][1]
3296
+				)
3297
+			);
3298
+		}
3299
+		//set limit
3300
+		if (array_key_exists('limit', $query_params)) {
3301
+			if (is_array($query_params['limit'])) {
3302
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3303
+					$e = sprintf(
3304
+						__(
3305
+							"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)",
3306
+							"event_espresso"
3307
+						),
3308
+						http_build_query($query_params['limit'])
3309
+					);
3310
+					throw new EE_Error($e . "|" . $e);
3311
+				}
3312
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3313
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3314
+			} elseif (! empty ($query_params['limit'])) {
3315
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3316
+			}
3317
+		}
3318
+		//set order by
3319
+		if (array_key_exists('order_by', $query_params)) {
3320
+			if (is_array($query_params['order_by'])) {
3321
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3322
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3323
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3324
+				if (array_key_exists('order', $query_params)) {
3325
+					throw new EE_Error(
3326
+						sprintf(
3327
+							__(
3328
+								"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 ",
3329
+								"event_espresso"
3330
+							),
3331
+							get_class($this),
3332
+							implode(", ", array_keys($query_params['order_by'])),
3333
+							implode(", ", $query_params['order_by']),
3334
+							$query_params['order']
3335
+						)
3336
+					);
3337
+				}
3338
+				$this->_extract_related_models_from_sub_params_array_keys(
3339
+					$query_params['order_by'],
3340
+					$query_object,
3341
+					'order_by'
3342
+				);
3343
+				//assume it's an array of fields to order by
3344
+				$order_array = array();
3345
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3346
+					$order = $this->_extract_order($order);
3347
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3348
+				}
3349
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3350
+			} elseif (! empty ($query_params['order_by'])) {
3351
+				$this->_extract_related_model_info_from_query_param(
3352
+					$query_params['order_by'],
3353
+					$query_object,
3354
+					'order',
3355
+					$query_params['order_by']
3356
+				);
3357
+				$order = isset($query_params['order'])
3358
+					? $this->_extract_order($query_params['order'])
3359
+					: 'DESC';
3360
+				$query_object->set_order_by_sql(
3361
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3362
+				);
3363
+			}
3364
+		}
3365
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3366
+		if (! array_key_exists('order_by', $query_params)
3367
+			&& array_key_exists('order', $query_params)
3368
+			&& ! empty($query_params['order'])
3369
+		) {
3370
+			$pk_field = $this->get_primary_key_field();
3371
+			$order = $this->_extract_order($query_params['order']);
3372
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3373
+		}
3374
+		//set group by
3375
+		if (array_key_exists('group_by', $query_params)) {
3376
+			if (is_array($query_params['group_by'])) {
3377
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3378
+				$group_by_array = array();
3379
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3380
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3381
+				}
3382
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3383
+			} elseif (! empty ($query_params['group_by'])) {
3384
+				$query_object->set_group_by_sql(
3385
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3386
+				);
3387
+			}
3388
+		}
3389
+		//set having
3390
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3391
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3392
+		}
3393
+		//now, just verify they didn't pass anything wack
3394
+		foreach ($query_params as $query_key => $query_value) {
3395
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3396
+				throw new EE_Error(
3397
+					sprintf(
3398
+						__(
3399
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3400
+							'event_espresso'
3401
+						),
3402
+						$query_key,
3403
+						get_class($this),
3404
+						//						print_r( $this->_allowed_query_params, TRUE )
3405
+						implode(',', $this->_allowed_query_params)
3406
+					)
3407
+				);
3408
+			}
3409
+		}
3410
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3411
+		if (empty($main_model_join_sql)) {
3412
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3413
+		}
3414
+		return $query_object;
3415
+	}
3416
+
3417
+
3418
+
3419
+	/**
3420
+	 * Gets the where conditions that should be imposed on the query based on the
3421
+	 * context (eg reading frontend, backend, edit or delete).
3422
+	 *
3423
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3424
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3425
+	 * @throws \EE_Error
3426
+	 */
3427
+	public function caps_where_conditions($context = self::caps_read)
3428
+	{
3429
+		EEM_Base::verify_is_valid_cap_context($context);
3430
+		$cap_where_conditions = array();
3431
+		$cap_restrictions = $this->caps_missing($context);
3432
+		/**
3433
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3434
+		 */
3435
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3436
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3437
+				$restriction_if_no_cap->get_default_where_conditions());
3438
+		}
3439
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3440
+			$cap_restrictions);
3441
+	}
3442
+
3443
+
3444
+
3445
+	/**
3446
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3447
+	 * otherwise throws an exception
3448
+	 *
3449
+	 * @param string $should_be_order_string
3450
+	 * @return string either ASC, asc, DESC or desc
3451
+	 * @throws EE_Error
3452
+	 */
3453
+	private function _extract_order($should_be_order_string)
3454
+	{
3455
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3456
+			return $should_be_order_string;
3457
+		} else {
3458
+			throw new EE_Error(sprintf(__("While performing a query on '%s', tried to use '%s' as an order parameter. ",
3459
+				"event_espresso"), get_class($this), $should_be_order_string));
3460
+		}
3461
+	}
3462
+
3463
+
3464
+
3465
+	/**
3466
+	 * Looks at all the models which are included in this query, and asks each
3467
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3468
+	 * so they can be merged
3469
+	 *
3470
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3471
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3472
+	 *                                                                  'none' means NO default where conditions will
3473
+	 *                                                                  be used AT ALL during this query.
3474
+	 *                                                                  'other_models_only' means default where
3475
+	 *                                                                  conditions from other models will be used, but
3476
+	 *                                                                  not for this primary model. 'all', the default,
3477
+	 *                                                                  means default where conditions will apply as
3478
+	 *                                                                  normal
3479
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3480
+	 * @throws EE_Error
3481
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3482
+	 */
3483
+	private function _get_default_where_conditions_for_models_in_query(
3484
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3485
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3486
+		$where_query_params = array()
3487
+	) {
3488
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3489
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3490
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3491
+				"event_espresso"), $use_default_where_conditions,
3492
+				implode(", ", $allowed_used_default_where_conditions_values)));
3493
+		}
3494
+		$universal_query_params = array();
3495
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3496
+			$universal_query_params = $this->_get_default_where_conditions();
3497
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3498
+			$universal_query_params = $this->_get_minimum_where_conditions();
3499
+		}
3500
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3501
+			$related_model = $this->get_related_model_obj($model_name);
3502
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3503
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3504
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3505
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3506
+			} else {
3507
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3508
+				continue;
3509
+			}
3510
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3511
+				$related_model_universal_where_params,
3512
+				$where_query_params,
3513
+				$related_model,
3514
+				$model_relation_path
3515
+			);
3516
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3517
+				$universal_query_params,
3518
+				$overrides
3519
+			);
3520
+		}
3521
+		return $universal_query_params;
3522
+	}
3523
+
3524
+
3525
+
3526
+	/**
3527
+	 * Determines whether or not we should use default where conditions for the model in question
3528
+	 * (this model, or other related models).
3529
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3530
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3531
+	 * We should use default where conditions on related models when they requested to use default where conditions
3532
+	 * on all models, or specifically just on other related models
3533
+	 * @param      $default_where_conditions_value
3534
+	 * @param bool $for_this_model false means this is for OTHER related models
3535
+	 * @return bool
3536
+	 */
3537
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3538
+	{
3539
+		return (
3540
+				   $for_this_model
3541
+				   && in_array(
3542
+					   $default_where_conditions_value,
3543
+					   array(
3544
+						   EEM_Base::default_where_conditions_all,
3545
+						   EEM_Base::default_where_conditions_this_only,
3546
+						   EEM_Base::default_where_conditions_minimum_others,
3547
+					   ),
3548
+					   true
3549
+				   )
3550
+			   )
3551
+			   || (
3552
+				   ! $for_this_model
3553
+				   && in_array(
3554
+					   $default_where_conditions_value,
3555
+					   array(
3556
+						   EEM_Base::default_where_conditions_all,
3557
+						   EEM_Base::default_where_conditions_others_only,
3558
+					   ),
3559
+					   true
3560
+				   )
3561
+			   );
3562
+	}
3563
+
3564
+	/**
3565
+	 * Determines whether or not we should use default minimum conditions for the model in question
3566
+	 * (this model, or other related models).
3567
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3568
+	 * where conditions.
3569
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3570
+	 * on this model or others
3571
+	 * @param      $default_where_conditions_value
3572
+	 * @param bool $for_this_model false means this is for OTHER related models
3573
+	 * @return bool
3574
+	 */
3575
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3576
+	{
3577
+		return (
3578
+				   $for_this_model
3579
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3580
+			   )
3581
+			   || (
3582
+				   ! $for_this_model
3583
+				   && in_array(
3584
+					   $default_where_conditions_value,
3585
+					   array(
3586
+						   EEM_Base::default_where_conditions_minimum_others,
3587
+						   EEM_Base::default_where_conditions_minimum_all,
3588
+					   ),
3589
+					   true
3590
+				   )
3591
+			   );
3592
+	}
3593
+
3594
+
3595
+	/**
3596
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3597
+	 * then we also add a special where condition which allows for that model's primary key
3598
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3599
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3600
+	 *
3601
+	 * @param array    $default_where_conditions
3602
+	 * @param array    $provided_where_conditions
3603
+	 * @param EEM_Base $model
3604
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3605
+	 * @return array like EEM_Base::get_all's $query_params[0]
3606
+	 * @throws \EE_Error
3607
+	 */
3608
+	private function _override_defaults_or_make_null_friendly(
3609
+		$default_where_conditions,
3610
+		$provided_where_conditions,
3611
+		$model,
3612
+		$model_relation_path
3613
+	) {
3614
+		$null_friendly_where_conditions = array();
3615
+		$none_overridden = true;
3616
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3617
+		foreach ($default_where_conditions as $key => $val) {
3618
+			if (isset($provided_where_conditions[$key])) {
3619
+				$none_overridden = false;
3620
+			} else {
3621
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3622
+			}
3623
+		}
3624
+		if ($none_overridden && $default_where_conditions) {
3625
+			if ($model->has_primary_key_field()) {
3626
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3627
+																				. "."
3628
+																				. $model->primary_key_name()] = array('IS NULL');
3629
+			}/*else{
3630 3630
 				//@todo NO PK, use other defaults
3631 3631
 			}*/
3632
-        }
3633
-        return $null_friendly_where_conditions;
3634
-    }
3635
-
3636
-
3637
-
3638
-    /**
3639
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3640
-     * default where conditions on all get_all, update, and delete queries done by this model.
3641
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3642
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3643
-     *
3644
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3645
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3646
-     */
3647
-    private function _get_default_where_conditions($model_relation_path = null)
3648
-    {
3649
-        if ($this->_ignore_where_strategy) {
3650
-            return array();
3651
-        }
3652
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3653
-    }
3654
-
3655
-
3656
-
3657
-    /**
3658
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3659
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3660
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3661
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3662
-     * Similar to _get_default_where_conditions
3663
-     *
3664
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3665
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3666
-     */
3667
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3668
-    {
3669
-        if ($this->_ignore_where_strategy) {
3670
-            return array();
3671
-        }
3672
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3673
-    }
3674
-
3675
-
3676
-
3677
-    /**
3678
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3679
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3680
-     *
3681
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3682
-     * @return string
3683
-     * @throws \EE_Error
3684
-     */
3685
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3686
-    {
3687
-        $selects = $this->_get_columns_to_select_for_this_model();
3688
-        foreach (
3689
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3690
-            $name_of_other_model_included
3691
-        ) {
3692
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3693
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3694
-            foreach ($other_model_selects as $key => $value) {
3695
-                $selects[] = $value;
3696
-            }
3697
-        }
3698
-        return implode(", ", $selects);
3699
-    }
3700
-
3701
-
3702
-
3703
-    /**
3704
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3705
-     * So that's going to be the columns for all the fields on the model
3706
-     *
3707
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3708
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3709
-     */
3710
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3711
-    {
3712
-        $fields = $this->field_settings();
3713
-        $selects = array();
3714
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3715
-            $this->get_this_model_name());
3716
-        foreach ($fields as $field_obj) {
3717
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3718
-                         . $field_obj->get_table_alias()
3719
-                         . "."
3720
-                         . $field_obj->get_table_column()
3721
-                         . " AS '"
3722
-                         . $table_alias_with_model_relation_chain_prefix
3723
-                         . $field_obj->get_table_alias()
3724
-                         . "."
3725
-                         . $field_obj->get_table_column()
3726
-                         . "'";
3727
-        }
3728
-        //make sure we are also getting the PKs of each table
3729
-        $tables = $this->get_tables();
3730
-        if (count($tables) > 1) {
3731
-            foreach ($tables as $table_obj) {
3732
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3733
-                                       . $table_obj->get_fully_qualified_pk_column();
3734
-                if (! in_array($qualified_pk_column, $selects)) {
3735
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3736
-                }
3737
-            }
3738
-        }
3739
-        return $selects;
3740
-    }
3741
-
3742
-
3743
-
3744
-    /**
3745
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3746
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3747
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3748
-     * SQL for joining, and the data types
3749
-     *
3750
-     * @param null|string                 $original_query_param
3751
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3752
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3753
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3754
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3755
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3756
-     *                                                          or 'Registration's
3757
-     * @param string                      $original_query_param what it originally was (eg
3758
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3759
-     *                                                          matches $query_param
3760
-     * @throws EE_Error
3761
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3762
-     */
3763
-    private function _extract_related_model_info_from_query_param(
3764
-        $query_param,
3765
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3766
-        $query_param_type,
3767
-        $original_query_param = null
3768
-    ) {
3769
-        if ($original_query_param === null) {
3770
-            $original_query_param = $query_param;
3771
-        }
3772
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3773
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3774
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3775
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3776
-        //check to see if we have a field on this model
3777
-        $this_model_fields = $this->field_settings(true);
3778
-        if (array_key_exists($query_param, $this_model_fields)) {
3779
-            if ($allow_fields) {
3780
-                return;
3781
-            } else {
3782
-                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",
3783
-                    "event_espresso"),
3784
-                    $query_param, get_class($this), $query_param_type, $original_query_param));
3785
-            }
3786
-        } //check if this is a special logic query param
3787
-        elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3788
-            if ($allow_logic_query_params) {
3789
-                return;
3790
-            } else {
3791
-                throw new EE_Error(
3792
-                    sprintf(
3793
-                        __('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',
3794
-                            'event_espresso'),
3795
-                        implode('", "', $this->_logic_query_param_keys),
3796
-                        $query_param,
3797
-                        get_class($this),
3798
-                        '<br />',
3799
-                        "\t"
3800
-                        . ' $passed_in_query_info = <pre>'
3801
-                        . print_r($passed_in_query_info, true)
3802
-                        . '</pre>'
3803
-                        . "\n\t"
3804
-                        . ' $query_param_type = '
3805
-                        . $query_param_type
3806
-                        . "\n\t"
3807
-                        . ' $original_query_param = '
3808
-                        . $original_query_param
3809
-                    )
3810
-                );
3811
-            }
3812
-        } //check if it's a custom selection
3813
-        elseif (array_key_exists($query_param, $this->_custom_selections)) {
3814
-            return;
3815
-        }
3816
-        //check if has a model name at the beginning
3817
-        //and
3818
-        //check if it's a field on a related model
3819
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3820
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3821
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3822
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3823
-                if ($query_param === '') {
3824
-                    //nothing left to $query_param
3825
-                    //we should actually end in a field name, not a model like this!
3826
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3827
-                        "event_espresso"),
3828
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3829
-                } else {
3830
-                    $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3831
-                    $related_model_obj->_extract_related_model_info_from_query_param($query_param,
3832
-                        $passed_in_query_info, $query_param_type, $original_query_param);
3833
-                    return;
3834
-                }
3835
-            } elseif ($query_param === $valid_related_model_name) {
3836
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3837
-                return;
3838
-            }
3839
-        }
3840
-        //ok so $query_param didn't start with a model name
3841
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3842
-        //it's wack, that's what it is
3843
-        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",
3844
-            "event_espresso"),
3845
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3846
-    }
3847
-
3848
-
3849
-
3850
-    /**
3851
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3852
-     * and store it on $passed_in_query_info
3853
-     *
3854
-     * @param string                      $model_name
3855
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3856
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3857
-     *                                                          model and $model_name. Eg, if we are querying Event,
3858
-     *                                                          and are adding a join to 'Payment' with the original
3859
-     *                                                          query param key
3860
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3861
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3862
-     *                                                          Payment wants to add default query params so that it
3863
-     *                                                          will know what models to prepend onto its default query
3864
-     *                                                          params or in case it wants to rename tables (in case
3865
-     *                                                          there are multiple joins to the same table)
3866
-     * @return void
3867
-     * @throws \EE_Error
3868
-     */
3869
-    private function _add_join_to_model(
3870
-        $model_name,
3871
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3872
-        $original_query_param
3873
-    ) {
3874
-        $relation_obj = $this->related_settings_for($model_name);
3875
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3876
-        //check if the relation is HABTM, because then we're essentially doing two joins
3877
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3878
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3879
-            $join_model_obj = $relation_obj->get_join_model();
3880
-            //replace the model specified with the join model for this relation chain, whi
3881
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3882
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
3883
-            $new_query_info = new EE_Model_Query_Info_Carrier(
3884
-                array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3885
-                $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3886
-            $passed_in_query_info->merge($new_query_info);
3887
-        }
3888
-        //now just join to the other table pointed to by the relation object, and add its data types
3889
-        $new_query_info = new EE_Model_Query_Info_Carrier(
3890
-            array($model_relation_chain => $model_name),
3891
-            $relation_obj->get_join_statement($model_relation_chain));
3892
-        $passed_in_query_info->merge($new_query_info);
3893
-    }
3894
-
3895
-
3896
-
3897
-    /**
3898
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3899
-     *
3900
-     * @param array $where_params like EEM_Base::get_all
3901
-     * @return string of SQL
3902
-     * @throws \EE_Error
3903
-     */
3904
-    private function _construct_where_clause($where_params)
3905
-    {
3906
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3907
-        if ($SQL) {
3908
-            return " WHERE " . $SQL;
3909
-        } else {
3910
-            return '';
3911
-        }
3912
-    }
3913
-
3914
-
3915
-
3916
-    /**
3917
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3918
-     * and should be passed HAVING parameters, not WHERE parameters
3919
-     *
3920
-     * @param array $having_params
3921
-     * @return string
3922
-     * @throws \EE_Error
3923
-     */
3924
-    private function _construct_having_clause($having_params)
3925
-    {
3926
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3927
-        if ($SQL) {
3928
-            return " HAVING " . $SQL;
3929
-        } else {
3930
-            return '';
3931
-        }
3932
-    }
3933
-
3934
-
3935
-    /**
3936
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3937
-     * Event_Meta.meta_value = 'foo'))"
3938
-     *
3939
-     * @param array  $where_params see EEM_Base::get_all for documentation
3940
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3941
-     * @throws EE_Error
3942
-     * @return string of SQL
3943
-     */
3944
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3945
-    {
3946
-        $where_clauses = array();
3947
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3948
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3949
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
3950
-                switch ($query_param) {
3951
-                    case 'not':
3952
-                    case 'NOT':
3953
-                        $where_clauses[] = "! ("
3954
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3955
-                                $glue)
3956
-                                           . ")";
3957
-                        break;
3958
-                    case 'and':
3959
-                    case 'AND':
3960
-                        $where_clauses[] = " ("
3961
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3962
-                                ' AND ')
3963
-                                           . ")";
3964
-                        break;
3965
-                    case 'or':
3966
-                    case 'OR':
3967
-                        $where_clauses[] = " ("
3968
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3969
-                                ' OR ')
3970
-                                           . ")";
3971
-                        break;
3972
-                }
3973
-            } else {
3974
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
3975
-                //if it's not a normal field, maybe it's a custom selection?
3976
-                if (! $field_obj) {
3977
-                    if (isset($this->_custom_selections[$query_param][1])) {
3978
-                        $field_obj = $this->_custom_selections[$query_param][1];
3979
-                    } else {
3980
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3981
-                            "event_espresso"), $query_param));
3982
-                    }
3983
-                }
3984
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3985
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3986
-            }
3987
-        }
3988
-        return $where_clauses ? implode($glue, $where_clauses) : '';
3989
-    }
3990
-
3991
-
3992
-
3993
-    /**
3994
-     * Takes the input parameter and extract the table name (alias) and column name
3995
-     *
3996
-     * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3997
-     * @throws EE_Error
3998
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3999
-     */
4000
-    private function _deduce_column_name_from_query_param($query_param)
4001
-    {
4002
-        $field = $this->_deduce_field_from_query_param($query_param);
4003
-        if ($field) {
4004
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4005
-                $query_param);
4006
-            return $table_alias_prefix . $field->get_qualified_column();
4007
-        } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4008
-            //maybe it's custom selection item?
4009
-            //if so, just use it as the "column name"
4010
-            return $query_param;
4011
-        } else {
4012
-            throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4013
-                "event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4014
-        }
4015
-    }
4016
-
4017
-
4018
-
4019
-    /**
4020
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4021
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4022
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4023
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4024
-     *
4025
-     * @param string $condition_query_param_key
4026
-     * @return string
4027
-     */
4028
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4029
-    {
4030
-        $pos_of_star = strpos($condition_query_param_key, '*');
4031
-        if ($pos_of_star === false) {
4032
-            return $condition_query_param_key;
4033
-        } else {
4034
-            $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4035
-            return $condition_query_param_sans_star;
4036
-        }
4037
-    }
4038
-
4039
-
4040
-
4041
-    /**
4042
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4043
-     *
4044
-     * @param                            mixed      array | string    $op_and_value
4045
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4046
-     * @throws EE_Error
4047
-     * @return string
4048
-     */
4049
-    private function _construct_op_and_value($op_and_value, $field_obj)
4050
-    {
4051
-        if (is_array($op_and_value)) {
4052
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4053
-            if (! $operator) {
4054
-                $php_array_like_string = array();
4055
-                foreach ($op_and_value as $key => $value) {
4056
-                    $php_array_like_string[] = "$key=>$value";
4057
-                }
4058
-                throw new EE_Error(
4059
-                    sprintf(
4060
-                        __(
4061
-                            "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))",
4062
-                            "event_espresso"
4063
-                        ),
4064
-                        implode(",", $php_array_like_string)
4065
-                    )
4066
-                );
4067
-            }
4068
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4069
-        } else {
4070
-            $operator = '=';
4071
-            $value = $op_and_value;
4072
-        }
4073
-        //check to see if the value is actually another field
4074
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4075
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4076
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4077
-            //in this case, the value should be an array, or at least a comma-separated list
4078
-            //it will need to handle a little differently
4079
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4080
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4081
-            return $operator . SP . $cleaned_value;
4082
-        } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4083
-            //the value should be an array with count of two.
4084
-            if (count($value) !== 2) {
4085
-                throw new EE_Error(
4086
-                    sprintf(
4087
-                        __(
4088
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4089
-                            'event_espresso'
4090
-                        ),
4091
-                        "BETWEEN"
4092
-                    )
4093
-                );
4094
-            }
4095
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4096
-            return $operator . SP . $cleaned_value;
4097
-        } elseif (in_array($operator, $this->valid_null_style_operators())) {
4098
-            if ($value !== null) {
4099
-                throw new EE_Error(
4100
-                    sprintf(
4101
-                        __(
4102
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4103
-                            "event_espresso"
4104
-                        ),
4105
-                        $value,
4106
-                        $operator
4107
-                    )
4108
-                );
4109
-            }
4110
-            return $operator;
4111
-        } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4112
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4113
-            //remove other junk. So just treat it as a string.
4114
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4115
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4116
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4117
-        } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4118
-            throw new EE_Error(
4119
-                sprintf(
4120
-                    __(
4121
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4122
-                        'event_espresso'
4123
-                    ),
4124
-                    $operator,
4125
-                    $operator
4126
-                )
4127
-            );
4128
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4129
-            throw new EE_Error(
4130
-                sprintf(
4131
-                    __(
4132
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4133
-                        'event_espresso'
4134
-                    ),
4135
-                    $operator,
4136
-                    $operator
4137
-                )
4138
-            );
4139
-        } else {
4140
-            throw new EE_Error(
4141
-                sprintf(
4142
-                    __(
4143
-                        "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4144
-                        "event_espresso"
4145
-                    ),
4146
-                    http_build_query($op_and_value)
4147
-                )
4148
-            );
4149
-        }
4150
-    }
4151
-
4152
-
4153
-
4154
-    /**
4155
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4156
-     *
4157
-     * @param array                      $values
4158
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4159
-     *                                              '%s'
4160
-     * @return string
4161
-     * @throws \EE_Error
4162
-     */
4163
-    public function _construct_between_value($values, $field_obj)
4164
-    {
4165
-        $cleaned_values = array();
4166
-        foreach ($values as $value) {
4167
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4168
-        }
4169
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4170
-    }
4171
-
4172
-
4173
-
4174
-    /**
4175
-     * Takes an array or a comma-separated list of $values and cleans them
4176
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4177
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4178
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4179
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4180
-     *
4181
-     * @param mixed                      $values    array or comma-separated string
4182
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4183
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4184
-     * @throws \EE_Error
4185
-     */
4186
-    public function _construct_in_value($values, $field_obj)
4187
-    {
4188
-        //check if the value is a CSV list
4189
-        if (is_string($values)) {
4190
-            //in which case, turn it into an array
4191
-            $values = explode(",", $values);
4192
-        }
4193
-        $cleaned_values = array();
4194
-        foreach ($values as $value) {
4195
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4196
-        }
4197
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4198
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4199
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4200
-        if (empty($cleaned_values)) {
4201
-            $all_fields = $this->field_settings();
4202
-            $a_field = array_shift($all_fields);
4203
-            $main_table = $this->_get_main_table();
4204
-            $cleaned_values[] = "SELECT "
4205
-                                . $a_field->get_table_column()
4206
-                                . " FROM "
4207
-                                . $main_table->get_table_name()
4208
-                                . " WHERE FALSE";
4209
-        }
4210
-        return "(" . implode(",", $cleaned_values) . ")";
4211
-    }
4212
-
4213
-
4214
-
4215
-    /**
4216
-     * @param mixed                      $value
4217
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4218
-     * @throws EE_Error
4219
-     * @return false|null|string
4220
-     */
4221
-    private function _wpdb_prepare_using_field($value, $field_obj)
4222
-    {
4223
-        /** @type WPDB $wpdb */
4224
-        global $wpdb;
4225
-        if ($field_obj instanceof EE_Model_Field_Base) {
4226
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4227
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4228
-        } else {//$field_obj should really just be a data type
4229
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4230
-                throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4231
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4232
-            }
4233
-            return $wpdb->prepare($field_obj, $value);
4234
-        }
4235
-    }
4236
-
4237
-
4238
-
4239
-    /**
4240
-     * Takes the input parameter and finds the model field that it indicates.
4241
-     *
4242
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4243
-     * @throws EE_Error
4244
-     * @return EE_Model_Field_Base
4245
-     */
4246
-    protected function _deduce_field_from_query_param($query_param_name)
4247
-    {
4248
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4249
-        //which will help us find the database table and column
4250
-        $query_param_parts = explode(".", $query_param_name);
4251
-        if (empty($query_param_parts)) {
4252
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4253
-                'event_espresso'), $query_param_name));
4254
-        }
4255
-        $number_of_parts = count($query_param_parts);
4256
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4257
-        if ($number_of_parts === 1) {
4258
-            $field_name = $last_query_param_part;
4259
-            $model_obj = $this;
4260
-        } else {// $number_of_parts >= 2
4261
-            //the last part is the column name, and there are only 2parts. therefore...
4262
-            $field_name = $last_query_param_part;
4263
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4264
-        }
4265
-        try {
4266
-            return $model_obj->field_settings_for($field_name);
4267
-        } catch (EE_Error $e) {
4268
-            return null;
4269
-        }
4270
-    }
4271
-
4272
-
4273
-
4274
-    /**
4275
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4276
-     * alias and column which corresponds to it
4277
-     *
4278
-     * @param string $field_name
4279
-     * @throws EE_Error
4280
-     * @return string
4281
-     */
4282
-    public function _get_qualified_column_for_field($field_name)
4283
-    {
4284
-        $all_fields = $this->field_settings();
4285
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4286
-        if ($field) {
4287
-            return $field->get_qualified_column();
4288
-        } else {
4289
-            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.",
4290
-                'event_espresso'), $field_name, get_class($this)));
4291
-        }
4292
-    }
4293
-
4294
-
4295
-
4296
-    /**
4297
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4298
-     * Example usage:
4299
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4300
-     *      array(),
4301
-     *      ARRAY_A,
4302
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4303
-     *  );
4304
-     * is equivalent to
4305
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4306
-     * and
4307
-     *  EEM_Event::instance()->get_all_wpdb_results(
4308
-     *      array(
4309
-     *          array(
4310
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4311
-     *          ),
4312
-     *          ARRAY_A,
4313
-     *          implode(
4314
-     *              ', ',
4315
-     *              array_merge(
4316
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4317
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4318
-     *              )
4319
-     *          )
4320
-     *      )
4321
-     *  );
4322
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4323
-     *
4324
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4325
-     *                                            and the one whose fields you are selecting for example: when querying
4326
-     *                                            tickets model and selecting fields from the tickets model you would
4327
-     *                                            leave this parameter empty, because no models are needed to join
4328
-     *                                            between the queried model and the selected one. Likewise when
4329
-     *                                            querying the datetime model and selecting fields from the tickets
4330
-     *                                            model, it would also be left empty, because there is a direct
4331
-     *                                            relation from datetimes to tickets, so no model is needed to join
4332
-     *                                            them together. However, when querying from the event model and
4333
-     *                                            selecting fields from the ticket model, you should provide the string
4334
-     *                                            'Datetime', indicating that the event model must first join to the
4335
-     *                                            datetime model in order to find its relation to ticket model.
4336
-     *                                            Also, when querying from the venue model and selecting fields from
4337
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4338
-     *                                            indicating you need to join the venue model to the event model,
4339
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4340
-     *                                            This string is used to deduce the prefix that gets added onto the
4341
-     *                                            models' tables qualified columns
4342
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4343
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4344
-     *                                            qualified column names
4345
-     * @return array|string
4346
-     */
4347
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4348
-    {
4349
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4350
-        $qualified_columns = array();
4351
-        foreach ($this->field_settings() as $field_name => $field) {
4352
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4353
-        }
4354
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4355
-    }
4356
-
4357
-
4358
-
4359
-    /**
4360
-     * constructs the select use on special limit joins
4361
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4362
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4363
-     * (as that is typically where the limits would be set).
4364
-     *
4365
-     * @param  string       $table_alias The table the select is being built for
4366
-     * @param  mixed|string $limit       The limit for this select
4367
-     * @return string                The final select join element for the query.
4368
-     */
4369
-    public function _construct_limit_join_select($table_alias, $limit)
4370
-    {
4371
-        $SQL = '';
4372
-        foreach ($this->_tables as $table_obj) {
4373
-            if ($table_obj instanceof EE_Primary_Table) {
4374
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4375
-                    ? $table_obj->get_select_join_limit($limit)
4376
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4377
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4378
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4379
-                    ? $table_obj->get_select_join_limit_join($limit)
4380
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4381
-            }
4382
-        }
4383
-        return $SQL;
4384
-    }
4385
-
4386
-
4387
-
4388
-    /**
4389
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4390
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4391
-     *
4392
-     * @return string SQL
4393
-     * @throws \EE_Error
4394
-     */
4395
-    public function _construct_internal_join()
4396
-    {
4397
-        $SQL = $this->_get_main_table()->get_table_sql();
4398
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4399
-        return $SQL;
4400
-    }
4401
-
4402
-
4403
-
4404
-    /**
4405
-     * Constructs the SQL for joining all the tables on this model.
4406
-     * Normally $alias should be the primary table's alias, but in cases where
4407
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4408
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4409
-     * alias, this will construct SQL like:
4410
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4411
-     * With $alias being a secondary table's alias, this will construct SQL like:
4412
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4413
-     *
4414
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4415
-     * @return string
4416
-     */
4417
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4418
-    {
4419
-        $SQL = '';
4420
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4421
-        foreach ($this->_tables as $table_obj) {
4422
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4423
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4424
-                    //so we're joining to this table, meaning the table is already in
4425
-                    //the FROM statement, BUT the primary table isn't. So we want
4426
-                    //to add the inverse join sql
4427
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4428
-                } else {
4429
-                    //just add a regular JOIN to this table from the primary table
4430
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4431
-                }
4432
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4433
-        }
4434
-        return $SQL;
4435
-    }
4436
-
4437
-
4438
-
4439
-    /**
4440
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4441
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4442
-     * their data type (eg, '%s', '%d', etc)
4443
-     *
4444
-     * @return array
4445
-     */
4446
-    public function _get_data_types()
4447
-    {
4448
-        $data_types = array();
4449
-        foreach ($this->field_settings() as $field_obj) {
4450
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4451
-            /** @var $field_obj EE_Model_Field_Base */
4452
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4453
-        }
4454
-        return $data_types;
4455
-    }
4456
-
4457
-
4458
-
4459
-    /**
4460
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4461
-     *
4462
-     * @param string $model_name
4463
-     * @throws EE_Error
4464
-     * @return EEM_Base
4465
-     */
4466
-    public function get_related_model_obj($model_name)
4467
-    {
4468
-        $model_classname = "EEM_" . $model_name;
4469
-        if (! class_exists($model_classname)) {
4470
-            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",
4471
-                'event_espresso'), $model_name, $model_classname));
4472
-        }
4473
-        return call_user_func($model_classname . "::instance");
4474
-    }
4475
-
4476
-
4477
-
4478
-    /**
4479
-     * Returns the array of EE_ModelRelations for this model.
4480
-     *
4481
-     * @return EE_Model_Relation_Base[]
4482
-     */
4483
-    public function relation_settings()
4484
-    {
4485
-        return $this->_model_relations;
4486
-    }
4487
-
4488
-
4489
-
4490
-    /**
4491
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4492
-     * because without THOSE models, this model probably doesn't have much purpose.
4493
-     * (Eg, without an event, datetimes have little purpose.)
4494
-     *
4495
-     * @return EE_Belongs_To_Relation[]
4496
-     */
4497
-    public function belongs_to_relations()
4498
-    {
4499
-        $belongs_to_relations = array();
4500
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4501
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4502
-                $belongs_to_relations[$model_name] = $relation_obj;
4503
-            }
4504
-        }
4505
-        return $belongs_to_relations;
4506
-    }
4507
-
4508
-
4509
-
4510
-    /**
4511
-     * Returns the specified EE_Model_Relation, or throws an exception
4512
-     *
4513
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4514
-     * @throws EE_Error
4515
-     * @return EE_Model_Relation_Base
4516
-     */
4517
-    public function related_settings_for($relation_name)
4518
-    {
4519
-        $relatedModels = $this->relation_settings();
4520
-        if (! array_key_exists($relation_name, $relatedModels)) {
4521
-            throw new EE_Error(
4522
-                sprintf(
4523
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4524
-                        'event_espresso'),
4525
-                    $relation_name,
4526
-                    $this->_get_class_name(),
4527
-                    implode(', ', array_keys($relatedModels))
4528
-                )
4529
-            );
4530
-        }
4531
-        return $relatedModels[$relation_name];
4532
-    }
4533
-
4534
-
4535
-
4536
-    /**
4537
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4538
-     * fields
4539
-     *
4540
-     * @param string $fieldName
4541
-     * @param boolean $include_db_only_fields
4542
-     * @throws EE_Error
4543
-     * @return EE_Model_Field_Base
4544
-     */
4545
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4546
-    {
4547
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4548
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4549
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4550
-                get_class($this)));
4551
-        }
4552
-        return $fieldSettings[$fieldName];
4553
-    }
4554
-
4555
-
4556
-
4557
-    /**
4558
-     * Checks if this field exists on this model
4559
-     *
4560
-     * @param string $fieldName a key in the model's _field_settings array
4561
-     * @return boolean
4562
-     */
4563
-    public function has_field($fieldName)
4564
-    {
4565
-        $fieldSettings = $this->field_settings(true);
4566
-        if (isset($fieldSettings[$fieldName])) {
4567
-            return true;
4568
-        } else {
4569
-            return false;
4570
-        }
4571
-    }
4572
-
4573
-
4574
-
4575
-    /**
4576
-     * Returns whether or not this model has a relation to the specified model
4577
-     *
4578
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4579
-     * @return boolean
4580
-     */
4581
-    public function has_relation($relation_name)
4582
-    {
4583
-        $relations = $this->relation_settings();
4584
-        if (isset($relations[$relation_name])) {
4585
-            return true;
4586
-        } else {
4587
-            return false;
4588
-        }
4589
-    }
4590
-
4591
-
4592
-
4593
-    /**
4594
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4595
-     * Eg, on EE_Answer that would be ANS_ID field object
4596
-     *
4597
-     * @param $field_obj
4598
-     * @return boolean
4599
-     */
4600
-    public function is_primary_key_field($field_obj)
4601
-    {
4602
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4603
-    }
4604
-
4605
-
4606
-
4607
-    /**
4608
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4609
-     * Eg, on EE_Answer that would be ANS_ID field object
4610
-     *
4611
-     * @return EE_Model_Field_Base
4612
-     * @throws EE_Error
4613
-     */
4614
-    public function get_primary_key_field()
4615
-    {
4616
-        if ($this->_primary_key_field === null) {
4617
-            foreach ($this->field_settings(true) as $field_obj) {
4618
-                if ($this->is_primary_key_field($field_obj)) {
4619
-                    $this->_primary_key_field = $field_obj;
4620
-                    break;
4621
-                }
4622
-            }
4623
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4624
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4625
-                    get_class($this)));
4626
-            }
4627
-        }
4628
-        return $this->_primary_key_field;
4629
-    }
4630
-
4631
-
4632
-
4633
-    /**
4634
-     * Returns whether or not not there is a primary key on this model.
4635
-     * Internally does some caching.
4636
-     *
4637
-     * @return boolean
4638
-     */
4639
-    public function has_primary_key_field()
4640
-    {
4641
-        if ($this->_has_primary_key_field === null) {
4642
-            try {
4643
-                $this->get_primary_key_field();
4644
-                $this->_has_primary_key_field = true;
4645
-            } catch (EE_Error $e) {
4646
-                $this->_has_primary_key_field = false;
4647
-            }
4648
-        }
4649
-        return $this->_has_primary_key_field;
4650
-    }
4651
-
4652
-
4653
-
4654
-    /**
4655
-     * Finds the first field of type $field_class_name.
4656
-     *
4657
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4658
-     *                                 EE_Foreign_Key_Field, etc
4659
-     * @return EE_Model_Field_Base or null if none is found
4660
-     */
4661
-    public function get_a_field_of_type($field_class_name)
4662
-    {
4663
-        foreach ($this->field_settings() as $field) {
4664
-            if ($field instanceof $field_class_name) {
4665
-                return $field;
4666
-            }
4667
-        }
4668
-        return null;
4669
-    }
4670
-
4671
-
4672
-
4673
-    /**
4674
-     * Gets a foreign key field pointing to model.
4675
-     *
4676
-     * @param string $model_name eg Event, Registration, not EEM_Event
4677
-     * @return EE_Foreign_Key_Field_Base
4678
-     * @throws EE_Error
4679
-     */
4680
-    public function get_foreign_key_to($model_name)
4681
-    {
4682
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4683
-            foreach ($this->field_settings() as $field) {
4684
-                if (
4685
-                    $field instanceof EE_Foreign_Key_Field_Base
4686
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4687
-                ) {
4688
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4689
-                    break;
4690
-                }
4691
-            }
4692
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4694
-                    'event_espresso'), $model_name, get_class($this)));
4695
-            }
4696
-        }
4697
-        return $this->_cache_foreign_key_to_fields[$model_name];
4698
-    }
4699
-
4700
-
4701
-
4702
-    /**
4703
-     * Gets the actual table for the table alias
4704
-     *
4705
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4706
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4707
-     *                            Either one works
4708
-     * @return EE_Table_Base
4709
-     */
4710
-    public function get_table_for_alias($table_alias)
4711
-    {
4712
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4713
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4714
-    }
4715
-
4716
-
4717
-
4718
-    /**
4719
-     * Returns a flat array of all field son this model, instead of organizing them
4720
-     * by table_alias as they are in the constructor.
4721
-     *
4722
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4723
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4724
-     */
4725
-    public function field_settings($include_db_only_fields = false)
4726
-    {
4727
-        if ($include_db_only_fields) {
4728
-            if ($this->_cached_fields === null) {
4729
-                $this->_cached_fields = array();
4730
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4731
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4732
-                        $this->_cached_fields[$field_name] = $field_obj;
4733
-                    }
4734
-                }
4735
-            }
4736
-            return $this->_cached_fields;
4737
-        } else {
4738
-            if ($this->_cached_fields_non_db_only === null) {
4739
-                $this->_cached_fields_non_db_only = array();
4740
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4741
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
-                        /** @var $field_obj EE_Model_Field_Base */
4743
-                        if (! $field_obj->is_db_only_field()) {
4744
-                            $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4745
-                        }
4746
-                    }
4747
-                }
4748
-            }
4749
-            return $this->_cached_fields_non_db_only;
4750
-        }
4751
-    }
4752
-
4753
-
4754
-
4755
-    /**
4756
-     *        cycle though array of attendees and create objects out of each item
4757
-     *
4758
-     * @access        private
4759
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4760
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4761
-     *                           numerically indexed)
4762
-     * @throws \EE_Error
4763
-     */
4764
-    protected function _create_objects($rows = array())
4765
-    {
4766
-        $array_of_objects = array();
4767
-        if (empty($rows)) {
4768
-            return array();
4769
-        }
4770
-        $count_if_model_has_no_primary_key = 0;
4771
-        $has_primary_key = $this->has_primary_key_field();
4772
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4773
-        foreach ((array)$rows as $row) {
4774
-            if (empty($row)) {
4775
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4776
-                return array();
4777
-            }
4778
-            //check if we've already set this object in the results array,
4779
-            //in which case there's no need to process it further (again)
4780
-            if ($has_primary_key) {
4781
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4782
-                    $row,
4783
-                    $primary_key_field->get_qualified_column(),
4784
-                    $primary_key_field->get_table_column()
4785
-                );
4786
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4787
-                    continue;
4788
-                }
4789
-            }
4790
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4791
-            if (! $classInstance) {
4792
-                throw new EE_Error(
4793
-                    sprintf(
4794
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4795
-                        $this->get_this_model_name(),
4796
-                        http_build_query($row)
4797
-                    )
4798
-                );
4799
-            }
4800
-            //set the timezone on the instantiated objects
4801
-            $classInstance->set_timezone($this->_timezone);
4802
-            //make sure if there is any timezone setting present that we set the timezone for the object
4803
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4804
-            $array_of_objects[$key] = $classInstance;
4805
-            //also, for all the relations of type BelongsTo, see if we can cache
4806
-            //those related models
4807
-            //(we could do this for other relations too, but if there are conditions
4808
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4809
-            //so it requires a little more thought than just caching them immediately...)
4810
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4811
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4812
-                    //check if this model's INFO is present. If so, cache it on the model
4813
-                    $other_model = $relation_obj->get_other_model();
4814
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4815
-                    //if we managed to make a model object from the results, cache it on the main model object
4816
-                    if ($other_model_obj_maybe) {
4817
-                        //set timezone on these other model objects if they are present
4818
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4819
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4820
-                    }
4821
-                }
4822
-            }
4823
-        }
4824
-        return $array_of_objects;
4825
-    }
4826
-
4827
-
4828
-
4829
-    /**
4830
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4831
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4832
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4833
-     * object (as set in the model_field!).
4834
-     *
4835
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4836
-     */
4837
-    public function create_default_object()
4838
-    {
4839
-        $this_model_fields_and_values = array();
4840
-        //setup the row using default values;
4841
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4842
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4843
-        }
4844
-        $className = $this->_get_class_name();
4845
-        $classInstance = EE_Registry::instance()
4846
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4847
-        return $classInstance;
4848
-    }
4849
-
4850
-
4851
-
4852
-    /**
4853
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4854
-     *                             or an stdClass where each property is the name of a column,
4855
-     * @return EE_Base_Class
4856
-     * @throws \EE_Error
4857
-     */
4858
-    public function instantiate_class_from_array_or_object($cols_n_values)
4859
-    {
4860
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4861
-            $cols_n_values = get_object_vars($cols_n_values);
4862
-        }
4863
-        $primary_key = null;
4864
-        //make sure the array only has keys that are fields/columns on this model
4865
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4866
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4867
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4868
-        }
4869
-        $className = $this->_get_class_name();
4870
-        //check we actually found results that we can use to build our model object
4871
-        //if not, return null
4872
-        if ($this->has_primary_key_field()) {
4873
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4874
-                return null;
4875
-            }
4876
-        } else if ($this->unique_indexes()) {
4877
-            $first_column = reset($this_model_fields_n_values);
4878
-            if (empty($first_column)) {
4879
-                return null;
4880
-            }
4881
-        }
4882
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4883
-        if ($primary_key) {
4884
-            $classInstance = $this->get_from_entity_map($primary_key);
4885
-            if (! $classInstance) {
4886
-                $classInstance = EE_Registry::instance()
4887
-                                            ->load_class($className,
4888
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
4889
-                // add this new object to the entity map
4890
-                $classInstance = $this->add_to_entity_map($classInstance);
4891
-            }
4892
-        } else {
4893
-            $classInstance = EE_Registry::instance()
4894
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4895
-                                            true, false);
4896
-        }
4897
-        //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.
4898
-        $this->set_timezone($classInstance->get_timezone());
4899
-        return $classInstance;
4900
-    }
4901
-
4902
-
4903
-
4904
-    /**
4905
-     * Gets the model object from the  entity map if it exists
4906
-     *
4907
-     * @param int|string $id the ID of the model object
4908
-     * @return EE_Base_Class
4909
-     */
4910
-    public function get_from_entity_map($id)
4911
-    {
4912
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4913
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4914
-    }
4915
-
4916
-
4917
-
4918
-    /**
4919
-     * add_to_entity_map
4920
-     * Adds the object to the model's entity mappings
4921
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4922
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4923
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4924
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
4925
-     *        then this method should be called immediately after the update query
4926
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4927
-     * so on multisite, the entity map is specific to the query being done for a specific site.
4928
-     *
4929
-     * @param    EE_Base_Class $object
4930
-     * @throws EE_Error
4931
-     * @return \EE_Base_Class
4932
-     */
4933
-    public function add_to_entity_map(EE_Base_Class $object)
4934
-    {
4935
-        $className = $this->_get_class_name();
4936
-        if (! $object instanceof $className) {
4937
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4938
-                is_object($object) ? get_class($object) : $object, $className));
4939
-        }
4940
-        /** @var $object EE_Base_Class */
4941
-        if (! $object->ID()) {
4942
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4943
-                "event_espresso"), get_class($this)));
4944
-        }
4945
-        // double check it's not already there
4946
-        $classInstance = $this->get_from_entity_map($object->ID());
4947
-        if ($classInstance) {
4948
-            return $classInstance;
4949
-        } else {
4950
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4951
-            return $object;
4952
-        }
4953
-    }
4954
-
4955
-
4956
-
4957
-    /**
4958
-     * if a valid identifier is provided, then that entity is unset from the entity map,
4959
-     * if no identifier is provided, then the entire entity map is emptied
4960
-     *
4961
-     * @param int|string $id the ID of the model object
4962
-     * @return boolean
4963
-     */
4964
-    public function clear_entity_map($id = null)
4965
-    {
4966
-        if (empty($id)) {
4967
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4968
-            return true;
4969
-        }
4970
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4971
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4972
-            return true;
4973
-        }
4974
-        return false;
4975
-    }
4976
-
4977
-
4978
-
4979
-    /**
4980
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4981
-     * Given an array where keys are column (or column alias) names and values,
4982
-     * returns an array of their corresponding field names and database values
4983
-     *
4984
-     * @param array $cols_n_values
4985
-     * @return array
4986
-     */
4987
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4988
-    {
4989
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4990
-    }
4991
-
4992
-
4993
-
4994
-    /**
4995
-     * _deduce_fields_n_values_from_cols_n_values
4996
-     * Given an array where keys are column (or column alias) names and values,
4997
-     * returns an array of their corresponding field names and database values
4998
-     *
4999
-     * @param string $cols_n_values
5000
-     * @return array
5001
-     */
5002
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5003
-    {
5004
-        $this_model_fields_n_values = array();
5005
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5006
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5007
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5008
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5009
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5010
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5011
-                    if (! $field_obj->is_db_only_field()) {
5012
-                        //prepare field as if its coming from db
5013
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5014
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5015
-                    }
5016
-                }
5017
-            } else {
5018
-                //the table's rows existed. Use their values
5019
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5020
-                    if (! $field_obj->is_db_only_field()) {
5021
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5022
-                            $cols_n_values, $field_obj->get_qualified_column(),
5023
-                            $field_obj->get_table_column()
5024
-                        );
5025
-                    }
5026
-                }
5027
-            }
5028
-        }
5029
-        return $this_model_fields_n_values;
5030
-    }
5031
-
5032
-
5033
-
5034
-    /**
5035
-     * @param $cols_n_values
5036
-     * @param $qualified_column
5037
-     * @param $regular_column
5038
-     * @return null
5039
-     */
5040
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5041
-    {
5042
-        $value = null;
5043
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5044
-        //does the field on the model relate to this column retrieved from the db?
5045
-        //or is it a db-only field? (not relating to the model)
5046
-        if (isset($cols_n_values[$qualified_column])) {
5047
-            $value = $cols_n_values[$qualified_column];
5048
-        } elseif (isset($cols_n_values[$regular_column])) {
5049
-            $value = $cols_n_values[$regular_column];
5050
-        }
5051
-        return $value;
5052
-    }
5053
-
5054
-
5055
-
5056
-    /**
5057
-     * refresh_entity_map_from_db
5058
-     * Makes sure the model object in the entity map at $id assumes the values
5059
-     * of the database (opposite of EE_base_Class::save())
5060
-     *
5061
-     * @param int|string $id
5062
-     * @return EE_Base_Class
5063
-     * @throws \EE_Error
5064
-     */
5065
-    public function refresh_entity_map_from_db($id)
5066
-    {
5067
-        $obj_in_map = $this->get_from_entity_map($id);
5068
-        if ($obj_in_map) {
5069
-            $wpdb_results = $this->_get_all_wpdb_results(
5070
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5071
-            );
5072
-            if ($wpdb_results && is_array($wpdb_results)) {
5073
-                $one_row = reset($wpdb_results);
5074
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5075
-                    $obj_in_map->set_from_db($field_name, $db_value);
5076
-                }
5077
-                //clear the cache of related model objects
5078
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5079
-                    $obj_in_map->clear_cache($relation_name, null, true);
5080
-                }
5081
-            }
5082
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5083
-            return $obj_in_map;
5084
-        } else {
5085
-            return $this->get_one_by_ID($id);
5086
-        }
5087
-    }
5088
-
5089
-
5090
-
5091
-    /**
5092
-     * refresh_entity_map_with
5093
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5094
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5095
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5096
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5097
-     *
5098
-     * @param int|string    $id
5099
-     * @param EE_Base_Class $replacing_model_obj
5100
-     * @return \EE_Base_Class
5101
-     * @throws \EE_Error
5102
-     */
5103
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5104
-    {
5105
-        $obj_in_map = $this->get_from_entity_map($id);
5106
-        if ($obj_in_map) {
5107
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5108
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5109
-                    $obj_in_map->set($field_name, $value);
5110
-                }
5111
-                //make the model object in the entity map's cache match the $replacing_model_obj
5112
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5113
-                    $obj_in_map->clear_cache($relation_name, null, true);
5114
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5115
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5116
-                    }
5117
-                }
5118
-            }
5119
-            return $obj_in_map;
5120
-        } else {
5121
-            $this->add_to_entity_map($replacing_model_obj);
5122
-            return $replacing_model_obj;
5123
-        }
5124
-    }
5125
-
5126
-
5127
-
5128
-    /**
5129
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5130
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5131
-     * require_once($this->_getClassName().".class.php");
5132
-     *
5133
-     * @return string
5134
-     */
5135
-    private function _get_class_name()
5136
-    {
5137
-        return "EE_" . $this->get_this_model_name();
5138
-    }
5139
-
5140
-
5141
-
5142
-    /**
5143
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5144
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5145
-     * it would be 'Events'.
5146
-     *
5147
-     * @param int $quantity
5148
-     * @return string
5149
-     */
5150
-    public function item_name($quantity = 1)
5151
-    {
5152
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5153
-    }
5154
-
5155
-
5156
-
5157
-    /**
5158
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5159
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5160
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5161
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5162
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5163
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5164
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5165
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5166
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5167
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5168
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5169
-     *        return $previousReturnValue.$returnString;
5170
-     * }
5171
-     * require('EEM_Answer.model.php');
5172
-     * $answer=EEM_Answer::instance();
5173
-     * echo $answer->my_callback('monkeys',100);
5174
-     * //will output "you called my_callback! and passed args:monkeys,100"
5175
-     *
5176
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5177
-     * @param array  $args       array of original arguments passed to the function
5178
-     * @throws EE_Error
5179
-     * @return mixed whatever the plugin which calls add_filter decides
5180
-     */
5181
-    public function __call($methodName, $args)
5182
-    {
5183
-        $className = get_class($this);
5184
-        $tagName = "FHEE__{$className}__{$methodName}";
5185
-        if (! has_filter($tagName)) {
5186
-            throw new EE_Error(
5187
-                sprintf(
5188
-                    __('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 );',
5189
-                        'event_espresso'),
5190
-                    $methodName,
5191
-                    $className,
5192
-                    $tagName,
5193
-                    '<br />'
5194
-                )
5195
-            );
5196
-        }
5197
-        return apply_filters($tagName, null, $this, $args);
5198
-    }
5199
-
5200
-
5201
-
5202
-    /**
5203
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5204
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5205
-     *
5206
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5207
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5208
-     *                                                       the object's class name
5209
-     *                                                       or object's ID
5210
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5211
-     *                                                       exists in the database. If it does not, we add it
5212
-     * @throws EE_Error
5213
-     * @return EE_Base_Class
5214
-     */
5215
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5216
-    {
5217
-        $className = $this->_get_class_name();
5218
-        if ($base_class_obj_or_id instanceof $className) {
5219
-            $model_object = $base_class_obj_or_id;
5220
-        } else {
5221
-            $primary_key_field = $this->get_primary_key_field();
5222
-            if (
5223
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5224
-                && (
5225
-                    is_int($base_class_obj_or_id)
5226
-                    || is_string($base_class_obj_or_id)
5227
-                )
5228
-            ) {
5229
-                // assume it's an ID.
5230
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5231
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5232
-            } else if (
5233
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5234
-                && is_string($base_class_obj_or_id)
5235
-            ) {
5236
-                // assume its a string representation of the object
5237
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5238
-            } else {
5239
-                throw new EE_Error(
5240
-                    sprintf(
5241
-                        __(
5242
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5243
-                            'event_espresso'
5244
-                        ),
5245
-                        $base_class_obj_or_id,
5246
-                        $this->_get_class_name(),
5247
-                        print_r($base_class_obj_or_id, true)
5248
-                    )
5249
-                );
5250
-            }
5251
-        }
5252
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5253
-            $model_object->save();
5254
-        }
5255
-        return $model_object;
5256
-    }
5257
-
5258
-
5259
-
5260
-    /**
5261
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5262
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5263
-     * returns it ID.
5264
-     *
5265
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5266
-     * @return int|string depending on the type of this model object's ID
5267
-     * @throws EE_Error
5268
-     */
5269
-    public function ensure_is_ID($base_class_obj_or_id)
5270
-    {
5271
-        $className = $this->_get_class_name();
5272
-        if ($base_class_obj_or_id instanceof $className) {
5273
-            /** @var $base_class_obj_or_id EE_Base_Class */
5274
-            $id = $base_class_obj_or_id->ID();
5275
-        } elseif (is_int($base_class_obj_or_id)) {
5276
-            //assume it's an ID
5277
-            $id = $base_class_obj_or_id;
5278
-        } elseif (is_string($base_class_obj_or_id)) {
5279
-            //assume its a string representation of the object
5280
-            $id = $base_class_obj_or_id;
5281
-        } else {
5282
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5283
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5284
-                print_r($base_class_obj_or_id, true)));
5285
-        }
5286
-        return $id;
5287
-    }
5288
-
5289
-
5290
-
5291
-    /**
5292
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5293
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5294
-     * been sanitized and converted into the appropriate domain.
5295
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5296
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5297
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5298
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5299
-     * $EVT = EEM_Event::instance(); $old_setting =
5300
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5301
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5302
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5303
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5304
-     *
5305
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5306
-     * @return void
5307
-     */
5308
-    public function assume_values_already_prepared_by_model_object(
5309
-        $values_already_prepared = self::not_prepared_by_model_object
5310
-    ) {
5311
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5312
-    }
5313
-
5314
-
5315
-
5316
-    /**
5317
-     * Read comments for assume_values_already_prepared_by_model_object()
5318
-     *
5319
-     * @return int
5320
-     */
5321
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5322
-    {
5323
-        return $this->_values_already_prepared_by_model_object;
5324
-    }
5325
-
5326
-
5327
-
5328
-    /**
5329
-     * Gets all the indexes on this model
5330
-     *
5331
-     * @return EE_Index[]
5332
-     */
5333
-    public function indexes()
5334
-    {
5335
-        return $this->_indexes;
5336
-    }
5337
-
5338
-
5339
-
5340
-    /**
5341
-     * Gets all the Unique Indexes on this model
5342
-     *
5343
-     * @return EE_Unique_Index[]
5344
-     */
5345
-    public function unique_indexes()
5346
-    {
5347
-        $unique_indexes = array();
5348
-        foreach ($this->_indexes as $name => $index) {
5349
-            if ($index instanceof EE_Unique_Index) {
5350
-                $unique_indexes [$name] = $index;
5351
-            }
5352
-        }
5353
-        return $unique_indexes;
5354
-    }
5355
-
5356
-
5357
-
5358
-    /**
5359
-     * Gets all the fields which, when combined, make the primary key.
5360
-     * This is usually just an array with 1 element (the primary key), but in cases
5361
-     * where there is no primary key, it's a combination of fields as defined
5362
-     * on a primary index
5363
-     *
5364
-     * @return EE_Model_Field_Base[] indexed by the field's name
5365
-     * @throws \EE_Error
5366
-     */
5367
-    public function get_combined_primary_key_fields()
5368
-    {
5369
-        foreach ($this->indexes() as $index) {
5370
-            if ($index instanceof EE_Primary_Key_Index) {
5371
-                return $index->fields();
5372
-            }
5373
-        }
5374
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5375
-    }
5376
-
5377
-
5378
-
5379
-    /**
5380
-     * Used to build a primary key string (when the model has no primary key),
5381
-     * which can be used a unique string to identify this model object.
5382
-     *
5383
-     * @param array $cols_n_values keys are field names, values are their values
5384
-     * @return string
5385
-     * @throws \EE_Error
5386
-     */
5387
-    public function get_index_primary_key_string($cols_n_values)
5388
-    {
5389
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5390
-            $this->get_combined_primary_key_fields());
5391
-        return http_build_query($cols_n_values_for_primary_key_index);
5392
-    }
5393
-
5394
-
5395
-
5396
-    /**
5397
-     * Gets the field values from the primary key string
5398
-     *
5399
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5400
-     * @param string $index_primary_key_string
5401
-     * @return null|array
5402
-     * @throws \EE_Error
5403
-     */
5404
-    public function parse_index_primary_key_string($index_primary_key_string)
5405
-    {
5406
-        $key_fields = $this->get_combined_primary_key_fields();
5407
-        //check all of them are in the $id
5408
-        $key_vals_in_combined_pk = array();
5409
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5410
-        foreach ($key_fields as $key_field_name => $field_obj) {
5411
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5412
-                return null;
5413
-            }
5414
-        }
5415
-        return $key_vals_in_combined_pk;
5416
-    }
5417
-
5418
-
5419
-
5420
-    /**
5421
-     * verifies that an array of key-value pairs for model fields has a key
5422
-     * for each field comprising the primary key index
5423
-     *
5424
-     * @param array $key_vals
5425
-     * @return boolean
5426
-     * @throws \EE_Error
5427
-     */
5428
-    public function has_all_combined_primary_key_fields($key_vals)
5429
-    {
5430
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5431
-        foreach ($keys_it_should_have as $key) {
5432
-            if (! isset($key_vals[$key])) {
5433
-                return false;
5434
-            }
5435
-        }
5436
-        return true;
5437
-    }
5438
-
5439
-
5440
-
5441
-    /**
5442
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5443
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5444
-     *
5445
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5446
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5447
-     * @throws EE_Error
5448
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5449
-     *                                                              indexed)
5450
-     */
5451
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5452
-    {
5453
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5454
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5455
-        } elseif (is_array($model_object_or_attributes_array)) {
5456
-            $attributes_array = $model_object_or_attributes_array;
5457
-        } else {
5458
-            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",
5459
-                "event_espresso"), $model_object_or_attributes_array));
5460
-        }
5461
-        //even copies obviously won't have the same ID, so remove the primary key
5462
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5463
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5464
-            unset($attributes_array[$this->primary_key_name()]);
5465
-        }
5466
-        if (isset($query_params[0])) {
5467
-            $query_params[0] = array_merge($attributes_array, $query_params);
5468
-        } else {
5469
-            $query_params[0] = $attributes_array;
5470
-        }
5471
-        return $this->get_all($query_params);
5472
-    }
5473
-
5474
-
5475
-
5476
-    /**
5477
-     * Gets the first copy we find. See get_all_copies for more details
5478
-     *
5479
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5480
-     * @param array $query_params
5481
-     * @return EE_Base_Class
5482
-     * @throws \EE_Error
5483
-     */
5484
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5485
-    {
5486
-        if (! is_array($query_params)) {
5487
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5488
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5489
-                    gettype($query_params)), '4.6.0');
5490
-            $query_params = array();
5491
-        }
5492
-        $query_params['limit'] = 1;
5493
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5494
-        if (is_array($copies)) {
5495
-            return array_shift($copies);
5496
-        } else {
5497
-            return null;
5498
-        }
5499
-    }
5500
-
5501
-
5502
-
5503
-    /**
5504
-     * Updates the item with the specified id. Ignores default query parameters because
5505
-     * we have specified the ID, and its assumed we KNOW what we're doing
5506
-     *
5507
-     * @param array      $fields_n_values keys are field names, values are their new values
5508
-     * @param int|string $id              the value of the primary key to update
5509
-     * @return int number of rows updated
5510
-     * @throws \EE_Error
5511
-     */
5512
-    public function update_by_ID($fields_n_values, $id)
5513
-    {
5514
-        $query_params = array(
5515
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5516
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5517
-        );
5518
-        return $this->update($fields_n_values, $query_params);
5519
-    }
5520
-
5521
-
5522
-
5523
-    /**
5524
-     * Changes an operator which was supplied to the models into one usable in SQL
5525
-     *
5526
-     * @param string $operator_supplied
5527
-     * @return string an operator which can be used in SQL
5528
-     * @throws EE_Error
5529
-     */
5530
-    private function _prepare_operator_for_sql($operator_supplied)
5531
-    {
5532
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5533
-            : null;
5534
-        if ($sql_operator) {
5535
-            return $sql_operator;
5536
-        } else {
5537
-            throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5538
-                "event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5539
-        }
5540
-    }
5541
-
5542
-
5543
-
5544
-    /**
5545
-     * Gets the valid operators
5546
-     * @return array keys are accepted strings, values are the SQL they are converted to
5547
-     */
5548
-    public function valid_operators(){
5549
-        return $this->_valid_operators;
5550
-    }
5551
-
5552
-
5553
-
5554
-    /**
5555
-     * Gets the between-style operators (take 2 arguments).
5556
-     * @return array keys are accepted strings, values are the SQL they are converted to
5557
-     */
5558
-    public function valid_between_style_operators()
5559
-    {
5560
-        return array_intersect(
5561
-            $this->valid_operators(),
5562
-            $this->_between_style_operators
5563
-        );
5564
-    }
5565
-
5566
-    /**
5567
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5568
-     * @return array keys are accepted strings, values are the SQL they are converted to
5569
-     */
5570
-    public function valid_like_style_operators()
5571
-    {
5572
-        return array_intersect(
5573
-            $this->valid_operators(),
5574
-            $this->_like_style_operators
5575
-        );
5576
-    }
5577
-
5578
-    /**
5579
-     * Gets the "in"-style operators
5580
-     * @return array keys are accepted strings, values are the SQL they are converted to
5581
-     */
5582
-    public function valid_in_style_operators()
5583
-    {
5584
-        return array_intersect(
5585
-            $this->valid_operators(),
5586
-            $this->_in_style_operators
5587
-        );
5588
-    }
5589
-
5590
-    /**
5591
-     * Gets the "null"-style operators (accept no arguments)
5592
-     * @return array keys are accepted strings, values are the SQL they are converted to
5593
-     */
5594
-    public function valid_null_style_operators()
5595
-    {
5596
-        return array_intersect(
5597
-            $this->valid_operators(),
5598
-            $this->_null_style_operators
5599
-        );
5600
-    }
5601
-
5602
-    /**
5603
-     * Gets an array where keys are the primary keys and values are their 'names'
5604
-     * (as determined by the model object's name() function, which is often overridden)
5605
-     *
5606
-     * @param array $query_params like get_all's
5607
-     * @return string[]
5608
-     * @throws \EE_Error
5609
-     */
5610
-    public function get_all_names($query_params = array())
5611
-    {
5612
-        $objs = $this->get_all($query_params);
5613
-        $names = array();
5614
-        foreach ($objs as $obj) {
5615
-            $names[$obj->ID()] = $obj->name();
5616
-        }
5617
-        return $names;
5618
-    }
5619
-
5620
-
5621
-
5622
-    /**
5623
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5624
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5625
-     * this is duplicated effort and reduces efficiency) you would be better to use
5626
-     * array_keys() on $model_objects.
5627
-     *
5628
-     * @param \EE_Base_Class[] $model_objects
5629
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5630
-     *                                               in the returned array
5631
-     * @return array
5632
-     * @throws \EE_Error
5633
-     */
5634
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5635
-    {
5636
-        if (! $this->has_primary_key_field()) {
5637
-            if (WP_DEBUG) {
5638
-                EE_Error::add_error(
5639
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5640
-                    __FILE__,
5641
-                    __FUNCTION__,
5642
-                    __LINE__
5643
-                );
5644
-            }
5645
-        }
5646
-        $IDs = array();
5647
-        foreach ($model_objects as $model_object) {
5648
-            $id = $model_object->ID();
5649
-            if (! $id) {
5650
-                if ($filter_out_empty_ids) {
5651
-                    continue;
5652
-                }
5653
-                if (WP_DEBUG) {
5654
-                    EE_Error::add_error(
5655
-                        __(
5656
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5657
-                            'event_espresso'
5658
-                        ),
5659
-                        __FILE__,
5660
-                        __FUNCTION__,
5661
-                        __LINE__
5662
-                    );
5663
-                }
5664
-            }
5665
-            $IDs[] = $id;
5666
-        }
5667
-        return $IDs;
5668
-    }
5669
-
5670
-
5671
-
5672
-    /**
5673
-     * Returns the string used in capabilities relating to this model. If there
5674
-     * are no capabilities that relate to this model returns false
5675
-     *
5676
-     * @return string|false
5677
-     */
5678
-    public function cap_slug()
5679
-    {
5680
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5681
-    }
5682
-
5683
-
5684
-
5685
-    /**
5686
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5687
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5688
-     * only returns the cap restrictions array in that context (ie, the array
5689
-     * at that key)
5690
-     *
5691
-     * @param string $context
5692
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5693
-     * @throws \EE_Error
5694
-     */
5695
-    public function cap_restrictions($context = EEM_Base::caps_read)
5696
-    {
5697
-        EEM_Base::verify_is_valid_cap_context($context);
5698
-        //check if we ought to run the restriction generator first
5699
-        if (
5700
-            isset($this->_cap_restriction_generators[$context])
5701
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5702
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5703
-        ) {
5704
-            $this->_cap_restrictions[$context] = array_merge(
5705
-                $this->_cap_restrictions[$context],
5706
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5707
-            );
5708
-        }
5709
-        //and make sure we've finalized the construction of each restriction
5710
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5711
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5712
-                $where_conditions_obj->_finalize_construct($this);
5713
-            }
5714
-        }
5715
-        return $this->_cap_restrictions[$context];
5716
-    }
5717
-
5718
-
5719
-
5720
-    /**
5721
-     * Indicating whether or not this model thinks its a wp core model
5722
-     *
5723
-     * @return boolean
5724
-     */
5725
-    public function is_wp_core_model()
5726
-    {
5727
-        return $this->_wp_core_model;
5728
-    }
5729
-
5730
-
5731
-
5732
-    /**
5733
-     * Gets all the caps that are missing which impose a restriction on
5734
-     * queries made in this context
5735
-     *
5736
-     * @param string $context one of EEM_Base::caps_ constants
5737
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5738
-     * @throws \EE_Error
5739
-     */
5740
-    public function caps_missing($context = EEM_Base::caps_read)
5741
-    {
5742
-        $missing_caps = array();
5743
-        $cap_restrictions = $this->cap_restrictions($context);
5744
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5745
-            if (! EE_Capabilities::instance()
5746
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5747
-            ) {
5748
-                $missing_caps[$cap] = $restriction_if_no_cap;
5749
-            }
5750
-        }
5751
-        return $missing_caps;
5752
-    }
5753
-
5754
-
5755
-
5756
-    /**
5757
-     * Gets the mapping from capability contexts to action strings used in capability names
5758
-     *
5759
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5760
-     * one of 'read', 'edit', or 'delete'
5761
-     */
5762
-    public function cap_contexts_to_cap_action_map()
5763
-    {
5764
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5765
-            $this);
5766
-    }
5767
-
5768
-
5769
-
5770
-    /**
5771
-     * Gets the action string for the specified capability context
5772
-     *
5773
-     * @param string $context
5774
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5775
-     * @throws \EE_Error
5776
-     */
5777
-    public function cap_action_for_context($context)
5778
-    {
5779
-        $mapping = $this->cap_contexts_to_cap_action_map();
5780
-        if (isset($mapping[$context])) {
5781
-            return $mapping[$context];
5782
-        }
5783
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5784
-            return $action;
5785
-        }
5786
-        throw new EE_Error(
5787
-            sprintf(
5788
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5789
-                $context,
5790
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5791
-            )
5792
-        );
5793
-    }
5794
-
5795
-
5796
-
5797
-    /**
5798
-     * Returns all the capability contexts which are valid when querying models
5799
-     *
5800
-     * @return array
5801
-     */
5802
-    public static function valid_cap_contexts()
5803
-    {
5804
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5805
-            self::caps_read,
5806
-            self::caps_read_admin,
5807
-            self::caps_edit,
5808
-            self::caps_delete,
5809
-        ));
5810
-    }
5811
-
5812
-
5813
-
5814
-    /**
5815
-     * Returns all valid options for 'default_where_conditions'
5816
-     *
5817
-     * @return array
5818
-     */
5819
-    public static function valid_default_where_conditions()
5820
-    {
5821
-        return array(
5822
-            EEM_Base::default_where_conditions_all,
5823
-            EEM_Base::default_where_conditions_this_only,
5824
-            EEM_Base::default_where_conditions_others_only,
5825
-            EEM_Base::default_where_conditions_minimum_all,
5826
-            EEM_Base::default_where_conditions_minimum_others,
5827
-            EEM_Base::default_where_conditions_none
5828
-        );
5829
-    }
5830
-
5831
-    // public static function default_where_conditions_full
5832
-    /**
5833
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5834
-     *
5835
-     * @param string $context
5836
-     * @return bool
5837
-     * @throws \EE_Error
5838
-     */
5839
-    static public function verify_is_valid_cap_context($context)
5840
-    {
5841
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5842
-        if (in_array($context, $valid_cap_contexts)) {
5843
-            return true;
5844
-        } else {
5845
-            throw new EE_Error(
5846
-                sprintf(
5847
-                    __('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5848
-                        'event_espresso'),
5849
-                    $context,
5850
-                    'EEM_Base',
5851
-                    implode(',', $valid_cap_contexts)
5852
-                )
5853
-            );
5854
-        }
5855
-    }
5856
-
5857
-
5858
-
5859
-    /**
5860
-     * Clears all the models field caches. This is only useful when a sub-class
5861
-     * might have added a field or something and these caches might be invalidated
5862
-     */
5863
-    protected function _invalidate_field_caches()
5864
-    {
5865
-        $this->_cache_foreign_key_to_fields = array();
5866
-        $this->_cached_fields = null;
5867
-        $this->_cached_fields_non_db_only = null;
5868
-    }
5869
-
5870
-
5871
-
5872
-    /**
5873
-     * Gets the list of all the where query param keys that relate to logic instead of field names
5874
-     * (eg "and", "or", "not").
5875
-     *
5876
-     * @return array
5877
-     */
5878
-    public function logic_query_param_keys()
5879
-    {
5880
-        return $this->_logic_query_param_keys;
5881
-    }
5882
-
5883
-
5884
-
5885
-    /**
5886
-     * Determines whether or not the where query param array key is for a logic query param.
5887
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5888
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5889
-     *
5890
-     * @param $query_param_key
5891
-     * @return bool
5892
-     */
5893
-    public function is_logic_query_param_key($query_param_key)
5894
-    {
5895
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5896
-            if ($query_param_key === $logic_query_param_key
5897
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5898
-            ) {
5899
-                return true;
5900
-            }
5901
-        }
5902
-        return false;
5903
-    }
3632
+		}
3633
+		return $null_friendly_where_conditions;
3634
+	}
3635
+
3636
+
3637
+
3638
+	/**
3639
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3640
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3641
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3642
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3643
+	 *
3644
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3645
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3646
+	 */
3647
+	private function _get_default_where_conditions($model_relation_path = null)
3648
+	{
3649
+		if ($this->_ignore_where_strategy) {
3650
+			return array();
3651
+		}
3652
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3653
+	}
3654
+
3655
+
3656
+
3657
+	/**
3658
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3659
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3660
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3661
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3662
+	 * Similar to _get_default_where_conditions
3663
+	 *
3664
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3665
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3666
+	 */
3667
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3668
+	{
3669
+		if ($this->_ignore_where_strategy) {
3670
+			return array();
3671
+		}
3672
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3673
+	}
3674
+
3675
+
3676
+
3677
+	/**
3678
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3679
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3680
+	 *
3681
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3682
+	 * @return string
3683
+	 * @throws \EE_Error
3684
+	 */
3685
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3686
+	{
3687
+		$selects = $this->_get_columns_to_select_for_this_model();
3688
+		foreach (
3689
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3690
+			$name_of_other_model_included
3691
+		) {
3692
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3693
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3694
+			foreach ($other_model_selects as $key => $value) {
3695
+				$selects[] = $value;
3696
+			}
3697
+		}
3698
+		return implode(", ", $selects);
3699
+	}
3700
+
3701
+
3702
+
3703
+	/**
3704
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3705
+	 * So that's going to be the columns for all the fields on the model
3706
+	 *
3707
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3708
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3709
+	 */
3710
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3711
+	{
3712
+		$fields = $this->field_settings();
3713
+		$selects = array();
3714
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3715
+			$this->get_this_model_name());
3716
+		foreach ($fields as $field_obj) {
3717
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3718
+						 . $field_obj->get_table_alias()
3719
+						 . "."
3720
+						 . $field_obj->get_table_column()
3721
+						 . " AS '"
3722
+						 . $table_alias_with_model_relation_chain_prefix
3723
+						 . $field_obj->get_table_alias()
3724
+						 . "."
3725
+						 . $field_obj->get_table_column()
3726
+						 . "'";
3727
+		}
3728
+		//make sure we are also getting the PKs of each table
3729
+		$tables = $this->get_tables();
3730
+		if (count($tables) > 1) {
3731
+			foreach ($tables as $table_obj) {
3732
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3733
+									   . $table_obj->get_fully_qualified_pk_column();
3734
+				if (! in_array($qualified_pk_column, $selects)) {
3735
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3736
+				}
3737
+			}
3738
+		}
3739
+		return $selects;
3740
+	}
3741
+
3742
+
3743
+
3744
+	/**
3745
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3746
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3747
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3748
+	 * SQL for joining, and the data types
3749
+	 *
3750
+	 * @param null|string                 $original_query_param
3751
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3752
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3753
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3754
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3755
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3756
+	 *                                                          or 'Registration's
3757
+	 * @param string                      $original_query_param what it originally was (eg
3758
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3759
+	 *                                                          matches $query_param
3760
+	 * @throws EE_Error
3761
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3762
+	 */
3763
+	private function _extract_related_model_info_from_query_param(
3764
+		$query_param,
3765
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3766
+		$query_param_type,
3767
+		$original_query_param = null
3768
+	) {
3769
+		if ($original_query_param === null) {
3770
+			$original_query_param = $query_param;
3771
+		}
3772
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3773
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3774
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3775
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3776
+		//check to see if we have a field on this model
3777
+		$this_model_fields = $this->field_settings(true);
3778
+		if (array_key_exists($query_param, $this_model_fields)) {
3779
+			if ($allow_fields) {
3780
+				return;
3781
+			} else {
3782
+				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",
3783
+					"event_espresso"),
3784
+					$query_param, get_class($this), $query_param_type, $original_query_param));
3785
+			}
3786
+		} //check if this is a special logic query param
3787
+		elseif (in_array($query_param, $this->_logic_query_param_keys, true)) {
3788
+			if ($allow_logic_query_params) {
3789
+				return;
3790
+			} else {
3791
+				throw new EE_Error(
3792
+					sprintf(
3793
+						__('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',
3794
+							'event_espresso'),
3795
+						implode('", "', $this->_logic_query_param_keys),
3796
+						$query_param,
3797
+						get_class($this),
3798
+						'<br />',
3799
+						"\t"
3800
+						. ' $passed_in_query_info = <pre>'
3801
+						. print_r($passed_in_query_info, true)
3802
+						. '</pre>'
3803
+						. "\n\t"
3804
+						. ' $query_param_type = '
3805
+						. $query_param_type
3806
+						. "\n\t"
3807
+						. ' $original_query_param = '
3808
+						. $original_query_param
3809
+					)
3810
+				);
3811
+			}
3812
+		} //check if it's a custom selection
3813
+		elseif (array_key_exists($query_param, $this->_custom_selections)) {
3814
+			return;
3815
+		}
3816
+		//check if has a model name at the beginning
3817
+		//and
3818
+		//check if it's a field on a related model
3819
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3820
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3821
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3822
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3823
+				if ($query_param === '') {
3824
+					//nothing left to $query_param
3825
+					//we should actually end in a field name, not a model like this!
3826
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3827
+						"event_espresso"),
3828
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3829
+				} else {
3830
+					$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3831
+					$related_model_obj->_extract_related_model_info_from_query_param($query_param,
3832
+						$passed_in_query_info, $query_param_type, $original_query_param);
3833
+					return;
3834
+				}
3835
+			} elseif ($query_param === $valid_related_model_name) {
3836
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3837
+				return;
3838
+			}
3839
+		}
3840
+		//ok so $query_param didn't start with a model name
3841
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3842
+		//it's wack, that's what it is
3843
+		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",
3844
+			"event_espresso"),
3845
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3846
+	}
3847
+
3848
+
3849
+
3850
+	/**
3851
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3852
+	 * and store it on $passed_in_query_info
3853
+	 *
3854
+	 * @param string                      $model_name
3855
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3856
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3857
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3858
+	 *                                                          and are adding a join to 'Payment' with the original
3859
+	 *                                                          query param key
3860
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3861
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3862
+	 *                                                          Payment wants to add default query params so that it
3863
+	 *                                                          will know what models to prepend onto its default query
3864
+	 *                                                          params or in case it wants to rename tables (in case
3865
+	 *                                                          there are multiple joins to the same table)
3866
+	 * @return void
3867
+	 * @throws \EE_Error
3868
+	 */
3869
+	private function _add_join_to_model(
3870
+		$model_name,
3871
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3872
+		$original_query_param
3873
+	) {
3874
+		$relation_obj = $this->related_settings_for($model_name);
3875
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3876
+		//check if the relation is HABTM, because then we're essentially doing two joins
3877
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3878
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3879
+			$join_model_obj = $relation_obj->get_join_model();
3880
+			//replace the model specified with the join model for this relation chain, whi
3881
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
3882
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
3883
+			$new_query_info = new EE_Model_Query_Info_Carrier(
3884
+				array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
3885
+				$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model));
3886
+			$passed_in_query_info->merge($new_query_info);
3887
+		}
3888
+		//now just join to the other table pointed to by the relation object, and add its data types
3889
+		$new_query_info = new EE_Model_Query_Info_Carrier(
3890
+			array($model_relation_chain => $model_name),
3891
+			$relation_obj->get_join_statement($model_relation_chain));
3892
+		$passed_in_query_info->merge($new_query_info);
3893
+	}
3894
+
3895
+
3896
+
3897
+	/**
3898
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
3899
+	 *
3900
+	 * @param array $where_params like EEM_Base::get_all
3901
+	 * @return string of SQL
3902
+	 * @throws \EE_Error
3903
+	 */
3904
+	private function _construct_where_clause($where_params)
3905
+	{
3906
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3907
+		if ($SQL) {
3908
+			return " WHERE " . $SQL;
3909
+		} else {
3910
+			return '';
3911
+		}
3912
+	}
3913
+
3914
+
3915
+
3916
+	/**
3917
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
3918
+	 * and should be passed HAVING parameters, not WHERE parameters
3919
+	 *
3920
+	 * @param array $having_params
3921
+	 * @return string
3922
+	 * @throws \EE_Error
3923
+	 */
3924
+	private function _construct_having_clause($having_params)
3925
+	{
3926
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3927
+		if ($SQL) {
3928
+			return " HAVING " . $SQL;
3929
+		} else {
3930
+			return '';
3931
+		}
3932
+	}
3933
+
3934
+
3935
+	/**
3936
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
3937
+	 * Event_Meta.meta_value = 'foo'))"
3938
+	 *
3939
+	 * @param array  $where_params see EEM_Base::get_all for documentation
3940
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
3941
+	 * @throws EE_Error
3942
+	 * @return string of SQL
3943
+	 */
3944
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
3945
+	{
3946
+		$where_clauses = array();
3947
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3948
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3949
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
3950
+				switch ($query_param) {
3951
+					case 'not':
3952
+					case 'NOT':
3953
+						$where_clauses[] = "! ("
3954
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3955
+								$glue)
3956
+										   . ")";
3957
+						break;
3958
+					case 'and':
3959
+					case 'AND':
3960
+						$where_clauses[] = " ("
3961
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3962
+								' AND ')
3963
+										   . ")";
3964
+						break;
3965
+					case 'or':
3966
+					case 'OR':
3967
+						$where_clauses[] = " ("
3968
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
3969
+								' OR ')
3970
+										   . ")";
3971
+						break;
3972
+				}
3973
+			} else {
3974
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
3975
+				//if it's not a normal field, maybe it's a custom selection?
3976
+				if (! $field_obj) {
3977
+					if (isset($this->_custom_selections[$query_param][1])) {
3978
+						$field_obj = $this->_custom_selections[$query_param][1];
3979
+					} else {
3980
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
3981
+							"event_espresso"), $query_param));
3982
+					}
3983
+				}
3984
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3985
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3986
+			}
3987
+		}
3988
+		return $where_clauses ? implode($glue, $where_clauses) : '';
3989
+	}
3990
+
3991
+
3992
+
3993
+	/**
3994
+	 * Takes the input parameter and extract the table name (alias) and column name
3995
+	 *
3996
+	 * @param array $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
3997
+	 * @throws EE_Error
3998
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
3999
+	 */
4000
+	private function _deduce_column_name_from_query_param($query_param)
4001
+	{
4002
+		$field = $this->_deduce_field_from_query_param($query_param);
4003
+		if ($field) {
4004
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4005
+				$query_param);
4006
+			return $table_alias_prefix . $field->get_qualified_column();
4007
+		} elseif (array_key_exists($query_param, $this->_custom_selections)) {
4008
+			//maybe it's custom selection item?
4009
+			//if so, just use it as the "column name"
4010
+			return $query_param;
4011
+		} else {
4012
+			throw new EE_Error(sprintf(__("%s is not a valid field on this model, nor a custom selection (%s)",
4013
+				"event_espresso"), $query_param, implode(",", $this->_custom_selections)));
4014
+		}
4015
+	}
4016
+
4017
+
4018
+
4019
+	/**
4020
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4021
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4022
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4023
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4024
+	 *
4025
+	 * @param string $condition_query_param_key
4026
+	 * @return string
4027
+	 */
4028
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4029
+	{
4030
+		$pos_of_star = strpos($condition_query_param_key, '*');
4031
+		if ($pos_of_star === false) {
4032
+			return $condition_query_param_key;
4033
+		} else {
4034
+			$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4035
+			return $condition_query_param_sans_star;
4036
+		}
4037
+	}
4038
+
4039
+
4040
+
4041
+	/**
4042
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4043
+	 *
4044
+	 * @param                            mixed      array | string    $op_and_value
4045
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4046
+	 * @throws EE_Error
4047
+	 * @return string
4048
+	 */
4049
+	private function _construct_op_and_value($op_and_value, $field_obj)
4050
+	{
4051
+		if (is_array($op_and_value)) {
4052
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4053
+			if (! $operator) {
4054
+				$php_array_like_string = array();
4055
+				foreach ($op_and_value as $key => $value) {
4056
+					$php_array_like_string[] = "$key=>$value";
4057
+				}
4058
+				throw new EE_Error(
4059
+					sprintf(
4060
+						__(
4061
+							"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))",
4062
+							"event_espresso"
4063
+						),
4064
+						implode(",", $php_array_like_string)
4065
+					)
4066
+				);
4067
+			}
4068
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4069
+		} else {
4070
+			$operator = '=';
4071
+			$value = $op_and_value;
4072
+		}
4073
+		//check to see if the value is actually another field
4074
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4075
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4076
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4077
+			//in this case, the value should be an array, or at least a comma-separated list
4078
+			//it will need to handle a little differently
4079
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4080
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4081
+			return $operator . SP . $cleaned_value;
4082
+		} elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4083
+			//the value should be an array with count of two.
4084
+			if (count($value) !== 2) {
4085
+				throw new EE_Error(
4086
+					sprintf(
4087
+						__(
4088
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4089
+							'event_espresso'
4090
+						),
4091
+						"BETWEEN"
4092
+					)
4093
+				);
4094
+			}
4095
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4096
+			return $operator . SP . $cleaned_value;
4097
+		} elseif (in_array($operator, $this->valid_null_style_operators())) {
4098
+			if ($value !== null) {
4099
+				throw new EE_Error(
4100
+					sprintf(
4101
+						__(
4102
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4103
+							"event_espresso"
4104
+						),
4105
+						$value,
4106
+						$operator
4107
+					)
4108
+				);
4109
+			}
4110
+			return $operator;
4111
+		} elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4112
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4113
+			//remove other junk. So just treat it as a string.
4114
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4115
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4116
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4117
+		} elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4118
+			throw new EE_Error(
4119
+				sprintf(
4120
+					__(
4121
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4122
+						'event_espresso'
4123
+					),
4124
+					$operator,
4125
+					$operator
4126
+				)
4127
+			);
4128
+		} elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4129
+			throw new EE_Error(
4130
+				sprintf(
4131
+					__(
4132
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4133
+						'event_espresso'
4134
+					),
4135
+					$operator,
4136
+					$operator
4137
+				)
4138
+			);
4139
+		} else {
4140
+			throw new EE_Error(
4141
+				sprintf(
4142
+					__(
4143
+						"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4144
+						"event_espresso"
4145
+					),
4146
+					http_build_query($op_and_value)
4147
+				)
4148
+			);
4149
+		}
4150
+	}
4151
+
4152
+
4153
+
4154
+	/**
4155
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4156
+	 *
4157
+	 * @param array                      $values
4158
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4159
+	 *                                              '%s'
4160
+	 * @return string
4161
+	 * @throws \EE_Error
4162
+	 */
4163
+	public function _construct_between_value($values, $field_obj)
4164
+	{
4165
+		$cleaned_values = array();
4166
+		foreach ($values as $value) {
4167
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4168
+		}
4169
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4170
+	}
4171
+
4172
+
4173
+
4174
+	/**
4175
+	 * Takes an array or a comma-separated list of $values and cleans them
4176
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4177
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4178
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4179
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4180
+	 *
4181
+	 * @param mixed                      $values    array or comma-separated string
4182
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4183
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4184
+	 * @throws \EE_Error
4185
+	 */
4186
+	public function _construct_in_value($values, $field_obj)
4187
+	{
4188
+		//check if the value is a CSV list
4189
+		if (is_string($values)) {
4190
+			//in which case, turn it into an array
4191
+			$values = explode(",", $values);
4192
+		}
4193
+		$cleaned_values = array();
4194
+		foreach ($values as $value) {
4195
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4196
+		}
4197
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4198
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4199
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4200
+		if (empty($cleaned_values)) {
4201
+			$all_fields = $this->field_settings();
4202
+			$a_field = array_shift($all_fields);
4203
+			$main_table = $this->_get_main_table();
4204
+			$cleaned_values[] = "SELECT "
4205
+								. $a_field->get_table_column()
4206
+								. " FROM "
4207
+								. $main_table->get_table_name()
4208
+								. " WHERE FALSE";
4209
+		}
4210
+		return "(" . implode(",", $cleaned_values) . ")";
4211
+	}
4212
+
4213
+
4214
+
4215
+	/**
4216
+	 * @param mixed                      $value
4217
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4218
+	 * @throws EE_Error
4219
+	 * @return false|null|string
4220
+	 */
4221
+	private function _wpdb_prepare_using_field($value, $field_obj)
4222
+	{
4223
+		/** @type WPDB $wpdb */
4224
+		global $wpdb;
4225
+		if ($field_obj instanceof EE_Model_Field_Base) {
4226
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4227
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4228
+		} else {//$field_obj should really just be a data type
4229
+			if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4230
+				throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4231
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)));
4232
+			}
4233
+			return $wpdb->prepare($field_obj, $value);
4234
+		}
4235
+	}
4236
+
4237
+
4238
+
4239
+	/**
4240
+	 * Takes the input parameter and finds the model field that it indicates.
4241
+	 *
4242
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4243
+	 * @throws EE_Error
4244
+	 * @return EE_Model_Field_Base
4245
+	 */
4246
+	protected function _deduce_field_from_query_param($query_param_name)
4247
+	{
4248
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4249
+		//which will help us find the database table and column
4250
+		$query_param_parts = explode(".", $query_param_name);
4251
+		if (empty($query_param_parts)) {
4252
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4253
+				'event_espresso'), $query_param_name));
4254
+		}
4255
+		$number_of_parts = count($query_param_parts);
4256
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4257
+		if ($number_of_parts === 1) {
4258
+			$field_name = $last_query_param_part;
4259
+			$model_obj = $this;
4260
+		} else {// $number_of_parts >= 2
4261
+			//the last part is the column name, and there are only 2parts. therefore...
4262
+			$field_name = $last_query_param_part;
4263
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4264
+		}
4265
+		try {
4266
+			return $model_obj->field_settings_for($field_name);
4267
+		} catch (EE_Error $e) {
4268
+			return null;
4269
+		}
4270
+	}
4271
+
4272
+
4273
+
4274
+	/**
4275
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4276
+	 * alias and column which corresponds to it
4277
+	 *
4278
+	 * @param string $field_name
4279
+	 * @throws EE_Error
4280
+	 * @return string
4281
+	 */
4282
+	public function _get_qualified_column_for_field($field_name)
4283
+	{
4284
+		$all_fields = $this->field_settings();
4285
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4286
+		if ($field) {
4287
+			return $field->get_qualified_column();
4288
+		} else {
4289
+			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.",
4290
+				'event_espresso'), $field_name, get_class($this)));
4291
+		}
4292
+	}
4293
+
4294
+
4295
+
4296
+	/**
4297
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4298
+	 * Example usage:
4299
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4300
+	 *      array(),
4301
+	 *      ARRAY_A,
4302
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4303
+	 *  );
4304
+	 * is equivalent to
4305
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4306
+	 * and
4307
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4308
+	 *      array(
4309
+	 *          array(
4310
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4311
+	 *          ),
4312
+	 *          ARRAY_A,
4313
+	 *          implode(
4314
+	 *              ', ',
4315
+	 *              array_merge(
4316
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4317
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4318
+	 *              )
4319
+	 *          )
4320
+	 *      )
4321
+	 *  );
4322
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4323
+	 *
4324
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4325
+	 *                                            and the one whose fields you are selecting for example: when querying
4326
+	 *                                            tickets model and selecting fields from the tickets model you would
4327
+	 *                                            leave this parameter empty, because no models are needed to join
4328
+	 *                                            between the queried model and the selected one. Likewise when
4329
+	 *                                            querying the datetime model and selecting fields from the tickets
4330
+	 *                                            model, it would also be left empty, because there is a direct
4331
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4332
+	 *                                            them together. However, when querying from the event model and
4333
+	 *                                            selecting fields from the ticket model, you should provide the string
4334
+	 *                                            'Datetime', indicating that the event model must first join to the
4335
+	 *                                            datetime model in order to find its relation to ticket model.
4336
+	 *                                            Also, when querying from the venue model and selecting fields from
4337
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4338
+	 *                                            indicating you need to join the venue model to the event model,
4339
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4340
+	 *                                            This string is used to deduce the prefix that gets added onto the
4341
+	 *                                            models' tables qualified columns
4342
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4343
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4344
+	 *                                            qualified column names
4345
+	 * @return array|string
4346
+	 */
4347
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4348
+	{
4349
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4350
+		$qualified_columns = array();
4351
+		foreach ($this->field_settings() as $field_name => $field) {
4352
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4353
+		}
4354
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4355
+	}
4356
+
4357
+
4358
+
4359
+	/**
4360
+	 * constructs the select use on special limit joins
4361
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4362
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4363
+	 * (as that is typically where the limits would be set).
4364
+	 *
4365
+	 * @param  string       $table_alias The table the select is being built for
4366
+	 * @param  mixed|string $limit       The limit for this select
4367
+	 * @return string                The final select join element for the query.
4368
+	 */
4369
+	public function _construct_limit_join_select($table_alias, $limit)
4370
+	{
4371
+		$SQL = '';
4372
+		foreach ($this->_tables as $table_obj) {
4373
+			if ($table_obj instanceof EE_Primary_Table) {
4374
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4375
+					? $table_obj->get_select_join_limit($limit)
4376
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4377
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4378
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4379
+					? $table_obj->get_select_join_limit_join($limit)
4380
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4381
+			}
4382
+		}
4383
+		return $SQL;
4384
+	}
4385
+
4386
+
4387
+
4388
+	/**
4389
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4390
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4391
+	 *
4392
+	 * @return string SQL
4393
+	 * @throws \EE_Error
4394
+	 */
4395
+	public function _construct_internal_join()
4396
+	{
4397
+		$SQL = $this->_get_main_table()->get_table_sql();
4398
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4399
+		return $SQL;
4400
+	}
4401
+
4402
+
4403
+
4404
+	/**
4405
+	 * Constructs the SQL for joining all the tables on this model.
4406
+	 * Normally $alias should be the primary table's alias, but in cases where
4407
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4408
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4409
+	 * alias, this will construct SQL like:
4410
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4411
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4412
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4413
+	 *
4414
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4415
+	 * @return string
4416
+	 */
4417
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4418
+	{
4419
+		$SQL = '';
4420
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4421
+		foreach ($this->_tables as $table_obj) {
4422
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4423
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4424
+					//so we're joining to this table, meaning the table is already in
4425
+					//the FROM statement, BUT the primary table isn't. So we want
4426
+					//to add the inverse join sql
4427
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4428
+				} else {
4429
+					//just add a regular JOIN to this table from the primary table
4430
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4431
+				}
4432
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4433
+		}
4434
+		return $SQL;
4435
+	}
4436
+
4437
+
4438
+
4439
+	/**
4440
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4441
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4442
+	 * their data type (eg, '%s', '%d', etc)
4443
+	 *
4444
+	 * @return array
4445
+	 */
4446
+	public function _get_data_types()
4447
+	{
4448
+		$data_types = array();
4449
+		foreach ($this->field_settings() as $field_obj) {
4450
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4451
+			/** @var $field_obj EE_Model_Field_Base */
4452
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4453
+		}
4454
+		return $data_types;
4455
+	}
4456
+
4457
+
4458
+
4459
+	/**
4460
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4461
+	 *
4462
+	 * @param string $model_name
4463
+	 * @throws EE_Error
4464
+	 * @return EEM_Base
4465
+	 */
4466
+	public function get_related_model_obj($model_name)
4467
+	{
4468
+		$model_classname = "EEM_" . $model_name;
4469
+		if (! class_exists($model_classname)) {
4470
+			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",
4471
+				'event_espresso'), $model_name, $model_classname));
4472
+		}
4473
+		return call_user_func($model_classname . "::instance");
4474
+	}
4475
+
4476
+
4477
+
4478
+	/**
4479
+	 * Returns the array of EE_ModelRelations for this model.
4480
+	 *
4481
+	 * @return EE_Model_Relation_Base[]
4482
+	 */
4483
+	public function relation_settings()
4484
+	{
4485
+		return $this->_model_relations;
4486
+	}
4487
+
4488
+
4489
+
4490
+	/**
4491
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4492
+	 * because without THOSE models, this model probably doesn't have much purpose.
4493
+	 * (Eg, without an event, datetimes have little purpose.)
4494
+	 *
4495
+	 * @return EE_Belongs_To_Relation[]
4496
+	 */
4497
+	public function belongs_to_relations()
4498
+	{
4499
+		$belongs_to_relations = array();
4500
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4501
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4502
+				$belongs_to_relations[$model_name] = $relation_obj;
4503
+			}
4504
+		}
4505
+		return $belongs_to_relations;
4506
+	}
4507
+
4508
+
4509
+
4510
+	/**
4511
+	 * Returns the specified EE_Model_Relation, or throws an exception
4512
+	 *
4513
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4514
+	 * @throws EE_Error
4515
+	 * @return EE_Model_Relation_Base
4516
+	 */
4517
+	public function related_settings_for($relation_name)
4518
+	{
4519
+		$relatedModels = $this->relation_settings();
4520
+		if (! array_key_exists($relation_name, $relatedModels)) {
4521
+			throw new EE_Error(
4522
+				sprintf(
4523
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4524
+						'event_espresso'),
4525
+					$relation_name,
4526
+					$this->_get_class_name(),
4527
+					implode(', ', array_keys($relatedModels))
4528
+				)
4529
+			);
4530
+		}
4531
+		return $relatedModels[$relation_name];
4532
+	}
4533
+
4534
+
4535
+
4536
+	/**
4537
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4538
+	 * fields
4539
+	 *
4540
+	 * @param string $fieldName
4541
+	 * @param boolean $include_db_only_fields
4542
+	 * @throws EE_Error
4543
+	 * @return EE_Model_Field_Base
4544
+	 */
4545
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4546
+	{
4547
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4548
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4549
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4550
+				get_class($this)));
4551
+		}
4552
+		return $fieldSettings[$fieldName];
4553
+	}
4554
+
4555
+
4556
+
4557
+	/**
4558
+	 * Checks if this field exists on this model
4559
+	 *
4560
+	 * @param string $fieldName a key in the model's _field_settings array
4561
+	 * @return boolean
4562
+	 */
4563
+	public function has_field($fieldName)
4564
+	{
4565
+		$fieldSettings = $this->field_settings(true);
4566
+		if (isset($fieldSettings[$fieldName])) {
4567
+			return true;
4568
+		} else {
4569
+			return false;
4570
+		}
4571
+	}
4572
+
4573
+
4574
+
4575
+	/**
4576
+	 * Returns whether or not this model has a relation to the specified model
4577
+	 *
4578
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4579
+	 * @return boolean
4580
+	 */
4581
+	public function has_relation($relation_name)
4582
+	{
4583
+		$relations = $this->relation_settings();
4584
+		if (isset($relations[$relation_name])) {
4585
+			return true;
4586
+		} else {
4587
+			return false;
4588
+		}
4589
+	}
4590
+
4591
+
4592
+
4593
+	/**
4594
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4595
+	 * Eg, on EE_Answer that would be ANS_ID field object
4596
+	 *
4597
+	 * @param $field_obj
4598
+	 * @return boolean
4599
+	 */
4600
+	public function is_primary_key_field($field_obj)
4601
+	{
4602
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4603
+	}
4604
+
4605
+
4606
+
4607
+	/**
4608
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4609
+	 * Eg, on EE_Answer that would be ANS_ID field object
4610
+	 *
4611
+	 * @return EE_Model_Field_Base
4612
+	 * @throws EE_Error
4613
+	 */
4614
+	public function get_primary_key_field()
4615
+	{
4616
+		if ($this->_primary_key_field === null) {
4617
+			foreach ($this->field_settings(true) as $field_obj) {
4618
+				if ($this->is_primary_key_field($field_obj)) {
4619
+					$this->_primary_key_field = $field_obj;
4620
+					break;
4621
+				}
4622
+			}
4623
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4624
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4625
+					get_class($this)));
4626
+			}
4627
+		}
4628
+		return $this->_primary_key_field;
4629
+	}
4630
+
4631
+
4632
+
4633
+	/**
4634
+	 * Returns whether or not not there is a primary key on this model.
4635
+	 * Internally does some caching.
4636
+	 *
4637
+	 * @return boolean
4638
+	 */
4639
+	public function has_primary_key_field()
4640
+	{
4641
+		if ($this->_has_primary_key_field === null) {
4642
+			try {
4643
+				$this->get_primary_key_field();
4644
+				$this->_has_primary_key_field = true;
4645
+			} catch (EE_Error $e) {
4646
+				$this->_has_primary_key_field = false;
4647
+			}
4648
+		}
4649
+		return $this->_has_primary_key_field;
4650
+	}
4651
+
4652
+
4653
+
4654
+	/**
4655
+	 * Finds the first field of type $field_class_name.
4656
+	 *
4657
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4658
+	 *                                 EE_Foreign_Key_Field, etc
4659
+	 * @return EE_Model_Field_Base or null if none is found
4660
+	 */
4661
+	public function get_a_field_of_type($field_class_name)
4662
+	{
4663
+		foreach ($this->field_settings() as $field) {
4664
+			if ($field instanceof $field_class_name) {
4665
+				return $field;
4666
+			}
4667
+		}
4668
+		return null;
4669
+	}
4670
+
4671
+
4672
+
4673
+	/**
4674
+	 * Gets a foreign key field pointing to model.
4675
+	 *
4676
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4677
+	 * @return EE_Foreign_Key_Field_Base
4678
+	 * @throws EE_Error
4679
+	 */
4680
+	public function get_foreign_key_to($model_name)
4681
+	{
4682
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4683
+			foreach ($this->field_settings() as $field) {
4684
+				if (
4685
+					$field instanceof EE_Foreign_Key_Field_Base
4686
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4687
+				) {
4688
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4689
+					break;
4690
+				}
4691
+			}
4692
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4694
+					'event_espresso'), $model_name, get_class($this)));
4695
+			}
4696
+		}
4697
+		return $this->_cache_foreign_key_to_fields[$model_name];
4698
+	}
4699
+
4700
+
4701
+
4702
+	/**
4703
+	 * Gets the actual table for the table alias
4704
+	 *
4705
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4706
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4707
+	 *                            Either one works
4708
+	 * @return EE_Table_Base
4709
+	 */
4710
+	public function get_table_for_alias($table_alias)
4711
+	{
4712
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4713
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4714
+	}
4715
+
4716
+
4717
+
4718
+	/**
4719
+	 * Returns a flat array of all field son this model, instead of organizing them
4720
+	 * by table_alias as they are in the constructor.
4721
+	 *
4722
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4723
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4724
+	 */
4725
+	public function field_settings($include_db_only_fields = false)
4726
+	{
4727
+		if ($include_db_only_fields) {
4728
+			if ($this->_cached_fields === null) {
4729
+				$this->_cached_fields = array();
4730
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4731
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4732
+						$this->_cached_fields[$field_name] = $field_obj;
4733
+					}
4734
+				}
4735
+			}
4736
+			return $this->_cached_fields;
4737
+		} else {
4738
+			if ($this->_cached_fields_non_db_only === null) {
4739
+				$this->_cached_fields_non_db_only = array();
4740
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4741
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742
+						/** @var $field_obj EE_Model_Field_Base */
4743
+						if (! $field_obj->is_db_only_field()) {
4744
+							$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4745
+						}
4746
+					}
4747
+				}
4748
+			}
4749
+			return $this->_cached_fields_non_db_only;
4750
+		}
4751
+	}
4752
+
4753
+
4754
+
4755
+	/**
4756
+	 *        cycle though array of attendees and create objects out of each item
4757
+	 *
4758
+	 * @access        private
4759
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4760
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4761
+	 *                           numerically indexed)
4762
+	 * @throws \EE_Error
4763
+	 */
4764
+	protected function _create_objects($rows = array())
4765
+	{
4766
+		$array_of_objects = array();
4767
+		if (empty($rows)) {
4768
+			return array();
4769
+		}
4770
+		$count_if_model_has_no_primary_key = 0;
4771
+		$has_primary_key = $this->has_primary_key_field();
4772
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4773
+		foreach ((array)$rows as $row) {
4774
+			if (empty($row)) {
4775
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4776
+				return array();
4777
+			}
4778
+			//check if we've already set this object in the results array,
4779
+			//in which case there's no need to process it further (again)
4780
+			if ($has_primary_key) {
4781
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4782
+					$row,
4783
+					$primary_key_field->get_qualified_column(),
4784
+					$primary_key_field->get_table_column()
4785
+				);
4786
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4787
+					continue;
4788
+				}
4789
+			}
4790
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4791
+			if (! $classInstance) {
4792
+				throw new EE_Error(
4793
+					sprintf(
4794
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4795
+						$this->get_this_model_name(),
4796
+						http_build_query($row)
4797
+					)
4798
+				);
4799
+			}
4800
+			//set the timezone on the instantiated objects
4801
+			$classInstance->set_timezone($this->_timezone);
4802
+			//make sure if there is any timezone setting present that we set the timezone for the object
4803
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4804
+			$array_of_objects[$key] = $classInstance;
4805
+			//also, for all the relations of type BelongsTo, see if we can cache
4806
+			//those related models
4807
+			//(we could do this for other relations too, but if there are conditions
4808
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4809
+			//so it requires a little more thought than just caching them immediately...)
4810
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4811
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4812
+					//check if this model's INFO is present. If so, cache it on the model
4813
+					$other_model = $relation_obj->get_other_model();
4814
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4815
+					//if we managed to make a model object from the results, cache it on the main model object
4816
+					if ($other_model_obj_maybe) {
4817
+						//set timezone on these other model objects if they are present
4818
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4819
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4820
+					}
4821
+				}
4822
+			}
4823
+		}
4824
+		return $array_of_objects;
4825
+	}
4826
+
4827
+
4828
+
4829
+	/**
4830
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4831
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4832
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4833
+	 * object (as set in the model_field!).
4834
+	 *
4835
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4836
+	 */
4837
+	public function create_default_object()
4838
+	{
4839
+		$this_model_fields_and_values = array();
4840
+		//setup the row using default values;
4841
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4842
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4843
+		}
4844
+		$className = $this->_get_class_name();
4845
+		$classInstance = EE_Registry::instance()
4846
+									->load_class($className, array($this_model_fields_and_values), false, false);
4847
+		return $classInstance;
4848
+	}
4849
+
4850
+
4851
+
4852
+	/**
4853
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4854
+	 *                             or an stdClass where each property is the name of a column,
4855
+	 * @return EE_Base_Class
4856
+	 * @throws \EE_Error
4857
+	 */
4858
+	public function instantiate_class_from_array_or_object($cols_n_values)
4859
+	{
4860
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4861
+			$cols_n_values = get_object_vars($cols_n_values);
4862
+		}
4863
+		$primary_key = null;
4864
+		//make sure the array only has keys that are fields/columns on this model
4865
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4866
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
4867
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
4868
+		}
4869
+		$className = $this->_get_class_name();
4870
+		//check we actually found results that we can use to build our model object
4871
+		//if not, return null
4872
+		if ($this->has_primary_key_field()) {
4873
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
4874
+				return null;
4875
+			}
4876
+		} else if ($this->unique_indexes()) {
4877
+			$first_column = reset($this_model_fields_n_values);
4878
+			if (empty($first_column)) {
4879
+				return null;
4880
+			}
4881
+		}
4882
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4883
+		if ($primary_key) {
4884
+			$classInstance = $this->get_from_entity_map($primary_key);
4885
+			if (! $classInstance) {
4886
+				$classInstance = EE_Registry::instance()
4887
+											->load_class($className,
4888
+												array($this_model_fields_n_values, $this->_timezone), true, false);
4889
+				// add this new object to the entity map
4890
+				$classInstance = $this->add_to_entity_map($classInstance);
4891
+			}
4892
+		} else {
4893
+			$classInstance = EE_Registry::instance()
4894
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
4895
+											true, false);
4896
+		}
4897
+		//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.
4898
+		$this->set_timezone($classInstance->get_timezone());
4899
+		return $classInstance;
4900
+	}
4901
+
4902
+
4903
+
4904
+	/**
4905
+	 * Gets the model object from the  entity map if it exists
4906
+	 *
4907
+	 * @param int|string $id the ID of the model object
4908
+	 * @return EE_Base_Class
4909
+	 */
4910
+	public function get_from_entity_map($id)
4911
+	{
4912
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
4913
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
4914
+	}
4915
+
4916
+
4917
+
4918
+	/**
4919
+	 * add_to_entity_map
4920
+	 * Adds the object to the model's entity mappings
4921
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
4922
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
4923
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
4924
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
4925
+	 *        then this method should be called immediately after the update query
4926
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
4927
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
4928
+	 *
4929
+	 * @param    EE_Base_Class $object
4930
+	 * @throws EE_Error
4931
+	 * @return \EE_Base_Class
4932
+	 */
4933
+	public function add_to_entity_map(EE_Base_Class $object)
4934
+	{
4935
+		$className = $this->_get_class_name();
4936
+		if (! $object instanceof $className) {
4937
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4938
+				is_object($object) ? get_class($object) : $object, $className));
4939
+		}
4940
+		/** @var $object EE_Base_Class */
4941
+		if (! $object->ID()) {
4942
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4943
+				"event_espresso"), get_class($this)));
4944
+		}
4945
+		// double check it's not already there
4946
+		$classInstance = $this->get_from_entity_map($object->ID());
4947
+		if ($classInstance) {
4948
+			return $classInstance;
4949
+		} else {
4950
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
4951
+			return $object;
4952
+		}
4953
+	}
4954
+
4955
+
4956
+
4957
+	/**
4958
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
4959
+	 * if no identifier is provided, then the entire entity map is emptied
4960
+	 *
4961
+	 * @param int|string $id the ID of the model object
4962
+	 * @return boolean
4963
+	 */
4964
+	public function clear_entity_map($id = null)
4965
+	{
4966
+		if (empty($id)) {
4967
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
4968
+			return true;
4969
+		}
4970
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
4971
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
4972
+			return true;
4973
+		}
4974
+		return false;
4975
+	}
4976
+
4977
+
4978
+
4979
+	/**
4980
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
4981
+	 * Given an array where keys are column (or column alias) names and values,
4982
+	 * returns an array of their corresponding field names and database values
4983
+	 *
4984
+	 * @param array $cols_n_values
4985
+	 * @return array
4986
+	 */
4987
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
4988
+	{
4989
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
4990
+	}
4991
+
4992
+
4993
+
4994
+	/**
4995
+	 * _deduce_fields_n_values_from_cols_n_values
4996
+	 * Given an array where keys are column (or column alias) names and values,
4997
+	 * returns an array of their corresponding field names and database values
4998
+	 *
4999
+	 * @param string $cols_n_values
5000
+	 * @return array
5001
+	 */
5002
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5003
+	{
5004
+		$this_model_fields_n_values = array();
5005
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5006
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5007
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5008
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5009
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5010
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5011
+					if (! $field_obj->is_db_only_field()) {
5012
+						//prepare field as if its coming from db
5013
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5014
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5015
+					}
5016
+				}
5017
+			} else {
5018
+				//the table's rows existed. Use their values
5019
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5020
+					if (! $field_obj->is_db_only_field()) {
5021
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5022
+							$cols_n_values, $field_obj->get_qualified_column(),
5023
+							$field_obj->get_table_column()
5024
+						);
5025
+					}
5026
+				}
5027
+			}
5028
+		}
5029
+		return $this_model_fields_n_values;
5030
+	}
5031
+
5032
+
5033
+
5034
+	/**
5035
+	 * @param $cols_n_values
5036
+	 * @param $qualified_column
5037
+	 * @param $regular_column
5038
+	 * @return null
5039
+	 */
5040
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5041
+	{
5042
+		$value = null;
5043
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5044
+		//does the field on the model relate to this column retrieved from the db?
5045
+		//or is it a db-only field? (not relating to the model)
5046
+		if (isset($cols_n_values[$qualified_column])) {
5047
+			$value = $cols_n_values[$qualified_column];
5048
+		} elseif (isset($cols_n_values[$regular_column])) {
5049
+			$value = $cols_n_values[$regular_column];
5050
+		}
5051
+		return $value;
5052
+	}
5053
+
5054
+
5055
+
5056
+	/**
5057
+	 * refresh_entity_map_from_db
5058
+	 * Makes sure the model object in the entity map at $id assumes the values
5059
+	 * of the database (opposite of EE_base_Class::save())
5060
+	 *
5061
+	 * @param int|string $id
5062
+	 * @return EE_Base_Class
5063
+	 * @throws \EE_Error
5064
+	 */
5065
+	public function refresh_entity_map_from_db($id)
5066
+	{
5067
+		$obj_in_map = $this->get_from_entity_map($id);
5068
+		if ($obj_in_map) {
5069
+			$wpdb_results = $this->_get_all_wpdb_results(
5070
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5071
+			);
5072
+			if ($wpdb_results && is_array($wpdb_results)) {
5073
+				$one_row = reset($wpdb_results);
5074
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5075
+					$obj_in_map->set_from_db($field_name, $db_value);
5076
+				}
5077
+				//clear the cache of related model objects
5078
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5079
+					$obj_in_map->clear_cache($relation_name, null, true);
5080
+				}
5081
+			}
5082
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5083
+			return $obj_in_map;
5084
+		} else {
5085
+			return $this->get_one_by_ID($id);
5086
+		}
5087
+	}
5088
+
5089
+
5090
+
5091
+	/**
5092
+	 * refresh_entity_map_with
5093
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5094
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5095
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5096
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5097
+	 *
5098
+	 * @param int|string    $id
5099
+	 * @param EE_Base_Class $replacing_model_obj
5100
+	 * @return \EE_Base_Class
5101
+	 * @throws \EE_Error
5102
+	 */
5103
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5104
+	{
5105
+		$obj_in_map = $this->get_from_entity_map($id);
5106
+		if ($obj_in_map) {
5107
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5108
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5109
+					$obj_in_map->set($field_name, $value);
5110
+				}
5111
+				//make the model object in the entity map's cache match the $replacing_model_obj
5112
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5113
+					$obj_in_map->clear_cache($relation_name, null, true);
5114
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5115
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5116
+					}
5117
+				}
5118
+			}
5119
+			return $obj_in_map;
5120
+		} else {
5121
+			$this->add_to_entity_map($replacing_model_obj);
5122
+			return $replacing_model_obj;
5123
+		}
5124
+	}
5125
+
5126
+
5127
+
5128
+	/**
5129
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5130
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5131
+	 * require_once($this->_getClassName().".class.php");
5132
+	 *
5133
+	 * @return string
5134
+	 */
5135
+	private function _get_class_name()
5136
+	{
5137
+		return "EE_" . $this->get_this_model_name();
5138
+	}
5139
+
5140
+
5141
+
5142
+	/**
5143
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5144
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5145
+	 * it would be 'Events'.
5146
+	 *
5147
+	 * @param int $quantity
5148
+	 * @return string
5149
+	 */
5150
+	public function item_name($quantity = 1)
5151
+	{
5152
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5153
+	}
5154
+
5155
+
5156
+
5157
+	/**
5158
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5159
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5160
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5161
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5162
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5163
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5164
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5165
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5166
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5167
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5168
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5169
+	 *        return $previousReturnValue.$returnString;
5170
+	 * }
5171
+	 * require('EEM_Answer.model.php');
5172
+	 * $answer=EEM_Answer::instance();
5173
+	 * echo $answer->my_callback('monkeys',100);
5174
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5175
+	 *
5176
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5177
+	 * @param array  $args       array of original arguments passed to the function
5178
+	 * @throws EE_Error
5179
+	 * @return mixed whatever the plugin which calls add_filter decides
5180
+	 */
5181
+	public function __call($methodName, $args)
5182
+	{
5183
+		$className = get_class($this);
5184
+		$tagName = "FHEE__{$className}__{$methodName}";
5185
+		if (! has_filter($tagName)) {
5186
+			throw new EE_Error(
5187
+				sprintf(
5188
+					__('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 );',
5189
+						'event_espresso'),
5190
+					$methodName,
5191
+					$className,
5192
+					$tagName,
5193
+					'<br />'
5194
+				)
5195
+			);
5196
+		}
5197
+		return apply_filters($tagName, null, $this, $args);
5198
+	}
5199
+
5200
+
5201
+
5202
+	/**
5203
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5204
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5205
+	 *
5206
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5207
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5208
+	 *                                                       the object's class name
5209
+	 *                                                       or object's ID
5210
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5211
+	 *                                                       exists in the database. If it does not, we add it
5212
+	 * @throws EE_Error
5213
+	 * @return EE_Base_Class
5214
+	 */
5215
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5216
+	{
5217
+		$className = $this->_get_class_name();
5218
+		if ($base_class_obj_or_id instanceof $className) {
5219
+			$model_object = $base_class_obj_or_id;
5220
+		} else {
5221
+			$primary_key_field = $this->get_primary_key_field();
5222
+			if (
5223
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5224
+				&& (
5225
+					is_int($base_class_obj_or_id)
5226
+					|| is_string($base_class_obj_or_id)
5227
+				)
5228
+			) {
5229
+				// assume it's an ID.
5230
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5231
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5232
+			} else if (
5233
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5234
+				&& is_string($base_class_obj_or_id)
5235
+			) {
5236
+				// assume its a string representation of the object
5237
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5238
+			} else {
5239
+				throw new EE_Error(
5240
+					sprintf(
5241
+						__(
5242
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5243
+							'event_espresso'
5244
+						),
5245
+						$base_class_obj_or_id,
5246
+						$this->_get_class_name(),
5247
+						print_r($base_class_obj_or_id, true)
5248
+					)
5249
+				);
5250
+			}
5251
+		}
5252
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5253
+			$model_object->save();
5254
+		}
5255
+		return $model_object;
5256
+	}
5257
+
5258
+
5259
+
5260
+	/**
5261
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5262
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5263
+	 * returns it ID.
5264
+	 *
5265
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5266
+	 * @return int|string depending on the type of this model object's ID
5267
+	 * @throws EE_Error
5268
+	 */
5269
+	public function ensure_is_ID($base_class_obj_or_id)
5270
+	{
5271
+		$className = $this->_get_class_name();
5272
+		if ($base_class_obj_or_id instanceof $className) {
5273
+			/** @var $base_class_obj_or_id EE_Base_Class */
5274
+			$id = $base_class_obj_or_id->ID();
5275
+		} elseif (is_int($base_class_obj_or_id)) {
5276
+			//assume it's an ID
5277
+			$id = $base_class_obj_or_id;
5278
+		} elseif (is_string($base_class_obj_or_id)) {
5279
+			//assume its a string representation of the object
5280
+			$id = $base_class_obj_or_id;
5281
+		} else {
5282
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5283
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5284
+				print_r($base_class_obj_or_id, true)));
5285
+		}
5286
+		return $id;
5287
+	}
5288
+
5289
+
5290
+
5291
+	/**
5292
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5293
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5294
+	 * been sanitized and converted into the appropriate domain.
5295
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5296
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5297
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5298
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5299
+	 * $EVT = EEM_Event::instance(); $old_setting =
5300
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5301
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5302
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5303
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5304
+	 *
5305
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5306
+	 * @return void
5307
+	 */
5308
+	public function assume_values_already_prepared_by_model_object(
5309
+		$values_already_prepared = self::not_prepared_by_model_object
5310
+	) {
5311
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5312
+	}
5313
+
5314
+
5315
+
5316
+	/**
5317
+	 * Read comments for assume_values_already_prepared_by_model_object()
5318
+	 *
5319
+	 * @return int
5320
+	 */
5321
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5322
+	{
5323
+		return $this->_values_already_prepared_by_model_object;
5324
+	}
5325
+
5326
+
5327
+
5328
+	/**
5329
+	 * Gets all the indexes on this model
5330
+	 *
5331
+	 * @return EE_Index[]
5332
+	 */
5333
+	public function indexes()
5334
+	{
5335
+		return $this->_indexes;
5336
+	}
5337
+
5338
+
5339
+
5340
+	/**
5341
+	 * Gets all the Unique Indexes on this model
5342
+	 *
5343
+	 * @return EE_Unique_Index[]
5344
+	 */
5345
+	public function unique_indexes()
5346
+	{
5347
+		$unique_indexes = array();
5348
+		foreach ($this->_indexes as $name => $index) {
5349
+			if ($index instanceof EE_Unique_Index) {
5350
+				$unique_indexes [$name] = $index;
5351
+			}
5352
+		}
5353
+		return $unique_indexes;
5354
+	}
5355
+
5356
+
5357
+
5358
+	/**
5359
+	 * Gets all the fields which, when combined, make the primary key.
5360
+	 * This is usually just an array with 1 element (the primary key), but in cases
5361
+	 * where there is no primary key, it's a combination of fields as defined
5362
+	 * on a primary index
5363
+	 *
5364
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5365
+	 * @throws \EE_Error
5366
+	 */
5367
+	public function get_combined_primary_key_fields()
5368
+	{
5369
+		foreach ($this->indexes() as $index) {
5370
+			if ($index instanceof EE_Primary_Key_Index) {
5371
+				return $index->fields();
5372
+			}
5373
+		}
5374
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5375
+	}
5376
+
5377
+
5378
+
5379
+	/**
5380
+	 * Used to build a primary key string (when the model has no primary key),
5381
+	 * which can be used a unique string to identify this model object.
5382
+	 *
5383
+	 * @param array $cols_n_values keys are field names, values are their values
5384
+	 * @return string
5385
+	 * @throws \EE_Error
5386
+	 */
5387
+	public function get_index_primary_key_string($cols_n_values)
5388
+	{
5389
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5390
+			$this->get_combined_primary_key_fields());
5391
+		return http_build_query($cols_n_values_for_primary_key_index);
5392
+	}
5393
+
5394
+
5395
+
5396
+	/**
5397
+	 * Gets the field values from the primary key string
5398
+	 *
5399
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5400
+	 * @param string $index_primary_key_string
5401
+	 * @return null|array
5402
+	 * @throws \EE_Error
5403
+	 */
5404
+	public function parse_index_primary_key_string($index_primary_key_string)
5405
+	{
5406
+		$key_fields = $this->get_combined_primary_key_fields();
5407
+		//check all of them are in the $id
5408
+		$key_vals_in_combined_pk = array();
5409
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5410
+		foreach ($key_fields as $key_field_name => $field_obj) {
5411
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5412
+				return null;
5413
+			}
5414
+		}
5415
+		return $key_vals_in_combined_pk;
5416
+	}
5417
+
5418
+
5419
+
5420
+	/**
5421
+	 * verifies that an array of key-value pairs for model fields has a key
5422
+	 * for each field comprising the primary key index
5423
+	 *
5424
+	 * @param array $key_vals
5425
+	 * @return boolean
5426
+	 * @throws \EE_Error
5427
+	 */
5428
+	public function has_all_combined_primary_key_fields($key_vals)
5429
+	{
5430
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5431
+		foreach ($keys_it_should_have as $key) {
5432
+			if (! isset($key_vals[$key])) {
5433
+				return false;
5434
+			}
5435
+		}
5436
+		return true;
5437
+	}
5438
+
5439
+
5440
+
5441
+	/**
5442
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5443
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5444
+	 *
5445
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5446
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5447
+	 * @throws EE_Error
5448
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5449
+	 *                                                              indexed)
5450
+	 */
5451
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5452
+	{
5453
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5454
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5455
+		} elseif (is_array($model_object_or_attributes_array)) {
5456
+			$attributes_array = $model_object_or_attributes_array;
5457
+		} else {
5458
+			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",
5459
+				"event_espresso"), $model_object_or_attributes_array));
5460
+		}
5461
+		//even copies obviously won't have the same ID, so remove the primary key
5462
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5463
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5464
+			unset($attributes_array[$this->primary_key_name()]);
5465
+		}
5466
+		if (isset($query_params[0])) {
5467
+			$query_params[0] = array_merge($attributes_array, $query_params);
5468
+		} else {
5469
+			$query_params[0] = $attributes_array;
5470
+		}
5471
+		return $this->get_all($query_params);
5472
+	}
5473
+
5474
+
5475
+
5476
+	/**
5477
+	 * Gets the first copy we find. See get_all_copies for more details
5478
+	 *
5479
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5480
+	 * @param array $query_params
5481
+	 * @return EE_Base_Class
5482
+	 * @throws \EE_Error
5483
+	 */
5484
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5485
+	{
5486
+		if (! is_array($query_params)) {
5487
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5488
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5489
+					gettype($query_params)), '4.6.0');
5490
+			$query_params = array();
5491
+		}
5492
+		$query_params['limit'] = 1;
5493
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5494
+		if (is_array($copies)) {
5495
+			return array_shift($copies);
5496
+		} else {
5497
+			return null;
5498
+		}
5499
+	}
5500
+
5501
+
5502
+
5503
+	/**
5504
+	 * Updates the item with the specified id. Ignores default query parameters because
5505
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5506
+	 *
5507
+	 * @param array      $fields_n_values keys are field names, values are their new values
5508
+	 * @param int|string $id              the value of the primary key to update
5509
+	 * @return int number of rows updated
5510
+	 * @throws \EE_Error
5511
+	 */
5512
+	public function update_by_ID($fields_n_values, $id)
5513
+	{
5514
+		$query_params = array(
5515
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5516
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5517
+		);
5518
+		return $this->update($fields_n_values, $query_params);
5519
+	}
5520
+
5521
+
5522
+
5523
+	/**
5524
+	 * Changes an operator which was supplied to the models into one usable in SQL
5525
+	 *
5526
+	 * @param string $operator_supplied
5527
+	 * @return string an operator which can be used in SQL
5528
+	 * @throws EE_Error
5529
+	 */
5530
+	private function _prepare_operator_for_sql($operator_supplied)
5531
+	{
5532
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5533
+			: null;
5534
+		if ($sql_operator) {
5535
+			return $sql_operator;
5536
+		} else {
5537
+			throw new EE_Error(sprintf(__("The operator '%s' is not in the list of valid operators: %s",
5538
+				"event_espresso"), $operator_supplied, implode(",", array_keys($this->_valid_operators))));
5539
+		}
5540
+	}
5541
+
5542
+
5543
+
5544
+	/**
5545
+	 * Gets the valid operators
5546
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5547
+	 */
5548
+	public function valid_operators(){
5549
+		return $this->_valid_operators;
5550
+	}
5551
+
5552
+
5553
+
5554
+	/**
5555
+	 * Gets the between-style operators (take 2 arguments).
5556
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5557
+	 */
5558
+	public function valid_between_style_operators()
5559
+	{
5560
+		return array_intersect(
5561
+			$this->valid_operators(),
5562
+			$this->_between_style_operators
5563
+		);
5564
+	}
5565
+
5566
+	/**
5567
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5568
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5569
+	 */
5570
+	public function valid_like_style_operators()
5571
+	{
5572
+		return array_intersect(
5573
+			$this->valid_operators(),
5574
+			$this->_like_style_operators
5575
+		);
5576
+	}
5577
+
5578
+	/**
5579
+	 * Gets the "in"-style operators
5580
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5581
+	 */
5582
+	public function valid_in_style_operators()
5583
+	{
5584
+		return array_intersect(
5585
+			$this->valid_operators(),
5586
+			$this->_in_style_operators
5587
+		);
5588
+	}
5589
+
5590
+	/**
5591
+	 * Gets the "null"-style operators (accept no arguments)
5592
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5593
+	 */
5594
+	public function valid_null_style_operators()
5595
+	{
5596
+		return array_intersect(
5597
+			$this->valid_operators(),
5598
+			$this->_null_style_operators
5599
+		);
5600
+	}
5601
+
5602
+	/**
5603
+	 * Gets an array where keys are the primary keys and values are their 'names'
5604
+	 * (as determined by the model object's name() function, which is often overridden)
5605
+	 *
5606
+	 * @param array $query_params like get_all's
5607
+	 * @return string[]
5608
+	 * @throws \EE_Error
5609
+	 */
5610
+	public function get_all_names($query_params = array())
5611
+	{
5612
+		$objs = $this->get_all($query_params);
5613
+		$names = array();
5614
+		foreach ($objs as $obj) {
5615
+			$names[$obj->ID()] = $obj->name();
5616
+		}
5617
+		return $names;
5618
+	}
5619
+
5620
+
5621
+
5622
+	/**
5623
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5624
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5625
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5626
+	 * array_keys() on $model_objects.
5627
+	 *
5628
+	 * @param \EE_Base_Class[] $model_objects
5629
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5630
+	 *                                               in the returned array
5631
+	 * @return array
5632
+	 * @throws \EE_Error
5633
+	 */
5634
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5635
+	{
5636
+		if (! $this->has_primary_key_field()) {
5637
+			if (WP_DEBUG) {
5638
+				EE_Error::add_error(
5639
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5640
+					__FILE__,
5641
+					__FUNCTION__,
5642
+					__LINE__
5643
+				);
5644
+			}
5645
+		}
5646
+		$IDs = array();
5647
+		foreach ($model_objects as $model_object) {
5648
+			$id = $model_object->ID();
5649
+			if (! $id) {
5650
+				if ($filter_out_empty_ids) {
5651
+					continue;
5652
+				}
5653
+				if (WP_DEBUG) {
5654
+					EE_Error::add_error(
5655
+						__(
5656
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5657
+							'event_espresso'
5658
+						),
5659
+						__FILE__,
5660
+						__FUNCTION__,
5661
+						__LINE__
5662
+					);
5663
+				}
5664
+			}
5665
+			$IDs[] = $id;
5666
+		}
5667
+		return $IDs;
5668
+	}
5669
+
5670
+
5671
+
5672
+	/**
5673
+	 * Returns the string used in capabilities relating to this model. If there
5674
+	 * are no capabilities that relate to this model returns false
5675
+	 *
5676
+	 * @return string|false
5677
+	 */
5678
+	public function cap_slug()
5679
+	{
5680
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5681
+	}
5682
+
5683
+
5684
+
5685
+	/**
5686
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5687
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5688
+	 * only returns the cap restrictions array in that context (ie, the array
5689
+	 * at that key)
5690
+	 *
5691
+	 * @param string $context
5692
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5693
+	 * @throws \EE_Error
5694
+	 */
5695
+	public function cap_restrictions($context = EEM_Base::caps_read)
5696
+	{
5697
+		EEM_Base::verify_is_valid_cap_context($context);
5698
+		//check if we ought to run the restriction generator first
5699
+		if (
5700
+			isset($this->_cap_restriction_generators[$context])
5701
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5702
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5703
+		) {
5704
+			$this->_cap_restrictions[$context] = array_merge(
5705
+				$this->_cap_restrictions[$context],
5706
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5707
+			);
5708
+		}
5709
+		//and make sure we've finalized the construction of each restriction
5710
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5711
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5712
+				$where_conditions_obj->_finalize_construct($this);
5713
+			}
5714
+		}
5715
+		return $this->_cap_restrictions[$context];
5716
+	}
5717
+
5718
+
5719
+
5720
+	/**
5721
+	 * Indicating whether or not this model thinks its a wp core model
5722
+	 *
5723
+	 * @return boolean
5724
+	 */
5725
+	public function is_wp_core_model()
5726
+	{
5727
+		return $this->_wp_core_model;
5728
+	}
5729
+
5730
+
5731
+
5732
+	/**
5733
+	 * Gets all the caps that are missing which impose a restriction on
5734
+	 * queries made in this context
5735
+	 *
5736
+	 * @param string $context one of EEM_Base::caps_ constants
5737
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5738
+	 * @throws \EE_Error
5739
+	 */
5740
+	public function caps_missing($context = EEM_Base::caps_read)
5741
+	{
5742
+		$missing_caps = array();
5743
+		$cap_restrictions = $this->cap_restrictions($context);
5744
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5745
+			if (! EE_Capabilities::instance()
5746
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5747
+			) {
5748
+				$missing_caps[$cap] = $restriction_if_no_cap;
5749
+			}
5750
+		}
5751
+		return $missing_caps;
5752
+	}
5753
+
5754
+
5755
+
5756
+	/**
5757
+	 * Gets the mapping from capability contexts to action strings used in capability names
5758
+	 *
5759
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5760
+	 * one of 'read', 'edit', or 'delete'
5761
+	 */
5762
+	public function cap_contexts_to_cap_action_map()
5763
+	{
5764
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5765
+			$this);
5766
+	}
5767
+
5768
+
5769
+
5770
+	/**
5771
+	 * Gets the action string for the specified capability context
5772
+	 *
5773
+	 * @param string $context
5774
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5775
+	 * @throws \EE_Error
5776
+	 */
5777
+	public function cap_action_for_context($context)
5778
+	{
5779
+		$mapping = $this->cap_contexts_to_cap_action_map();
5780
+		if (isset($mapping[$context])) {
5781
+			return $mapping[$context];
5782
+		}
5783
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5784
+			return $action;
5785
+		}
5786
+		throw new EE_Error(
5787
+			sprintf(
5788
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5789
+				$context,
5790
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5791
+			)
5792
+		);
5793
+	}
5794
+
5795
+
5796
+
5797
+	/**
5798
+	 * Returns all the capability contexts which are valid when querying models
5799
+	 *
5800
+	 * @return array
5801
+	 */
5802
+	public static function valid_cap_contexts()
5803
+	{
5804
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5805
+			self::caps_read,
5806
+			self::caps_read_admin,
5807
+			self::caps_edit,
5808
+			self::caps_delete,
5809
+		));
5810
+	}
5811
+
5812
+
5813
+
5814
+	/**
5815
+	 * Returns all valid options for 'default_where_conditions'
5816
+	 *
5817
+	 * @return array
5818
+	 */
5819
+	public static function valid_default_where_conditions()
5820
+	{
5821
+		return array(
5822
+			EEM_Base::default_where_conditions_all,
5823
+			EEM_Base::default_where_conditions_this_only,
5824
+			EEM_Base::default_where_conditions_others_only,
5825
+			EEM_Base::default_where_conditions_minimum_all,
5826
+			EEM_Base::default_where_conditions_minimum_others,
5827
+			EEM_Base::default_where_conditions_none
5828
+		);
5829
+	}
5830
+
5831
+	// public static function default_where_conditions_full
5832
+	/**
5833
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5834
+	 *
5835
+	 * @param string $context
5836
+	 * @return bool
5837
+	 * @throws \EE_Error
5838
+	 */
5839
+	static public function verify_is_valid_cap_context($context)
5840
+	{
5841
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5842
+		if (in_array($context, $valid_cap_contexts)) {
5843
+			return true;
5844
+		} else {
5845
+			throw new EE_Error(
5846
+				sprintf(
5847
+					__('Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5848
+						'event_espresso'),
5849
+					$context,
5850
+					'EEM_Base',
5851
+					implode(',', $valid_cap_contexts)
5852
+				)
5853
+			);
5854
+		}
5855
+	}
5856
+
5857
+
5858
+
5859
+	/**
5860
+	 * Clears all the models field caches. This is only useful when a sub-class
5861
+	 * might have added a field or something and these caches might be invalidated
5862
+	 */
5863
+	protected function _invalidate_field_caches()
5864
+	{
5865
+		$this->_cache_foreign_key_to_fields = array();
5866
+		$this->_cached_fields = null;
5867
+		$this->_cached_fields_non_db_only = null;
5868
+	}
5869
+
5870
+
5871
+
5872
+	/**
5873
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
5874
+	 * (eg "and", "or", "not").
5875
+	 *
5876
+	 * @return array
5877
+	 */
5878
+	public function logic_query_param_keys()
5879
+	{
5880
+		return $this->_logic_query_param_keys;
5881
+	}
5882
+
5883
+
5884
+
5885
+	/**
5886
+	 * Determines whether or not the where query param array key is for a logic query param.
5887
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' shoudl all return true, whereas
5888
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
5889
+	 *
5890
+	 * @param $query_param_key
5891
+	 * @return bool
5892
+	 */
5893
+	public function is_logic_query_param_key($query_param_key)
5894
+	{
5895
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5896
+			if ($query_param_key === $logic_query_param_key
5897
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
5898
+			) {
5899
+				return true;
5900
+			}
5901
+		}
5902
+		return false;
5903
+	}
5904 5904
 
5905 5905
 
5906 5906
 
Please login to merge, or discard this patch.
Spacing   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -505,8 +505,8 @@  discard block
 block discarded – undo
505 505
     protected function __construct($timezone = null)
506 506
     {
507 507
         // check that the model has not been loaded too soon
508
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
509
-            throw new EE_Error (
508
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
509
+            throw new EE_Error(
510 510
                 sprintf(
511 511
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
512 512
                         'event_espresso'),
@@ -526,7 +526,7 @@  discard block
 block discarded – undo
526 526
          *
527 527
          * @var EE_Table_Base[] $_tables
528 528
          */
529
-        $this->_tables = apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
529
+        $this->_tables = apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
530 530
         foreach ($this->_tables as $table_alias => $table_obj) {
531 531
             /** @var $table_obj EE_Table_Base */
532 532
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -541,10 +541,10 @@  discard block
 block discarded – undo
541 541
          *
542 542
          * @param EE_Model_Field_Base[] $_fields
543 543
          */
544
-        $this->_fields = apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
544
+        $this->_fields = apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
545 545
         $this->_invalidate_field_caches();
546 546
         foreach ($this->_fields as $table_alias => $fields_for_table) {
547
-            if (! array_key_exists($table_alias, $this->_tables)) {
547
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
548 548
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
549 549
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
550 550
             }
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
          *
573 573
          * @param EE_Model_Relation_Base[] $_model_relations
574 574
          */
575
-        $this->_model_relations = apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
575
+        $this->_model_relations = apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
576 576
             $this->_model_relations);
577 577
         foreach ($this->_model_relations as $model_name => $relation_obj) {
578 578
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -584,12 +584,12 @@  discard block
 block discarded – undo
584 584
         }
585 585
         $this->set_timezone($timezone);
586 586
         //finalize default where condition strategy, or set default
587
-        if (! $this->_default_where_conditions_strategy) {
587
+        if ( ! $this->_default_where_conditions_strategy) {
588 588
             //nothing was set during child constructor, so set default
589 589
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
590 590
         }
591 591
         $this->_default_where_conditions_strategy->_finalize_construct($this);
592
-        if (! $this->_minimum_where_conditions_strategy) {
592
+        if ( ! $this->_minimum_where_conditions_strategy) {
593 593
             //nothing was set during child constructor, so set default
594 594
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
595 595
         }
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
         //initialize the standard cap restriction generators if none were specified by the child constructor
603 603
         if ($this->_cap_restriction_generators !== false) {
604 604
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
605
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
605
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
606 606
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
607 607
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
608 608
                         new EE_Restriction_Generator_Protected(),
@@ -615,10 +615,10 @@  discard block
 block discarded – undo
615 615
         //if there are cap restriction generators, use them to make the default cap restrictions
616 616
         if ($this->_cap_restriction_generators !== false) {
617 617
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
618
-                if (! $generator_object) {
618
+                if ( ! $generator_object) {
619 619
                     continue;
620 620
                 }
621
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
621
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
622 622
                     throw new EE_Error(
623 623
                         sprintf(
624 624
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -629,12 +629,12 @@  discard block
 block discarded – undo
629 629
                     );
630 630
                 }
631 631
                 $action = $this->cap_action_for_context($context);
632
-                if (! $generator_object->construction_finalized()) {
632
+                if ( ! $generator_object->construction_finalized()) {
633 633
                     $generator_object->_construct_finalize($this, $action);
634 634
                 }
635 635
             }
636 636
         }
637
-        do_action('AHEE__' . get_class($this) . '__construct__end');
637
+        do_action('AHEE__'.get_class($this).'__construct__end');
638 638
     }
639 639
 
640 640
 
@@ -647,7 +647,7 @@  discard block
 block discarded – undo
647 647
      */
648 648
     public static function set_model_query_blog_id($blog_id = 0)
649 649
     {
650
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
650
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
651 651
     }
652 652
 
653 653
 
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
     public static function instance($timezone = null)
678 678
     {
679 679
         // check if instance of Espresso_model already exists
680
-        if (! static::$_instance instanceof static) {
680
+        if ( ! static::$_instance instanceof static) {
681 681
             // instantiate Espresso_model
682 682
             static::$_instance = new static($timezone);
683 683
         }
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
             foreach ($r->getDefaultProperties() as $property => $value) {
709 709
                 //don't set instance to null like it was originally,
710 710
                 //but it's static anyways, and we're ignoring static properties (for now at least)
711
-                if (! isset($static_properties[$property])) {
711
+                if ( ! isset($static_properties[$property])) {
712 712
                     static::$_instance->{$property} = $value;
713 713
                 }
714 714
             }
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
      */
732 732
     public function status_array($translated = false)
733 733
     {
734
-        if (! array_key_exists('Status', $this->_model_relations)) {
734
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
735 735
             return array();
736 736
         }
737 737
         $model_name = $this->get_this_model_name();
@@ -934,17 +934,17 @@  discard block
 block discarded – undo
934 934
     public function wp_user_field_name()
935 935
     {
936 936
         try {
937
-            if (! empty($this->_model_chain_to_wp_user)) {
937
+            if ( ! empty($this->_model_chain_to_wp_user)) {
938 938
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
939 939
                 $last_model_name = end($models_to_follow_to_wp_users);
940 940
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
941
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
941
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
942 942
             } else {
943 943
                 $model_with_fk_to_wp_users = $this;
944 944
                 $model_chain_to_wp_user = '';
945 945
             }
946 946
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
947
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
947
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
948 948
         } catch (EE_Error $e) {
949 949
             return false;
950 950
         }
@@ -1016,12 +1016,12 @@  discard block
 block discarded – undo
1016 1016
         // remember the custom selections, if any, and type cast as array
1017 1017
         // (unless $columns_to_select is an object, then just set as an empty array)
1018 1018
         // Note: (array) 'some string' === array( 'some string' )
1019
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1019
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1020 1020
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1021 1021
         $select_expressions = $columns_to_select !== null
1022 1022
             ? $this->_construct_select_from_input($columns_to_select)
1023 1023
             : $this->_construct_default_select_sql($model_query_info);
1024
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1024
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1025 1025
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1026 1026
     }
1027 1027
 
@@ -1066,7 +1066,7 @@  discard block
 block discarded – undo
1066 1066
         if (is_array($columns_to_select)) {
1067 1067
             $select_sql_array = array();
1068 1068
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1069
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1070 1070
                     throw new EE_Error(
1071 1071
                         sprintf(
1072 1072
                             __(
@@ -1078,7 +1078,7 @@  discard block
 block discarded – undo
1078 1078
                         )
1079 1079
                     );
1080 1080
                 }
1081
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1081
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types)) {
1082 1082
                     throw new EE_Error(
1083 1083
                         sprintf(
1084 1084
                             __(
@@ -1150,7 +1150,7 @@  discard block
 block discarded – undo
1150 1150
      */
1151 1151
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1152 1152
     {
1153
-        if (! isset($query_params[0])) {
1153
+        if ( ! isset($query_params[0])) {
1154 1154
             $query_params[0] = array();
1155 1155
         }
1156 1156
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1175,7 +1175,7 @@  discard block
 block discarded – undo
1175 1175
      */
1176 1176
     public function get_one($query_params = array())
1177 1177
     {
1178
-        if (! is_array($query_params)) {
1178
+        if ( ! is_array($query_params)) {
1179 1179
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1180 1180
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1181 1181
                     gettype($query_params)), '4.6.0');
@@ -1343,7 +1343,7 @@  discard block
 block discarded – undo
1343 1343
                 return array();
1344 1344
             }
1345 1345
         }
1346
-        if (! is_array($query_params)) {
1346
+        if ( ! is_array($query_params)) {
1347 1347
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1348 1348
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1349 1349
                     gettype($query_params)), '4.6.0');
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1354 1354
         $query_params['limit'] = $limit;
1355 1355
         //set direction
1356
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1356
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1357 1357
         $query_params['order_by'] = $operand === '>'
1358 1358
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1359 1359
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1432,7 +1432,7 @@  discard block
 block discarded – undo
1432 1432
     {
1433 1433
         $field_settings = $this->field_settings_for($field_name);
1434 1434
         //if not a valid EE_Datetime_Field then throw error
1435
-        if (! $field_settings instanceof EE_Datetime_Field) {
1435
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1436 1436
             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.',
1437 1437
                 'event_espresso'), $field_name));
1438 1438
         }
@@ -1509,7 +1509,7 @@  discard block
 block discarded – undo
1509 1509
         //load EEH_DTT_Helper
1510 1510
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1511 1511
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1512
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1512
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1513 1513
     }
1514 1514
 
1515 1515
 
@@ -1577,7 +1577,7 @@  discard block
 block discarded – undo
1577 1577
      */
1578 1578
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1579 1579
     {
1580
-        if (! is_array($query_params)) {
1580
+        if ( ! is_array($query_params)) {
1581 1581
             EE_Error::doing_it_wrong('EEM_Base::update',
1582 1582
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1583 1583
                     gettype($query_params)), '4.6.0');
@@ -1599,7 +1599,7 @@  discard block
 block discarded – undo
1599 1599
          * @param EEM_Base $model           the model being queried
1600 1600
          * @param array    $query_params    see EEM_Base::get_all()
1601 1601
          */
1602
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1602
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1603 1603
             $query_params);
1604 1604
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1605 1605
         //to do that, for each table, verify that it's PK isn't null.
@@ -1613,7 +1613,7 @@  discard block
 block discarded – undo
1613 1613
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1614 1614
         foreach ($wpdb_select_results as $wpdb_result) {
1615 1615
             // type cast stdClass as array
1616
-            $wpdb_result = (array)$wpdb_result;
1616
+            $wpdb_result = (array) $wpdb_result;
1617 1617
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1618 1618
             if ($this->has_primary_key_field()) {
1619 1619
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1630,13 +1630,13 @@  discard block
 block discarded – undo
1630 1630
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1631 1631
                     //if there is no private key for this table on the results, it means there's no entry
1632 1632
                     //in this table, right? so insert a row in the current table, using any fields available
1633
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1633
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1634 1634
                            && $wpdb_result[$this_table_pk_column])
1635 1635
                     ) {
1636 1636
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1637 1637
                             $main_table_pk_value);
1638 1638
                         //if we died here, report the error
1639
-                        if (! $success) {
1639
+                        if ( ! $success) {
1640 1640
                             return false;
1641 1641
                         }
1642 1642
                     }
@@ -1667,7 +1667,7 @@  discard block
 block discarded – undo
1667 1667
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1668 1668
                 }
1669 1669
             }
1670
-            if (! $model_objs_affected_ids) {
1670
+            if ( ! $model_objs_affected_ids) {
1671 1671
                 //wait wait wait- if nothing was affected let's stop here
1672 1672
                 return 0;
1673 1673
             }
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
                . $model_query_info->get_full_join_sql()
1695 1695
                . " SET "
1696 1696
                . $this->_construct_update_sql($fields_n_values)
1697
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1697
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1698 1698
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1699 1699
         /**
1700 1700
          * Action called after a model update call has been made.
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
          * @param int      $rows_affected
1706 1706
          */
1707 1707
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1708
-        return $rows_affected;//how many supposedly got updated
1708
+        return $rows_affected; //how many supposedly got updated
1709 1709
     }
1710 1710
 
1711 1711
 
@@ -1733,7 +1733,7 @@  discard block
 block discarded – undo
1733 1733
         }
1734 1734
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1735 1735
         $select_expressions = $field->get_qualified_column();
1736
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1736
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1737 1737
         return $this->_do_wpdb_query('get_col', array($SQL));
1738 1738
     }
1739 1739
 
@@ -1751,7 +1751,7 @@  discard block
 block discarded – undo
1751 1751
     {
1752 1752
         $query_params['limit'] = 1;
1753 1753
         $col = $this->get_col($query_params, $field_to_select);
1754
-        if (! empty($col)) {
1754
+        if ( ! empty($col)) {
1755 1755
             return reset($col);
1756 1756
         } else {
1757 1757
             return null;
@@ -1783,7 +1783,7 @@  discard block
 block discarded – undo
1783 1783
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1784 1784
             $value_sql = $prepared_value === null ? 'NULL'
1785 1785
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1786
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1786
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1787 1787
         }
1788 1788
         return implode(",", $cols_n_values);
1789 1789
     }
@@ -1919,7 +1919,7 @@  discard block
 block discarded – undo
1919 1919
          * @param int      $rows_deleted
1920 1920
          */
1921 1921
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted);
1922
-        return $rows_deleted;//how many supposedly got deleted
1922
+        return $rows_deleted; //how many supposedly got deleted
1923 1923
     }
1924 1924
 
1925 1925
 
@@ -2004,7 +2004,7 @@  discard block
 block discarded – undo
2004 2004
              * @var EE_Primary_Key_Field_Base[] $other_tables_fk_fields EE_Foreign_Key_Field_Base[] keys are table aliases
2005 2005
              */
2006 2006
             $other_tables_fk_fields = array();
2007
-            foreach($other_tables as $other_table_alias => $other_table_obj){
2007
+            foreach ($other_tables as $other_table_alias => $other_table_obj) {
2008 2008
                 $other_tables_pk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_pk_column());
2009 2009
                 $other_tables_fk_fields[$other_table_alias] = $this->get_field_by_column($other_table_obj->get_fully_qualified_fk_column());
2010 2010
             }
@@ -2029,7 +2029,7 @@  discard block
 block discarded – undo
2029 2029
                     );
2030 2030
                 }
2031 2031
                 //other tables
2032
-                if (! empty($other_tables)) {
2032
+                if ( ! empty($other_tables)) {
2033 2033
                     foreach ($other_tables as $other_table_alias => $other_table_obj) {
2034 2034
                         $other_table_pk_field = $other_tables_pk_fields[$other_table_alias];
2035 2035
                         $other_table_fk_field = $other_tables_fk_fields[$other_table_alias];
@@ -2063,7 +2063,7 @@  discard block
 block discarded – undo
2063 2063
             foreach ($deletes as $column => $values) {
2064 2064
                 //make sure we have unique $values;
2065 2065
                 $values = array_unique($values);
2066
-                $query[] = $column . ' IN(' . implode(",", $values) . ')';
2066
+                $query[] = $column.' IN('.implode(",", $values).')';
2067 2067
             }
2068 2068
             return ! empty($query) ? implode(' AND ', $query) : '';
2069 2069
         }
@@ -2080,7 +2080,7 @@  discard block
 block discarded – undo
2080 2080
                                                            . $delete_object[$field_in_combined_primary_key->get_qualified_column()];
2081 2081
                     }
2082 2082
                 }
2083
-                $ways_to_identify_a_row[] = "(" . implode(" AND ", $combined_primary_key_row_values) . ")";
2083
+                $ways_to_identify_a_row[] = "(".implode(" AND ", $combined_primary_key_row_values).")";
2084 2084
             }
2085 2085
             return implode(" OR ", $ways_to_identify_a_row);
2086 2086
         } else {
@@ -2099,8 +2099,8 @@  discard block
 block discarded – undo
2099 2099
      */
2100 2100
     public function get_field_by_column($qualified_column_name)
2101 2101
     {
2102
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2103
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2102
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2103
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2104 2104
                return $field_obj;
2105 2105
            }
2106 2106
        }
@@ -2151,9 +2151,9 @@  discard block
 block discarded – undo
2151 2151
                 $column_to_count = '*';
2152 2152
             }
2153 2153
         }
2154
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2155
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2156
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2154
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2155
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2156
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2157 2157
     }
2158 2158
 
2159 2159
 
@@ -2175,13 +2175,13 @@  discard block
 block discarded – undo
2175 2175
             $field_obj = $this->get_primary_key_field();
2176 2176
         }
2177 2177
         $column_to_count = $field_obj->get_qualified_column();
2178
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2178
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2179 2179
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2180 2180
         $data_type = $field_obj->get_wpdb_data_type();
2181 2181
         if ($data_type === '%d' || $data_type === '%s') {
2182
-            return (float)$return_value;
2182
+            return (float) $return_value;
2183 2183
         } else {//must be %f
2184
-            return (float)$return_value;
2184
+            return (float) $return_value;
2185 2185
         }
2186 2186
     }
2187 2187
 
@@ -2202,13 +2202,13 @@  discard block
 block discarded – undo
2202 2202
         //if we're in maintenance mode level 2, DON'T run any queries
2203 2203
         //because level 2 indicates the database needs updating and
2204 2204
         //is probably out of sync with the code
2205
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2205
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2206 2206
             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.",
2207 2207
                 "event_espresso")));
2208 2208
         }
2209 2209
         /** @type WPDB $wpdb */
2210 2210
         global $wpdb;
2211
-        if (! method_exists($wpdb, $wpdb_method)) {
2211
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2212 2212
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2213 2213
                 'event_espresso'), $wpdb_method));
2214 2214
         }
@@ -2220,7 +2220,7 @@  discard block
 block discarded – undo
2220 2220
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2221 2221
         if (WP_DEBUG) {
2222 2222
             $wpdb->show_errors($old_show_errors_value);
2223
-            if (! empty($wpdb->last_error)) {
2223
+            if ( ! empty($wpdb->last_error)) {
2224 2224
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2225 2225
             } elseif ($result === false) {
2226 2226
                 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"',
@@ -2280,7 +2280,7 @@  discard block
 block discarded – undo
2280 2280
                     return $result;
2281 2281
                     break;
2282 2282
             }
2283
-            if (! empty($error_message)) {
2283
+            if ( ! empty($error_message)) {
2284 2284
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2285 2285
                 trigger_error($error_message);
2286 2286
             }
@@ -2356,11 +2356,11 @@  discard block
 block discarded – undo
2356 2356
      */
2357 2357
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2358 2358
     {
2359
-        return " FROM " . $model_query_info->get_full_join_sql() .
2360
-               $model_query_info->get_where_sql() .
2361
-               $model_query_info->get_group_by_sql() .
2362
-               $model_query_info->get_having_sql() .
2363
-               $model_query_info->get_order_by_sql() .
2359
+        return " FROM ".$model_query_info->get_full_join_sql().
2360
+               $model_query_info->get_where_sql().
2361
+               $model_query_info->get_group_by_sql().
2362
+               $model_query_info->get_having_sql().
2363
+               $model_query_info->get_order_by_sql().
2364 2364
                $model_query_info->get_limit_sql();
2365 2365
     }
2366 2366
 
@@ -2556,12 +2556,12 @@  discard block
 block discarded – undo
2556 2556
         $related_model = $this->get_related_model_obj($model_name);
2557 2557
         //we're just going to use the query params on the related model's normal get_all query,
2558 2558
         //except add a condition to say to match the current mod
2559
-        if (! isset($query_params['default_where_conditions'])) {
2559
+        if ( ! isset($query_params['default_where_conditions'])) {
2560 2560
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2561 2561
         }
2562 2562
         $this_model_name = $this->get_this_model_name();
2563 2563
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2564
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2564
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2565 2565
         return $related_model->count($query_params, $field_to_count, $distinct);
2566 2566
     }
2567 2567
 
@@ -2581,7 +2581,7 @@  discard block
 block discarded – undo
2581 2581
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2582 2582
     {
2583 2583
         $related_model = $this->get_related_model_obj($model_name);
2584
-        if (! is_array($query_params)) {
2584
+        if ( ! is_array($query_params)) {
2585 2585
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2586 2586
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2587 2587
                     gettype($query_params)), '4.6.0');
@@ -2589,12 +2589,12 @@  discard block
 block discarded – undo
2589 2589
         }
2590 2590
         //we're just going to use the query params on the related model's normal get_all query,
2591 2591
         //except add a condition to say to match the current mod
2592
-        if (! isset($query_params['default_where_conditions'])) {
2592
+        if ( ! isset($query_params['default_where_conditions'])) {
2593 2593
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2594 2594
         }
2595 2595
         $this_model_name = $this->get_this_model_name();
2596 2596
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2597
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2597
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2598 2598
         return $related_model->sum($query_params, $field_to_sum);
2599 2599
     }
2600 2600
 
@@ -2648,7 +2648,7 @@  discard block
 block discarded – undo
2648 2648
                 $field_with_model_name = $field;
2649 2649
             }
2650 2650
         }
2651
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2651
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2652 2652
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2653 2653
                 $this->get_this_model_name()));
2654 2654
         }
@@ -2681,7 +2681,7 @@  discard block
 block discarded – undo
2681 2681
          * @param array    $fields_n_values keys are the fields and values are their new values
2682 2682
          * @param EEM_Base $model           the model used
2683 2683
          */
2684
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2684
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2685 2685
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2686 2686
             $main_table = $this->_get_main_table();
2687 2687
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2789,7 +2789,7 @@  discard block
 block discarded – undo
2789 2789
         }
2790 2790
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2791 2791
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2792
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2792
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2793 2793
         }
2794 2794
         //if there is nothing to base this search on, then we shouldn't find anything
2795 2795
         if (empty($query_params)) {
@@ -2876,7 +2876,7 @@  discard block
 block discarded – undo
2876 2876
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2877 2877
             //so add the fk to the main table as a column
2878 2878
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2879
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2879
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2880 2880
         }
2881 2881
         //insert the new entry
2882 2882
         $result = $this->_do_wpdb_query('insert',
@@ -2915,7 +2915,7 @@  discard block
 block discarded – undo
2915 2915
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
2916 2916
     {
2917 2917
         //if this field doesn't allow nullable, don't allow it
2918
-        if (! $field_obj->is_nullable()
2918
+        if ( ! $field_obj->is_nullable()
2919 2919
             && (
2920 2920
                 ! isset($fields_n_values[$field_obj->get_name()]) || $fields_n_values[$field_obj->get_name()] === null)
2921 2921
         ) {
@@ -3078,7 +3078,7 @@  discard block
 block discarded – undo
3078 3078
                     $query_info_carrier,
3079 3079
                     'group_by'
3080 3080
                 );
3081
-            } elseif (! empty ($query_params['group_by'])) {
3081
+            } elseif ( ! empty ($query_params['group_by'])) {
3082 3082
                 $this->_extract_related_model_info_from_query_param(
3083 3083
                     $query_params['group_by'],
3084 3084
                     $query_info_carrier,
@@ -3100,7 +3100,7 @@  discard block
 block discarded – undo
3100 3100
                     $query_info_carrier,
3101 3101
                     'order_by'
3102 3102
                 );
3103
-            } elseif (! empty($query_params['order_by'])) {
3103
+            } elseif ( ! empty($query_params['order_by'])) {
3104 3104
                 $this->_extract_related_model_info_from_query_param(
3105 3105
                     $query_params['order_by'],
3106 3106
                     $query_info_carrier,
@@ -3135,8 +3135,8 @@  discard block
 block discarded – undo
3135 3135
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3136 3136
         $query_param_type
3137 3137
     ) {
3138
-        if (! empty($sub_query_params)) {
3139
-            $sub_query_params = (array)$sub_query_params;
3138
+        if ( ! empty($sub_query_params)) {
3139
+            $sub_query_params = (array) $sub_query_params;
3140 3140
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3141 3141
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3142 3142
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3147,7 +3147,7 @@  discard block
 block discarded – undo
3147 3147
                 //of array('Registration.TXN_ID'=>23)
3148 3148
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3149 3149
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3150
-                    if (! is_array($possibly_array_of_params)) {
3150
+                    if ( ! is_array($possibly_array_of_params)) {
3151 3151
                         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'))",
3152 3152
                             "event_espresso"),
3153 3153
                             $param, $possibly_array_of_params));
@@ -3163,7 +3163,7 @@  discard block
 block discarded – undo
3163 3163
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3164 3164
                     //indicating that $possible_array_of_params[1] is actually a field name,
3165 3165
                     //from which we should extract query parameters!
3166
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3166
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3167 3167
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3168 3168
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3169 3169
                     }
@@ -3193,8 +3193,8 @@  discard block
 block discarded – undo
3193 3193
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3194 3194
         $query_param_type
3195 3195
     ) {
3196
-        if (! empty($sub_query_params)) {
3197
-            if (! is_array($sub_query_params)) {
3196
+        if ( ! empty($sub_query_params)) {
3197
+            if ( ! is_array($sub_query_params)) {
3198 3198
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3199 3199
                     $sub_query_params));
3200 3200
             }
@@ -3223,7 +3223,7 @@  discard block
 block discarded – undo
3223 3223
      */
3224 3224
     public function _create_model_query_info_carrier($query_params)
3225 3225
     {
3226
-        if (! is_array($query_params)) {
3226
+        if ( ! is_array($query_params)) {
3227 3227
             EE_Error::doing_it_wrong(
3228 3228
                 'EEM_Base::_create_model_query_info_carrier',
3229 3229
                 sprintf(
@@ -3299,7 +3299,7 @@  discard block
 block discarded – undo
3299 3299
         //set limit
3300 3300
         if (array_key_exists('limit', $query_params)) {
3301 3301
             if (is_array($query_params['limit'])) {
3302
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3302
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3303 3303
                     $e = sprintf(
3304 3304
                         __(
3305 3305
                             "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)",
@@ -3307,12 +3307,12 @@  discard block
 block discarded – undo
3307 3307
                         ),
3308 3308
                         http_build_query($query_params['limit'])
3309 3309
                     );
3310
-                    throw new EE_Error($e . "|" . $e);
3310
+                    throw new EE_Error($e."|".$e);
3311 3311
                 }
3312 3312
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3313
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3314
-            } elseif (! empty ($query_params['limit'])) {
3315
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3313
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3314
+            } elseif ( ! empty ($query_params['limit'])) {
3315
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3316 3316
             }
3317 3317
         }
3318 3318
         //set order by
@@ -3344,10 +3344,10 @@  discard block
 block discarded – undo
3344 3344
                 $order_array = array();
3345 3345
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3346 3346
                     $order = $this->_extract_order($order);
3347
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3347
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3348 3348
                 }
3349
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3350
-            } elseif (! empty ($query_params['order_by'])) {
3349
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3350
+            } elseif ( ! empty ($query_params['order_by'])) {
3351 3351
                 $this->_extract_related_model_info_from_query_param(
3352 3352
                     $query_params['order_by'],
3353 3353
                     $query_object,
@@ -3358,18 +3358,18 @@  discard block
 block discarded – undo
3358 3358
                     ? $this->_extract_order($query_params['order'])
3359 3359
                     : 'DESC';
3360 3360
                 $query_object->set_order_by_sql(
3361
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3361
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3362 3362
                 );
3363 3363
             }
3364 3364
         }
3365 3365
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3366
-        if (! array_key_exists('order_by', $query_params)
3366
+        if ( ! array_key_exists('order_by', $query_params)
3367 3367
             && array_key_exists('order', $query_params)
3368 3368
             && ! empty($query_params['order'])
3369 3369
         ) {
3370 3370
             $pk_field = $this->get_primary_key_field();
3371 3371
             $order = $this->_extract_order($query_params['order']);
3372
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3372
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3373 3373
         }
3374 3374
         //set group by
3375 3375
         if (array_key_exists('group_by', $query_params)) {
@@ -3379,10 +3379,10 @@  discard block
 block discarded – undo
3379 3379
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3380 3380
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3381 3381
                 }
3382
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3383
-            } elseif (! empty ($query_params['group_by'])) {
3382
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3383
+            } elseif ( ! empty ($query_params['group_by'])) {
3384 3384
                 $query_object->set_group_by_sql(
3385
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3385
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3386 3386
                 );
3387 3387
             }
3388 3388
         }
@@ -3392,7 +3392,7 @@  discard block
 block discarded – undo
3392 3392
         }
3393 3393
         //now, just verify they didn't pass anything wack
3394 3394
         foreach ($query_params as $query_key => $query_value) {
3395
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3395
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3396 3396
                 throw new EE_Error(
3397 3397
                     sprintf(
3398 3398
                         __(
@@ -3486,22 +3486,22 @@  discard block
 block discarded – undo
3486 3486
         $where_query_params = array()
3487 3487
     ) {
3488 3488
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3489
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3489
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3490 3490
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3491 3491
                 "event_espresso"), $use_default_where_conditions,
3492 3492
                 implode(", ", $allowed_used_default_where_conditions_values)));
3493 3493
         }
3494 3494
         $universal_query_params = array();
3495
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3495
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3496 3496
             $universal_query_params = $this->_get_default_where_conditions();
3497
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3497
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3498 3498
             $universal_query_params = $this->_get_minimum_where_conditions();
3499 3499
         }
3500 3500
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3501 3501
             $related_model = $this->get_related_model_obj($model_name);
3502
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3502
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3503 3503
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3504
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3504
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3505 3505
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3506 3506
             } else {
3507 3507
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3534,7 +3534,7 @@  discard block
 block discarded – undo
3534 3534
      * @param bool $for_this_model false means this is for OTHER related models
3535 3535
      * @return bool
3536 3536
      */
3537
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3537
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3538 3538
     {
3539 3539
         return (
3540 3540
                    $for_this_model
@@ -3613,7 +3613,7 @@  discard block
 block discarded – undo
3613 3613
     ) {
3614 3614
         $null_friendly_where_conditions = array();
3615 3615
         $none_overridden = true;
3616
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3616
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3617 3617
         foreach ($default_where_conditions as $key => $val) {
3618 3618
             if (isset($provided_where_conditions[$key])) {
3619 3619
                 $none_overridden = false;
@@ -3731,7 +3731,7 @@  discard block
 block discarded – undo
3731 3731
             foreach ($tables as $table_obj) {
3732 3732
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3733 3733
                                        . $table_obj->get_fully_qualified_pk_column();
3734
-                if (! in_array($qualified_pk_column, $selects)) {
3734
+                if ( ! in_array($qualified_pk_column, $selects)) {
3735 3735
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3736 3736
                 }
3737 3737
             }
@@ -3817,9 +3817,9 @@  discard block
 block discarded – undo
3817 3817
         //and
3818 3818
         //check if it's a field on a related model
3819 3819
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3820
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3820
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3821 3821
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3822
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3822
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3823 3823
                 if ($query_param === '') {
3824 3824
                     //nothing left to $query_param
3825 3825
                     //we should actually end in a field name, not a model like this!
@@ -3905,7 +3905,7 @@  discard block
 block discarded – undo
3905 3905
     {
3906 3906
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
3907 3907
         if ($SQL) {
3908
-            return " WHERE " . $SQL;
3908
+            return " WHERE ".$SQL;
3909 3909
         } else {
3910 3910
             return '';
3911 3911
         }
@@ -3925,7 +3925,7 @@  discard block
 block discarded – undo
3925 3925
     {
3926 3926
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
3927 3927
         if ($SQL) {
3928
-            return " HAVING " . $SQL;
3928
+            return " HAVING ".$SQL;
3929 3929
         } else {
3930 3930
             return '';
3931 3931
         }
@@ -3945,7 +3945,7 @@  discard block
 block discarded – undo
3945 3945
     {
3946 3946
         $where_clauses = array();
3947 3947
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
3948
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
3948
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
3949 3949
             if (in_array($query_param, $this->_logic_query_param_keys)) {
3950 3950
                 switch ($query_param) {
3951 3951
                     case 'not':
@@ -3973,7 +3973,7 @@  discard block
 block discarded – undo
3973 3973
             } else {
3974 3974
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
3975 3975
                 //if it's not a normal field, maybe it's a custom selection?
3976
-                if (! $field_obj) {
3976
+                if ( ! $field_obj) {
3977 3977
                     if (isset($this->_custom_selections[$query_param][1])) {
3978 3978
                         $field_obj = $this->_custom_selections[$query_param][1];
3979 3979
                     } else {
@@ -3982,7 +3982,7 @@  discard block
 block discarded – undo
3982 3982
                     }
3983 3983
                 }
3984 3984
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
3985
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
3985
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
3986 3986
             }
3987 3987
         }
3988 3988
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4003,7 +4003,7 @@  discard block
 block discarded – undo
4003 4003
         if ($field) {
4004 4004
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4005 4005
                 $query_param);
4006
-            return $table_alias_prefix . $field->get_qualified_column();
4006
+            return $table_alias_prefix.$field->get_qualified_column();
4007 4007
         } elseif (array_key_exists($query_param, $this->_custom_selections)) {
4008 4008
             //maybe it's custom selection item?
4009 4009
             //if so, just use it as the "column name"
@@ -4050,7 +4050,7 @@  discard block
 block discarded – undo
4050 4050
     {
4051 4051
         if (is_array($op_and_value)) {
4052 4052
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4053
-            if (! $operator) {
4053
+            if ( ! $operator) {
4054 4054
                 $php_array_like_string = array();
4055 4055
                 foreach ($op_and_value as $key => $value) {
4056 4056
                     $php_array_like_string[] = "$key=>$value";
@@ -4072,13 +4072,13 @@  discard block
 block discarded – undo
4072 4072
         }
4073 4073
         //check to see if the value is actually another field
4074 4074
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4075
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4075
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4076 4076
         } elseif (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4077 4077
             //in this case, the value should be an array, or at least a comma-separated list
4078 4078
             //it will need to handle a little differently
4079 4079
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4080 4080
             //note: $cleaned_value has already been run through $wpdb->prepare()
4081
-            return $operator . SP . $cleaned_value;
4081
+            return $operator.SP.$cleaned_value;
4082 4082
         } elseif (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4083 4083
             //the value should be an array with count of two.
4084 4084
             if (count($value) !== 2) {
@@ -4093,7 +4093,7 @@  discard block
 block discarded – undo
4093 4093
                 );
4094 4094
             }
4095 4095
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4096
-            return $operator . SP . $cleaned_value;
4096
+            return $operator.SP.$cleaned_value;
4097 4097
         } elseif (in_array($operator, $this->valid_null_style_operators())) {
4098 4098
             if ($value !== null) {
4099 4099
                 throw new EE_Error(
@@ -4111,9 +4111,9 @@  discard block
 block discarded – undo
4111 4111
         } elseif (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4112 4112
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4113 4113
             //remove other junk. So just treat it as a string.
4114
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4115
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4116
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4114
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4115
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4116
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4117 4117
         } elseif (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4118 4118
             throw new EE_Error(
4119 4119
                 sprintf(
@@ -4125,7 +4125,7 @@  discard block
 block discarded – undo
4125 4125
                     $operator
4126 4126
                 )
4127 4127
             );
4128
-        } elseif (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4128
+        } elseif ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4129 4129
             throw new EE_Error(
4130 4130
                 sprintf(
4131 4131
                     __(
@@ -4166,7 +4166,7 @@  discard block
 block discarded – undo
4166 4166
         foreach ($values as $value) {
4167 4167
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4168 4168
         }
4169
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4169
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4170 4170
     }
4171 4171
 
4172 4172
 
@@ -4207,7 +4207,7 @@  discard block
 block discarded – undo
4207 4207
                                 . $main_table->get_table_name()
4208 4208
                                 . " WHERE FALSE";
4209 4209
         }
4210
-        return "(" . implode(",", $cleaned_values) . ")";
4210
+        return "(".implode(",", $cleaned_values).")";
4211 4211
     }
4212 4212
 
4213 4213
 
@@ -4226,7 +4226,7 @@  discard block
 block discarded – undo
4226 4226
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4227 4227
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4228 4228
         } else {//$field_obj should really just be a data type
4229
-            if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4229
+            if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4230 4230
                 throw new EE_Error(sprintf(__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4231 4231
                     $field_obj, implode(",", $this->_valid_wpdb_data_types)));
4232 4232
             }
@@ -4346,10 +4346,10 @@  discard block
 block discarded – undo
4346 4346
      */
4347 4347
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4348 4348
     {
4349
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4349
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4350 4350
         $qualified_columns = array();
4351 4351
         foreach ($this->field_settings() as $field_name => $field) {
4352
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4352
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4353 4353
         }
4354 4354
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4355 4355
     }
@@ -4373,11 +4373,11 @@  discard block
 block discarded – undo
4373 4373
             if ($table_obj instanceof EE_Primary_Table) {
4374 4374
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4375 4375
                     ? $table_obj->get_select_join_limit($limit)
4376
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4376
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4377 4377
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4378 4378
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4379 4379
                     ? $table_obj->get_select_join_limit_join($limit)
4380
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4380
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4381 4381
             }
4382 4382
         }
4383 4383
         return $SQL;
@@ -4465,12 +4465,12 @@  discard block
 block discarded – undo
4465 4465
      */
4466 4466
     public function get_related_model_obj($model_name)
4467 4467
     {
4468
-        $model_classname = "EEM_" . $model_name;
4469
-        if (! class_exists($model_classname)) {
4468
+        $model_classname = "EEM_".$model_name;
4469
+        if ( ! class_exists($model_classname)) {
4470 4470
             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",
4471 4471
                 'event_espresso'), $model_name, $model_classname));
4472 4472
         }
4473
-        return call_user_func($model_classname . "::instance");
4473
+        return call_user_func($model_classname."::instance");
4474 4474
     }
4475 4475
 
4476 4476
 
@@ -4517,7 +4517,7 @@  discard block
 block discarded – undo
4517 4517
     public function related_settings_for($relation_name)
4518 4518
     {
4519 4519
         $relatedModels = $this->relation_settings();
4520
-        if (! array_key_exists($relation_name, $relatedModels)) {
4520
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4521 4521
             throw new EE_Error(
4522 4522
                 sprintf(
4523 4523
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4545,7 +4545,7 @@  discard block
 block discarded – undo
4545 4545
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4546 4546
     {
4547 4547
         $fieldSettings = $this->field_settings($include_db_only_fields);
4548
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4548
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4549 4549
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4550 4550
                 get_class($this)));
4551 4551
         }
@@ -4620,7 +4620,7 @@  discard block
 block discarded – undo
4620 4620
                     break;
4621 4621
                 }
4622 4622
             }
4623
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4623
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4624 4624
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4625 4625
                     get_class($this)));
4626 4626
             }
@@ -4679,7 +4679,7 @@  discard block
 block discarded – undo
4679 4679
      */
4680 4680
     public function get_foreign_key_to($model_name)
4681 4681
     {
4682
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4682
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4683 4683
             foreach ($this->field_settings() as $field) {
4684 4684
                 if (
4685 4685
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4689,7 +4689,7 @@  discard block
 block discarded – undo
4689 4689
                     break;
4690 4690
                 }
4691 4691
             }
4692
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4692
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4693 4693
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4694 4694
                     'event_espresso'), $model_name, get_class($this)));
4695 4695
             }
@@ -4740,7 +4740,7 @@  discard block
 block discarded – undo
4740 4740
                 foreach ($this->_fields as $fields_corresponding_to_table) {
4741 4741
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4742 4742
                         /** @var $field_obj EE_Model_Field_Base */
4743
-                        if (! $field_obj->is_db_only_field()) {
4743
+                        if ( ! $field_obj->is_db_only_field()) {
4744 4744
                             $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4745 4745
                         }
4746 4746
                     }
@@ -4770,7 +4770,7 @@  discard block
 block discarded – undo
4770 4770
         $count_if_model_has_no_primary_key = 0;
4771 4771
         $has_primary_key = $this->has_primary_key_field();
4772 4772
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4773
-        foreach ((array)$rows as $row) {
4773
+        foreach ((array) $rows as $row) {
4774 4774
             if (empty($row)) {
4775 4775
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4776 4776
                 return array();
@@ -4788,7 +4788,7 @@  discard block
 block discarded – undo
4788 4788
                 }
4789 4789
             }
4790 4790
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4791
-            if (! $classInstance) {
4791
+            if ( ! $classInstance) {
4792 4792
                 throw new EE_Error(
4793 4793
                     sprintf(
4794 4794
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4857,7 +4857,7 @@  discard block
 block discarded – undo
4857 4857
      */
4858 4858
     public function instantiate_class_from_array_or_object($cols_n_values)
4859 4859
     {
4860
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4860
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4861 4861
             $cols_n_values = get_object_vars($cols_n_values);
4862 4862
         }
4863 4863
         $primary_key = null;
@@ -4882,7 +4882,7 @@  discard block
 block discarded – undo
4882 4882
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
4883 4883
         if ($primary_key) {
4884 4884
             $classInstance = $this->get_from_entity_map($primary_key);
4885
-            if (! $classInstance) {
4885
+            if ( ! $classInstance) {
4886 4886
                 $classInstance = EE_Registry::instance()
4887 4887
                                             ->load_class($className,
4888 4888
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -4933,12 +4933,12 @@  discard block
 block discarded – undo
4933 4933
     public function add_to_entity_map(EE_Base_Class $object)
4934 4934
     {
4935 4935
         $className = $this->_get_class_name();
4936
-        if (! $object instanceof $className) {
4936
+        if ( ! $object instanceof $className) {
4937 4937
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
4938 4938
                 is_object($object) ? get_class($object) : $object, $className));
4939 4939
         }
4940 4940
         /** @var $object EE_Base_Class */
4941
-        if (! $object->ID()) {
4941
+        if ( ! $object->ID()) {
4942 4942
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
4943 4943
                 "event_espresso"), get_class($this)));
4944 4944
         }
@@ -5008,7 +5008,7 @@  discard block
 block discarded – undo
5008 5008
             //there is a primary key on this table and its not set. Use defaults for all its columns
5009 5009
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5010 5010
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5011
-                    if (! $field_obj->is_db_only_field()) {
5011
+                    if ( ! $field_obj->is_db_only_field()) {
5012 5012
                         //prepare field as if its coming from db
5013 5013
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5014 5014
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5017,7 +5017,7 @@  discard block
 block discarded – undo
5017 5017
             } else {
5018 5018
                 //the table's rows existed. Use their values
5019 5019
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5020
-                    if (! $field_obj->is_db_only_field()) {
5020
+                    if ( ! $field_obj->is_db_only_field()) {
5021 5021
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5022 5022
                             $cols_n_values, $field_obj->get_qualified_column(),
5023 5023
                             $field_obj->get_table_column()
@@ -5134,7 +5134,7 @@  discard block
 block discarded – undo
5134 5134
      */
5135 5135
     private function _get_class_name()
5136 5136
     {
5137
-        return "EE_" . $this->get_this_model_name();
5137
+        return "EE_".$this->get_this_model_name();
5138 5138
     }
5139 5139
 
5140 5140
 
@@ -5149,7 +5149,7 @@  discard block
 block discarded – undo
5149 5149
      */
5150 5150
     public function item_name($quantity = 1)
5151 5151
     {
5152
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5152
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5153 5153
     }
5154 5154
 
5155 5155
 
@@ -5182,7 +5182,7 @@  discard block
 block discarded – undo
5182 5182
     {
5183 5183
         $className = get_class($this);
5184 5184
         $tagName = "FHEE__{$className}__{$methodName}";
5185
-        if (! has_filter($tagName)) {
5185
+        if ( ! has_filter($tagName)) {
5186 5186
             throw new EE_Error(
5187 5187
                 sprintf(
5188 5188
                     __('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 );',
@@ -5408,7 +5408,7 @@  discard block
 block discarded – undo
5408 5408
         $key_vals_in_combined_pk = array();
5409 5409
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5410 5410
         foreach ($key_fields as $key_field_name => $field_obj) {
5411
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5411
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5412 5412
                 return null;
5413 5413
             }
5414 5414
         }
@@ -5429,7 +5429,7 @@  discard block
 block discarded – undo
5429 5429
     {
5430 5430
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5431 5431
         foreach ($keys_it_should_have as $key) {
5432
-            if (! isset($key_vals[$key])) {
5432
+            if ( ! isset($key_vals[$key])) {
5433 5433
                 return false;
5434 5434
             }
5435 5435
         }
@@ -5483,7 +5483,7 @@  discard block
 block discarded – undo
5483 5483
      */
5484 5484
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5485 5485
     {
5486
-        if (! is_array($query_params)) {
5486
+        if ( ! is_array($query_params)) {
5487 5487
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5488 5488
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5489 5489
                     gettype($query_params)), '4.6.0');
@@ -5545,7 +5545,7 @@  discard block
 block discarded – undo
5545 5545
      * Gets the valid operators
5546 5546
      * @return array keys are accepted strings, values are the SQL they are converted to
5547 5547
      */
5548
-    public function valid_operators(){
5548
+    public function valid_operators() {
5549 5549
         return $this->_valid_operators;
5550 5550
     }
5551 5551
 
@@ -5633,7 +5633,7 @@  discard block
 block discarded – undo
5633 5633
      */
5634 5634
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5635 5635
     {
5636
-        if (! $this->has_primary_key_field()) {
5636
+        if ( ! $this->has_primary_key_field()) {
5637 5637
             if (WP_DEBUG) {
5638 5638
                 EE_Error::add_error(
5639 5639
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5646,7 +5646,7 @@  discard block
 block discarded – undo
5646 5646
         $IDs = array();
5647 5647
         foreach ($model_objects as $model_object) {
5648 5648
             $id = $model_object->ID();
5649
-            if (! $id) {
5649
+            if ( ! $id) {
5650 5650
                 if ($filter_out_empty_ids) {
5651 5651
                     continue;
5652 5652
                 }
@@ -5742,8 +5742,8 @@  discard block
 block discarded – undo
5742 5742
         $missing_caps = array();
5743 5743
         $cap_restrictions = $this->cap_restrictions($context);
5744 5744
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5745
-            if (! EE_Capabilities::instance()
5746
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5745
+            if ( ! EE_Capabilities::instance()
5746
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5747 5747
             ) {
5748 5748
                 $missing_caps[$cap] = $restriction_if_no_cap;
5749 5749
             }
@@ -5894,7 +5894,7 @@  discard block
 block discarded – undo
5894 5894
     {
5895 5895
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
5896 5896
             if ($query_param_key === $logic_query_param_key
5897
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
5897
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
5898 5898
             ) {
5899 5899
                 return true;
5900 5900
             }
Please login to merge, or discard this patch.
modules/core_rest_api/EED_Core_Rest_Api.module.php 2 patches
Indentation   +1234 added lines, -1234 removed lines patch added patch discarded remove patch
@@ -20,1241 +20,1241 @@
 block discarded – undo
20 20
 class EED_Core_Rest_Api extends \EED_Module
21 21
 {
22 22
 
23
-    const ee_api_namespace           = 'ee/v';
23
+	const ee_api_namespace           = 'ee/v';
24 24
 
25
-    const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
26
-
27
-    const saved_routes_option_names  = 'ee_core_routes';
28
-
29
-    /**
30
-     * string used in _links response bodies to make them globally unique.
31
-     *
32
-     * @see http://v2.wp-api.org/extending/linking/
33
-     */
34
-    const ee_api_link_namespace = 'https://api.eventespresso.com/';
35
-
36
-    /**
37
-     * @var CalculatedModelFields
38
-     */
39
-    protected static $_field_calculator = null;
40
-
41
-
42
-
43
-    /**
44
-     * @return EED_Core_Rest_Api
45
-     */
46
-    public static function instance()
47
-    {
48
-        self::$_field_calculator = new CalculatedModelFields();
49
-        return parent::get_instance(__CLASS__);
50
-    }
51
-
52
-
53
-
54
-    /**
55
-     *    set_hooks - for hooking into EE Core, other modules, etc
56
-     *
57
-     * @access    public
58
-     * @return    void
59
-     */
60
-    public static function set_hooks()
61
-    {
62
-        self::set_hooks_both();
63
-    }
64
-
65
-
66
-
67
-    /**
68
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
-     *
70
-     * @access    public
71
-     * @return    void
72
-     */
73
-    public static function set_hooks_admin()
74
-    {
75
-        self::set_hooks_both();
76
-    }
77
-
78
-
79
-
80
-    public static function set_hooks_both()
81
-    {
82
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
-        add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
84
-        add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
85
-        add_filter('rest_index',
86
-            array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
87
-        EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * sets up hooks which only need to be included as part of REST API requests;
94
-     * other requests like to the frontend or admin etc don't need them
95
-     */
96
-    public static function set_hooks_rest_api()
97
-    {
98
-        //set hooks which account for changes made to the API
99
-        EED_Core_Rest_Api::_set_hooks_for_changes();
100
-    }
101
-
102
-
103
-
104
-    /**
105
-     * public wrapper of _set_hooks_for_changes.
106
-     * Loads all the hooks which make requests to old versions of the API
107
-     * appear the same as they always did
108
-     */
109
-    public static function set_hooks_for_changes()
110
-    {
111
-        self::_set_hooks_for_changes();
112
-    }
113
-
114
-
115
-
116
-    /**
117
-     * Loads all the hooks which make requests to old versions of the API
118
-     * appear the same as they always did
119
-     */
120
-    protected static function _set_hooks_for_changes()
121
-    {
122
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
123
-        foreach ($folder_contents as $classname_in_namespace => $filepath) {
124
-            //ignore the base parent class
125
-            //and legacy named classes
126
-            if ($classname_in_namespace === 'ChangesInBase'
127
-                || strpos($classname_in_namespace, 'Changes_In_') === 0
128
-            ) {
129
-                continue;
130
-            }
131
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
132
-            if (class_exists($full_classname)) {
133
-                $instance_of_class = new $full_classname;
134
-                if ($instance_of_class instanceof ChangesInBase) {
135
-                    $instance_of_class->setHooks();
136
-                }
137
-            }
138
-        }
139
-    }
140
-
141
-
142
-
143
-    /**
144
-     * Filters the WP routes to add our EE-related ones. This takes a bit of time
145
-     * so we actually prefer to only do it when an EE plugin is activated or upgraded
146
-     */
147
-    public static function register_routes()
148
-    {
149
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
150
-            foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
151
-                /**
152
-                 * @var array $data_for_multiple_endpoints numerically indexed array
153
-                 *                                         but can also contain route options like {
154
-                 * @type array    $schema                      {
155
-                 * @type callable $schema_callback
156
-                 * @type array    $callback_args               arguments that will be passed to the callback, after the
157
-                 * WP_REST_Request of course
158
-                 * }
159
-                 * }
160
-                 */
161
-                //when registering routes, register all the endpoints' data at the same time
162
-                $multiple_endpoint_args = array();
163
-                foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
164
-                    /**
165
-                     * @var array     $data_for_single_endpoint {
166
-                     * @type callable $callback
167
-                     * @type string methods
168
-                     * @type array args
169
-                     * @type array _links
170
-                     * @type array    $callback_args            arguments that will be passed to the callback, after the
171
-                     * WP_REST_Request of course
172
-                     * }
173
-                     */
174
-                    //skip route options
175
-                    if (! is_numeric($endpoint_key)) {
176
-                        continue;
177
-                    }
178
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179
-                        throw new EE_Error(
180
-                            esc_html__(
181
-                                // @codingStandardsIgnoreStart
182
-                                'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
183
-                                // @codingStandardsIgnoreEnd
184
-                                'event_espresso')
185
-                        );
186
-                    }
187
-                    $callback = $data_for_single_endpoint['callback'];
188
-                    $single_endpoint_args = array(
189
-                        'methods' => $data_for_single_endpoint['methods'],
190
-                        'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
191
-                            : array(),
192
-                    );
193
-                    if (isset($data_for_single_endpoint['_links'])) {
194
-                        $single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
195
-                    }
196
-                    if (isset($data_for_single_endpoint['callback_args'])) {
197
-                        $callback_args = $data_for_single_endpoint['callback_args'];
198
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
199
-                            $callback,
200
-                            $callback_args
201
-                        ) {
202
-                            array_unshift($callback_args, $request);
203
-                            return call_user_func_array(
204
-                                $callback,
205
-                                $callback_args
206
-                            );
207
-                        };
208
-                    } else {
209
-                        $single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
210
-                    }
211
-                    $multiple_endpoint_args[] = $single_endpoint_args;
212
-                }
213
-                if (isset($data_for_multiple_endpoints['schema'])) {
214
-                    $schema_route_data = $data_for_multiple_endpoints['schema'];
215
-                    $schema_callback = $schema_route_data['schema_callback'];
216
-                    $callback_args = $schema_route_data['callback_args'];
217
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
218
-                        return call_user_func_array(
219
-                            $schema_callback,
220
-                            $callback_args
221
-                        );
222
-                    };
223
-                }
224
-                register_rest_route(
225
-                    $namespace,
226
-                    $relative_route,
227
-                    $multiple_endpoint_args
228
-                );
229
-            }
230
-        }
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * Checks if there was a version change or something that merits invalidating the cached
237
-     * route data. If so, invalidates the cached route data so that it gets refreshed
238
-     * next time the WP API is used
239
-     */
240
-    public static function invalidate_cached_route_data_on_version_change()
241
-    {
242
-        if (EE_System::instance()->detect_req_type() != EE_System::req_type_normal) {
243
-            EED_Core_Rest_Api::invalidate_cached_route_data();
244
-        }
245
-        foreach (EE_Registry::instance()->addons as $addon) {
246
-            if ($addon instanceof EE_Addon && $addon->detect_req_type() != EE_System::req_type_normal) {
247
-                EED_Core_Rest_Api::invalidate_cached_route_data();
248
-            }
249
-        }
250
-    }
251
-
252
-
253
-
254
-    /**
255
-     * Removes the cached route data so it will get refreshed next time the WP API is used
256
-     */
257
-    public static function invalidate_cached_route_data()
258
-    {
259
-        //delete the saved EE REST API routes
260
-        foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
262
-        }
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * Gets the EE route data
269
-     *
270
-     * @return array top-level key is the namespace, next-level key is the route and its value is array{
271
-     * @type string|array $callback
272
-     * @type string       $methods
273
-     * @type boolean      $hidden_endpoint
274
-     * }
275
-     */
276
-    public static function get_ee_route_data()
277
-    {
278
-        $ee_routes = array();
279
-        foreach (self::versions_served() as $version => $hidden_endpoints) {
280
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
281
-                $version,
282
-                $hidden_endpoints
283
-            );
284
-        }
285
-        return $ee_routes;
286
-    }
287
-
288
-
289
-
290
-    /**
291
-     * Gets the EE route data from the wp options if it exists already,
292
-     * otherwise re-generates it and saves it to the option
293
-     *
294
-     * @param string  $version
295
-     * @param boolean $hidden_endpoints
296
-     * @return array
297
-     */
298
-    protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299
-    {
300
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302
-            $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303
-        }
304
-        return $ee_routes;
305
-    }
306
-
307
-
308
-
309
-    /**
310
-     * Saves the EE REST API route data to a wp option and returns it
311
-     *
312
-     * @param string  $version
313
-     * @param boolean $hidden_endpoints
314
-     * @return mixed|null
315
-     */
316
-    protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
317
-    {
318
-        $instance = self::instance();
319
-        $routes = apply_filters(
320
-            'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
321
-            array_replace_recursive(
322
-                $instance->_get_config_route_data_for_version($version, $hidden_endpoints),
323
-                $instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
324
-                $instance->_get_model_route_data_for_version($version, $hidden_endpoints),
325
-                $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326
-            )
327
-        );
328
-        $option_name = self::saved_routes_option_names . $version;
329
-        if (get_option($option_name)) {
330
-            update_option($option_name, $routes, true);
331
-        } else {
332
-            add_option($option_name, $routes, null, 'no');
333
-        }
334
-        return $routes;
335
-    }
336
-
337
-
338
-
339
-    /**
340
-     * Calculates all the EE routes and saves it to a WordPress option so we don't
341
-     * need to calculate it on every request
342
-     *
343
-     * @deprecated since version 4.9.1
344
-     * @return void
345
-     */
346
-    public static function save_ee_routes()
347
-    {
348
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
349
-            $instance = self::instance();
350
-            $routes = apply_filters(
351
-                'EED_Core_Rest_Api__save_ee_routes__routes',
352
-                array_replace_recursive(
353
-                    $instance->_register_config_routes(),
354
-                    $instance->_register_meta_routes(),
355
-                    $instance->_register_model_routes(),
356
-                    $instance->_register_rpc_routes()
357
-                )
358
-            );
359
-            update_option(self::saved_routes_option_names, $routes, true);
360
-        }
361
-    }
362
-
363
-
364
-
365
-    /**
366
-     * Gets all the route information relating to EE models
367
-     *
368
-     * @return array @see get_ee_route_data
369
-     * @deprecated since version 4.9.1
370
-     */
371
-    protected function _register_model_routes()
372
-    {
373
-        $model_routes = array();
374
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
375
-            $model_routes[EED_Core_Rest_Api::ee_api_namespace
376
-                          . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
377
-        }
378
-        return $model_routes;
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * Decides whether or not to add write endpoints for this model.
385
-     *
386
-     * Currently, this defaults to exclude all global tables and models
387
-     * which would allow inserting WP core data (we don't want to duplicate
388
-     * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
389
-     * @param EEM_Base $model
390
-     * @return bool
391
-     */
392
-    public static function should_have_write_endpoints(EEM_Base $model)
393
-    {
394
-        if ($model->is_wp_core_model()){
395
-            return false;
396
-        }
397
-        foreach($model->get_tables() as $table){
398
-            if( $table->is_global()){
399
-                return false;
400
-            }
401
-        }
402
-        return true;
403
-    }
404
-
405
-
406
-
407
-    /**
408
-     * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
409
-     * in this versioned namespace of EE4
410
-     * @param $version
411
-     * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412
-     */
413
-    public static function model_names_with_plural_routes($version){
414
-        $model_version_info = new ModelVersionInfo($version);
415
-        $models_to_register = $model_version_info->modelsForRequestedVersion();
416
-        //let's not bother having endpoints for extra metas
417
-        unset($models_to_register['Extra_Meta']);
418
-        unset($models_to_register['Extra_Join']);
419
-        unset($models_to_register['Post_Meta']);
420
-        return apply_filters(
421
-            'FHEE__EED_Core_REST_API___register_model_routes',
422
-            $models_to_register
423
-        );
424
-    }
425
-
426
-
427
-
428
-    /**
429
-     * Gets the route data for EE models in the specified version
430
-     *
431
-     * @param string  $version
432
-     * @param boolean $hidden_endpoint
433
-     * @return array
434
-     */
435
-    protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
436
-    {
437
-        $model_routes = array();
438
-        $model_version_info = new ModelVersionInfo($version);
439
-        foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440
-            $model = \EE_Registry::instance()->load_model($model_name);
441
-            //if this isn't a valid model then let's skip iterate to the next item in the loop.
442
-            if (! $model instanceof EEM_Base) {
443
-                continue;
444
-            }
445
-            //yes we could just register one route for ALL models, but then they wouldn't show up in the index
446
-            $plural_model_route = EED_Core_Rest_Api::get_collection_route($model_name);
447
-            $singular_model_route = EED_Core_Rest_Api::get_entity_route($model_name, '(?P<id>[^\/]+)');
448
-            $model_routes[$plural_model_route] = array(
449
-                array(
450
-                    'callback'        => array(
451
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
452
-                        'handleRequestGetAll',
453
-                    ),
454
-                    'callback_args'   => array($version, $model_name),
455
-                    'methods'         => WP_REST_Server::READABLE,
456
-                    'hidden_endpoint' => $hidden_endpoint,
457
-                    'args'            => $this->_get_read_query_params($model, $version),
458
-                    '_links'          => array(
459
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
460
-                    ),
461
-                ),
462
-                'schema' => array(
463
-                    'schema_callback' => array(
464
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
-                        'handleSchemaRequest',
466
-                    ),
467
-                    'callback_args'   => array($version, $model_name),
468
-                ),
469
-            );
470
-            $model_routes[$singular_model_route] = array(
471
-                array(
472
-                    'callback'        => array(
473
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Read',
474
-                        'handleRequestGetOne',
475
-                    ),
476
-                    'callback_args'   => array($version, $model_name),
477
-                    'methods'         => WP_REST_Server::READABLE,
478
-                    'hidden_endpoint' => $hidden_endpoint,
479
-                    'args'            => $this->_get_response_selection_query_params($model, $version),
480
-                ),
481
-            );
482
-            if( apply_filters(
483
-                'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484
-                $this->should_have_write_endpoints($model),
485
-                $model
486
-            )){
487
-                $model_routes[$plural_model_route][] = array(
488
-                    'callback'        => array(
489
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Write',
490
-                        'handleRequestInsert',
491
-                    ),
492
-                    'callback_args'   => array($version, $model_name),
493
-                    'methods'         => WP_REST_Server::CREATABLE,
494
-                    'hidden_endpoint' => $hidden_endpoint,
495
-                    'args'            => $this->_get_write_params($model_name, $model_version_info, true),
496
-                );
497
-                $model_routes[$singular_model_route] = array_merge(
498
-                    $model_routes[$singular_model_route],
499
-                    array(
500
-                        array(
501
-                            'callback'        => array(
502
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
503
-                                'handleRequestUpdate',
504
-                            ),
505
-                            'callback_args'   => array($version, $model_name),
506
-                            'methods'         => WP_REST_Server::EDITABLE,
507
-                            'hidden_endpoint' => $hidden_endpoint,
508
-                            'args'            => $this->_get_write_params($model_name, $model_version_info, false),
509
-                        ),
510
-                        array(
511
-                            'callback'        => array(
512
-                                'EventEspresso\core\libraries\rest_api\controllers\model\Write',
513
-                                'handleRequestDelete',
514
-                            ),
515
-                            'callback_args'   => array($version, $model_name),
516
-                            'methods'         => WP_REST_Server::DELETABLE,
517
-                            'hidden_endpoint' => $hidden_endpoint,
518
-                            'args'            => $this->_get_delete_query_params($model, $version),
519
-                        )
520
-                    )
521
-                );
522
-            }
523
-            foreach ($model->relation_settings() as $relation_name => $relation_obj) {
524
-
525
-                $related_route = EED_Core_Rest_Api::get_relation_route_via(
526
-                    $model_name,
527
-                    '(?P<id>[^\/]+)',
528
-                    $relation_obj
529
-                );
530
-                $endpoints = array(
531
-                    array(
532
-                        'callback'        => array(
533
-                            'EventEspresso\core\libraries\rest_api\controllers\model\Read',
534
-                            'handleRequestGetRelated',
535
-                        ),
536
-                        'callback_args'   => array($version, $model_name, $relation_name),
537
-                        'methods'         => WP_REST_Server::READABLE,
538
-                        'hidden_endpoint' => $hidden_endpoint,
539
-                        'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
540
-                    ),
541
-                );
542
-                $model_routes[$related_route] = $endpoints;
543
-            }
544
-        }
545
-        return $model_routes;
546
-    }
547
-
548
-
549
-
550
-    /**
551
-     * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
552
-     * excluding the preceding slash.
553
-     * Eg you pass get_plural_route_to('Event') = 'events'
554
-     * @param string $model_name eg Event or Venue
555
-     * @return string
556
-     */
557
-    public static function get_collection_route($model_name)
558
-    {
559
-        return EEH_Inflector::pluralize_and_lower($model_name);
560
-    }
561
-
562
-
563
-
564
-    /**
565
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
566
-     * excluding the preceding slash.
567
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
568
-     * @param string $model_name eg Event or Venue
569
-     * @param string $id
570
-     * @return string
571
-     */
572
-    public static function get_entity_route($model_name, $id)
573
-    {
574
-        return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
575
-    }
576
-
577
-
578
-    /**
579
-     * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
580
-     * excluding the preceding slash.
581
-     * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
582
-     *
583
-     * @param string                $model_name eg Event or Venue
584
-     * @param string                $id
585
-     * @param EE_Model_Relation_Base $relation_obj
586
-     * @return string
587
-     */
588
-    public static function get_relation_route_via($model_name, $id, $relation_obj)
589
-    {
590
-        $related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
591
-            $relation_obj->get_other_model()->get_this_model_name(),
592
-            $relation_obj
593
-        );
594
-        return EED_Core_Rest_Api::get_entity_route($model_name, $id) . '/' . $related_model_name_endpoint_part;
595
-    }
596
-
597
-
598
-
599
-    /**
600
-     * Adds onto the $relative_route the EE4 REST API versioned namespace.
601
-     * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
602
-     * @param string $relative_route
603
-     * @param string $version
604
-     * @return string
605
-     */
606
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * Adds all the RPC-style routes (remote procedure call-like routes, ie
614
-     * routes that don't conform to the traditional REST CRUD-style).
615
-     *
616
-     * @deprecated since 4.9.1
617
-     */
618
-    protected function _register_rpc_routes()
619
-    {
620
-        $routes = array();
621
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
622
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
623
-                $version,
624
-                $hidden_endpoint
625
-            );
626
-        }
627
-        return $routes;
628
-    }
629
-
630
-
631
-
632
-    /**
633
-     * @param string  $version
634
-     * @param boolean $hidden_endpoint
635
-     * @return array
636
-     */
637
-    protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
638
-    {
639
-        $this_versions_routes = array();
640
-        //checkin endpoint
641
-        $this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
642
-            array(
643
-                'callback'        => array(
644
-                    'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
645
-                    'handleRequestToggleCheckin',
646
-                ),
647
-                'methods'         => WP_REST_Server::CREATABLE,
648
-                'hidden_endpoint' => $hidden_endpoint,
649
-                'args'            => array(
650
-                    'force' => array(
651
-                        'required'    => false,
652
-                        'default'     => false,
653
-                        'description' => __(
654
-                            // @codingStandardsIgnoreStart
655
-                            'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
656
-                            // @codingStandardsIgnoreEnd
657
-                            'event_espresso'
658
-                        ),
659
-                    ),
660
-                ),
661
-                'callback_args'   => array($version),
662
-            ),
663
-        );
664
-        return apply_filters(
665
-            'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
666
-            $this_versions_routes,
667
-            $version,
668
-            $hidden_endpoint
669
-        );
670
-    }
671
-
672
-
673
-
674
-    /**
675
-     * Gets the query params that can be used when request one or many
676
-     *
677
-     * @param EEM_Base $model
678
-     * @param string   $version
679
-     * @return array
680
-     */
681
-    protected function _get_response_selection_query_params(\EEM_Base $model, $version)
682
-    {
683
-        return apply_filters(
684
-            'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
685
-            array(
686
-                'include'   => array(
687
-                    'required' => false,
688
-                    'default'  => '*',
689
-                    'type'     => 'string',
690
-                ),
691
-                'calculate' => array(
692
-                    'required'          => false,
693
-                    'default'           => '',
694
-                    'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
695
-                    'type'              => 'string',
696
-                    //because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
697
-                    //freaks out. We'll just validate this argument while handling the request
698
-                    'validate_callback' => null,
699
-                    'sanitize_callback' => null,
700
-                ),
701
-            ),
702
-            $model,
703
-            $version
704
-        );
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * Gets the parameters acceptable for delete requests
711
-     *
712
-     * @param \EEM_Base $model
713
-     * @param string    $version
714
-     * @return array
715
-     */
716
-    protected function _get_delete_query_params(\EEM_Base $model, $version)
717
-    {
718
-        $params_for_delete = array(
719
-            'allow_blocking' => array(
720
-                'required' => false,
721
-                'default'  => true,
722
-                'type'     => 'boolean',
723
-            ),
724
-        );
725
-        $params_for_delete['force'] = array(
726
-            'required' => false,
727
-            'default'  => false,
728
-            'type'     => 'boolean',
729
-        );
730
-        return apply_filters(
731
-            'FHEE__EED_Core_Rest_Api___get_delete_query_params',
732
-            $params_for_delete,
733
-            $model,
734
-            $version
735
-        );
736
-    }
737
-
738
-
739
-
740
-    /**
741
-     * Gets info about reading query params that are acceptable
742
-     *
743
-     * @param \EEM_Base $model eg 'Event' or 'Venue'
744
-     * @param  string   $version
745
-     * @return array    describing the args acceptable when querying this model
746
-     * @throws \EE_Error
747
-     */
748
-    protected function _get_read_query_params(\EEM_Base $model, $version)
749
-    {
750
-        $default_orderby = array();
751
-        foreach ($model->get_combined_primary_key_fields() as $key_field) {
752
-            $default_orderby[$key_field->get_name()] = 'ASC';
753
-        }
754
-        return array_merge(
755
-            $this->_get_response_selection_query_params($model, $version),
756
-            array(
757
-                'where'    => array(
758
-                    'required' => false,
759
-                    'default'  => array(),
760
-                    'type'     => 'object',
761
-                ),
762
-                'limit'    => array(
763
-                    'required' => false,
764
-                    'default'  => EED_Core_Rest_Api::get_default_query_limit(),
765
-                    'type'     => array(
766
-                        'object',
767
-                        'string',
768
-                        'integer',
769
-                    ),
770
-                ),
771
-                'order_by' => array(
772
-                    'required' => false,
773
-                    'default'  => $default_orderby,
774
-                    'type'     => array(
775
-                        'object',
776
-                        'string',
777
-                    ),
778
-                ),
779
-                'group_by' => array(
780
-                    'required' => false,
781
-                    'default'  => null,
782
-                    'type'     => array(
783
-                        'object',
784
-                        'string',
785
-                    ),
786
-                ),
787
-                'having'   => array(
788
-                    'required' => false,
789
-                    'default'  => null,
790
-                    'type'     => 'object',
791
-                ),
792
-                'caps'     => array(
793
-                    'required' => false,
794
-                    'default'  => EEM_Base::caps_read,
795
-                    'type'     => 'string',
796
-                ),
797
-            )
798
-        );
799
-    }
800
-
801
-
802
-
803
-    /**
804
-     * Gets parameter information for a model regarding writing data
805
-     *
806
-     * @param string           $model_name
807
-     * @param ModelVersionInfo $model_version_info
808
-     * @param boolean          $create                                       whether this is for request to create (in which case we need
809
-     *                                                                       all required params) or just to update (in which case we don't need those on every request)
810
-     * @return array
811
-     */
812
-    protected function _get_write_params(
813
-        $model_name,
814
-        ModelVersionInfo $model_version_info,
815
-        $create = false
816
-    ) {
817
-        $model = EE_Registry::instance()->load_model($model_name);
818
-        $fields = $model_version_info->fieldsOnModelInThisVersion($model);
819
-        $args_info = array();
820
-        foreach ($fields as $field_name => $field_obj) {
821
-            if ($field_obj->is_auto_increment()) {
822
-                //totally ignore auto increment IDs
823
-                continue;
824
-            }
825
-            $arg_info = $field_obj->getSchema();
826
-            $required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
827
-            $arg_info['required'] = $required;
828
-            //remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
829
-            unset($arg_info['readonly']);
830
-            $schema_properties = $field_obj->getSchemaProperties();
831
-            if ($field_obj->getSchemaType() === 'object'
832
-                && isset($schema_properties['raw'])
833
-            ) {
834
-                //if there's a "raw" form of this argument, use those properties instead
835
-                $arg_info = array_replace(
836
-                    $arg_info,
837
-                    $schema_properties['raw']
838
-                );
839
-            }
840
-            $arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
841
-                $field_obj,
842
-                $field_obj->get_default_value(),
843
-                $model_version_info->requestedVersion()
844
-            );
845
-            //we do our own validation and sanitization within the controller
846
-            $arg_info['sanitize_callback'] =
847
-                array(
848
-                    'EED_Core_Rest_Api',
849
-                    'default_sanitize_callback',
850
-                );
851
-            $args_info[$field_name] = $arg_info;
852
-            if ($field_obj instanceof EE_Datetime_Field) {
853
-                $gmt_arg_info = $arg_info;
854
-                $gmt_arg_info['description'] = sprintf(
855
-                    esc_html__(
856
-                        '%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
857
-                        'event_espresso'
858
-                    ),
859
-                    $field_obj->get_nicename(),
860
-                    $field_name
861
-                );
862
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
863
-            }
864
-        }
865
-        return $args_info;
866
-    }
867
-
868
-
869
-
870
-    /**
871
-     * Replacement for WP API's 'rest_parse_request_arg'. If the value is blank but not required, don't bother validating it.
872
-     * Also, it uses our email validation instead of WP API's default.
873
-     * @param                 $value
874
-     * @param WP_REST_Request $request
875
-     * @param                 $param
876
-     * @return bool|true|WP_Error
877
-     */
878
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
879
-    {
880
-        $attributes = $request->get_attributes();
881
-        if (! isset($attributes['args'][$param])
882
-            || ! is_array($attributes['args'][$param])) {
883
-            $validation_result = true;
884
-        } else {
885
-            $args = $attributes['args'][$param];
886
-            if ((
887
-                    $value === ''
888
-                    || $value === null
889
-                )
890
-                && (! isset($args['required'])
891
-                    || $args['required'] === false
892
-                )
893
-            ) {
894
-                //not required and not provided? that's cool
895
-                $validation_result = true;
896
-            } elseif (isset($args['format'])
897
-                && $args['format'] === 'email'
898
-            ) {
899
-                if (! self::_validate_email($value)) {
900
-                    $validation_result = new WP_Error(
901
-                        'rest_invalid_param',
902
-                        esc_html__('The email address is not valid or does not exist.', 'event_espresso')
903
-                    );
904
-                } else {
905
-                    $validation_result = true;
906
-                }
907
-            } else {
908
-                $validation_result = rest_validate_value_from_schema($value, $args, $param);
909
-            }
910
-        }
911
-        if (is_wp_error($validation_result)) {
912
-            return $validation_result;
913
-        }
914
-        return rest_sanitize_request_arg($value, $request, $param);
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * Returns whether or not this email address is vaild. Copied from EE_Email_Valdiation_Strategy::_validate_email()
921
-     * @param $email
922
-     * @return bool
923
-     */
924
-    protected static function _validate_email($email){
925
-        $validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
926
-            ? EE_Registry::instance()->CFG->registration->email_validation_level
927
-            : 'wp_default';
928
-        if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
929
-            // email not in correct {string}@{string} format
930
-            return false;
931
-        } else {
932
-            $atIndex = strrpos( $email, "@" );
933
-            $domain = substr( $email, $atIndex + 1 );
934
-            $local = substr( $email, 0, $atIndex );
935
-            $localLen = strlen( $local );
936
-            $domainLen = strlen( $domain );
937
-            if ( $localLen < 1 || $localLen > 64 ) {
938
-                // local part length exceeded
939
-                return false;
940
-            } else if ( $domainLen < 1 || $domainLen > 255 ) {
941
-                // domain part length exceeded
942
-                return false;
943
-            } else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
944
-                // local part starts or ends with '.'
945
-                return false;
946
-            } else if ( preg_match( '/\\.\\./', $local ) ) {
947
-                // local part has two consecutive dots
948
-                return false;
949
-            } else if ( preg_match( '/\\.\\./', $domain ) ) {
950
-                // domain part has two consecutive dots
951
-                return false;
952
-            } else if ( $validation_level === 'wp_default' ) {
953
-                return is_email( $email );
954
-            } else if (
955
-                ( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
956
-                // plz see http://stackoverflow.com/a/24817336 re: the following regex
957
-                && ! preg_match(
958
-                    '/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
959
-                    $email
960
-                )
961
-            ) {
962
-                return false;
963
-            }
964
-            if ( $validation_level === 'i18n_dns' ) {
965
-                if ( ! checkdnsrr( $domain, "MX" ) ) {
966
-                    // domain not found in MX records
967
-                    return false;
968
-                } else if ( ! checkdnsrr( $domain, "A" ) ) {
969
-                    // domain not found in A records
970
-                    return false;
971
-                }
972
-            }
973
-        }
974
-        // you have successfully run the gauntlet young Padawan
975
-        return true;
976
-    }
977
-
978
-
979
-
980
-    /**
981
-     * Gets routes for the config
982
-     *
983
-     * @return array @see _register_model_routes
984
-     * @deprecated since version 4.9.1
985
-     */
986
-    protected function _register_config_routes()
987
-    {
988
-        $config_routes = array();
989
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
990
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
991
-                $version,
992
-                $hidden_endpoint
993
-            );
994
-        }
995
-        return $config_routes;
996
-    }
997
-
998
-
999
-
1000
-    /**
1001
-     * Gets routes for the config for the specified version
1002
-     *
1003
-     * @param string  $version
1004
-     * @param boolean $hidden_endpoint
1005
-     * @return array
1006
-     */
1007
-    protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1008
-    {
1009
-        return array(
1010
-            'config'    => array(
1011
-                array(
1012
-                    'callback'        => array(
1013
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1014
-                        'handleRequest',
1015
-                    ),
1016
-                    'methods'         => WP_REST_Server::READABLE,
1017
-                    'hidden_endpoint' => $hidden_endpoint,
1018
-                    'callback_args'   => array($version),
1019
-                ),
1020
-            ),
1021
-            'site_info' => array(
1022
-                array(
1023
-                    'callback'        => array(
1024
-                        'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1025
-                        'handleRequestSiteInfo',
1026
-                    ),
1027
-                    'methods'         => WP_REST_Server::READABLE,
1028
-                    'hidden_endpoint' => $hidden_endpoint,
1029
-                    'callback_args'   => array($version),
1030
-                ),
1031
-            ),
1032
-        );
1033
-    }
1034
-
1035
-
1036
-
1037
-    /**
1038
-     * Gets the meta info routes
1039
-     *
1040
-     * @return array @see _register_model_routes
1041
-     * @deprecated since version 4.9.1
1042
-     */
1043
-    protected function _register_meta_routes()
1044
-    {
1045
-        $meta_routes = array();
1046
-        foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1048
-                $version,
1049
-                $hidden_endpoint
1050
-            );
1051
-        }
1052
-        return $meta_routes;
1053
-    }
1054
-
1055
-
1056
-
1057
-    /**
1058
-     * @param string  $version
1059
-     * @param boolean $hidden_endpoint
1060
-     * @return array
1061
-     */
1062
-    protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1063
-    {
1064
-        return array(
1065
-            'resources' => array(
1066
-                array(
1067
-                    'callback'        => array(
1068
-                        'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1069
-                        'handleRequestModelsMeta',
1070
-                    ),
1071
-                    'methods'         => WP_REST_Server::READABLE,
1072
-                    'hidden_endpoint' => $hidden_endpoint,
1073
-                    'callback_args'   => array($version),
1074
-                ),
1075
-            ),
1076
-        );
1077
-    }
1078
-
1079
-
1080
-
1081
-    /**
1082
-     * Tries to hide old 4.6 endpoints from the
1083
-     *
1084
-     * @param array $route_data
1085
-     * @return array
1086
-     */
1087
-    public static function hide_old_endpoints($route_data)
1088
-    {
1089
-        //allow API clients to override which endpoints get hidden, in case
1090
-        //they want to discover particular endpoints
1091
-        //also, we don't have access to the request so we have to just grab it from the superglobal
1092
-        $force_show_ee_namespace = ltrim(
1093
-            EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1094
-            '/'
1095
-        );
1096
-        foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1097
-            foreach ($relative_urls as $resource_name => $endpoints) {
1098
-                foreach ($endpoints as $key => $endpoint) {
1099
-                    //skip schema and other route options
1100
-                    if (! is_numeric($key)) {
1101
-                        continue;
1102
-                    }
1103
-                    //by default, hide "hidden_endpoint"s, unless the request indicates
1104
-                    //to $force_show_ee_namespace, in which case only show that one
1105
-                    //namespace's endpoints (and hide all others)
1106
-                    if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107
-                        || ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108
-                    ) {
1109
-                        $full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1110
-                        unset($route_data[$full_route]);
1111
-                    }
1112
-                }
1113
-            }
1114
-        }
1115
-        return $route_data;
1116
-    }
1117
-
1118
-
1119
-
1120
-    /**
1121
-     * Returns an array describing which versions of core support serving requests for.
1122
-     * Keys are core versions' major and minor version, and values are the
1123
-     * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1124
-     * data by just removing a few models and fields from the responses. However, 4.15 might remove
1125
-     * the answers table entirely, in which case it would be very difficult for
1126
-     * it to serve 4.6-style responses.
1127
-     * Versions of core that are missing from this array are unknowns.
1128
-     * previous ver
1129
-     *
1130
-     * @return array
1131
-     */
1132
-    public static function version_compatibilities()
1133
-    {
1134
-        return apply_filters(
1135
-            'FHEE__EED_Core_REST_API__version_compatibilities',
1136
-            array(
1137
-                '4.8.29' => '4.8.29',
1138
-                '4.8.33' => '4.8.29',
1139
-                '4.8.34' => '4.8.29',
1140
-                '4.8.36' => '4.8.29',
1141
-            )
1142
-        );
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * Gets the latest API version served. Eg if there
1149
-     * are two versions served of the API, 4.8.29 and 4.8.32, and
1150
-     * we are on core version 4.8.34, it will return the string "4.8.32"
1151
-     *
1152
-     * @return string
1153
-     */
1154
-    public static function latest_rest_api_version()
1155
-    {
1156
-        $versions_served = \EED_Core_Rest_Api::versions_served();
1157
-        $versions_served_keys = array_keys($versions_served);
1158
-        return end($versions_served_keys);
1159
-    }
1160
-
1161
-
1162
-
1163
-    /**
1164
-     * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1165
-     * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1166
-     * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1167
-     * We also indicate whether or not this version should be put in the index or not
1168
-     *
1169
-     * @return array keys are API version numbers (just major and minor numbers), and values
1170
-     * are whether or not they should be hidden
1171
-     */
1172
-    public static function versions_served()
1173
-    {
1174
-        $versions_served = array();
1175
-        $possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1176
-        $lowest_compatible_version = end($possibly_served_versions);
1177
-        reset($possibly_served_versions);
1178
-        $versions_served_historically = array_keys($possibly_served_versions);
1179
-        $latest_version = end($versions_served_historically);
1180
-        reset($versions_served_historically);
1181
-        //for each version of core we have ever served:
1182
-        foreach ($versions_served_historically as $key_versioned_endpoint) {
1183
-            //if it's not above the current core version, and it's compatible with the current version of core
1184
-            if ($key_versioned_endpoint == $latest_version) {
1185
-                //don't hide the latest version in the index
1186
-                $versions_served[$key_versioned_endpoint] = false;
1187
-            } elseif ($key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1188
-                && $key_versioned_endpoint >= $lowest_compatible_version
1189
-            ) {
1190
-                //include, but hide, previous versions which are still supported
1191
-                $versions_served[$key_versioned_endpoint] = true;
1192
-            } elseif (apply_filters(
1193
-                'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1194
-                false,
1195
-                $possibly_served_versions
1196
-            )) {
1197
-                //if a version is no longer supported, don't include it in index or list of versions served
1198
-                $versions_served[$key_versioned_endpoint] = true;
1199
-            }
1200
-        }
1201
-        return $versions_served;
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Gets the major and minor version of EE core's version string
1208
-     *
1209
-     * @return string
1210
-     */
1211
-    public static function core_version()
1212
-    {
1213
-        return apply_filters(
1214
-            'FHEE__EED_Core_REST_API__core_version',
1215
-            implode(
1216
-                '.',
1217
-                array_slice(
1218
-                    explode(
1219
-                        '.',
1220
-                        espresso_version()
1221
-                    ),
1222
-                0,
1223
-                3
1224
-                )
1225
-            )
1226
-        );
1227
-    }
1228
-
1229
-
1230
-
1231
-    /**
1232
-     * Gets the default limit that should be used when querying for resources
1233
-     *
1234
-     * @return int
1235
-     */
1236
-    public static function get_default_query_limit()
1237
-    {
1238
-        //we actually don't use a const because we want folks to always use
1239
-        //this method, not the const directly
1240
-        return apply_filters(
1241
-            'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1242
-            50
1243
-        );
1244
-    }
1245
-
1246
-
1247
-
1248
-    /**
1249
-     *    run - initial module setup
1250
-     *
1251
-     * @access    public
1252
-     * @param  WP $WP
1253
-     * @return    void
1254
-     */
1255
-    public function run($WP)
1256
-    {
1257
-    }
25
+	const ee_api_namespace_for_regex = 'ee\/v([^/]*)\/';
26
+
27
+	const saved_routes_option_names  = 'ee_core_routes';
28
+
29
+	/**
30
+	 * string used in _links response bodies to make them globally unique.
31
+	 *
32
+	 * @see http://v2.wp-api.org/extending/linking/
33
+	 */
34
+	const ee_api_link_namespace = 'https://api.eventespresso.com/';
35
+
36
+	/**
37
+	 * @var CalculatedModelFields
38
+	 */
39
+	protected static $_field_calculator = null;
40
+
41
+
42
+
43
+	/**
44
+	 * @return EED_Core_Rest_Api
45
+	 */
46
+	public static function instance()
47
+	{
48
+		self::$_field_calculator = new CalculatedModelFields();
49
+		return parent::get_instance(__CLASS__);
50
+	}
51
+
52
+
53
+
54
+	/**
55
+	 *    set_hooks - for hooking into EE Core, other modules, etc
56
+	 *
57
+	 * @access    public
58
+	 * @return    void
59
+	 */
60
+	public static function set_hooks()
61
+	{
62
+		self::set_hooks_both();
63
+	}
64
+
65
+
66
+
67
+	/**
68
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
69
+	 *
70
+	 * @access    public
71
+	 * @return    void
72
+	 */
73
+	public static function set_hooks_admin()
74
+	{
75
+		self::set_hooks_both();
76
+	}
77
+
78
+
79
+
80
+	public static function set_hooks_both()
81
+	{
82
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'register_routes'), 10);
83
+		add_action('rest_api_init', array('EED_Core_Rest_Api', 'set_hooks_rest_api'), 5);
84
+		add_filter('rest_route_data', array('EED_Core_Rest_Api', 'hide_old_endpoints'), 10, 2);
85
+		add_filter('rest_index',
86
+			array('EventEspresso\core\libraries\rest_api\controllers\model\Meta', 'filterEeMetadataIntoIndex'));
87
+		EED_Core_Rest_Api::invalidate_cached_route_data_on_version_change();
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * sets up hooks which only need to be included as part of REST API requests;
94
+	 * other requests like to the frontend or admin etc don't need them
95
+	 */
96
+	public static function set_hooks_rest_api()
97
+	{
98
+		//set hooks which account for changes made to the API
99
+		EED_Core_Rest_Api::_set_hooks_for_changes();
100
+	}
101
+
102
+
103
+
104
+	/**
105
+	 * public wrapper of _set_hooks_for_changes.
106
+	 * Loads all the hooks which make requests to old versions of the API
107
+	 * appear the same as they always did
108
+	 */
109
+	public static function set_hooks_for_changes()
110
+	{
111
+		self::_set_hooks_for_changes();
112
+	}
113
+
114
+
115
+
116
+	/**
117
+	 * Loads all the hooks which make requests to old versions of the API
118
+	 * appear the same as they always did
119
+	 */
120
+	protected static function _set_hooks_for_changes()
121
+	{
122
+		$folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
123
+		foreach ($folder_contents as $classname_in_namespace => $filepath) {
124
+			//ignore the base parent class
125
+			//and legacy named classes
126
+			if ($classname_in_namespace === 'ChangesInBase'
127
+				|| strpos($classname_in_namespace, 'Changes_In_') === 0
128
+			) {
129
+				continue;
130
+			}
131
+			$full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
132
+			if (class_exists($full_classname)) {
133
+				$instance_of_class = new $full_classname;
134
+				if ($instance_of_class instanceof ChangesInBase) {
135
+					$instance_of_class->setHooks();
136
+				}
137
+			}
138
+		}
139
+	}
140
+
141
+
142
+
143
+	/**
144
+	 * Filters the WP routes to add our EE-related ones. This takes a bit of time
145
+	 * so we actually prefer to only do it when an EE plugin is activated or upgraded
146
+	 */
147
+	public static function register_routes()
148
+	{
149
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_routes) {
150
+			foreach ($relative_routes as $relative_route => $data_for_multiple_endpoints) {
151
+				/**
152
+				 * @var array $data_for_multiple_endpoints numerically indexed array
153
+				 *                                         but can also contain route options like {
154
+				 * @type array    $schema                      {
155
+				 * @type callable $schema_callback
156
+				 * @type array    $callback_args               arguments that will be passed to the callback, after the
157
+				 * WP_REST_Request of course
158
+				 * }
159
+				 * }
160
+				 */
161
+				//when registering routes, register all the endpoints' data at the same time
162
+				$multiple_endpoint_args = array();
163
+				foreach ($data_for_multiple_endpoints as $endpoint_key => $data_for_single_endpoint) {
164
+					/**
165
+					 * @var array     $data_for_single_endpoint {
166
+					 * @type callable $callback
167
+					 * @type string methods
168
+					 * @type array args
169
+					 * @type array _links
170
+					 * @type array    $callback_args            arguments that will be passed to the callback, after the
171
+					 * WP_REST_Request of course
172
+					 * }
173
+					 */
174
+					//skip route options
175
+					if (! is_numeric($endpoint_key)) {
176
+						continue;
177
+					}
178
+					if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179
+						throw new EE_Error(
180
+							esc_html__(
181
+								// @codingStandardsIgnoreStart
182
+								'Endpoint configuration data needs to have entries "callback" (callable) and "methods" (comma-separated list of accepts HTTP methods).',
183
+								// @codingStandardsIgnoreEnd
184
+								'event_espresso')
185
+						);
186
+					}
187
+					$callback = $data_for_single_endpoint['callback'];
188
+					$single_endpoint_args = array(
189
+						'methods' => $data_for_single_endpoint['methods'],
190
+						'args'    => isset($data_for_single_endpoint['args']) ? $data_for_single_endpoint['args']
191
+							: array(),
192
+					);
193
+					if (isset($data_for_single_endpoint['_links'])) {
194
+						$single_endpoint_args['_links'] = $data_for_single_endpoint['_links'];
195
+					}
196
+					if (isset($data_for_single_endpoint['callback_args'])) {
197
+						$callback_args = $data_for_single_endpoint['callback_args'];
198
+						$single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
199
+							$callback,
200
+							$callback_args
201
+						) {
202
+							array_unshift($callback_args, $request);
203
+							return call_user_func_array(
204
+								$callback,
205
+								$callback_args
206
+							);
207
+						};
208
+					} else {
209
+						$single_endpoint_args['callback'] = $data_for_single_endpoint['callback'];
210
+					}
211
+					$multiple_endpoint_args[] = $single_endpoint_args;
212
+				}
213
+				if (isset($data_for_multiple_endpoints['schema'])) {
214
+					$schema_route_data = $data_for_multiple_endpoints['schema'];
215
+					$schema_callback = $schema_route_data['schema_callback'];
216
+					$callback_args = $schema_route_data['callback_args'];
217
+					$multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
218
+						return call_user_func_array(
219
+							$schema_callback,
220
+							$callback_args
221
+						);
222
+					};
223
+				}
224
+				register_rest_route(
225
+					$namespace,
226
+					$relative_route,
227
+					$multiple_endpoint_args
228
+				);
229
+			}
230
+		}
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * Checks if there was a version change or something that merits invalidating the cached
237
+	 * route data. If so, invalidates the cached route data so that it gets refreshed
238
+	 * next time the WP API is used
239
+	 */
240
+	public static function invalidate_cached_route_data_on_version_change()
241
+	{
242
+		if (EE_System::instance()->detect_req_type() != EE_System::req_type_normal) {
243
+			EED_Core_Rest_Api::invalidate_cached_route_data();
244
+		}
245
+		foreach (EE_Registry::instance()->addons as $addon) {
246
+			if ($addon instanceof EE_Addon && $addon->detect_req_type() != EE_System::req_type_normal) {
247
+				EED_Core_Rest_Api::invalidate_cached_route_data();
248
+			}
249
+		}
250
+	}
251
+
252
+
253
+
254
+	/**
255
+	 * Removes the cached route data so it will get refreshed next time the WP API is used
256
+	 */
257
+	public static function invalidate_cached_route_data()
258
+	{
259
+		//delete the saved EE REST API routes
260
+		foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
+			delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
262
+		}
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * Gets the EE route data
269
+	 *
270
+	 * @return array top-level key is the namespace, next-level key is the route and its value is array{
271
+	 * @type string|array $callback
272
+	 * @type string       $methods
273
+	 * @type boolean      $hidden_endpoint
274
+	 * }
275
+	 */
276
+	public static function get_ee_route_data()
277
+	{
278
+		$ee_routes = array();
279
+		foreach (self::versions_served() as $version => $hidden_endpoints) {
280
+			$ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
281
+				$version,
282
+				$hidden_endpoints
283
+			);
284
+		}
285
+		return $ee_routes;
286
+	}
287
+
288
+
289
+
290
+	/**
291
+	 * Gets the EE route data from the wp options if it exists already,
292
+	 * otherwise re-generates it and saves it to the option
293
+	 *
294
+	 * @param string  $version
295
+	 * @param boolean $hidden_endpoints
296
+	 * @return array
297
+	 */
298
+	protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299
+	{
300
+		$ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
+		if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302
+			$ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303
+		}
304
+		return $ee_routes;
305
+	}
306
+
307
+
308
+
309
+	/**
310
+	 * Saves the EE REST API route data to a wp option and returns it
311
+	 *
312
+	 * @param string  $version
313
+	 * @param boolean $hidden_endpoints
314
+	 * @return mixed|null
315
+	 */
316
+	protected static function _save_ee_route_data_for_version($version, $hidden_endpoints = false)
317
+	{
318
+		$instance = self::instance();
319
+		$routes = apply_filters(
320
+			'EED_Core_Rest_Api__save_ee_route_data_for_version__routes',
321
+			array_replace_recursive(
322
+				$instance->_get_config_route_data_for_version($version, $hidden_endpoints),
323
+				$instance->_get_meta_route_data_for_version($version, $hidden_endpoints),
324
+				$instance->_get_model_route_data_for_version($version, $hidden_endpoints),
325
+				$instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326
+			)
327
+		);
328
+		$option_name = self::saved_routes_option_names . $version;
329
+		if (get_option($option_name)) {
330
+			update_option($option_name, $routes, true);
331
+		} else {
332
+			add_option($option_name, $routes, null, 'no');
333
+		}
334
+		return $routes;
335
+	}
336
+
337
+
338
+
339
+	/**
340
+	 * Calculates all the EE routes and saves it to a WordPress option so we don't
341
+	 * need to calculate it on every request
342
+	 *
343
+	 * @deprecated since version 4.9.1
344
+	 * @return void
345
+	 */
346
+	public static function save_ee_routes()
347
+	{
348
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
349
+			$instance = self::instance();
350
+			$routes = apply_filters(
351
+				'EED_Core_Rest_Api__save_ee_routes__routes',
352
+				array_replace_recursive(
353
+					$instance->_register_config_routes(),
354
+					$instance->_register_meta_routes(),
355
+					$instance->_register_model_routes(),
356
+					$instance->_register_rpc_routes()
357
+				)
358
+			);
359
+			update_option(self::saved_routes_option_names, $routes, true);
360
+		}
361
+	}
362
+
363
+
364
+
365
+	/**
366
+	 * Gets all the route information relating to EE models
367
+	 *
368
+	 * @return array @see get_ee_route_data
369
+	 * @deprecated since version 4.9.1
370
+	 */
371
+	protected function _register_model_routes()
372
+	{
373
+		$model_routes = array();
374
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
375
+			$model_routes[EED_Core_Rest_Api::ee_api_namespace
376
+						  . $version] = $this->_get_config_route_data_for_version($version, $hidden_endpoint);
377
+		}
378
+		return $model_routes;
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * Decides whether or not to add write endpoints for this model.
385
+	 *
386
+	 * Currently, this defaults to exclude all global tables and models
387
+	 * which would allow inserting WP core data (we don't want to duplicate
388
+	 * what WP API does, as it's unnecessary, extra work, and potentially extra bugs)
389
+	 * @param EEM_Base $model
390
+	 * @return bool
391
+	 */
392
+	public static function should_have_write_endpoints(EEM_Base $model)
393
+	{
394
+		if ($model->is_wp_core_model()){
395
+			return false;
396
+		}
397
+		foreach($model->get_tables() as $table){
398
+			if( $table->is_global()){
399
+				return false;
400
+			}
401
+		}
402
+		return true;
403
+	}
404
+
405
+
406
+
407
+	/**
408
+	 * Gets the names of all models which should have plural routes (eg `ee/v4.8.36/events`)
409
+	 * in this versioned namespace of EE4
410
+	 * @param $version
411
+	 * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412
+	 */
413
+	public static function model_names_with_plural_routes($version){
414
+		$model_version_info = new ModelVersionInfo($version);
415
+		$models_to_register = $model_version_info->modelsForRequestedVersion();
416
+		//let's not bother having endpoints for extra metas
417
+		unset($models_to_register['Extra_Meta']);
418
+		unset($models_to_register['Extra_Join']);
419
+		unset($models_to_register['Post_Meta']);
420
+		return apply_filters(
421
+			'FHEE__EED_Core_REST_API___register_model_routes',
422
+			$models_to_register
423
+		);
424
+	}
425
+
426
+
427
+
428
+	/**
429
+	 * Gets the route data for EE models in the specified version
430
+	 *
431
+	 * @param string  $version
432
+	 * @param boolean $hidden_endpoint
433
+	 * @return array
434
+	 */
435
+	protected function _get_model_route_data_for_version($version, $hidden_endpoint = false)
436
+	{
437
+		$model_routes = array();
438
+		$model_version_info = new ModelVersionInfo($version);
439
+		foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440
+			$model = \EE_Registry::instance()->load_model($model_name);
441
+			//if this isn't a valid model then let's skip iterate to the next item in the loop.
442
+			if (! $model instanceof EEM_Base) {
443
+				continue;
444
+			}
445
+			//yes we could just register one route for ALL models, but then they wouldn't show up in the index
446
+			$plural_model_route = EED_Core_Rest_Api::get_collection_route($model_name);
447
+			$singular_model_route = EED_Core_Rest_Api::get_entity_route($model_name, '(?P<id>[^\/]+)');
448
+			$model_routes[$plural_model_route] = array(
449
+				array(
450
+					'callback'        => array(
451
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
452
+						'handleRequestGetAll',
453
+					),
454
+					'callback_args'   => array($version, $model_name),
455
+					'methods'         => WP_REST_Server::READABLE,
456
+					'hidden_endpoint' => $hidden_endpoint,
457
+					'args'            => $this->_get_read_query_params($model, $version),
458
+					'_links'          => array(
459
+						'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
460
+					),
461
+				),
462
+				'schema' => array(
463
+					'schema_callback' => array(
464
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
465
+						'handleSchemaRequest',
466
+					),
467
+					'callback_args'   => array($version, $model_name),
468
+				),
469
+			);
470
+			$model_routes[$singular_model_route] = array(
471
+				array(
472
+					'callback'        => array(
473
+						'EventEspresso\core\libraries\rest_api\controllers\model\Read',
474
+						'handleRequestGetOne',
475
+					),
476
+					'callback_args'   => array($version, $model_name),
477
+					'methods'         => WP_REST_Server::READABLE,
478
+					'hidden_endpoint' => $hidden_endpoint,
479
+					'args'            => $this->_get_response_selection_query_params($model, $version),
480
+				),
481
+			);
482
+			if( apply_filters(
483
+				'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484
+				$this->should_have_write_endpoints($model),
485
+				$model
486
+			)){
487
+				$model_routes[$plural_model_route][] = array(
488
+					'callback'        => array(
489
+						'EventEspresso\core\libraries\rest_api\controllers\model\Write',
490
+						'handleRequestInsert',
491
+					),
492
+					'callback_args'   => array($version, $model_name),
493
+					'methods'         => WP_REST_Server::CREATABLE,
494
+					'hidden_endpoint' => $hidden_endpoint,
495
+					'args'            => $this->_get_write_params($model_name, $model_version_info, true),
496
+				);
497
+				$model_routes[$singular_model_route] = array_merge(
498
+					$model_routes[$singular_model_route],
499
+					array(
500
+						array(
501
+							'callback'        => array(
502
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
503
+								'handleRequestUpdate',
504
+							),
505
+							'callback_args'   => array($version, $model_name),
506
+							'methods'         => WP_REST_Server::EDITABLE,
507
+							'hidden_endpoint' => $hidden_endpoint,
508
+							'args'            => $this->_get_write_params($model_name, $model_version_info, false),
509
+						),
510
+						array(
511
+							'callback'        => array(
512
+								'EventEspresso\core\libraries\rest_api\controllers\model\Write',
513
+								'handleRequestDelete',
514
+							),
515
+							'callback_args'   => array($version, $model_name),
516
+							'methods'         => WP_REST_Server::DELETABLE,
517
+							'hidden_endpoint' => $hidden_endpoint,
518
+							'args'            => $this->_get_delete_query_params($model, $version),
519
+						)
520
+					)
521
+				);
522
+			}
523
+			foreach ($model->relation_settings() as $relation_name => $relation_obj) {
524
+
525
+				$related_route = EED_Core_Rest_Api::get_relation_route_via(
526
+					$model_name,
527
+					'(?P<id>[^\/]+)',
528
+					$relation_obj
529
+				);
530
+				$endpoints = array(
531
+					array(
532
+						'callback'        => array(
533
+							'EventEspresso\core\libraries\rest_api\controllers\model\Read',
534
+							'handleRequestGetRelated',
535
+						),
536
+						'callback_args'   => array($version, $model_name, $relation_name),
537
+						'methods'         => WP_REST_Server::READABLE,
538
+						'hidden_endpoint' => $hidden_endpoint,
539
+						'args'            => $this->_get_read_query_params($relation_obj->get_other_model(), $version),
540
+					),
541
+				);
542
+				$model_routes[$related_route] = $endpoints;
543
+			}
544
+		}
545
+		return $model_routes;
546
+	}
547
+
548
+
549
+
550
+	/**
551
+	 * Gets the relative URI to a model's REST API plural route, after the EE4 versioned namespace,
552
+	 * excluding the preceding slash.
553
+	 * Eg you pass get_plural_route_to('Event') = 'events'
554
+	 * @param string $model_name eg Event or Venue
555
+	 * @return string
556
+	 */
557
+	public static function get_collection_route($model_name)
558
+	{
559
+		return EEH_Inflector::pluralize_and_lower($model_name);
560
+	}
561
+
562
+
563
+
564
+	/**
565
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
566
+	 * excluding the preceding slash.
567
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
568
+	 * @param string $model_name eg Event or Venue
569
+	 * @param string $id
570
+	 * @return string
571
+	 */
572
+	public static function get_entity_route($model_name, $id)
573
+	{
574
+		return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
575
+	}
576
+
577
+
578
+	/**
579
+	 * Gets the relative URI to a model's REST API singular route, after the EE4 versioned namespace,
580
+	 * excluding the preceding slash.
581
+	 * Eg you pass get_plural_route_to('Event', 12) = 'events/12'
582
+	 *
583
+	 * @param string                $model_name eg Event or Venue
584
+	 * @param string                $id
585
+	 * @param EE_Model_Relation_Base $relation_obj
586
+	 * @return string
587
+	 */
588
+	public static function get_relation_route_via($model_name, $id, $relation_obj)
589
+	{
590
+		$related_model_name_endpoint_part = ModelRead::getRelatedEntityName(
591
+			$relation_obj->get_other_model()->get_this_model_name(),
592
+			$relation_obj
593
+		);
594
+		return EED_Core_Rest_Api::get_entity_route($model_name, $id) . '/' . $related_model_name_endpoint_part;
595
+	}
596
+
597
+
598
+
599
+	/**
600
+	 * Adds onto the $relative_route the EE4 REST API versioned namespace.
601
+	 * Eg if given '4.8.36' and 'events', will return 'ee/v4.8.36/events'
602
+	 * @param string $relative_route
603
+	 * @param string $version
604
+	 * @return string
605
+	 */
606
+	public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
+		return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * Adds all the RPC-style routes (remote procedure call-like routes, ie
614
+	 * routes that don't conform to the traditional REST CRUD-style).
615
+	 *
616
+	 * @deprecated since 4.9.1
617
+	 */
618
+	protected function _register_rpc_routes()
619
+	{
620
+		$routes = array();
621
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
622
+			$routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
623
+				$version,
624
+				$hidden_endpoint
625
+			);
626
+		}
627
+		return $routes;
628
+	}
629
+
630
+
631
+
632
+	/**
633
+	 * @param string  $version
634
+	 * @param boolean $hidden_endpoint
635
+	 * @return array
636
+	 */
637
+	protected function _get_rpc_route_data_for_version($version, $hidden_endpoint = false)
638
+	{
639
+		$this_versions_routes = array();
640
+		//checkin endpoint
641
+		$this_versions_routes['registrations/(?P<REG_ID>\d+)/toggle_checkin_for_datetime/(?P<DTT_ID>\d+)'] = array(
642
+			array(
643
+				'callback'        => array(
644
+					'EventEspresso\core\libraries\rest_api\controllers\rpc\Checkin',
645
+					'handleRequestToggleCheckin',
646
+				),
647
+				'methods'         => WP_REST_Server::CREATABLE,
648
+				'hidden_endpoint' => $hidden_endpoint,
649
+				'args'            => array(
650
+					'force' => array(
651
+						'required'    => false,
652
+						'default'     => false,
653
+						'description' => __(
654
+							// @codingStandardsIgnoreStart
655
+							'Whether to force toggle checkin, or to verify the registration status and allowed ticket uses',
656
+							// @codingStandardsIgnoreEnd
657
+							'event_espresso'
658
+						),
659
+					),
660
+				),
661
+				'callback_args'   => array($version),
662
+			),
663
+		);
664
+		return apply_filters(
665
+			'FHEE__EED_Core_Rest_Api___register_rpc_routes__this_versions_routes',
666
+			$this_versions_routes,
667
+			$version,
668
+			$hidden_endpoint
669
+		);
670
+	}
671
+
672
+
673
+
674
+	/**
675
+	 * Gets the query params that can be used when request one or many
676
+	 *
677
+	 * @param EEM_Base $model
678
+	 * @param string   $version
679
+	 * @return array
680
+	 */
681
+	protected function _get_response_selection_query_params(\EEM_Base $model, $version)
682
+	{
683
+		return apply_filters(
684
+			'FHEE__EED_Core_Rest_Api___get_response_selection_query_params',
685
+			array(
686
+				'include'   => array(
687
+					'required' => false,
688
+					'default'  => '*',
689
+					'type'     => 'string',
690
+				),
691
+				'calculate' => array(
692
+					'required'          => false,
693
+					'default'           => '',
694
+					'enum'              => self::$_field_calculator->retrieveCalculatedFieldsForModel($model),
695
+					'type'              => 'string',
696
+					//because we accept a CSV'd list of the enumerated strings, WP core validation and sanitization
697
+					//freaks out. We'll just validate this argument while handling the request
698
+					'validate_callback' => null,
699
+					'sanitize_callback' => null,
700
+				),
701
+			),
702
+			$model,
703
+			$version
704
+		);
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * Gets the parameters acceptable for delete requests
711
+	 *
712
+	 * @param \EEM_Base $model
713
+	 * @param string    $version
714
+	 * @return array
715
+	 */
716
+	protected function _get_delete_query_params(\EEM_Base $model, $version)
717
+	{
718
+		$params_for_delete = array(
719
+			'allow_blocking' => array(
720
+				'required' => false,
721
+				'default'  => true,
722
+				'type'     => 'boolean',
723
+			),
724
+		);
725
+		$params_for_delete['force'] = array(
726
+			'required' => false,
727
+			'default'  => false,
728
+			'type'     => 'boolean',
729
+		);
730
+		return apply_filters(
731
+			'FHEE__EED_Core_Rest_Api___get_delete_query_params',
732
+			$params_for_delete,
733
+			$model,
734
+			$version
735
+		);
736
+	}
737
+
738
+
739
+
740
+	/**
741
+	 * Gets info about reading query params that are acceptable
742
+	 *
743
+	 * @param \EEM_Base $model eg 'Event' or 'Venue'
744
+	 * @param  string   $version
745
+	 * @return array    describing the args acceptable when querying this model
746
+	 * @throws \EE_Error
747
+	 */
748
+	protected function _get_read_query_params(\EEM_Base $model, $version)
749
+	{
750
+		$default_orderby = array();
751
+		foreach ($model->get_combined_primary_key_fields() as $key_field) {
752
+			$default_orderby[$key_field->get_name()] = 'ASC';
753
+		}
754
+		return array_merge(
755
+			$this->_get_response_selection_query_params($model, $version),
756
+			array(
757
+				'where'    => array(
758
+					'required' => false,
759
+					'default'  => array(),
760
+					'type'     => 'object',
761
+				),
762
+				'limit'    => array(
763
+					'required' => false,
764
+					'default'  => EED_Core_Rest_Api::get_default_query_limit(),
765
+					'type'     => array(
766
+						'object',
767
+						'string',
768
+						'integer',
769
+					),
770
+				),
771
+				'order_by' => array(
772
+					'required' => false,
773
+					'default'  => $default_orderby,
774
+					'type'     => array(
775
+						'object',
776
+						'string',
777
+					),
778
+				),
779
+				'group_by' => array(
780
+					'required' => false,
781
+					'default'  => null,
782
+					'type'     => array(
783
+						'object',
784
+						'string',
785
+					),
786
+				),
787
+				'having'   => array(
788
+					'required' => false,
789
+					'default'  => null,
790
+					'type'     => 'object',
791
+				),
792
+				'caps'     => array(
793
+					'required' => false,
794
+					'default'  => EEM_Base::caps_read,
795
+					'type'     => 'string',
796
+				),
797
+			)
798
+		);
799
+	}
800
+
801
+
802
+
803
+	/**
804
+	 * Gets parameter information for a model regarding writing data
805
+	 *
806
+	 * @param string           $model_name
807
+	 * @param ModelVersionInfo $model_version_info
808
+	 * @param boolean          $create                                       whether this is for request to create (in which case we need
809
+	 *                                                                       all required params) or just to update (in which case we don't need those on every request)
810
+	 * @return array
811
+	 */
812
+	protected function _get_write_params(
813
+		$model_name,
814
+		ModelVersionInfo $model_version_info,
815
+		$create = false
816
+	) {
817
+		$model = EE_Registry::instance()->load_model($model_name);
818
+		$fields = $model_version_info->fieldsOnModelInThisVersion($model);
819
+		$args_info = array();
820
+		foreach ($fields as $field_name => $field_obj) {
821
+			if ($field_obj->is_auto_increment()) {
822
+				//totally ignore auto increment IDs
823
+				continue;
824
+			}
825
+			$arg_info = $field_obj->getSchema();
826
+			$required = $create && ! $field_obj->is_nullable() && $field_obj->get_default_value() === null;
827
+			$arg_info['required'] = $required;
828
+			//remove the read-only flag. If it were read-only we wouldn't list it as an argument while writing, right?
829
+			unset($arg_info['readonly']);
830
+			$schema_properties = $field_obj->getSchemaProperties();
831
+			if ($field_obj->getSchemaType() === 'object'
832
+				&& isset($schema_properties['raw'])
833
+			) {
834
+				//if there's a "raw" form of this argument, use those properties instead
835
+				$arg_info = array_replace(
836
+					$arg_info,
837
+					$schema_properties['raw']
838
+				);
839
+			}
840
+			$arg_info['default'] = ModelDataTranslator::prepareFieldValueForJson(
841
+				$field_obj,
842
+				$field_obj->get_default_value(),
843
+				$model_version_info->requestedVersion()
844
+			);
845
+			//we do our own validation and sanitization within the controller
846
+			$arg_info['sanitize_callback'] =
847
+				array(
848
+					'EED_Core_Rest_Api',
849
+					'default_sanitize_callback',
850
+				);
851
+			$args_info[$field_name] = $arg_info;
852
+			if ($field_obj instanceof EE_Datetime_Field) {
853
+				$gmt_arg_info = $arg_info;
854
+				$gmt_arg_info['description'] = sprintf(
855
+					esc_html__(
856
+						'%1$s - the value for this field in UTC. Ignored if %2$s is provided.',
857
+						'event_espresso'
858
+					),
859
+					$field_obj->get_nicename(),
860
+					$field_name
861
+				);
862
+				$args_info[$field_name . '_gmt'] = $gmt_arg_info;
863
+			}
864
+		}
865
+		return $args_info;
866
+	}
867
+
868
+
869
+
870
+	/**
871
+	 * Replacement for WP API's 'rest_parse_request_arg'. If the value is blank but not required, don't bother validating it.
872
+	 * Also, it uses our email validation instead of WP API's default.
873
+	 * @param                 $value
874
+	 * @param WP_REST_Request $request
875
+	 * @param                 $param
876
+	 * @return bool|true|WP_Error
877
+	 */
878
+	public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
879
+	{
880
+		$attributes = $request->get_attributes();
881
+		if (! isset($attributes['args'][$param])
882
+			|| ! is_array($attributes['args'][$param])) {
883
+			$validation_result = true;
884
+		} else {
885
+			$args = $attributes['args'][$param];
886
+			if ((
887
+					$value === ''
888
+					|| $value === null
889
+				)
890
+				&& (! isset($args['required'])
891
+					|| $args['required'] === false
892
+				)
893
+			) {
894
+				//not required and not provided? that's cool
895
+				$validation_result = true;
896
+			} elseif (isset($args['format'])
897
+				&& $args['format'] === 'email'
898
+			) {
899
+				if (! self::_validate_email($value)) {
900
+					$validation_result = new WP_Error(
901
+						'rest_invalid_param',
902
+						esc_html__('The email address is not valid or does not exist.', 'event_espresso')
903
+					);
904
+				} else {
905
+					$validation_result = true;
906
+				}
907
+			} else {
908
+				$validation_result = rest_validate_value_from_schema($value, $args, $param);
909
+			}
910
+		}
911
+		if (is_wp_error($validation_result)) {
912
+			return $validation_result;
913
+		}
914
+		return rest_sanitize_request_arg($value, $request, $param);
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * Returns whether or not this email address is vaild. Copied from EE_Email_Valdiation_Strategy::_validate_email()
921
+	 * @param $email
922
+	 * @return bool
923
+	 */
924
+	protected static function _validate_email($email){
925
+		$validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
926
+			? EE_Registry::instance()->CFG->registration->email_validation_level
927
+			: 'wp_default';
928
+		if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
929
+			// email not in correct {string}@{string} format
930
+			return false;
931
+		} else {
932
+			$atIndex = strrpos( $email, "@" );
933
+			$domain = substr( $email, $atIndex + 1 );
934
+			$local = substr( $email, 0, $atIndex );
935
+			$localLen = strlen( $local );
936
+			$domainLen = strlen( $domain );
937
+			if ( $localLen < 1 || $localLen > 64 ) {
938
+				// local part length exceeded
939
+				return false;
940
+			} else if ( $domainLen < 1 || $domainLen > 255 ) {
941
+				// domain part length exceeded
942
+				return false;
943
+			} else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
944
+				// local part starts or ends with '.'
945
+				return false;
946
+			} else if ( preg_match( '/\\.\\./', $local ) ) {
947
+				// local part has two consecutive dots
948
+				return false;
949
+			} else if ( preg_match( '/\\.\\./', $domain ) ) {
950
+				// domain part has two consecutive dots
951
+				return false;
952
+			} else if ( $validation_level === 'wp_default' ) {
953
+				return is_email( $email );
954
+			} else if (
955
+				( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
956
+				// plz see http://stackoverflow.com/a/24817336 re: the following regex
957
+				&& ! preg_match(
958
+					'/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
959
+					$email
960
+				)
961
+			) {
962
+				return false;
963
+			}
964
+			if ( $validation_level === 'i18n_dns' ) {
965
+				if ( ! checkdnsrr( $domain, "MX" ) ) {
966
+					// domain not found in MX records
967
+					return false;
968
+				} else if ( ! checkdnsrr( $domain, "A" ) ) {
969
+					// domain not found in A records
970
+					return false;
971
+				}
972
+			}
973
+		}
974
+		// you have successfully run the gauntlet young Padawan
975
+		return true;
976
+	}
977
+
978
+
979
+
980
+	/**
981
+	 * Gets routes for the config
982
+	 *
983
+	 * @return array @see _register_model_routes
984
+	 * @deprecated since version 4.9.1
985
+	 */
986
+	protected function _register_config_routes()
987
+	{
988
+		$config_routes = array();
989
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
990
+			$config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
991
+				$version,
992
+				$hidden_endpoint
993
+			);
994
+		}
995
+		return $config_routes;
996
+	}
997
+
998
+
999
+
1000
+	/**
1001
+	 * Gets routes for the config for the specified version
1002
+	 *
1003
+	 * @param string  $version
1004
+	 * @param boolean $hidden_endpoint
1005
+	 * @return array
1006
+	 */
1007
+	protected function _get_config_route_data_for_version($version, $hidden_endpoint)
1008
+	{
1009
+		return array(
1010
+			'config'    => array(
1011
+				array(
1012
+					'callback'        => array(
1013
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1014
+						'handleRequest',
1015
+					),
1016
+					'methods'         => WP_REST_Server::READABLE,
1017
+					'hidden_endpoint' => $hidden_endpoint,
1018
+					'callback_args'   => array($version),
1019
+				),
1020
+			),
1021
+			'site_info' => array(
1022
+				array(
1023
+					'callback'        => array(
1024
+						'EventEspresso\core\libraries\rest_api\controllers\config\Read',
1025
+						'handleRequestSiteInfo',
1026
+					),
1027
+					'methods'         => WP_REST_Server::READABLE,
1028
+					'hidden_endpoint' => $hidden_endpoint,
1029
+					'callback_args'   => array($version),
1030
+				),
1031
+			),
1032
+		);
1033
+	}
1034
+
1035
+
1036
+
1037
+	/**
1038
+	 * Gets the meta info routes
1039
+	 *
1040
+	 * @return array @see _register_model_routes
1041
+	 * @deprecated since version 4.9.1
1042
+	 */
1043
+	protected function _register_meta_routes()
1044
+	{
1045
+		$meta_routes = array();
1046
+		foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
+			$meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1048
+				$version,
1049
+				$hidden_endpoint
1050
+			);
1051
+		}
1052
+		return $meta_routes;
1053
+	}
1054
+
1055
+
1056
+
1057
+	/**
1058
+	 * @param string  $version
1059
+	 * @param boolean $hidden_endpoint
1060
+	 * @return array
1061
+	 */
1062
+	protected function _get_meta_route_data_for_version($version, $hidden_endpoint = false)
1063
+	{
1064
+		return array(
1065
+			'resources' => array(
1066
+				array(
1067
+					'callback'        => array(
1068
+						'EventEspresso\core\libraries\rest_api\controllers\model\Meta',
1069
+						'handleRequestModelsMeta',
1070
+					),
1071
+					'methods'         => WP_REST_Server::READABLE,
1072
+					'hidden_endpoint' => $hidden_endpoint,
1073
+					'callback_args'   => array($version),
1074
+				),
1075
+			),
1076
+		);
1077
+	}
1078
+
1079
+
1080
+
1081
+	/**
1082
+	 * Tries to hide old 4.6 endpoints from the
1083
+	 *
1084
+	 * @param array $route_data
1085
+	 * @return array
1086
+	 */
1087
+	public static function hide_old_endpoints($route_data)
1088
+	{
1089
+		//allow API clients to override which endpoints get hidden, in case
1090
+		//they want to discover particular endpoints
1091
+		//also, we don't have access to the request so we have to just grab it from the superglobal
1092
+		$force_show_ee_namespace = ltrim(
1093
+			EEH_Array::is_set($_REQUEST, 'force_show_ee_namespace', ''),
1094
+			'/'
1095
+		);
1096
+		foreach (EED_Core_Rest_Api::get_ee_route_data() as $namespace => $relative_urls) {
1097
+			foreach ($relative_urls as $resource_name => $endpoints) {
1098
+				foreach ($endpoints as $key => $endpoint) {
1099
+					//skip schema and other route options
1100
+					if (! is_numeric($key)) {
1101
+						continue;
1102
+					}
1103
+					//by default, hide "hidden_endpoint"s, unless the request indicates
1104
+					//to $force_show_ee_namespace, in which case only show that one
1105
+					//namespace's endpoints (and hide all others)
1106
+					if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107
+						|| ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108
+					) {
1109
+						$full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1110
+						unset($route_data[$full_route]);
1111
+					}
1112
+				}
1113
+			}
1114
+		}
1115
+		return $route_data;
1116
+	}
1117
+
1118
+
1119
+
1120
+	/**
1121
+	 * Returns an array describing which versions of core support serving requests for.
1122
+	 * Keys are core versions' major and minor version, and values are the
1123
+	 * LOWEST requested version they can serve. Eg, 4.7 can serve requests for 4.6-like
1124
+	 * data by just removing a few models and fields from the responses. However, 4.15 might remove
1125
+	 * the answers table entirely, in which case it would be very difficult for
1126
+	 * it to serve 4.6-style responses.
1127
+	 * Versions of core that are missing from this array are unknowns.
1128
+	 * previous ver
1129
+	 *
1130
+	 * @return array
1131
+	 */
1132
+	public static function version_compatibilities()
1133
+	{
1134
+		return apply_filters(
1135
+			'FHEE__EED_Core_REST_API__version_compatibilities',
1136
+			array(
1137
+				'4.8.29' => '4.8.29',
1138
+				'4.8.33' => '4.8.29',
1139
+				'4.8.34' => '4.8.29',
1140
+				'4.8.36' => '4.8.29',
1141
+			)
1142
+		);
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * Gets the latest API version served. Eg if there
1149
+	 * are two versions served of the API, 4.8.29 and 4.8.32, and
1150
+	 * we are on core version 4.8.34, it will return the string "4.8.32"
1151
+	 *
1152
+	 * @return string
1153
+	 */
1154
+	public static function latest_rest_api_version()
1155
+	{
1156
+		$versions_served = \EED_Core_Rest_Api::versions_served();
1157
+		$versions_served_keys = array_keys($versions_served);
1158
+		return end($versions_served_keys);
1159
+	}
1160
+
1161
+
1162
+
1163
+	/**
1164
+	 * Using EED_Core_Rest_Api::version_compatibilities(), determines what version of
1165
+	 * EE the API can serve requests for. Eg, if we are on 4.15 of core, and
1166
+	 * we can serve requests from 4.12 or later, this will return array( '4.12', '4.13', '4.14', '4.15' ).
1167
+	 * We also indicate whether or not this version should be put in the index or not
1168
+	 *
1169
+	 * @return array keys are API version numbers (just major and minor numbers), and values
1170
+	 * are whether or not they should be hidden
1171
+	 */
1172
+	public static function versions_served()
1173
+	{
1174
+		$versions_served = array();
1175
+		$possibly_served_versions = EED_Core_Rest_Api::version_compatibilities();
1176
+		$lowest_compatible_version = end($possibly_served_versions);
1177
+		reset($possibly_served_versions);
1178
+		$versions_served_historically = array_keys($possibly_served_versions);
1179
+		$latest_version = end($versions_served_historically);
1180
+		reset($versions_served_historically);
1181
+		//for each version of core we have ever served:
1182
+		foreach ($versions_served_historically as $key_versioned_endpoint) {
1183
+			//if it's not above the current core version, and it's compatible with the current version of core
1184
+			if ($key_versioned_endpoint == $latest_version) {
1185
+				//don't hide the latest version in the index
1186
+				$versions_served[$key_versioned_endpoint] = false;
1187
+			} elseif ($key_versioned_endpoint < EED_Core_Rest_Api::core_version()
1188
+				&& $key_versioned_endpoint >= $lowest_compatible_version
1189
+			) {
1190
+				//include, but hide, previous versions which are still supported
1191
+				$versions_served[$key_versioned_endpoint] = true;
1192
+			} elseif (apply_filters(
1193
+				'FHEE__EED_Core_Rest_Api__versions_served__include_incompatible_versions',
1194
+				false,
1195
+				$possibly_served_versions
1196
+			)) {
1197
+				//if a version is no longer supported, don't include it in index or list of versions served
1198
+				$versions_served[$key_versioned_endpoint] = true;
1199
+			}
1200
+		}
1201
+		return $versions_served;
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Gets the major and minor version of EE core's version string
1208
+	 *
1209
+	 * @return string
1210
+	 */
1211
+	public static function core_version()
1212
+	{
1213
+		return apply_filters(
1214
+			'FHEE__EED_Core_REST_API__core_version',
1215
+			implode(
1216
+				'.',
1217
+				array_slice(
1218
+					explode(
1219
+						'.',
1220
+						espresso_version()
1221
+					),
1222
+				0,
1223
+				3
1224
+				)
1225
+			)
1226
+		);
1227
+	}
1228
+
1229
+
1230
+
1231
+	/**
1232
+	 * Gets the default limit that should be used when querying for resources
1233
+	 *
1234
+	 * @return int
1235
+	 */
1236
+	public static function get_default_query_limit()
1237
+	{
1238
+		//we actually don't use a const because we want folks to always use
1239
+		//this method, not the const directly
1240
+		return apply_filters(
1241
+			'FHEE__EED_Core_Rest_Api__get_default_query_limit',
1242
+			50
1243
+		);
1244
+	}
1245
+
1246
+
1247
+
1248
+	/**
1249
+	 *    run - initial module setup
1250
+	 *
1251
+	 * @access    public
1252
+	 * @param  WP $WP
1253
+	 * @return    void
1254
+	 */
1255
+	public function run($WP)
1256
+	{
1257
+	}
1258 1258
 }
1259 1259
 
1260 1260
 // End of file EED_Core_Rest_Api.module.php
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
      */
120 120
     protected static function _set_hooks_for_changes()
121 121
     {
122
-        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES . 'rest_api' . DS . 'changes'), false);
122
+        $folder_contents = EEH_File::get_contents_of_folders(array(EE_LIBRARIES.'rest_api'.DS.'changes'), false);
123 123
         foreach ($folder_contents as $classname_in_namespace => $filepath) {
124 124
             //ignore the base parent class
125 125
             //and legacy named classes
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
             ) {
129 129
                 continue;
130 130
             }
131
-            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\' . $classname_in_namespace;
131
+            $full_classname = 'EventEspresso\core\libraries\rest_api\changes\\'.$classname_in_namespace;
132 132
             if (class_exists($full_classname)) {
133 133
                 $instance_of_class = new $full_classname;
134 134
                 if ($instance_of_class instanceof ChangesInBase) {
@@ -172,10 +172,10 @@  discard block
 block discarded – undo
172 172
                      * }
173 173
                      */
174 174
                     //skip route options
175
-                    if (! is_numeric($endpoint_key)) {
175
+                    if ( ! is_numeric($endpoint_key)) {
176 176
                         continue;
177 177
                     }
178
-                    if (! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
178
+                    if ( ! isset($data_for_single_endpoint['callback'], $data_for_single_endpoint['methods'])) {
179 179
                         throw new EE_Error(
180 180
                             esc_html__(
181 181
                                 // @codingStandardsIgnoreStart
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
                     }
196 196
                     if (isset($data_for_single_endpoint['callback_args'])) {
197 197
                         $callback_args = $data_for_single_endpoint['callback_args'];
198
-                        $single_endpoint_args['callback'] = function (\WP_REST_Request $request) use (
198
+                        $single_endpoint_args['callback'] = function(\WP_REST_Request $request) use (
199 199
                             $callback,
200 200
                             $callback_args
201 201
                         ) {
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
                     $schema_route_data = $data_for_multiple_endpoints['schema'];
215 215
                     $schema_callback = $schema_route_data['schema_callback'];
216 216
                     $callback_args = $schema_route_data['callback_args'];
217
-                    $multiple_endpoint_args['schema'] = function () use ($schema_callback, $callback_args) {
217
+                    $multiple_endpoint_args['schema'] = function() use ($schema_callback, $callback_args) {
218 218
                         return call_user_func_array(
219 219
                             $schema_callback,
220 220
                             $callback_args
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
     {
259 259
         //delete the saved EE REST API routes
260 260
         foreach (EED_Core_Rest_Api::versions_served() as $version => $hidden) {
261
-            delete_option(EED_Core_Rest_Api::saved_routes_option_names . $version);
261
+            delete_option(EED_Core_Rest_Api::saved_routes_option_names.$version);
262 262
         }
263 263
     }
264 264
 
@@ -277,7 +277,7 @@  discard block
 block discarded – undo
277 277
     {
278 278
         $ee_routes = array();
279 279
         foreach (self::versions_served() as $version => $hidden_endpoints) {
280
-            $ee_routes[self::ee_api_namespace . $version] = self::_get_ee_route_data_for_version(
280
+            $ee_routes[self::ee_api_namespace.$version] = self::_get_ee_route_data_for_version(
281 281
                 $version,
282 282
                 $hidden_endpoints
283 283
             );
@@ -297,8 +297,8 @@  discard block
 block discarded – undo
297 297
      */
298 298
     protected static function _get_ee_route_data_for_version($version, $hidden_endpoints = false)
299 299
     {
300
-        $ee_routes = get_option(self::saved_routes_option_names . $version, null);
301
-        if (! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
300
+        $ee_routes = get_option(self::saved_routes_option_names.$version, null);
301
+        if ( ! $ee_routes || (defined('EE_REST_API_DEBUG_MODE') && EE_REST_API_DEBUG_MODE)) {
302 302
             $ee_routes = self::_save_ee_route_data_for_version($version, $hidden_endpoints);
303 303
         }
304 304
         return $ee_routes;
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
                 $instance->_get_rpc_route_data_for_version($version, $hidden_endpoints)
326 326
             )
327 327
         );
328
-        $option_name = self::saved_routes_option_names . $version;
328
+        $option_name = self::saved_routes_option_names.$version;
329 329
         if (get_option($option_name)) {
330 330
             update_option($option_name, $routes, true);
331 331
         } else {
@@ -391,11 +391,11 @@  discard block
 block discarded – undo
391 391
      */
392 392
     public static function should_have_write_endpoints(EEM_Base $model)
393 393
     {
394
-        if ($model->is_wp_core_model()){
394
+        if ($model->is_wp_core_model()) {
395 395
             return false;
396 396
         }
397
-        foreach($model->get_tables() as $table){
398
-            if( $table->is_global()){
397
+        foreach ($model->get_tables() as $table) {
398
+            if ($table->is_global()) {
399 399
                 return false;
400 400
             }
401 401
         }
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
      * @param $version
411 411
      * @return array keys are model names (eg 'Event') and values ar etheir classnames (eg 'EEM_Event')
412 412
      */
413
-    public static function model_names_with_plural_routes($version){
413
+    public static function model_names_with_plural_routes($version) {
414 414
         $model_version_info = new ModelVersionInfo($version);
415 415
         $models_to_register = $model_version_info->modelsForRequestedVersion();
416 416
         //let's not bother having endpoints for extra metas
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
         foreach ($this->model_names_with_plural_routes($version) as $model_name => $model_classname) {
440 440
             $model = \EE_Registry::instance()->load_model($model_name);
441 441
             //if this isn't a valid model then let's skip iterate to the next item in the loop.
442
-            if (! $model instanceof EEM_Base) {
442
+            if ( ! $model instanceof EEM_Base) {
443 443
                 continue;
444 444
             }
445 445
             //yes we could just register one route for ALL models, but then they wouldn't show up in the index
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
                     'hidden_endpoint' => $hidden_endpoint,
457 457
                     'args'            => $this->_get_read_query_params($model, $version),
458 458
                     '_links'          => array(
459
-                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace . $version . $singular_model_route),
459
+                        'self' => rest_url(EED_Core_Rest_Api::ee_api_namespace.$version.$singular_model_route),
460 460
                     ),
461 461
                 ),
462 462
                 'schema' => array(
@@ -479,11 +479,11 @@  discard block
 block discarded – undo
479 479
                     'args'            => $this->_get_response_selection_query_params($model, $version),
480 480
                 ),
481 481
             );
482
-            if( apply_filters(
482
+            if (apply_filters(
483 483
                 'FHEE__EED_Core_Rest_Api___get_model_route_data_for_version__add_write_endpoints',
484 484
                 $this->should_have_write_endpoints($model),
485 485
                 $model
486
-            )){
486
+            )) {
487 487
                 $model_routes[$plural_model_route][] = array(
488 488
                     'callback'        => array(
489 489
                         'EventEspresso\core\libraries\rest_api\controllers\model\Write',
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
      */
572 572
     public static function get_entity_route($model_name, $id)
573 573
     {
574
-        return EEH_Inflector::pluralize_and_lower($model_name) . '/' . $id;
574
+        return EEH_Inflector::pluralize_and_lower($model_name).'/'.$id;
575 575
     }
576 576
 
577 577
 
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
             $relation_obj->get_other_model()->get_this_model_name(),
592 592
             $relation_obj
593 593
         );
594
-        return EED_Core_Rest_Api::get_entity_route($model_name, $id) . '/' . $related_model_name_endpoint_part;
594
+        return EED_Core_Rest_Api::get_entity_route($model_name, $id).'/'.$related_model_name_endpoint_part;
595 595
     }
596 596
 
597 597
 
@@ -603,8 +603,8 @@  discard block
 block discarded – undo
603 603
      * @param string $version
604 604
      * @return string
605 605
      */
606
-    public static function get_versioned_route_to($relative_route, $version = '4.8.36'){
607
-        return '/' . EED_Core_Rest_Api::ee_api_namespace . $version . '/' . $relative_route;
606
+    public static function get_versioned_route_to($relative_route, $version = '4.8.36') {
607
+        return '/'.EED_Core_Rest_Api::ee_api_namespace.$version.'/'.$relative_route;
608 608
     }
609 609
 
610 610
 
@@ -619,7 +619,7 @@  discard block
 block discarded – undo
619 619
     {
620 620
         $routes = array();
621 621
         foreach (self::versions_served() as $version => $hidden_endpoint) {
622
-            $routes[self::ee_api_namespace . $version] = $this->_get_rpc_route_data_for_version(
622
+            $routes[self::ee_api_namespace.$version] = $this->_get_rpc_route_data_for_version(
623 623
                 $version,
624 624
                 $hidden_endpoint
625 625
             );
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
                     $field_obj->get_nicename(),
860 860
                     $field_name
861 861
                 );
862
-                $args_info[$field_name . '_gmt'] = $gmt_arg_info;
862
+                $args_info[$field_name.'_gmt'] = $gmt_arg_info;
863 863
             }
864 864
         }
865 865
         return $args_info;
@@ -875,10 +875,10 @@  discard block
 block discarded – undo
875 875
      * @param                 $param
876 876
      * @return bool|true|WP_Error
877 877
      */
878
-    public static function default_sanitize_callback( $value, WP_REST_Request $request, $param)
878
+    public static function default_sanitize_callback($value, WP_REST_Request $request, $param)
879 879
     {
880 880
         $attributes = $request->get_attributes();
881
-        if (! isset($attributes['args'][$param])
881
+        if ( ! isset($attributes['args'][$param])
882 882
             || ! is_array($attributes['args'][$param])) {
883 883
             $validation_result = true;
884 884
         } else {
@@ -887,7 +887,7 @@  discard block
 block discarded – undo
887 887
                     $value === ''
888 888
                     || $value === null
889 889
                 )
890
-                && (! isset($args['required'])
890
+                && ( ! isset($args['required'])
891 891
                     || $args['required'] === false
892 892
                 )
893 893
             ) {
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
             } elseif (isset($args['format'])
897 897
                 && $args['format'] === 'email'
898 898
             ) {
899
-                if (! self::_validate_email($value)) {
899
+                if ( ! self::_validate_email($value)) {
900 900
                     $validation_result = new WP_Error(
901 901
                         'rest_invalid_param',
902 902
                         esc_html__('The email address is not valid or does not exist.', 'event_espresso')
@@ -921,38 +921,38 @@  discard block
 block discarded – undo
921 921
      * @param $email
922 922
      * @return bool
923 923
      */
924
-    protected static function _validate_email($email){
925
-        $validation_level = isset( EE_Registry::instance()->CFG->registration->email_validation_level )
924
+    protected static function _validate_email($email) {
925
+        $validation_level = isset(EE_Registry::instance()->CFG->registration->email_validation_level)
926 926
             ? EE_Registry::instance()->CFG->registration->email_validation_level
927 927
             : 'wp_default';
928
-        if ( ! preg_match( '/^.+\@\S+$/', $email ) ) { // \.\S+
928
+        if ( ! preg_match('/^.+\@\S+$/', $email)) { // \.\S+
929 929
             // email not in correct {string}@{string} format
930 930
             return false;
931 931
         } else {
932
-            $atIndex = strrpos( $email, "@" );
933
-            $domain = substr( $email, $atIndex + 1 );
934
-            $local = substr( $email, 0, $atIndex );
935
-            $localLen = strlen( $local );
936
-            $domainLen = strlen( $domain );
937
-            if ( $localLen < 1 || $localLen > 64 ) {
932
+            $atIndex = strrpos($email, "@");
933
+            $domain = substr($email, $atIndex + 1);
934
+            $local = substr($email, 0, $atIndex);
935
+            $localLen = strlen($local);
936
+            $domainLen = strlen($domain);
937
+            if ($localLen < 1 || $localLen > 64) {
938 938
                 // local part length exceeded
939 939
                 return false;
940
-            } else if ( $domainLen < 1 || $domainLen > 255 ) {
940
+            } else if ($domainLen < 1 || $domainLen > 255) {
941 941
                 // domain part length exceeded
942 942
                 return false;
943
-            } else if ( $local[ 0 ] === '.' || $local[ $localLen - 1 ] === '.' ) {
943
+            } else if ($local[0] === '.' || $local[$localLen - 1] === '.') {
944 944
                 // local part starts or ends with '.'
945 945
                 return false;
946
-            } else if ( preg_match( '/\\.\\./', $local ) ) {
946
+            } else if (preg_match('/\\.\\./', $local)) {
947 947
                 // local part has two consecutive dots
948 948
                 return false;
949
-            } else if ( preg_match( '/\\.\\./', $domain ) ) {
949
+            } else if (preg_match('/\\.\\./', $domain)) {
950 950
                 // domain part has two consecutive dots
951 951
                 return false;
952
-            } else if ( $validation_level === 'wp_default' ) {
953
-                return is_email( $email );
952
+            } else if ($validation_level === 'wp_default') {
953
+                return is_email($email);
954 954
             } else if (
955
-                ( $validation_level === 'i18n' || $validation_level === 'i18n_dns' )
955
+                ($validation_level === 'i18n' || $validation_level === 'i18n_dns')
956 956
                 // plz see http://stackoverflow.com/a/24817336 re: the following regex
957 957
                 && ! preg_match(
958 958
                     '/^(?!\.)((?!.*\.{2})[a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\.!#$%&\'*+-\/=?^_`{|}~\-\d]+)@(?!\.)([a-zA-Z0-9\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}\-\.\d]+)((\.([a-zA-Z\x{0080}-\x{00FF}\x{0100}-\x{017F}\x{0180}-\x{024F}\x{0250}-\x{02AF}\x{0300}-\x{036F}\x{0370}-\x{03FF}\x{0400}-\x{04FF}\x{0500}-\x{052F}\x{0530}-\x{058F}\x{0590}-\x{05FF}\x{0600}-\x{06FF}\x{0700}-\x{074F}\x{0750}-\x{077F}\x{0780}-\x{07BF}\x{07C0}-\x{07FF}\x{0900}-\x{097F}\x{0980}-\x{09FF}\x{0A00}-\x{0A7F}\x{0A80}-\x{0AFF}\x{0B00}-\x{0B7F}\x{0B80}-\x{0BFF}\x{0C00}-\x{0C7F}\x{0C80}-\x{0CFF}\x{0D00}-\x{0D7F}\x{0D80}-\x{0DFF}\x{0E00}-\x{0E7F}\x{0E80}-\x{0EFF}\x{0F00}-\x{0FFF}\x{1000}-\x{109F}\x{10A0}-\x{10FF}\x{1100}-\x{11FF}\x{1200}-\x{137F}\x{1380}-\x{139F}\x{13A0}-\x{13FF}\x{1400}-\x{167F}\x{1680}-\x{169F}\x{16A0}-\x{16FF}\x{1700}-\x{171F}\x{1720}-\x{173F}\x{1740}-\x{175F}\x{1760}-\x{177F}\x{1780}-\x{17FF}\x{1800}-\x{18AF}\x{1900}-\x{194F}\x{1950}-\x{197F}\x{1980}-\x{19DF}\x{19E0}-\x{19FF}\x{1A00}-\x{1A1F}\x{1B00}-\x{1B7F}\x{1D00}-\x{1D7F}\x{1D80}-\x{1DBF}\x{1DC0}-\x{1DFF}\x{1E00}-\x{1EFF}\x{1F00}-\x{1FFF}\x{20D0}-\x{20FF}\x{2100}-\x{214F}\x{2C00}-\x{2C5F}\x{2C60}-\x{2C7F}\x{2C80}-\x{2CFF}\x{2D00}-\x{2D2F}\x{2D30}-\x{2D7F}\x{2D80}-\x{2DDF}\x{2F00}-\x{2FDF}\x{2FF0}-\x{2FFF}\x{3040}-\x{309F}\x{30A0}-\x{30FF}\x{3100}-\x{312F}\x{3130}-\x{318F}\x{3190}-\x{319F}\x{31C0}-\x{31EF}\x{31F0}-\x{31FF}\x{3200}-\x{32FF}\x{3300}-\x{33FF}\x{3400}-\x{4DBF}\x{4DC0}-\x{4DFF}\x{4E00}-\x{9FFF}\x{A000}-\x{A48F}\x{A490}-\x{A4CF}\x{A700}-\x{A71F}\x{A800}-\x{A82F}\x{A840}-\x{A87F}\x{AC00}-\x{D7AF}\x{F900}-\x{FAFF}]){2,63})+)$/u',
@@ -961,11 +961,11 @@  discard block
 block discarded – undo
961 961
             ) {
962 962
                 return false;
963 963
             }
964
-            if ( $validation_level === 'i18n_dns' ) {
965
-                if ( ! checkdnsrr( $domain, "MX" ) ) {
964
+            if ($validation_level === 'i18n_dns') {
965
+                if ( ! checkdnsrr($domain, "MX")) {
966 966
                     // domain not found in MX records
967 967
                     return false;
968
-                } else if ( ! checkdnsrr( $domain, "A" ) ) {
968
+                } else if ( ! checkdnsrr($domain, "A")) {
969 969
                     // domain not found in A records
970 970
                     return false;
971 971
                 }
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
     {
988 988
         $config_routes = array();
989 989
         foreach (self::versions_served() as $version => $hidden_endpoint) {
990
-            $config_routes[self::ee_api_namespace . $version] = $this->_get_config_route_data_for_version(
990
+            $config_routes[self::ee_api_namespace.$version] = $this->_get_config_route_data_for_version(
991 991
                 $version,
992 992
                 $hidden_endpoint
993 993
             );
@@ -1044,7 +1044,7 @@  discard block
 block discarded – undo
1044 1044
     {
1045 1045
         $meta_routes = array();
1046 1046
         foreach (self::versions_served() as $version => $hidden_endpoint) {
1047
-            $meta_routes[self::ee_api_namespace . $version] = $this->_get_meta_route_data_for_version(
1047
+            $meta_routes[self::ee_api_namespace.$version] = $this->_get_meta_route_data_for_version(
1048 1048
                 $version,
1049 1049
                 $hidden_endpoint
1050 1050
             );
@@ -1097,7 +1097,7 @@  discard block
 block discarded – undo
1097 1097
             foreach ($relative_urls as $resource_name => $endpoints) {
1098 1098
                 foreach ($endpoints as $key => $endpoint) {
1099 1099
                     //skip schema and other route options
1100
-                    if (! is_numeric($key)) {
1100
+                    if ( ! is_numeric($key)) {
1101 1101
                         continue;
1102 1102
                     }
1103 1103
                     //by default, hide "hidden_endpoint"s, unless the request indicates
@@ -1106,7 +1106,7 @@  discard block
 block discarded – undo
1106 1106
                     if (($endpoint['hidden_endpoint'] && $force_show_ee_namespace === '')
1107 1107
                         || ($force_show_ee_namespace !== '' && $force_show_ee_namespace !== $namespace)
1108 1108
                     ) {
1109
-                        $full_route = '/' . ltrim($namespace, '/') . '/' . ltrim($resource_name, '/');
1109
+                        $full_route = '/'.ltrim($namespace, '/').'/'.ltrim($resource_name, '/');
1110 1110
                         unset($route_data[$full_route]);
1111 1111
                     }
1112 1112
                 }
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.40.rc.011');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.40.rc.011');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.