Completed
Branch BUG/11294/expired-cart-ticket-... (e3a2a5)
by
unknown
13:35 queued 11s
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6176 added lines, -6176 removed lines patch added patch discarded remove patch
@@ -34,6184 +34,6184 @@
 block discarded – undo
34 34
 abstract class EEM_Base extends EE_Base implements ResettableInterface
35 35
 {
36 36
 
37
-    /**
38
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
-     * They almost always WILL NOT, but it's not necessarily a requirement.
41
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
-     *
43
-     * @var boolean
44
-     */
45
-    private $_values_already_prepared_by_model_object = 0;
46
-
47
-    /**
48
-     * when $_values_already_prepared_by_model_object equals this, we assume
49
-     * the data is just like form input that needs to have the model fields'
50
-     * prepare_for_set and prepare_for_use_in_db called on it
51
-     */
52
-    const not_prepared_by_model_object = 0;
53
-
54
-    /**
55
-     * when $_values_already_prepared_by_model_object equals this, we
56
-     * assume this value is coming from a model object and doesn't need to have
57
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
58
-     */
59
-    const prepared_by_model_object = 1;
60
-
61
-    /**
62
-     * when $_values_already_prepared_by_model_object equals this, we assume
63
-     * the values are already to be used in the database (ie no processing is done
64
-     * on them by the model's fields)
65
-     */
66
-    const prepared_for_use_in_db = 2;
67
-
68
-
69
-    protected $singular_item = 'Item';
70
-
71
-    protected $plural_item   = 'Items';
72
-
73
-    /**
74
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
-     */
76
-    protected $_tables;
77
-
78
-    /**
79
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
-     *
83
-     * @var \EE_Model_Field_Base[][] $_fields
84
-     */
85
-    protected $_fields;
86
-
87
-    /**
88
-     * array of different kinds of relations
89
-     *
90
-     * @var \EE_Model_Relation_Base[] $_model_relations
91
-     */
92
-    protected $_model_relations;
93
-
94
-    /**
95
-     * @var \EE_Index[] $_indexes
96
-     */
97
-    protected $_indexes = array();
98
-
99
-    /**
100
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
101
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
-     * by setting the same columns as used in these queries in the query yourself.
103
-     *
104
-     * @var EE_Default_Where_Conditions
105
-     */
106
-    protected $_default_where_conditions_strategy;
107
-
108
-    /**
109
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
-     * This is particularly useful when you want something between 'none' and 'default'
111
-     *
112
-     * @var EE_Default_Where_Conditions
113
-     */
114
-    protected $_minimum_where_conditions_strategy;
115
-
116
-    /**
117
-     * String describing how to find the "owner" of this model's objects.
118
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
-     * But when there isn't, this indicates which related model, or transiently-related model,
120
-     * has the foreign key to the wp_users table.
121
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
-     * related to events, and events have a foreign key to wp_users.
123
-     * On EEM_Transaction, this would be 'Transaction.Event'
124
-     *
125
-     * @var string
126
-     */
127
-    protected $_model_chain_to_wp_user = '';
128
-
129
-    /**
130
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
-     * don't need it (particularly CPT models)
132
-     *
133
-     * @var bool
134
-     */
135
-    protected $_ignore_where_strategy = false;
136
-
137
-    /**
138
-     * String used in caps relating to this model. Eg, if the caps relating to this
139
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
-     *
141
-     * @var string. If null it hasn't been initialized yet. If false then we
142
-     * have indicated capabilities don't apply to this
143
-     */
144
-    protected $_caps_slug = null;
145
-
146
-    /**
147
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
-     * and next-level keys are capability names, and each's value is a
149
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
-     * they specify which context to use (ie, frontend, backend, edit or delete)
151
-     * and then each capability in the corresponding sub-array that they're missing
152
-     * adds the where conditions onto the query.
153
-     *
154
-     * @var array
155
-     */
156
-    protected $_cap_restrictions = array(
157
-        self::caps_read       => array(),
158
-        self::caps_read_admin => array(),
159
-        self::caps_edit       => array(),
160
-        self::caps_delete     => array(),
161
-    );
162
-
163
-    /**
164
-     * Array defining which cap restriction generators to use to create default
165
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
166
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
-     * automatically set this to false (not just null).
169
-     *
170
-     * @var EE_Restriction_Generator_Base[]
171
-     */
172
-    protected $_cap_restriction_generators = array();
173
-
174
-    /**
175
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
-     */
177
-    const caps_read       = 'read';
178
-
179
-    const caps_read_admin = 'read_admin';
180
-
181
-    const caps_edit       = 'edit';
182
-
183
-    const caps_delete     = 'delete';
184
-
185
-    /**
186
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
-     * maps to 'read' because when looking for relevant permissions we're going to use
189
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
190
-     *
191
-     * @var array
192
-     */
193
-    protected $_cap_contexts_to_cap_action_map = array(
194
-        self::caps_read       => 'read',
195
-        self::caps_read_admin => 'read',
196
-        self::caps_edit       => 'edit',
197
-        self::caps_delete     => 'delete',
198
-    );
199
-
200
-    /**
201
-     * Timezone
202
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
-     * EE_Datetime_Field data type will have access to it.
206
-     *
207
-     * @var string
208
-     */
209
-    protected $_timezone;
210
-
211
-
212
-    /**
213
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
-     * multisite.
215
-     *
216
-     * @var int
217
-     */
218
-    protected static $_model_query_blog_id;
219
-
220
-    /**
221
-     * A copy of _fields, except the array keys are the model names pointed to by
222
-     * the field
223
-     *
224
-     * @var EE_Model_Field_Base[]
225
-     */
226
-    private $_cache_foreign_key_to_fields = array();
227
-
228
-    /**
229
-     * Cached list of all the fields on the model, indexed by their name
230
-     *
231
-     * @var EE_Model_Field_Base[]
232
-     */
233
-    private $_cached_fields = null;
234
-
235
-    /**
236
-     * Cached list of all the fields on the model, except those that are
237
-     * marked as only pertinent to the database
238
-     *
239
-     * @var EE_Model_Field_Base[]
240
-     */
241
-    private $_cached_fields_non_db_only = null;
242
-
243
-    /**
244
-     * A cached reference to the primary key for quick lookup
245
-     *
246
-     * @var EE_Model_Field_Base
247
-     */
248
-    private $_primary_key_field = null;
249
-
250
-    /**
251
-     * Flag indicating whether this model has a primary key or not
252
-     *
253
-     * @var boolean
254
-     */
255
-    protected $_has_primary_key_field = null;
256
-
257
-    /**
258
-     * Whether or not this model is based off a table in WP core only (CPTs should set
259
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
-     * This should be true for models that deal with data that should exist independent of EE.
261
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
263
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
265
-     * @var boolean
266
-     */
267
-    protected $_wp_core_model = false;
268
-
269
-    /**
270
-     *    List of valid operators that can be used for querying.
271
-     * The keys are all operators we'll accept, the values are the real SQL
272
-     * operators used
273
-     *
274
-     * @var array
275
-     */
276
-    protected $_valid_operators = array(
277
-        '='           => '=',
278
-        '<='          => '<=',
279
-        '<'           => '<',
280
-        '>='          => '>=',
281
-        '>'           => '>',
282
-        '!='          => '!=',
283
-        'LIKE'        => 'LIKE',
284
-        'like'        => 'LIKE',
285
-        'NOT_LIKE'    => 'NOT LIKE',
286
-        'not_like'    => 'NOT LIKE',
287
-        'NOT LIKE'    => 'NOT LIKE',
288
-        'not like'    => 'NOT LIKE',
289
-        'IN'          => 'IN',
290
-        'in'          => 'IN',
291
-        'NOT_IN'      => 'NOT IN',
292
-        'not_in'      => 'NOT IN',
293
-        'NOT IN'      => 'NOT IN',
294
-        'not in'      => 'NOT IN',
295
-        'between'     => 'BETWEEN',
296
-        'BETWEEN'     => 'BETWEEN',
297
-        'IS_NOT_NULL' => 'IS NOT NULL',
298
-        'is_not_null' => 'IS NOT NULL',
299
-        'IS NOT NULL' => 'IS NOT NULL',
300
-        'is not null' => 'IS NOT NULL',
301
-        'IS_NULL'     => 'IS NULL',
302
-        'is_null'     => 'IS NULL',
303
-        'IS NULL'     => 'IS NULL',
304
-        'is null'     => 'IS NULL',
305
-        'REGEXP'      => 'REGEXP',
306
-        'regexp'      => 'REGEXP',
307
-        'NOT_REGEXP'  => 'NOT REGEXP',
308
-        'not_regexp'  => 'NOT REGEXP',
309
-        'NOT REGEXP'  => 'NOT REGEXP',
310
-        'not regexp'  => 'NOT REGEXP',
311
-    );
312
-
313
-    /**
314
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
-     *
316
-     * @var array
317
-     */
318
-    protected $_in_style_operators = array('IN', 'NOT IN');
319
-
320
-    /**
321
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
-     * '12-31-2012'"
323
-     *
324
-     * @var array
325
-     */
326
-    protected $_between_style_operators = array('BETWEEN');
327
-
328
-    /**
329
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
-     * @var array
331
-     */
332
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
-    /**
334
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
-     * on a join table.
336
-     *
337
-     * @var array
338
-     */
339
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
-
341
-    /**
342
-     * Allowed values for $query_params['order'] for ordering in queries
343
-     *
344
-     * @var array
345
-     */
346
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
-
348
-    /**
349
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
351
-     *
352
-     * @var array
353
-     */
354
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
-
356
-    /**
357
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
359
-     *
360
-     * @var array
361
-     */
362
-    private $_allowed_query_params = array(
363
-        0,
364
-        'limit',
365
-        'order_by',
366
-        'group_by',
367
-        'having',
368
-        'force_join',
369
-        'order',
370
-        'on_join_limit',
371
-        'default_where_conditions',
372
-        'caps',
373
-        'extra_selects'
374
-    );
375
-
376
-    /**
377
-     * All the data types that can be used in $wpdb->prepare statements.
378
-     *
379
-     * @var array
380
-     */
381
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
-
383
-    /**
384
-     * @var EE_Registry $EE
385
-     */
386
-    protected $EE = null;
387
-
388
-
389
-    /**
390
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
-     *
392
-     * @var int
393
-     */
394
-    protected $_show_next_x_db_queries = 0;
395
-
396
-    /**
397
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
-     * WHERE, GROUP_BY, etc.
400
-     *
401
-     * @var CustomSelects
402
-     */
403
-    protected $_custom_selections = array();
404
-
405
-    /**
406
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
-     * caches every model object we've fetched from the DB on this request
408
-     *
409
-     * @var array
410
-     */
411
-    protected $_entity_map;
412
-
413
-    /**
414
-     * @var LoaderInterface $loader
415
-     */
416
-    private static $loader;
417
-
418
-
419
-    /**
420
-     * constant used to show EEM_Base has not yet verified the db on this http request
421
-     */
422
-    const db_verified_none = 0;
423
-
424
-    /**
425
-     * constant used to show EEM_Base has verified the EE core db on this http request,
426
-     * but not the addons' dbs
427
-     */
428
-    const db_verified_core = 1;
429
-
430
-    /**
431
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
-     * the EE core db too)
433
-     */
434
-    const db_verified_addons = 2;
435
-
436
-    /**
437
-     * indicates whether an EEM_Base child has already re-verified the DB
438
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
439
-     * looking like EEM_Base::db_verified_*
440
-     *
441
-     * @var int - 0 = none, 1 = core, 2 = addons
442
-     */
443
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
444
-
445
-    /**
446
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
-     *        registrations for non-trashed tickets for non-trashed datetimes)
449
-     */
450
-    const default_where_conditions_all = 'all';
451
-
452
-    /**
453
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
-     *        models which share tables with other models, this can return data for the wrong model.
458
-     */
459
-    const default_where_conditions_this_only = 'this_model_only';
460
-
461
-    /**
462
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
-     */
466
-    const default_where_conditions_others_only = 'other_models_only';
467
-
468
-    /**
469
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
472
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
-     *        (regardless of whether those events and venues are trashed)
474
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
-     *        events.
476
-     */
477
-    const default_where_conditions_minimum_all = 'minimum';
478
-
479
-    /**
480
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
-     *        not)
484
-     */
485
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
-
487
-    /**
488
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
-     *        it's possible it will return table entries for other models. You should use
491
-     *        EEM_Base::default_where_conditions_minimum_all instead.
492
-     */
493
-    const default_where_conditions_none = 'none';
494
-
495
-
496
-
497
-    /**
498
-     * About all child constructors:
499
-     * they should define the _tables, _fields and _model_relations arrays.
500
-     * Should ALWAYS be called after child constructor.
501
-     * In order to make the child constructors to be as simple as possible, this parent constructor
502
-     * finalizes constructing all the object's attributes.
503
-     * Generally, rather than requiring a child to code
504
-     * $this->_tables = array(
505
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
-     *        ...);
507
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
-     * each EE_Table has a function to set the table's alias after the constructor, using
509
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
-     * do something similar.
511
-     *
512
-     * @param null $timezone
513
-     * @throws EE_Error
514
-     */
515
-    protected function __construct($timezone = null)
516
-    {
517
-        // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
520
-                sprintf(
521
-                    __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
-                        'event_espresso'),
523
-                    get_class($this)
524
-                )
525
-            );
526
-        }
527
-        /**
528
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
-         */
530
-        if (empty(EEM_Base::$_model_query_blog_id)) {
531
-            EEM_Base::set_model_query_blog_id();
532
-        }
533
-        /**
534
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
-         * just use EE_Register_Model_Extension
536
-         *
537
-         * @var EE_Table_Base[] $_tables
538
-         */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
-        foreach ($this->_tables as $table_alias => $table_obj) {
541
-            /** @var $table_obj EE_Table_Base */
542
-            $table_obj->_construct_finalize_with_alias($table_alias);
543
-            if ($table_obj instanceof EE_Secondary_Table) {
544
-                /** @var $table_obj EE_Secondary_Table */
545
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
-            }
547
-        }
548
-        /**
549
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
-         * EE_Register_Model_Extension
551
-         *
552
-         * @param EE_Model_Field_Base[] $_fields
553
-         */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
-        $this->_invalidate_field_caches();
556
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
558
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
-            }
561
-            foreach ($fields_for_table as $field_name => $field_obj) {
562
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
-                //primary key field base has a slightly different _construct_finalize
564
-                /** @var $field_obj EE_Model_Field_Base */
565
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
-            }
567
-        }
568
-        // everything is related to Extra_Meta
569
-        if (get_class($this) !== 'EEM_Extra_Meta') {
570
-            //make extra meta related to everything, but don't block deleting things just
571
-            //because they have related extra meta info. For now just orphan those extra meta
572
-            //in the future we should automatically delete them
573
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        //and change logs
576
-        if (get_class($this) !== 'EEM_Change_Log') {
577
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
-        }
579
-        /**
580
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
-         * EE_Register_Model_Extension
582
-         *
583
-         * @param EE_Model_Relation_Base[] $_model_relations
584
-         */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
-            $this->_model_relations);
587
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
588
-            /** @var $relation_obj EE_Model_Relation_Base */
589
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
-        }
591
-        foreach ($this->_indexes as $index_name => $index_obj) {
592
-            /** @var $index_obj EE_Index */
593
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
-        }
595
-        $this->set_timezone($timezone);
596
-        //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
598
-            //nothing was set during child constructor, so set default
599
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
-        }
601
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
603
-            //nothing was set during child constructor, so set default
604
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
-        }
606
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
608
-        //to indicate to NOT set it, set it to the logical default
609
-        if ($this->_caps_slug === null) {
610
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
-        }
612
-        //initialize the standard cap restriction generators if none were specified by the child constructor
613
-        if ($this->_cap_restriction_generators !== false) {
614
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
617
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
-                        new EE_Restriction_Generator_Protected(),
619
-                        $cap_context,
620
-                        $this
621
-                    );
622
-                }
623
-            }
624
-        }
625
-        //if there are cap restriction generators, use them to make the default cap restrictions
626
-        if ($this->_cap_restriction_generators !== false) {
627
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
629
-                    continue;
630
-                }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
-                    throw new EE_Error(
633
-                        sprintf(
634
-                            __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
-                                'event_espresso'),
636
-                            $context,
637
-                            $this->get_this_model_name()
638
-                        )
639
-                    );
640
-                }
641
-                $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
643
-                    $generator_object->_construct_finalize($this, $action);
644
-                }
645
-            }
646
-        }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
648
-    }
649
-
650
-
651
-
652
-    /**
653
-     * Used to set the $_model_query_blog_id static property.
654
-     *
655
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
-     *                      value for get_current_blog_id() will be used.
657
-     */
658
-    public static function set_model_query_blog_id($blog_id = 0)
659
-    {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
-    }
662
-
663
-
664
-
665
-    /**
666
-     * Returns whatever is set as the internal $model_query_blog_id.
667
-     *
668
-     * @return int
669
-     */
670
-    public static function get_model_query_blog_id()
671
-    {
672
-        return EEM_Base::$_model_query_blog_id;
673
-    }
674
-
675
-
676
-
677
-    /**
678
-     * This function is a singleton method used to instantiate the Espresso_model object
679
-     *
680
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
-     *                                (and any incoming timezone data that gets saved).
682
-     *                                Note this just sends the timezone info to the date time model field objects.
683
-     *                                Default is NULL
684
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
-     * @return static (as in the concrete child class)
686
-     * @throws EE_Error
687
-     * @throws InvalidArgumentException
688
-     * @throws InvalidDataTypeException
689
-     * @throws InvalidInterfaceException
690
-     */
691
-    public static function instance($timezone = null)
692
-    {
693
-        // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
695
-            // instantiate Espresso_model
696
-            static::$_instance = new static(
697
-                $timezone,
698
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
-            );
700
-        }
701
-        //we might have a timezone set, let set_timezone decide what to do with it
702
-        static::$_instance->set_timezone($timezone);
703
-        // Espresso_model object
704
-        return static::$_instance;
705
-    }
706
-
707
-
708
-
709
-    /**
710
-     * resets the model and returns it
711
-     *
712
-     * @param null | string $timezone
713
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
-     * all its properties reset; if it wasn't instantiated, returns null)
715
-     * @throws EE_Error
716
-     * @throws ReflectionException
717
-     * @throws InvalidArgumentException
718
-     * @throws InvalidDataTypeException
719
-     * @throws InvalidInterfaceException
720
-     */
721
-    public static function reset($timezone = null)
722
-    {
723
-        if (static::$_instance instanceof EEM_Base) {
724
-            //let's try to NOT swap out the current instance for a new one
725
-            //because if someone has a reference to it, we can't remove their reference
726
-            //so it's best to keep using the same reference, but change the original object
727
-            //reset all its properties to their original values as defined in the class
728
-            $r = new ReflectionClass(get_class(static::$_instance));
729
-            $static_properties = $r->getStaticProperties();
730
-            foreach ($r->getDefaultProperties() as $property => $value) {
731
-                //don't set instance to null like it was originally,
732
-                //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
734
-                    static::$_instance->{$property} = $value;
735
-                }
736
-            }
737
-            //and then directly call its constructor again, like we would if we were creating a new one
738
-            static::$_instance->__construct(
739
-                $timezone,
740
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
-            );
742
-            return self::instance();
743
-        }
744
-        return null;
745
-    }
746
-
747
-
748
-
749
-    /**
750
-     * @return LoaderInterface
751
-     * @throws InvalidArgumentException
752
-     * @throws InvalidDataTypeException
753
-     * @throws InvalidInterfaceException
754
-     */
755
-    private static function getLoader()
756
-    {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
758
-            EEM_Base::$loader = LoaderFactory::getLoader();
759
-        }
760
-        return EEM_Base::$loader;
761
-    }
762
-
763
-
764
-
765
-    /**
766
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
-     *
768
-     * @param  boolean $translated return localized strings or JUST the array.
769
-     * @return array
770
-     * @throws EE_Error
771
-     * @throws InvalidArgumentException
772
-     * @throws InvalidDataTypeException
773
-     * @throws InvalidInterfaceException
774
-     */
775
-    public function status_array($translated = false)
776
-    {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
778
-            return array();
779
-        }
780
-        $model_name = $this->get_this_model_name();
781
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
-        $status_array = array();
784
-        foreach ($stati as $status) {
785
-            $status_array[$status->ID()] = $status->get('STS_code');
786
-        }
787
-        return $translated
788
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
-            : $status_array;
790
-    }
791
-
792
-
793
-
794
-    /**
795
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
-     *
797
-     * @param array $query_params             {
798
-     * @var array $0 (where) array {
799
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
-     *                                        conditions based on related models (and even
803
-     *                                        models-related-to-related-models) prepend the model's name onto the field
804
-     *                                        name. Eg,
805
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
-     *                                        to Venues (even when each of those models actually consisted of two
813
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
814
-     *                                        just having
815
-     *                                        "Venue.VNU_ID", you could have
816
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
-     *                                        events are related to Registrations, which are related to Attendees). You
818
-     *                                        can take it even further with
819
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
-     *                                        (from the default of '='), change the value to an numerically-indexed
821
-     *                                        array, where the first item in the list is the operator. eg: array(
822
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
830
-     *                                        the value is a field, simply provide a third array item (true) to the
831
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
-     *                                        Note: you can also use related model field names like you would any other
834
-     *                                        field name. eg:
835
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
-     *                                        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__>' =>
837
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
844
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
-     *                                        "stick" until you specify an AND. eg
846
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
-     *                                        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 >>
851
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
-     *                                        too, eg:
854
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
859
-     *                                        the OFFSET, the 2nd is the LIMIT
860
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
-     *                                        following format array('on_join_limit'
863
-     *                                        => array( 'table_alias', array(1,2) ) ).
864
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
-     *                                        values are either 'ASC' or 'DESC'.
866
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
-     *                                        DESC..." respectively. Like the
869
-     *                                        'where' conditions, these fields can be on related models. Eg
870
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
872
-     *                                        Attendee, Price, Datetime, etc.)
873
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
875
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
-     *                                        order by the primary key. Eg,
878
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
-     *                                        //(will join with the Datetime model's table(s) and order by its field
880
-     *                                        DTT_EVT_start) or
881
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
-     *                                        'group_by'=>'VNU_ID', or
885
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
-     *                                        if no
887
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
888
-     *                                        model's primary key (or combined primary keys). This avoids some
889
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
890
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
-     *                                        results)
894
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
-     *                                        array where values are models to be joined in the query.Eg
896
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
898
-     *                                        probably only want to do this in hopes of increasing efficiency, as
899
-     *                                        related models which belongs to the current model
900
-     *                                        (ie, the current model has a foreign key to them, like how Registration
901
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
902
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
905
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
-     *                                        default where conditions set it to 'other_models_only'. If you only want
907
-     *                                        this model's default where conditions added to the query, use
908
-     *                                        'this_model_only'. If you want to use all default where conditions
909
-     *                                        (default), set to 'all'.
910
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
-     *                                        everything? Or should we only show the current user items they should be
913
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
-     *                                        }
916
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
-     *                                        array( array(
922
-     *                                        'OR'=>array(
923
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
-     *                                        )
926
-     *                                        ),
927
-     *                                        'limit'=>10,
928
-     *                                        'group_by'=>'TXN_ID'
929
-     *                                        ));
930
-     *                                        get all the answers to the question titled "shirt size" for event with id
931
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
-     *                                        'Question.QST_display_text'=>'shirt size',
933
-     *                                        'Registration.Event.EVT_ID'=>12
934
-     *                                        ),
935
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
936
-     *                                        ));
937
-     * @throws EE_Error
938
-     */
939
-    public function get_all($query_params = array())
940
-    {
941
-        if (isset($query_params['limit'])
942
-            && ! isset($query_params['group_by'])
943
-        ) {
944
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
-        }
946
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
-    }
948
-
949
-
950
-
951
-    /**
952
-     * Modifies the query parameters so we only get back model objects
953
-     * that "belong" to the current user
954
-     *
955
-     * @param array $query_params @see EEM_Base::get_all()
956
-     * @return array like EEM_Base::get_all
957
-     */
958
-    public function alter_query_params_to_only_include_mine($query_params = array())
959
-    {
960
-        $wp_user_field_name = $this->wp_user_field_name();
961
-        if ($wp_user_field_name) {
962
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
963
-        }
964
-        return $query_params;
965
-    }
966
-
967
-
968
-
969
-    /**
970
-     * Returns the name of the field's name that points to the WP_User table
971
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
-     * foreign key to the WP_User table)
973
-     *
974
-     * @return string|boolean string on success, boolean false when there is no
975
-     * foreign key to the WP_User table
976
-     */
977
-    public function wp_user_field_name()
978
-    {
979
-        try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
981
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
-                $last_model_name = end($models_to_follow_to_wp_users);
983
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
-            } else {
986
-                $model_with_fk_to_wp_users = $this;
987
-                $model_chain_to_wp_user = '';
988
-            }
989
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
991
-        } catch (EE_Error $e) {
992
-            return false;
993
-        }
994
-    }
995
-
996
-
997
-
998
-    /**
999
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
-     * (or transiently-related model) has a foreign key to the wp_users table;
1001
-     * useful for finding if model objects of this type are 'owned' by the current user.
1002
-     * This is an empty string when the foreign key is on this model and when it isn't,
1003
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
-     * (or transiently-related model)
1005
-     *
1006
-     * @return string
1007
-     */
1008
-    public function model_chain_to_wp_user()
1009
-    {
1010
-        return $this->_model_chain_to_wp_user;
1011
-    }
1012
-
1013
-
1014
-
1015
-    /**
1016
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
-     * like how registrations don't have a foreign key to wp_users, but the
1018
-     * events they are for are), or is unrelated to wp users.
1019
-     * generally available
1020
-     *
1021
-     * @return boolean
1022
-     */
1023
-    public function is_owned()
1024
-    {
1025
-        if ($this->model_chain_to_wp_user()) {
1026
-            return true;
1027
-        }
1028
-        try {
1029
-            $this->get_foreign_key_to('WP_User');
1030
-            return true;
1031
-        } catch (EE_Error $e) {
1032
-            return false;
1033
-        }
1034
-    }
1035
-
1036
-
1037
-    /**
1038
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
-     * the model)
1041
-     *
1042
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1046
-     *                                  override this and set the select to "*", or a specific column name, like
1047
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
-     *                                  the aliases used to refer to this selection, and values are to be
1050
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
-     * @throws EE_Error
1054
-     * @throws InvalidArgumentException
1055
-     */
1056
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
-    {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
-        $select_expressions = $columns_to_select === null
1061
-            ? $this->_construct_default_select_sql($model_query_info)
1062
-            : '';
1063
-        if ($this->_custom_selections instanceof CustomSelects) {
1064
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
-            $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1067
-                : $custom_expressions;
1068
-        }
1069
-
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
-     * method of including extra select information.
1079
-     *
1080
-     * @param array             $query_params
1081
-     * @param null|array|string $columns_to_select
1082
-     * @return null|CustomSelects
1083
-     * @throws InvalidArgumentException
1084
-     */
1085
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
-    {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
-            return null;
1089
-        }
1090
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
-        return new CustomSelects($selects);
1093
-    }
1094
-
1095
-
1096
-
1097
-    /**
1098
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1099
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
-     * take care of joins, field preparation etc.
1101
-     *
1102
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1106
-     *                                  override this and set the select to "*", or a specific column name, like
1107
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
-     *                                  the aliases used to refer to this selection, and values are to be
1110
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
-     * @throws EE_Error
1114
-     */
1115
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
-    {
1117
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
-    }
1119
-
1120
-
1121
-
1122
-    /**
1123
-     * For creating a custom select statement
1124
-     *
1125
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
-     *                                 SQL, and 1=>is the datatype
1128
-     * @throws EE_Error
1129
-     * @return string
1130
-     */
1131
-    private function _construct_select_from_input($columns_to_select)
1132
-    {
1133
-        if (is_array($columns_to_select)) {
1134
-            $select_sql_array = array();
1135
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
-                    throw new EE_Error(
1138
-                        sprintf(
1139
-                            __(
1140
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
-                                'event_espresso'
1142
-                            ),
1143
-                            $selection_and_datatype,
1144
-                            $alias
1145
-                        )
1146
-                    );
1147
-                }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
-                    throw new EE_Error(
1150
-                        sprintf(
1151
-                            esc_html__(
1152
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
-                                'event_espresso'
1154
-                            ),
1155
-                            $selection_and_datatype[1],
1156
-                            $selection_and_datatype[0],
1157
-                            $alias,
1158
-                            implode(', ', $this->_valid_wpdb_data_types)
1159
-                        )
1160
-                    );
1161
-                }
1162
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
-            }
1164
-            $columns_to_select_string = implode(', ', $select_sql_array);
1165
-        } else {
1166
-            $columns_to_select_string = $columns_to_select;
1167
-        }
1168
-        return $columns_to_select_string;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
-     *
1176
-     * @return string
1177
-     * @throws EE_Error
1178
-     */
1179
-    public function primary_key_name()
1180
-    {
1181
-        return $this->get_primary_key_field()->get_name();
1182
-    }
1183
-
1184
-
1185
-
1186
-    /**
1187
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
-     * If there is no primary key on this model, $id is treated as primary key string
1189
-     *
1190
-     * @param mixed $id int or string, depending on the type of the model's primary key
1191
-     * @return EE_Base_Class
1192
-     */
1193
-    public function get_one_by_ID($id)
1194
-    {
1195
-        if ($this->get_from_entity_map($id)) {
1196
-            return $this->get_from_entity_map($id);
1197
-        }
1198
-        return $this->get_one(
1199
-            $this->alter_query_params_to_restrict_by_ID(
1200
-                $id,
1201
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
-            )
1203
-        );
1204
-    }
1205
-
1206
-
1207
-
1208
-    /**
1209
-     * Alters query parameters to only get items with this ID are returned.
1210
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
-     * or could just be a simple primary key ID
1212
-     *
1213
-     * @param int   $id
1214
-     * @param array $query_params
1215
-     * @return array of normal query params, @see EEM_Base::get_all
1216
-     * @throws EE_Error
1217
-     */
1218
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
-    {
1220
-        if (! isset($query_params[0])) {
1221
-            $query_params[0] = array();
1222
-        }
1223
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1224
-        if ($conditions_from_id === null) {
1225
-            $query_params[0][$this->primary_key_name()] = $id;
1226
-        } else {
1227
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1228
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
-        }
1230
-        return $query_params;
1231
-    }
1232
-
1233
-
1234
-
1235
-    /**
1236
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
-     * array. If no item is found, null is returned.
1238
-     *
1239
-     * @param array $query_params like EEM_Base's $query_params variable.
1240
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
-     * @throws EE_Error
1242
-     */
1243
-    public function get_one($query_params = array())
1244
-    {
1245
-        if (! is_array($query_params)) {
1246
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
-                    gettype($query_params)), '4.6.0');
1249
-            $query_params = array();
1250
-        }
1251
-        $query_params['limit'] = 1;
1252
-        $items = $this->get_all($query_params);
1253
-        if (empty($items)) {
1254
-            return null;
1255
-        }
1256
-        return array_shift($items);
1257
-    }
1258
-
1259
-
1260
-
1261
-    /**
1262
-     * Returns the next x number of items in sequence from the given value as
1263
-     * found in the database matching the given query conditions.
1264
-     *
1265
-     * @param mixed $current_field_value    Value used for the reference point.
1266
-     * @param null  $field_to_order_by      What field is used for the
1267
-     *                                      reference point.
1268
-     * @param int   $limit                  How many to return.
1269
-     * @param array $query_params           Extra conditions on the query.
1270
-     * @param null  $columns_to_select      If left null, then an array of
1271
-     *                                      EE_Base_Class objects is returned,
1272
-     *                                      otherwise you can indicate just the
1273
-     *                                      columns you want returned.
1274
-     * @return EE_Base_Class[]|array
1275
-     * @throws EE_Error
1276
-     */
1277
-    public function next_x(
1278
-        $current_field_value,
1279
-        $field_to_order_by = null,
1280
-        $limit = 1,
1281
-        $query_params = array(),
1282
-        $columns_to_select = null
1283
-    ) {
1284
-        return $this->_get_consecutive(
1285
-            $current_field_value,
1286
-            '>',
1287
-            $field_to_order_by,
1288
-            $limit,
1289
-            $query_params,
1290
-            $columns_to_select
1291
-        );
1292
-    }
1293
-
1294
-
1295
-
1296
-    /**
1297
-     * Returns the previous x number of items in sequence from the given value
1298
-     * as found in the database matching the given query conditions.
1299
-     *
1300
-     * @param mixed $current_field_value    Value used for the reference point.
1301
-     * @param null  $field_to_order_by      What field is used for the
1302
-     *                                      reference point.
1303
-     * @param int   $limit                  How many to return.
1304
-     * @param array $query_params           Extra conditions on the query.
1305
-     * @param null  $columns_to_select      If left null, then an array of
1306
-     *                                      EE_Base_Class objects is returned,
1307
-     *                                      otherwise you can indicate just the
1308
-     *                                      columns you want returned.
1309
-     * @return EE_Base_Class[]|array
1310
-     * @throws EE_Error
1311
-     */
1312
-    public function previous_x(
1313
-        $current_field_value,
1314
-        $field_to_order_by = null,
1315
-        $limit = 1,
1316
-        $query_params = array(),
1317
-        $columns_to_select = null
1318
-    ) {
1319
-        return $this->_get_consecutive(
1320
-            $current_field_value,
1321
-            '<',
1322
-            $field_to_order_by,
1323
-            $limit,
1324
-            $query_params,
1325
-            $columns_to_select
1326
-        );
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * Returns the next item in sequence from the given value as found in the
1333
-     * database matching the given query conditions.
1334
-     *
1335
-     * @param mixed $current_field_value    Value used for the reference point.
1336
-     * @param null  $field_to_order_by      What field is used for the
1337
-     *                                      reference point.
1338
-     * @param array $query_params           Extra conditions on the query.
1339
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
-     *                                      object is returned, otherwise you
1341
-     *                                      can indicate just the columns you
1342
-     *                                      want and a single array indexed by
1343
-     *                                      the columns will be returned.
1344
-     * @return EE_Base_Class|null|array()
1345
-     * @throws EE_Error
1346
-     */
1347
-    public function next(
1348
-        $current_field_value,
1349
-        $field_to_order_by = null,
1350
-        $query_params = array(),
1351
-        $columns_to_select = null
1352
-    ) {
1353
-        $results = $this->_get_consecutive(
1354
-            $current_field_value,
1355
-            '>',
1356
-            $field_to_order_by,
1357
-            1,
1358
-            $query_params,
1359
-            $columns_to_select
1360
-        );
1361
-        return empty($results) ? null : reset($results);
1362
-    }
1363
-
1364
-
1365
-
1366
-    /**
1367
-     * Returns the previous item in sequence from the given value as found in
1368
-     * the database matching the given query conditions.
1369
-     *
1370
-     * @param mixed $current_field_value    Value used for the reference point.
1371
-     * @param null  $field_to_order_by      What field is used for the
1372
-     *                                      reference point.
1373
-     * @param array $query_params           Extra conditions on the query.
1374
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
-     *                                      object is returned, otherwise you
1376
-     *                                      can indicate just the columns you
1377
-     *                                      want and a single array indexed by
1378
-     *                                      the columns will be returned.
1379
-     * @return EE_Base_Class|null|array()
1380
-     * @throws EE_Error
1381
-     */
1382
-    public function previous(
1383
-        $current_field_value,
1384
-        $field_to_order_by = null,
1385
-        $query_params = array(),
1386
-        $columns_to_select = null
1387
-    ) {
1388
-        $results = $this->_get_consecutive(
1389
-            $current_field_value,
1390
-            '<',
1391
-            $field_to_order_by,
1392
-            1,
1393
-            $query_params,
1394
-            $columns_to_select
1395
-        );
1396
-        return empty($results) ? null : reset($results);
1397
-    }
1398
-
1399
-
1400
-
1401
-    /**
1402
-     * Returns the a consecutive number of items in sequence from the given
1403
-     * value as found in the database matching the given query conditions.
1404
-     *
1405
-     * @param mixed  $current_field_value   Value used for the reference point.
1406
-     * @param string $operand               What operand is used for the sequence.
1407
-     * @param string $field_to_order_by     What field is used for the reference point.
1408
-     * @param int    $limit                 How many to return.
1409
-     * @param array  $query_params          Extra conditions on the query.
1410
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
-     *                                      otherwise you can indicate just the columns you want returned.
1412
-     * @return EE_Base_Class[]|array
1413
-     * @throws EE_Error
1414
-     */
1415
-    protected function _get_consecutive(
1416
-        $current_field_value,
1417
-        $operand = '>',
1418
-        $field_to_order_by = null,
1419
-        $limit = 1,
1420
-        $query_params = array(),
1421
-        $columns_to_select = null
1422
-    ) {
1423
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
-        if (empty($field_to_order_by)) {
1425
-            if ($this->has_primary_key_field()) {
1426
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1427
-            } else {
1428
-                if (WP_DEBUG) {
1429
-                    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).',
1430
-                        'event_espresso'));
1431
-                }
1432
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
-                return array();
1434
-            }
1435
-        }
1436
-        if (! is_array($query_params)) {
1437
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
-                    gettype($query_params)), '4.6.0');
1440
-            $query_params = array();
1441
-        }
1442
-        //let's add the where query param for consecutive look up.
1443
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
-        $query_params['limit'] = $limit;
1445
-        //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
-        $query_params['order_by'] = $operand === '>'
1448
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
-        if (empty($columns_to_select)) {
1452
-            return $this->get_all($query_params);
1453
-        }
1454
-        //getting just the fields
1455
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This sets the _timezone property after model object has been instantiated.
1462
-     *
1463
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
-     */
1465
-    public function set_timezone($timezone)
1466
-    {
1467
-        if ($timezone !== null) {
1468
-            $this->_timezone = $timezone;
1469
-        }
1470
-        //note we need to loop through relations and set the timezone on those objects as well.
1471
-        foreach ($this->_model_relations as $relation) {
1472
-            $relation->set_timezone($timezone);
1473
-        }
1474
-        //and finally we do the same for any datetime fields
1475
-        foreach ($this->_fields as $field) {
1476
-            if ($field instanceof EE_Datetime_Field) {
1477
-                $field->set_timezone($timezone);
1478
-            }
1479
-        }
1480
-    }
1481
-
1482
-
1483
-
1484
-    /**
1485
-     * This just returns whatever is set for the current timezone.
1486
-     *
1487
-     * @access public
1488
-     * @return string
1489
-     */
1490
-    public function get_timezone()
1491
-    {
1492
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
-        if (empty($this->_timezone)) {
1494
-            foreach ($this->_fields as $field) {
1495
-                if ($field instanceof EE_Datetime_Field) {
1496
-                    $this->set_timezone($field->get_timezone());
1497
-                    break;
1498
-                }
1499
-            }
1500
-        }
1501
-        //if timezone STILL empty then return the default timezone for the site.
1502
-        if (empty($this->_timezone)) {
1503
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
-        }
1505
-        return $this->_timezone;
1506
-    }
1507
-
1508
-
1509
-
1510
-    /**
1511
-     * This returns the date formats set for the given field name and also ensures that
1512
-     * $this->_timezone property is set correctly.
1513
-     *
1514
-     * @since 4.6.x
1515
-     * @param string $field_name The name of the field the formats are being retrieved for.
1516
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
-     * @return array formats in an array with the date format first, and the time format last.
1519
-     */
1520
-    public function get_formats_for($field_name, $pretty = false)
1521
-    {
1522
-        $field_settings = $this->field_settings_for($field_name);
1523
-        //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1525
-            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.',
1526
-                'event_espresso'), $field_name));
1527
-        }
1528
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
-        //the field.
1530
-        $this->_timezone = $field_settings->get_timezone();
1531
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
-    }
1533
-
1534
-
1535
-
1536
-    /**
1537
-     * This returns the current time in a format setup for a query on this model.
1538
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
-     * it will return:
1540
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
-     *  NOW
1542
-     *  - or a unix timestamp (equivalent to time())
1543
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
-     * @since 4.6.x
1547
-     * @param string $field_name       The field the current time is needed for.
1548
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
-     *                                 formatted string matching the set format for the field in the set timezone will
1550
-     *                                 be returned.
1551
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
-     *                                 exception is triggered.
1555
-     */
1556
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
-    {
1558
-        $formats = $this->get_formats_for($field_name);
1559
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
-        if ($timestamp) {
1561
-            return $DateTime->format('U');
1562
-        }
1563
-        //not returning timestamp, so return formatted string in timezone.
1564
-        switch ($what) {
1565
-            case 'time' :
1566
-                return $DateTime->format($formats[1]);
1567
-                break;
1568
-            case 'date' :
1569
-                return $DateTime->format($formats[0]);
1570
-                break;
1571
-            default :
1572
-                return $DateTime->format(implode(' ', $formats));
1573
-                break;
1574
-        }
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
-     * for the model are.  Returns a DateTime object.
1582
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
-     * ignored.
1585
-     *
1586
-     * @param string $field_name      The field being setup.
1587
-     * @param string $timestring      The date time string being used.
1588
-     * @param string $incoming_format The format for the time string.
1589
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
-     *                                format is
1592
-     *                                'U', this is ignored.
1593
-     * @return DateTime
1594
-     * @throws EE_Error
1595
-     */
1596
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
-    {
1598
-        //just using this to ensure the timezone is set correctly internally
1599
-        $this->get_formats_for($field_name);
1600
-        //load EEH_DTT_Helper
1601
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1604
-    }
1605
-
1606
-
1607
-
1608
-    /**
1609
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
-     *
1611
-     * @return EE_Table_Base[]
1612
-     */
1613
-    public function get_tables()
1614
-    {
1615
-        return $this->_tables;
1616
-    }
1617
-
1618
-
1619
-
1620
-    /**
1621
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1622
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1623
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1624
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1625
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1626
-     * model object with EVT_ID = 1
1627
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1628
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1629
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1630
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1631
-     * are not specified)
1632
-     *
1633
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1634
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1635
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1636
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1637
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1638
-     *                                         ID=34, we'd use this method as follows:
1639
-     *                                         EEM_Transaction::instance()->update(
1640
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1641
-     *                                         array(array('TXN_ID'=>34)));
1642
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1643
-     *                                         in client code into what's expected to be stored on each field. Eg,
1644
-     *                                         consider updating Question's QST_admin_label field is of type
1645
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1646
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1647
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1648
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1649
-     *                                         TRUE, it is assumed that you've already called
1650
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1651
-     *                                         malicious javascript. However, if
1652
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1653
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1654
-     *                                         and every other field, before insertion. We provide this parameter
1655
-     *                                         because model objects perform their prepare_for_set function on all
1656
-     *                                         their values, and so don't need to be called again (and in many cases,
1657
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1658
-     *                                         prepare_for_set method...)
1659
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1660
-     *                                         in this model's entity map according to $fields_n_values that match
1661
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1662
-     *                                         by setting this to FALSE, but be aware that model objects being used
1663
-     *                                         could get out-of-sync with the database
1664
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1665
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1666
-     *                                         bad)
1667
-     * @throws EE_Error
1668
-     */
1669
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670
-    {
1671
-        if (! is_array($query_params)) {
1672
-            EE_Error::doing_it_wrong('EEM_Base::update',
1673
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674
-                    gettype($query_params)), '4.6.0');
1675
-            $query_params = array();
1676
-        }
1677
-        /**
1678
-         * Action called before a model update call has been made.
1679
-         *
1680
-         * @param EEM_Base $model
1681
-         * @param array    $fields_n_values the updated fields and their new values
1682
-         * @param array    $query_params    @see EEM_Base::get_all()
1683
-         */
1684
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1685
-        /**
1686
-         * Filters the fields about to be updated given the query parameters. You can provide the
1687
-         * $query_params to $this->get_all() to find exactly which records will be updated
1688
-         *
1689
-         * @param array    $fields_n_values fields and their new values
1690
-         * @param EEM_Base $model           the model being queried
1691
-         * @param array    $query_params    see EEM_Base::get_all()
1692
-         */
1693
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694
-            $query_params);
1695
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1696
-        //to do that, for each table, verify that it's PK isn't null.
1697
-        $tables = $this->get_tables();
1698
-        //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
1699
-        //NOTE: we should make this code more efficient by NOT querying twice
1700
-        //before the real update, but that needs to first go through ALPHA testing
1701
-        //as it's dangerous. says Mike August 8 2014
1702
-        //we want to make sure the default_where strategy is ignored
1703
-        $this->_ignore_where_strategy = true;
1704
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705
-        foreach ($wpdb_select_results as $wpdb_result) {
1706
-            // type cast stdClass as array
1707
-            $wpdb_result = (array)$wpdb_result;
1708
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709
-            if ($this->has_primary_key_field()) {
1710
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1711
-            } else {
1712
-                //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)
1713
-                $main_table_pk_value = null;
1714
-            }
1715
-            //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
1716
-            //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
1717
-            if (count($tables) > 1) {
1718
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1719
-                //in that table, and so we'll want to insert one
1720
-                foreach ($tables as $table_obj) {
1721
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722
-                    //if there is no private key for this table on the results, it means there's no entry
1723
-                    //in this table, right? so insert a row in the current table, using any fields available
1724
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1725
-                           && $wpdb_result[$this_table_pk_column])
1726
-                    ) {
1727
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728
-                            $main_table_pk_value);
1729
-                        //if we died here, report the error
1730
-                        if (! $success) {
1731
-                            return false;
1732
-                        }
1733
-                    }
1734
-                }
1735
-            }
1736
-            //				//and now check that if we have cached any models by that ID on the model, that
1737
-            //				//they also get updated properly
1738
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1739
-            //				if( $model_object ){
1740
-            //					foreach( $fields_n_values as $field => $value ){
1741
-            //						$model_object->set($field, $value);
1742
-            //let's make sure default_where strategy is followed now
1743
-            $this->_ignore_where_strategy = false;
1744
-        }
1745
-        //if we want to keep model objects in sync, AND
1746
-        //if this wasn't called from a model object (to update itself)
1747
-        //then we want to make sure we keep all the existing
1748
-        //model objects in sync with the db
1749
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1750
-            if ($this->has_primary_key_field()) {
1751
-                $model_objs_affected_ids = $this->get_col($query_params);
1752
-            } else {
1753
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1754
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1755
-                $model_objs_affected_ids = array();
1756
-                foreach ($models_affected_key_columns as $row) {
1757
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1758
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759
-                }
1760
-            }
1761
-            if (! $model_objs_affected_ids) {
1762
-                //wait wait wait- if nothing was affected let's stop here
1763
-                return 0;
1764
-            }
1765
-            foreach ($model_objs_affected_ids as $id) {
1766
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1767
-                if ($model_obj_in_entity_map) {
1768
-                    foreach ($fields_n_values as $field => $new_value) {
1769
-                        $model_obj_in_entity_map->set($field, $new_value);
1770
-                    }
1771
-                }
1772
-            }
1773
-            //if there is a primary key on this model, we can now do a slight optimization
1774
-            if ($this->has_primary_key_field()) {
1775
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1776
-                $query_params = array(
1777
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1778
-                    'limit'                    => count($model_objs_affected_ids),
1779
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1780
-                );
1781
-            }
1782
-        }
1783
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1784
-        $SQL = "UPDATE "
1785
-               . $model_query_info->get_full_join_sql()
1786
-               . " SET "
1787
-               . $this->_construct_update_sql($fields_n_values)
1788
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790
-        /**
1791
-         * Action called after a model update call has been made.
1792
-         *
1793
-         * @param EEM_Base $model
1794
-         * @param array    $fields_n_values the updated fields and their new values
1795
-         * @param array    $query_params    @see EEM_Base::get_all()
1796
-         * @param int      $rows_affected
1797
-         */
1798
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
-        return $rows_affected;//how many supposedly got updated
1800
-    }
1801
-
1802
-
1803
-
1804
-    /**
1805
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1806
-     * are teh values of the field specified (or by default the primary key field)
1807
-     * that matched the query params. Note that you should pass the name of the
1808
-     * model FIELD, not the database table's column name.
1809
-     *
1810
-     * @param array  $query_params @see EEM_Base::get_all()
1811
-     * @param string $field_to_select
1812
-     * @return array just like $wpdb->get_col()
1813
-     * @throws EE_Error
1814
-     */
1815
-    public function get_col($query_params = array(), $field_to_select = null)
1816
-    {
1817
-        if ($field_to_select) {
1818
-            $field = $this->field_settings_for($field_to_select);
1819
-        } elseif ($this->has_primary_key_field()) {
1820
-            $field = $this->get_primary_key_field();
1821
-        } else {
1822
-            //no primary key, just grab the first column
1823
-            $field = reset($this->field_settings());
1824
-        }
1825
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1826
-        $select_expressions = $field->get_qualified_column();
1827
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1828
-        return $this->_do_wpdb_query('get_col', array($SQL));
1829
-    }
1830
-
1831
-
1832
-
1833
-    /**
1834
-     * Returns a single column value for a single row from the database
1835
-     *
1836
-     * @param array  $query_params    @see EEM_Base::get_all()
1837
-     * @param string $field_to_select @see EEM_Base::get_col()
1838
-     * @return string
1839
-     * @throws EE_Error
1840
-     */
1841
-    public function get_var($query_params = array(), $field_to_select = null)
1842
-    {
1843
-        $query_params['limit'] = 1;
1844
-        $col = $this->get_col($query_params, $field_to_select);
1845
-        if (! empty($col)) {
1846
-            return reset($col);
1847
-        }
1848
-        return null;
1849
-    }
1850
-
1851
-
1852
-
1853
-    /**
1854
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1855
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1856
-     * injection, but currently no further filtering is done
1857
-     *
1858
-     * @global      $wpdb
1859
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1860
-     *                               be updated to in the DB
1861
-     * @return string of SQL
1862
-     * @throws EE_Error
1863
-     */
1864
-    public function _construct_update_sql($fields_n_values)
1865
-    {
1866
-        /** @type WPDB $wpdb */
1867
-        global $wpdb;
1868
-        $cols_n_values = array();
1869
-        foreach ($fields_n_values as $field_name => $value) {
1870
-            $field_obj = $this->field_settings_for($field_name);
1871
-            //if the value is NULL, we want to assign the value to that.
1872
-            //wpdb->prepare doesn't really handle that properly
1873
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874
-            $value_sql = $prepared_value === null ? 'NULL'
1875
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1877
-        }
1878
-        return implode(",", $cols_n_values);
1879
-    }
1880
-
1881
-
1882
-
1883
-    /**
1884
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1885
-     * Performs a HARD delete, meaning the database row should always be removed,
1886
-     * not just have a flag field on it switched
1887
-     * Wrapper for EEM_Base::delete_permanently()
1888
-     *
1889
-     * @param mixed $id
1890
-     * @param boolean $allow_blocking
1891
-     * @return int the number of rows deleted
1892
-     * @throws EE_Error
1893
-     */
1894
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1895
-    {
1896
-        return $this->delete_permanently(
1897
-            array(
1898
-                array($this->get_primary_key_field()->get_name() => $id),
1899
-                'limit' => 1,
1900
-            ),
1901
-            $allow_blocking
1902
-        );
1903
-    }
1904
-
1905
-
1906
-
1907
-    /**
1908
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1909
-     * Wrapper for EEM_Base::delete()
1910
-     *
1911
-     * @param mixed $id
1912
-     * @param boolean $allow_blocking
1913
-     * @return int the number of rows deleted
1914
-     * @throws EE_Error
1915
-     */
1916
-    public function delete_by_ID($id, $allow_blocking = true)
1917
-    {
1918
-        return $this->delete(
1919
-            array(
1920
-                array($this->get_primary_key_field()->get_name() => $id),
1921
-                'limit' => 1,
1922
-            ),
1923
-            $allow_blocking
1924
-        );
1925
-    }
1926
-
1927
-
1928
-
1929
-    /**
1930
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1931
-     * meaning if the model has a field that indicates its been "trashed" or
1932
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1933
-     *
1934
-     * @see EEM_Base::delete_permanently
1935
-     * @param array   $query_params
1936
-     * @param boolean $allow_blocking
1937
-     * @return int how many rows got deleted
1938
-     * @throws EE_Error
1939
-     */
1940
-    public function delete($query_params, $allow_blocking = true)
1941
-    {
1942
-        return $this->delete_permanently($query_params, $allow_blocking);
1943
-    }
1944
-
1945
-
1946
-
1947
-    /**
1948
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1949
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1950
-     * as archived, not actually deleted
1951
-     *
1952
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1953
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1954
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1955
-     *                                deletes regardless of other objects which may depend on it. Its generally
1956
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1957
-     *                                DB
1958
-     * @return int how many rows got deleted
1959
-     * @throws EE_Error
1960
-     */
1961
-    public function delete_permanently($query_params, $allow_blocking = true)
1962
-    {
1963
-        /**
1964
-         * Action called just before performing a real deletion query. You can use the
1965
-         * model and its $query_params to find exactly which items will be deleted
1966
-         *
1967
-         * @param EEM_Base $model
1968
-         * @param array    $query_params   @see EEM_Base::get_all()
1969
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1970
-         *                                 to block (prevent) this deletion
1971
-         */
1972
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1973
-        //some MySQL databases may be running safe mode, which may restrict
1974
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1975
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1976
-        //to delete them
1977
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1978
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1979
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1980
-            $columns_and_ids_for_deleting
1981
-        );
1982
-        /**
1983
-         * Allows client code to act on the items being deleted before the query is actually executed.
1984
-         *
1985
-         * @param EEM_Base $this  The model instance being acted on.
1986
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1987
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1988
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1989
-         *                                                  derived from the incoming query parameters.
1990
-         *                                                  @see details on the structure of this array in the phpdocs
1991
-         *                                                  for the `_get_ids_for_delete_method`
1992
-         *
1993
-         */
1994
-        do_action('AHEE__EEM_Base__delete__before_query',
1995
-            $this,
1996
-            $query_params,
1997
-            $allow_blocking,
1998
-            $columns_and_ids_for_deleting
1999
-        );
2000
-        if ($deletion_where_query_part) {
2001
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
2002
-            $table_aliases = array_keys($this->_tables);
2003
-            $SQL = "DELETE "
2004
-                   . implode(", ", $table_aliases)
2005
-                   . " FROM "
2006
-                   . $model_query_info->get_full_join_sql()
2007
-                   . " WHERE "
2008
-                   . $deletion_where_query_part;
2009
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2010
-        } else {
2011
-            $rows_deleted = 0;
2012
-        }
2013
-
2014
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2015
-        //there was no error with the delete query.
2016
-        if ($this->has_primary_key_field()
2017
-            && $rows_deleted !== false
2018
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2019
-        ) {
2020
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2021
-            foreach ($ids_for_removal as $id) {
2022
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2023
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2024
-                }
2025
-            }
2026
-
2027
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2028
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2029
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2030
-            // (although it is possible).
2031
-            //Note this can be skipped by using the provided filter and returning false.
2032
-            if (apply_filters(
2033
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2034
-                ! $this instanceof EEM_Extra_Meta,
2035
-                $this
2036
-            )) {
2037
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2038
-                    0 => array(
2039
-                        'EXM_type' => $this->get_this_model_name(),
2040
-                        'OBJ_ID'   => array(
2041
-                            'IN',
2042
-                            $ids_for_removal
2043
-                        )
2044
-                    )
2045
-                ));
2046
-            }
2047
-        }
2048
-
2049
-        /**
2050
-         * Action called just after performing a real deletion query. Although at this point the
2051
-         * items should have been deleted
2052
-         *
2053
-         * @param EEM_Base $model
2054
-         * @param array    $query_params @see EEM_Base::get_all()
2055
-         * @param int      $rows_deleted
2056
-         */
2057
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;//how many supposedly got deleted
2059
-    }
2060
-
2061
-
2062
-
2063
-    /**
2064
-     * Checks all the relations that throw error messages when there are blocking related objects
2065
-     * for related model objects. If there are any related model objects on those relations,
2066
-     * adds an EE_Error, and return true
2067
-     *
2068
-     * @param EE_Base_Class|int $this_model_obj_or_id
2069
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2070
-     *                                                 should be ignored when determining whether there are related
2071
-     *                                                 model objects which block this model object's deletion. Useful
2072
-     *                                                 if you know A is related to B and are considering deleting A,
2073
-     *                                                 but want to see if A has any other objects blocking its deletion
2074
-     *                                                 before removing the relation between A and B
2075
-     * @return boolean
2076
-     * @throws EE_Error
2077
-     */
2078
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
-    {
2080
-        //first, if $ignore_this_model_obj was supplied, get its model
2081
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
-            $ignored_model = $ignore_this_model_obj->get_model();
2083
-        } else {
2084
-            $ignored_model = null;
2085
-        }
2086
-        //now check all the relations of $this_model_obj_or_id and see if there
2087
-        //are any related model objects blocking it?
2088
-        $is_blocked = false;
2089
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2091
-                //if $ignore_this_model_obj was supplied, then for the query
2092
-                //on that model needs to be told to ignore $ignore_this_model_obj
2093
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2095
-                        array(
2096
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2097
-                                '!=',
2098
-                                $ignore_this_model_obj->ID(),
2099
-                            ),
2100
-                        ),
2101
-                    ));
2102
-                } else {
2103
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2104
-                }
2105
-                if ($related_model_objects) {
2106
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2107
-                    $is_blocked = true;
2108
-                }
2109
-            }
2110
-        }
2111
-        return $is_blocked;
2112
-    }
2113
-
2114
-
2115
-    /**
2116
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2117
-     * @param array $row_results_for_deleting
2118
-     * @param bool  $allow_blocking
2119
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2120
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2121
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2122
-     *                 deleted. Example:
2123
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2124
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2125
-     *                 where each element is a group of columns and values that get deleted. Example:
2126
-     *                      array(
2127
-     *                          0 => array(
2128
-     *                              'Term_Relationship.object_id' => 1
2129
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2130
-     *                          ),
2131
-     *                          1 => array(
2132
-     *                              'Term_Relationship.object_id' => 1
2133
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2134
-     *                          )
2135
-     *                      )
2136
-     * @throws EE_Error
2137
-     */
2138
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2139
-    {
2140
-        $ids_to_delete_indexed_by_column = array();
2141
-        if ($this->has_primary_key_field()) {
2142
-            $primary_table = $this->_get_main_table();
2143
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2144
-            $other_tables = $this->_get_other_tables();
2145
-            $ids_to_delete_indexed_by_column = $query = array();
2146
-            foreach ($row_results_for_deleting as $item_to_delete) {
2147
-                //before we mark this item for deletion,
2148
-                //make sure there's no related entities blocking its deletion (if we're checking)
2149
-                if (
2150
-                    $allow_blocking
2151
-                    && $this->delete_is_blocked_by_related_models(
2152
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2153
-                    )
2154
-                ) {
2155
-                    continue;
2156
-                }
2157
-                //primary table deletes
2158
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2159
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2160
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2161
-                }
2162
-            }
2163
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2164
-            $fields = $this->get_combined_primary_key_fields();
2165
-            foreach ($row_results_for_deleting as $item_to_delete) {
2166
-                $ids_to_delete_indexed_by_column_for_row = array();
2167
-                foreach ($fields as $cpk_field) {
2168
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2169
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2170
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2171
-                    }
2172
-                }
2173
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2174
-            }
2175
-        } else {
2176
-            //so there's no primary key and no combined key...
2177
-            //sorry, can't help you
2178
-            throw new EE_Error(
2179
-                sprintf(
2180
-                    __(
2181
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2182
-                        "event_espresso"
2183
-                    ), get_class($this)
2184
-                )
2185
-            );
2186
-        }
2187
-        return $ids_to_delete_indexed_by_column;
2188
-    }
2189
-
2190
-
2191
-    /**
2192
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2193
-     * the corresponding query_part for the query performing the delete.
2194
-     *
2195
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2196
-     * @return string
2197
-     * @throws EE_Error
2198
-     */
2199
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2200
-        $query_part = '';
2201
-        if (empty($ids_to_delete_indexed_by_column)) {
2202
-            return $query_part;
2203
-        } elseif ($this->has_primary_key_field()) {
2204
-            $query = array();
2205
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206
-                //make sure we have unique $ids
2207
-                $ids = array_unique($ids);
2208
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2209
-            }
2210
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2212
-            $ways_to_identify_a_row = array();
2213
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214
-                $values_for_each_combined_primary_key_for_a_row = array();
2215
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2217
-                }
2218
-                $ways_to_identify_a_row[] = '('
2219
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2220
-                                            . ')';
2221
-            }
2222
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2223
-        }
2224
-        return $query_part;
2225
-    }
2226
-
2227
-
2228
-
2229
-    /**
2230
-     * Gets the model field by the fully qualified name
2231
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2232
-     * @return EE_Model_Field_Base
2233
-     */
2234
-    public function get_field_by_column($qualified_column_name)
2235
-    {
2236
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2237
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2238
-               return $field_obj;
2239
-           }
2240
-       }
2241
-        throw new EE_Error(
2242
-            sprintf(
2243
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2244
-                $this->get_this_model_name(),
2245
-                $qualified_column_name
2246
-            )
2247
-        );
2248
-    }
2249
-
2250
-
2251
-
2252
-    /**
2253
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2254
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2255
-     * column
2256
-     *
2257
-     * @param array  $query_params   like EEM_Base::get_all's
2258
-     * @param string $field_to_count field on model to count by (not column name)
2259
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2260
-     *                               that by the setting $distinct to TRUE;
2261
-     * @return int
2262
-     * @throws EE_Error
2263
-     */
2264
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2265
-    {
2266
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2267
-        if ($field_to_count) {
2268
-            $field_obj = $this->field_settings_for($field_to_count);
2269
-            $column_to_count = $field_obj->get_qualified_column();
2270
-        } elseif ($this->has_primary_key_field()) {
2271
-            $pk_field_obj = $this->get_primary_key_field();
2272
-            $column_to_count = $pk_field_obj->get_qualified_column();
2273
-        } else {
2274
-            //there's no primary key
2275
-            //if we're counting distinct items, and there's no primary key,
2276
-            //we need to list out the columns for distinction;
2277
-            //otherwise we can just use star
2278
-            if ($distinct) {
2279
-                $columns_to_use = array();
2280
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2281
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2282
-                }
2283
-                $column_to_count = implode(',', $columns_to_use);
2284
-            } else {
2285
-                $column_to_count = '*';
2286
-            }
2287
-        }
2288
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2297
-     *
2298
-     * @param array  $query_params like EEM_Base::get_all
2299
-     * @param string $field_to_sum name of field (array key in $_fields array)
2300
-     * @return float
2301
-     * @throws EE_Error
2302
-     */
2303
-    public function sum($query_params, $field_to_sum = null)
2304
-    {
2305
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
-        if ($field_to_sum) {
2307
-            $field_obj = $this->field_settings_for($field_to_sum);
2308
-        } else {
2309
-            $field_obj = $this->get_primary_key_field();
2310
-        }
2311
-        $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314
-        $data_type = $field_obj->get_wpdb_data_type();
2315
-        if ($data_type === '%d' || $data_type === '%s') {
2316
-            return (float)$return_value;
2317
-        }
2318
-        //must be %f
2319
-        return (float)$return_value;
2320
-    }
2321
-
2322
-
2323
-
2324
-    /**
2325
-     * Just calls the specified method on $wpdb with the given arguments
2326
-     * Consolidates a little extra error handling code
2327
-     *
2328
-     * @param string $wpdb_method
2329
-     * @param array  $arguments_to_provide
2330
-     * @throws EE_Error
2331
-     * @global wpdb  $wpdb
2332
-     * @return mixed
2333
-     */
2334
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
-    {
2336
-        //if we're in maintenance mode level 2, DON'T run any queries
2337
-        //because level 2 indicates the database needs updating and
2338
-        //is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
-            throw new EE_Error(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.",
2341
-                "event_espresso")));
2342
-        }
2343
-        /** @type WPDB $wpdb */
2344
-        global $wpdb;
2345
-        if (! method_exists($wpdb, $wpdb_method)) {
2346
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347
-                'event_espresso'), $wpdb_method));
2348
-        }
2349
-        if (WP_DEBUG) {
2350
-            $old_show_errors_value = $wpdb->show_errors;
2351
-            $wpdb->show_errors(false);
2352
-        }
2353
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2354
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2355
-        if (WP_DEBUG) {
2356
-            $wpdb->show_errors($old_show_errors_value);
2357
-            if (! empty($wpdb->last_error)) {
2358
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359
-            }
2360
-            if ($result === false) {
2361
-                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"',
2362
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2363
-            }
2364
-        } elseif ($result === false) {
2365
-            EE_Error::add_error(
2366
-                sprintf(
2367
-                    __('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"',
2368
-                        'event_espresso'),
2369
-                    $wpdb_method,
2370
-                    var_export($arguments_to_provide, true),
2371
-                    $wpdb->last_error
2372
-                ),
2373
-                __FILE__,
2374
-                __FUNCTION__,
2375
-                __LINE__
2376
-            );
2377
-        }
2378
-        return $result;
2379
-    }
2380
-
2381
-
2382
-
2383
-    /**
2384
-     * Attempts to run the indicated WPDB method with the provided arguments,
2385
-     * and if there's an error tries to verify the DB is correct. Uses
2386
-     * the static property EEM_Base::$_db_verification_level to determine whether
2387
-     * we should try to fix the EE core db, the addons, or just give up
2388
-     *
2389
-     * @param string $wpdb_method
2390
-     * @param array  $arguments_to_provide
2391
-     * @return mixed
2392
-     */
2393
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2394
-    {
2395
-        /** @type WPDB $wpdb */
2396
-        global $wpdb;
2397
-        $wpdb->last_error = null;
2398
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2399
-        // was there an error running the query? but we don't care on new activations
2400
-        // (we're going to setup the DB anyway on new activations)
2401
-        if (($result === false || ! empty($wpdb->last_error))
2402
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2403
-        ) {
2404
-            switch (EEM_Base::$_db_verification_level) {
2405
-                case EEM_Base::db_verified_none :
2406
-                    // let's double-check core's DB
2407
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2408
-                    break;
2409
-                case EEM_Base::db_verified_core :
2410
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2411
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2412
-                    break;
2413
-                case EEM_Base::db_verified_addons :
2414
-                    // ummmm... you in trouble
2415
-                    return $result;
2416
-                    break;
2417
-            }
2418
-            if (! empty($error_message)) {
2419
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420
-                trigger_error($error_message);
2421
-            }
2422
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2423
-        }
2424
-        return $result;
2425
-    }
2426
-
2427
-
2428
-
2429
-    /**
2430
-     * Verifies the EE core database is up-to-date and records that we've done it on
2431
-     * EEM_Base::$_db_verification_level
2432
-     *
2433
-     * @param string $wpdb_method
2434
-     * @param array  $arguments_to_provide
2435
-     * @return string
2436
-     */
2437
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2438
-    {
2439
-        /** @type WPDB $wpdb */
2440
-        global $wpdb;
2441
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2442
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2443
-        $error_message = sprintf(
2444
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2445
-                'event_espresso'),
2446
-            $wpdb->last_error,
2447
-            $wpdb_method,
2448
-            wp_json_encode($arguments_to_provide)
2449
-        );
2450
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2451
-        return $error_message;
2452
-    }
2453
-
2454
-
2455
-
2456
-    /**
2457
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2458
-     * EEM_Base::$_db_verification_level
2459
-     *
2460
-     * @param $wpdb_method
2461
-     * @param $arguments_to_provide
2462
-     * @return string
2463
-     */
2464
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2465
-    {
2466
-        /** @type WPDB $wpdb */
2467
-        global $wpdb;
2468
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2469
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2470
-        $error_message = sprintf(
2471
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2472
-                'event_espresso'),
2473
-            $wpdb->last_error,
2474
-            $wpdb_method,
2475
-            wp_json_encode($arguments_to_provide)
2476
-        );
2477
-        EE_System::instance()->initialize_addons();
2478
-        return $error_message;
2479
-    }
2480
-
2481
-
2482
-
2483
-    /**
2484
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2485
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2486
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2487
-     * ..."
2488
-     *
2489
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2490
-     * @return string
2491
-     */
2492
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493
-    {
2494
-        return " FROM " . $model_query_info->get_full_join_sql() .
2495
-               $model_query_info->get_where_sql() .
2496
-               $model_query_info->get_group_by_sql() .
2497
-               $model_query_info->get_having_sql() .
2498
-               $model_query_info->get_order_by_sql() .
2499
-               $model_query_info->get_limit_sql();
2500
-    }
2501
-
2502
-
2503
-
2504
-    /**
2505
-     * Set to easily debug the next X queries ran from this model.
2506
-     *
2507
-     * @param int $count
2508
-     */
2509
-    public function show_next_x_db_queries($count = 1)
2510
-    {
2511
-        $this->_show_next_x_db_queries = $count;
2512
-    }
2513
-
2514
-
2515
-
2516
-    /**
2517
-     * @param $sql_query
2518
-     */
2519
-    public function show_db_query_if_previously_requested($sql_query)
2520
-    {
2521
-        if ($this->_show_next_x_db_queries > 0) {
2522
-            echo $sql_query;
2523
-            $this->_show_next_x_db_queries--;
2524
-        }
2525
-    }
2526
-
2527
-
2528
-
2529
-    /**
2530
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2531
-     * There are the 3 cases:
2532
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2533
-     * $otherModelObject has no ID, it is first saved.
2534
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2535
-     * has no ID, it is first saved.
2536
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2537
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2538
-     * join table
2539
-     *
2540
-     * @param        EE_Base_Class                     /int $thisModelObject
2541
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2542
-     * @param string $relationName                     , key in EEM_Base::_relations
2543
-     *                                                 an attendee to a group, you also want to specify which role they
2544
-     *                                                 will have in that group. So you would use this parameter to
2545
-     *                                                 specify array('role-column-name'=>'role-id')
2546
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2547
-     *                                                 to for relation to methods that allow you to further specify
2548
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2549
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2550
-     *                                                 because these will be inserted in any new rows created as well.
2551
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2552
-     * @throws EE_Error
2553
-     */
2554
-    public function add_relationship_to(
2555
-        $id_or_obj,
2556
-        $other_model_id_or_obj,
2557
-        $relationName,
2558
-        $extra_join_model_fields_n_values = array()
2559
-    ) {
2560
-        $relation_obj = $this->related_settings_for($relationName);
2561
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2562
-    }
2563
-
2564
-
2565
-
2566
-    /**
2567
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2568
-     * There are the 3 cases:
2569
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2570
-     * error
2571
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2572
-     * an error
2573
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2574
-     *
2575
-     * @param        EE_Base_Class /int $id_or_obj
2576
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2577
-     * @param string $relationName key in EEM_Base::_relations
2578
-     * @return boolean of success
2579
-     * @throws EE_Error
2580
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2581
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2582
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2583
-     *                             because these will be inserted in any new rows created as well.
2584
-     */
2585
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2586
-    {
2587
-        $relation_obj = $this->related_settings_for($relationName);
2588
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2589
-    }
2590
-
2591
-
2592
-
2593
-    /**
2594
-     * @param mixed           $id_or_obj
2595
-     * @param string          $relationName
2596
-     * @param array           $where_query_params
2597
-     * @param EE_Base_Class[] objects to which relations were removed
2598
-     * @return \EE_Base_Class[]
2599
-     * @throws EE_Error
2600
-     */
2601
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2602
-    {
2603
-        $relation_obj = $this->related_settings_for($relationName);
2604
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2605
-    }
2606
-
2607
-
2608
-
2609
-    /**
2610
-     * Gets all the related items of the specified $model_name, using $query_params.
2611
-     * Note: by default, we remove the "default query params"
2612
-     * because we want to get even deleted items etc.
2613
-     *
2614
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2615
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2616
-     * @param array  $query_params like EEM_Base::get_all
2617
-     * @return EE_Base_Class[]
2618
-     * @throws EE_Error
2619
-     */
2620
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2621
-    {
2622
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2623
-        $relation_settings = $this->related_settings_for($model_name);
2624
-        return $relation_settings->get_all_related($model_obj, $query_params);
2625
-    }
2626
-
2627
-
2628
-
2629
-    /**
2630
-     * Deletes all the model objects across the relation indicated by $model_name
2631
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2632
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2633
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2634
-     *
2635
-     * @param EE_Base_Class|int|string $id_or_obj
2636
-     * @param string                   $model_name
2637
-     * @param array                    $query_params
2638
-     * @return int how many deleted
2639
-     * @throws EE_Error
2640
-     */
2641
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2642
-    {
2643
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2644
-        $relation_settings = $this->related_settings_for($model_name);
2645
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2646
-    }
2647
-
2648
-
2649
-
2650
-    /**
2651
-     * Hard deletes all the model objects across the relation indicated by $model_name
2652
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2653
-     * the model objects can't be hard deleted because of blocking related model objects,
2654
-     * just does a soft-delete on them instead.
2655
-     *
2656
-     * @param EE_Base_Class|int|string $id_or_obj
2657
-     * @param string                   $model_name
2658
-     * @param array                    $query_params
2659
-     * @return int how many deleted
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2663
-    {
2664
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2665
-        $relation_settings = $this->related_settings_for($model_name);
2666
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2667
-    }
2668
-
2669
-
2670
-
2671
-    /**
2672
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2673
-     * unless otherwise specified in the $query_params
2674
-     *
2675
-     * @param        int             /EE_Base_Class $id_or_obj
2676
-     * @param string $model_name     like 'Event', or 'Registration'
2677
-     * @param array  $query_params   like EEM_Base::get_all's
2678
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2679
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2680
-     *                               that by the setting $distinct to TRUE;
2681
-     * @return int
2682
-     * @throws EE_Error
2683
-     */
2684
-    public function count_related(
2685
-        $id_or_obj,
2686
-        $model_name,
2687
-        $query_params = array(),
2688
-        $field_to_count = null,
2689
-        $distinct = false
2690
-    ) {
2691
-        $related_model = $this->get_related_model_obj($model_name);
2692
-        //we're just going to use the query params on the related model's normal get_all query,
2693
-        //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2695
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
-        }
2697
-        $this_model_name = $this->get_this_model_name();
2698
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
-        return $related_model->count($query_params, $field_to_count, $distinct);
2701
-    }
2702
-
2703
-
2704
-
2705
-    /**
2706
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2707
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2708
-     *
2709
-     * @param        int           /EE_Base_Class $id_or_obj
2710
-     * @param string $model_name   like 'Event', or 'Registration'
2711
-     * @param array  $query_params like EEM_Base::get_all's
2712
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2713
-     * @return float
2714
-     * @throws EE_Error
2715
-     */
2716
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717
-    {
2718
-        $related_model = $this->get_related_model_obj($model_name);
2719
-        if (! is_array($query_params)) {
2720
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722
-                    gettype($query_params)), '4.6.0');
2723
-            $query_params = array();
2724
-        }
2725
-        //we're just going to use the query params on the related model's normal get_all query,
2726
-        //except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2728
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
-        }
2730
-        $this_model_name = $this->get_this_model_name();
2731
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2733
-        return $related_model->sum($query_params, $field_to_sum);
2734
-    }
2735
-
2736
-
2737
-
2738
-    /**
2739
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2740
-     * $modelObject
2741
-     *
2742
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2743
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2744
-     * @param array               $query_params     like EEM_Base::get_all's
2745
-     * @return EE_Base_Class
2746
-     * @throws EE_Error
2747
-     */
2748
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2749
-    {
2750
-        $query_params['limit'] = 1;
2751
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2752
-        if ($results) {
2753
-            return array_shift($results);
2754
-        }
2755
-        return null;
2756
-    }
2757
-
2758
-
2759
-
2760
-    /**
2761
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2762
-     *
2763
-     * @return string
2764
-     */
2765
-    public function get_this_model_name()
2766
-    {
2767
-        return str_replace("EEM_", "", get_class($this));
2768
-    }
2769
-
2770
-
2771
-
2772
-    /**
2773
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2774
-     *
2775
-     * @return EE_Any_Foreign_Model_Name_Field
2776
-     * @throws EE_Error
2777
-     */
2778
-    public function get_field_containing_related_model_name()
2779
-    {
2780
-        foreach ($this->field_settings(true) as $field) {
2781
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2782
-                $field_with_model_name = $field;
2783
-            }
2784
-        }
2785
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2786
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787
-                $this->get_this_model_name()));
2788
-        }
2789
-        return $field_with_model_name;
2790
-    }
2791
-
2792
-
2793
-
2794
-    /**
2795
-     * Inserts a new entry into the database, for each table.
2796
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2797
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2798
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2799
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2800
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2801
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2802
-     *
2803
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2804
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2805
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2806
-     *                              of EEM_Base)
2807
-     * @return int new primary key on main table that got inserted
2808
-     * @throws EE_Error
2809
-     */
2810
-    public function insert($field_n_values)
2811
-    {
2812
-        /**
2813
-         * Filters the fields and their values before inserting an item using the models
2814
-         *
2815
-         * @param array    $fields_n_values keys are the fields and values are their new values
2816
-         * @param EEM_Base $model           the model used
2817
-         */
2818
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2820
-            $main_table = $this->_get_main_table();
2821
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2822
-            if ($new_id !== false) {
2823
-                foreach ($this->_get_other_tables() as $other_table) {
2824
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2825
-                }
2826
-            }
2827
-            /**
2828
-             * Done just after attempting to insert a new model object
2829
-             *
2830
-             * @param EEM_Base   $model           used
2831
-             * @param array      $fields_n_values fields and their values
2832
-             * @param int|string the              ID of the newly-inserted model object
2833
-             */
2834
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2835
-            return $new_id;
2836
-        }
2837
-        return false;
2838
-    }
2839
-
2840
-
2841
-
2842
-    /**
2843
-     * Checks that the result would satisfy the unique indexes on this model
2844
-     *
2845
-     * @param array  $field_n_values
2846
-     * @param string $action
2847
-     * @return boolean
2848
-     * @throws EE_Error
2849
-     */
2850
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2851
-    {
2852
-        foreach ($this->unique_indexes() as $index_name => $index) {
2853
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2854
-            if ($this->exists(array($uniqueness_where_params))) {
2855
-                EE_Error::add_error(
2856
-                    sprintf(
2857
-                        __(
2858
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2859
-                            "event_espresso"
2860
-                        ),
2861
-                        $action,
2862
-                        $this->_get_class_name(),
2863
-                        $index_name,
2864
-                        implode(",", $index->field_names()),
2865
-                        http_build_query($uniqueness_where_params)
2866
-                    ),
2867
-                    __FILE__,
2868
-                    __FUNCTION__,
2869
-                    __LINE__
2870
-                );
2871
-                return false;
2872
-            }
2873
-        }
2874
-        return true;
2875
-    }
2876
-
2877
-
2878
-
2879
-    /**
2880
-     * Checks the database for an item that conflicts (ie, if this item were
2881
-     * saved to the DB would break some uniqueness requirement, like a primary key
2882
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2883
-     * can be either an EE_Base_Class or an array of fields n values
2884
-     *
2885
-     * @param EE_Base_Class|array $obj_or_fields_array
2886
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2887
-     *                                                 when looking for conflicts
2888
-     *                                                 (ie, if false, we ignore the model object's primary key
2889
-     *                                                 when finding "conflicts". If true, it's also considered).
2890
-     *                                                 Only works for INT primary key,
2891
-     *                                                 STRING primary keys cannot be ignored
2892
-     * @throws EE_Error
2893
-     * @return EE_Base_Class|array
2894
-     */
2895
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2896
-    {
2897
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2898
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2899
-        } elseif (is_array($obj_or_fields_array)) {
2900
-            $fields_n_values = $obj_or_fields_array;
2901
-        } else {
2902
-            throw new EE_Error(
2903
-                sprintf(
2904
-                    __(
2905
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2906
-                        "event_espresso"
2907
-                    ),
2908
-                    get_class($this),
2909
-                    $obj_or_fields_array
2910
-                )
2911
-            );
2912
-        }
2913
-        $query_params = array();
2914
-        if ($this->has_primary_key_field()
2915
-            && ($include_primary_key
2916
-                || $this->get_primary_key_field()
2917
-                   instanceof
2918
-                   EE_Primary_Key_String_Field)
2919
-            && isset($fields_n_values[$this->primary_key_name()])
2920
-        ) {
2921
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2922
-        }
2923
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2926
-        }
2927
-        //if there is nothing to base this search on, then we shouldn't find anything
2928
-        if (empty($query_params)) {
2929
-            return array();
2930
-        }
2931
-        return $this->get_one($query_params);
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Like count, but is optimized and returns a boolean instead of an int
2938
-     *
2939
-     * @param array $query_params
2940
-     * @return boolean
2941
-     * @throws EE_Error
2942
-     */
2943
-    public function exists($query_params)
2944
-    {
2945
-        $query_params['limit'] = 1;
2946
-        return $this->count($query_params) > 0;
2947
-    }
2948
-
2949
-
2950
-
2951
-    /**
2952
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2953
-     *
2954
-     * @param int|string $id
2955
-     * @return boolean
2956
-     * @throws EE_Error
2957
-     */
2958
-    public function exists_by_ID($id)
2959
-    {
2960
-        return $this->exists(
2961
-            array(
2962
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2963
-                array(
2964
-                    $this->primary_key_name() => $id,
2965
-                ),
2966
-            )
2967
-        );
2968
-    }
2969
-
2970
-
2971
-
2972
-    /**
2973
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2974
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2975
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2976
-     * on the main table)
2977
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2978
-     * cases where we want to call it directly rather than via insert().
2979
-     *
2980
-     * @access   protected
2981
-     * @param EE_Table_Base $table
2982
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2983
-     *                                       float
2984
-     * @param int           $new_id          for now we assume only int keys
2985
-     * @throws EE_Error
2986
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2987
-     * @return int ID of new row inserted, or FALSE on failure
2988
-     */
2989
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2990
-    {
2991
-        global $wpdb;
2992
-        $insertion_col_n_values = array();
2993
-        $format_for_insertion = array();
2994
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2995
-        foreach ($fields_on_table as $field_name => $field_obj) {
2996
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2997
-            if ($field_obj->is_auto_increment()) {
2998
-                continue;
2999
-            }
3000
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3001
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
3002
-            if ($prepared_value !== null) {
3003
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3004
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
3005
-            }
3006
-        }
3007
-        if ($table instanceof EE_Secondary_Table && $new_id) {
3008
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
3009
-            //so add the fk to the main table as a column
3010
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3012
-        }
3013
-        //insert the new entry
3014
-        $result = $this->_do_wpdb_query('insert',
3015
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3016
-        if ($result === false) {
3017
-            return false;
3018
-        }
3019
-        //ok, now what do we return for the ID of the newly-inserted thing?
3020
-        if ($this->has_primary_key_field()) {
3021
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3022
-                return $wpdb->insert_id;
3023
-            }
3024
-            //it's not an auto-increment primary key, so
3025
-            //it must have been supplied
3026
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3027
-        }
3028
-        //we can't return a  primary key because there is none. instead return
3029
-        //a unique string indicating this model
3030
-        return $this->get_index_primary_key_string($fields_n_values);
3031
-    }
3032
-
3033
-
3034
-
3035
-    /**
3036
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3037
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3038
-     * and there is no default, we pass it along. WPDB will take care of it)
3039
-     *
3040
-     * @param EE_Model_Field_Base $field_obj
3041
-     * @param array               $fields_n_values
3042
-     * @return mixed string|int|float depending on what the table column will be expecting
3043
-     * @throws EE_Error
3044
-     */
3045
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3046
-    {
3047
-        //if this field doesn't allow nullable, don't allow it
3048
-        if (
3049
-            ! $field_obj->is_nullable()
3050
-            && (
3051
-                ! isset($fields_n_values[$field_obj->get_name()])
3052
-                || $fields_n_values[$field_obj->get_name()] === null
3053
-            )
3054
-        ) {
3055
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3056
-        }
3057
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3058
-            ? $fields_n_values[$field_obj->get_name()]
3059
-            : null;
3060
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3061
-    }
3062
-
3063
-
3064
-
3065
-    /**
3066
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3067
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3068
-     * the field's prepare_for_set() method.
3069
-     *
3070
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3071
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3072
-     *                                   top of file)
3073
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3074
-     *                                   $value is a custom selection
3075
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3076
-     */
3077
-    private function _prepare_value_for_use_in_db($value, $field)
3078
-    {
3079
-        if ($field && $field instanceof EE_Model_Field_Base) {
3080
-            switch ($this->_values_already_prepared_by_model_object) {
3081
-                /** @noinspection PhpMissingBreakStatementInspection */
3082
-                case self::not_prepared_by_model_object:
3083
-                    $value = $field->prepare_for_set($value);
3084
-                //purposefully left out "return"
3085
-                case self::prepared_by_model_object:
3086
-                    /** @noinspection SuspiciousAssignmentsInspection */
3087
-                    $value = $field->prepare_for_use_in_db($value);
3088
-                case self::prepared_for_use_in_db:
3089
-                    //leave the value alone
3090
-            }
3091
-            return $value;
3092
-        }
3093
-        return $value;
3094
-    }
3095
-
3096
-
3097
-
3098
-    /**
3099
-     * Returns the main table on this model
3100
-     *
3101
-     * @return EE_Primary_Table
3102
-     * @throws EE_Error
3103
-     */
3104
-    protected function _get_main_table()
3105
-    {
3106
-        foreach ($this->_tables as $table) {
3107
-            if ($table instanceof EE_Primary_Table) {
3108
-                return $table;
3109
-            }
3110
-        }
3111
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3112
-            'event_espresso'), get_class($this)));
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * table
3119
-     * returns EE_Primary_Table table name
3120
-     *
3121
-     * @return string
3122
-     * @throws EE_Error
3123
-     */
3124
-    public function table()
3125
-    {
3126
-        return $this->_get_main_table()->get_table_name();
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * table
3133
-     * returns first EE_Secondary_Table table name
3134
-     *
3135
-     * @return string
3136
-     */
3137
-    public function second_table()
3138
-    {
3139
-        // grab second table from tables array
3140
-        $second_table = end($this->_tables);
3141
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
-    }
3143
-
3144
-
3145
-
3146
-    /**
3147
-     * get_table_obj_by_alias
3148
-     * returns table name given it's alias
3149
-     *
3150
-     * @param string $table_alias
3151
-     * @return EE_Primary_Table | EE_Secondary_Table
3152
-     */
3153
-    public function get_table_obj_by_alias($table_alias = '')
3154
-    {
3155
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
-     *
3163
-     * @return EE_Secondary_Table[]
3164
-     */
3165
-    protected function _get_other_tables()
3166
-    {
3167
-        $other_tables = array();
3168
-        foreach ($this->_tables as $table_alias => $table) {
3169
-            if ($table instanceof EE_Secondary_Table) {
3170
-                $other_tables[$table_alias] = $table;
3171
-            }
3172
-        }
3173
-        return $other_tables;
3174
-    }
3175
-
3176
-
3177
-
3178
-    /**
3179
-     * Finds all the fields that correspond to the given table
3180
-     *
3181
-     * @param string $table_alias , array key in EEM_Base::_tables
3182
-     * @return EE_Model_Field_Base[]
3183
-     */
3184
-    public function _get_fields_for_table($table_alias)
3185
-    {
3186
-        return $this->_fields[$table_alias];
3187
-    }
3188
-
3189
-
3190
-
3191
-    /**
3192
-     * Recurses through all the where parameters, and finds all the related models we'll need
3193
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
-     * related Registration, Transaction, and Payment models.
3197
-     *
3198
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3199
-     * @return EE_Model_Query_Info_Carrier
3200
-     * @throws EE_Error
3201
-     */
3202
-    public function _extract_related_models_from_query($query_params)
3203
-    {
3204
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
-        if (array_key_exists(0, $query_params)) {
3206
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
-        }
3208
-        if (array_key_exists('group_by', $query_params)) {
3209
-            if (is_array($query_params['group_by'])) {
3210
-                $this->_extract_related_models_from_sub_params_array_values(
3211
-                    $query_params['group_by'],
3212
-                    $query_info_carrier,
3213
-                    'group_by'
3214
-                );
3215
-            } elseif (! empty ($query_params['group_by'])) {
3216
-                $this->_extract_related_model_info_from_query_param(
3217
-                    $query_params['group_by'],
3218
-                    $query_info_carrier,
3219
-                    'group_by'
3220
-                );
3221
-            }
3222
-        }
3223
-        if (array_key_exists('having', $query_params)) {
3224
-            $this->_extract_related_models_from_sub_params_array_keys(
3225
-                $query_params[0],
3226
-                $query_info_carrier,
3227
-                'having'
3228
-            );
3229
-        }
3230
-        if (array_key_exists('order_by', $query_params)) {
3231
-            if (is_array($query_params['order_by'])) {
3232
-                $this->_extract_related_models_from_sub_params_array_keys(
3233
-                    $query_params['order_by'],
3234
-                    $query_info_carrier,
3235
-                    'order_by'
3236
-                );
3237
-            } elseif (! empty($query_params['order_by'])) {
3238
-                $this->_extract_related_model_info_from_query_param(
3239
-                    $query_params['order_by'],
3240
-                    $query_info_carrier,
3241
-                    'order_by'
3242
-                );
3243
-            }
3244
-        }
3245
-        if (array_key_exists('force_join', $query_params)) {
3246
-            $this->_extract_related_models_from_sub_params_array_values(
3247
-                $query_params['force_join'],
3248
-                $query_info_carrier,
3249
-                'force_join'
3250
-            );
3251
-        }
3252
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
-        return $query_info_carrier;
3254
-    }
3255
-
3256
-
3257
-
3258
-    /**
3259
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
-     *
3261
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3262
-     *                                                      $query_params['having']
3263
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3264
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3265
-     * @throws EE_Error
3266
-     * @return \EE_Model_Query_Info_Carrier
3267
-     */
3268
-    private function _extract_related_models_from_sub_params_array_keys(
3269
-        $sub_query_params,
3270
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271
-        $query_param_type
3272
-    ) {
3273
-        if (! empty($sub_query_params)) {
3274
-            $sub_query_params = (array)$sub_query_params;
3275
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3278
-                    $query_param_type);
3279
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
-                //of array('Registration.TXN_ID'=>23)
3283
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3286
-                        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'))",
3287
-                            "event_espresso"),
3288
-                            $param, $possibly_array_of_params));
3289
-                    }
3290
-                    $this->_extract_related_models_from_sub_params_array_keys(
3291
-                        $possibly_array_of_params,
3292
-                        $model_query_info_carrier, $query_param_type
3293
-                    );
3294
-                } elseif ($query_param_type === 0 //ie WHERE
3295
-                          && is_array($possibly_array_of_params)
3296
-                          && isset($possibly_array_of_params[2])
3297
-                          && $possibly_array_of_params[2] == true
3298
-                ) {
3299
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3301
-                    //from which we should extract query parameters!
3302
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305
-                    }
3306
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3307
-                        $model_query_info_carrier, $query_param_type);
3308
-                }
3309
-            }
3310
-        }
3311
-        return $model_query_info_carrier;
3312
-    }
3313
-
3314
-
3315
-
3316
-    /**
3317
-     * For extracting related models from forced_joins, where the array values contain the info about what
3318
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3319
-     *
3320
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3321
-     *                                                      $query_params['having']
3322
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3324
-     * @throws EE_Error
3325
-     * @return \EE_Model_Query_Info_Carrier
3326
-     */
3327
-    private function _extract_related_models_from_sub_params_array_values(
3328
-        $sub_query_params,
3329
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
-        $query_param_type
3331
-    ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3334
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335
-                    $sub_query_params));
3336
-            }
3337
-            foreach ($sub_query_params as $param) {
3338
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3340
-                    $query_param_type);
3341
-            }
3342
-        }
3343
-        return $model_query_info_carrier;
3344
-    }
3345
-
3346
-
3347
-
3348
-    /**
3349
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3350
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3351
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3352
-     * but use them in a different order. Eg, we need to know what models we are querying
3353
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3354
-     * other models before we can finalize the where clause SQL.
3355
-     *
3356
-     * @param array $query_params
3357
-     * @throws EE_Error
3358
-     * @return EE_Model_Query_Info_Carrier
3359
-     */
3360
-    public function _create_model_query_info_carrier($query_params)
3361
-    {
3362
-        if (! is_array($query_params)) {
3363
-            EE_Error::doing_it_wrong(
3364
-                'EEM_Base::_create_model_query_info_carrier',
3365
-                sprintf(
3366
-                    __(
3367
-                        '$query_params should be an array, you passed a variable of type %s',
3368
-                        'event_espresso'
3369
-                    ),
3370
-                    gettype($query_params)
3371
-                ),
3372
-                '4.6.0'
3373
-            );
3374
-            $query_params = array();
3375
-        }
3376
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3377
-        //first check if we should alter the query to account for caps or not
3378
-        //because the caps might require us to do extra joins
3379
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
-            $query_params[0] = $where_query_params = array_replace_recursive(
3381
-                $where_query_params,
3382
-                $this->caps_where_conditions(
3383
-                    $query_params['caps']
3384
-                )
3385
-            );
3386
-        }
3387
-        $query_object = $this->_extract_related_models_from_query($query_params);
3388
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3389
-        foreach ($where_query_params as $key => $value) {
3390
-            if (is_int($key)) {
3391
-                throw new EE_Error(
3392
-                    sprintf(
3393
-                        __(
3394
-                            "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.",
3395
-                            "event_espresso"
3396
-                        ),
3397
-                        $key,
3398
-                        var_export($value, true),
3399
-                        var_export($query_params, true),
3400
-                        get_class($this)
3401
-                    )
3402
-                );
3403
-            }
3404
-        }
3405
-        if (
3406
-            array_key_exists('default_where_conditions', $query_params)
3407
-            && ! empty($query_params['default_where_conditions'])
3408
-        ) {
3409
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3410
-        } else {
3411
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3412
-        }
3413
-        $where_query_params = array_merge(
3414
-            $this->_get_default_where_conditions_for_models_in_query(
3415
-                $query_object,
3416
-                $use_default_where_conditions,
3417
-                $where_query_params
3418
-            ),
3419
-            $where_query_params
3420
-        );
3421
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3422
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3423
-        // So we need to setup a subquery and use that for the main join.
3424
-        // Note for now this only works on the primary table for the model.
3425
-        // So for instance, you could set the limit array like this:
3426
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3427
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3428
-            $query_object->set_main_model_join_sql(
3429
-                $this->_construct_limit_join_select(
3430
-                    $query_params['on_join_limit'][0],
3431
-                    $query_params['on_join_limit'][1]
3432
-                )
3433
-            );
3434
-        }
3435
-        //set limit
3436
-        if (array_key_exists('limit', $query_params)) {
3437
-            if (is_array($query_params['limit'])) {
3438
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439
-                    $e = sprintf(
3440
-                        __(
3441
-                            "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)",
3442
-                            "event_espresso"
3443
-                        ),
3444
-                        http_build_query($query_params['limit'])
3445
-                    );
3446
-                    throw new EE_Error($e . "|" . $e);
3447
-                }
3448
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
-            } elseif (! empty ($query_params['limit'])) {
3451
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3452
-            }
3453
-        }
3454
-        //set order by
3455
-        if (array_key_exists('order_by', $query_params)) {
3456
-            if (is_array($query_params['order_by'])) {
3457
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3458
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3459
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3460
-                if (array_key_exists('order', $query_params)) {
3461
-                    throw new EE_Error(
3462
-                        sprintf(
3463
-                            __(
3464
-                                "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 ",
3465
-                                "event_espresso"
3466
-                            ),
3467
-                            get_class($this),
3468
-                            implode(", ", array_keys($query_params['order_by'])),
3469
-                            implode(", ", $query_params['order_by']),
3470
-                            $query_params['order']
3471
-                        )
3472
-                    );
3473
-                }
3474
-                $this->_extract_related_models_from_sub_params_array_keys(
3475
-                    $query_params['order_by'],
3476
-                    $query_object,
3477
-                    'order_by'
3478
-                );
3479
-                //assume it's an array of fields to order by
3480
-                $order_array = array();
3481
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482
-                    $order = $this->_extract_order($order);
3483
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3484
-                }
3485
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
-            } elseif (! empty ($query_params['order_by'])) {
3487
-                $this->_extract_related_model_info_from_query_param(
3488
-                    $query_params['order_by'],
3489
-                    $query_object,
3490
-                    'order',
3491
-                    $query_params['order_by']
3492
-                );
3493
-                $order = isset($query_params['order'])
3494
-                    ? $this->_extract_order($query_params['order'])
3495
-                    : 'DESC';
3496
-                $query_object->set_order_by_sql(
3497
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3498
-                );
3499
-            }
3500
-        }
3501
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
-        if (! array_key_exists('order_by', $query_params)
3503
-            && array_key_exists('order', $query_params)
3504
-            && ! empty($query_params['order'])
3505
-        ) {
3506
-            $pk_field = $this->get_primary_key_field();
3507
-            $order = $this->_extract_order($query_params['order']);
3508
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3509
-        }
3510
-        //set group by
3511
-        if (array_key_exists('group_by', $query_params)) {
3512
-            if (is_array($query_params['group_by'])) {
3513
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3514
-                $group_by_array = array();
3515
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517
-                }
3518
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
-            } elseif (! empty ($query_params['group_by'])) {
3520
-                $query_object->set_group_by_sql(
3521
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3522
-                );
3523
-            }
3524
-        }
3525
-        //set having
3526
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3527
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3528
-        }
3529
-        //now, just verify they didn't pass anything wack
3530
-        foreach ($query_params as $query_key => $query_value) {
3531
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3532
-                throw new EE_Error(
3533
-                    sprintf(
3534
-                        __(
3535
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3536
-                            'event_espresso'
3537
-                        ),
3538
-                        $query_key,
3539
-                        get_class($this),
3540
-                        //						print_r( $this->_allowed_query_params, TRUE )
3541
-                        implode(',', $this->_allowed_query_params)
3542
-                    )
3543
-                );
3544
-            }
3545
-        }
3546
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3547
-        if (empty($main_model_join_sql)) {
3548
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3549
-        }
3550
-        return $query_object;
3551
-    }
3552
-
3553
-
3554
-
3555
-    /**
3556
-     * Gets the where conditions that should be imposed on the query based on the
3557
-     * context (eg reading frontend, backend, edit or delete).
3558
-     *
3559
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3560
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3561
-     * @throws EE_Error
3562
-     */
3563
-    public function caps_where_conditions($context = self::caps_read)
3564
-    {
3565
-        EEM_Base::verify_is_valid_cap_context($context);
3566
-        $cap_where_conditions = array();
3567
-        $cap_restrictions = $this->caps_missing($context);
3568
-        /**
3569
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3570
-         */
3571
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3572
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3573
-                $restriction_if_no_cap->get_default_where_conditions());
3574
-        }
3575
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3576
-            $cap_restrictions);
3577
-    }
3578
-
3579
-
3580
-
3581
-    /**
3582
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3583
-     * otherwise throws an exception
3584
-     *
3585
-     * @param string $should_be_order_string
3586
-     * @return string either ASC, asc, DESC or desc
3587
-     * @throws EE_Error
3588
-     */
3589
-    private function _extract_order($should_be_order_string)
3590
-    {
3591
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3592
-            return $should_be_order_string;
3593
-        }
3594
-        throw new EE_Error(
3595
-            sprintf(
3596
-                __(
3597
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3598
-                    "event_espresso"
3599
-                ), get_class($this), $should_be_order_string
3600
-            )
3601
-        );
3602
-    }
3603
-
3604
-
3605
-
3606
-    /**
3607
-     * Looks at all the models which are included in this query, and asks each
3608
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3609
-     * so they can be merged
3610
-     *
3611
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3612
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3613
-     *                                                                  'none' means NO default where conditions will
3614
-     *                                                                  be used AT ALL during this query.
3615
-     *                                                                  'other_models_only' means default where
3616
-     *                                                                  conditions from other models will be used, but
3617
-     *                                                                  not for this primary model. 'all', the default,
3618
-     *                                                                  means default where conditions will apply as
3619
-     *                                                                  normal
3620
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3621
-     * @throws EE_Error
3622
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3623
-     */
3624
-    private function _get_default_where_conditions_for_models_in_query(
3625
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3626
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3627
-        $where_query_params = array()
3628
-    ) {
3629
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632
-                "event_espresso"), $use_default_where_conditions,
3633
-                implode(", ", $allowed_used_default_where_conditions_values)));
3634
-        }
3635
-        $universal_query_params = array();
3636
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3637
-            $universal_query_params = $this->_get_default_where_conditions();
3638
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3639
-            $universal_query_params = $this->_get_minimum_where_conditions();
3640
-        }
3641
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642
-            $related_model = $this->get_related_model_obj($model_name);
3643
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3644
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3646
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647
-            } else {
3648
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3649
-                continue;
3650
-            }
3651
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3652
-                $related_model_universal_where_params,
3653
-                $where_query_params,
3654
-                $related_model,
3655
-                $model_relation_path
3656
-            );
3657
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3658
-                $universal_query_params,
3659
-                $overrides
3660
-            );
3661
-        }
3662
-        return $universal_query_params;
3663
-    }
3664
-
3665
-
3666
-
3667
-    /**
3668
-     * Determines whether or not we should use default where conditions for the model in question
3669
-     * (this model, or other related models).
3670
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3671
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3672
-     * We should use default where conditions on related models when they requested to use default where conditions
3673
-     * on all models, or specifically just on other related models
3674
-     * @param      $default_where_conditions_value
3675
-     * @param bool $for_this_model false means this is for OTHER related models
3676
-     * @return bool
3677
-     */
3678
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3679
-    {
3680
-        return (
3681
-                   $for_this_model
3682
-                   && in_array(
3683
-                       $default_where_conditions_value,
3684
-                       array(
3685
-                           EEM_Base::default_where_conditions_all,
3686
-                           EEM_Base::default_where_conditions_this_only,
3687
-                           EEM_Base::default_where_conditions_minimum_others,
3688
-                       ),
3689
-                       true
3690
-                   )
3691
-               )
3692
-               || (
3693
-                   ! $for_this_model
3694
-                   && in_array(
3695
-                       $default_where_conditions_value,
3696
-                       array(
3697
-                           EEM_Base::default_where_conditions_all,
3698
-                           EEM_Base::default_where_conditions_others_only,
3699
-                       ),
3700
-                       true
3701
-                   )
3702
-               );
3703
-    }
3704
-
3705
-    /**
3706
-     * Determines whether or not we should use default minimum conditions for the model in question
3707
-     * (this model, or other related models).
3708
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3709
-     * where conditions.
3710
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3711
-     * on this model or others
3712
-     * @param      $default_where_conditions_value
3713
-     * @param bool $for_this_model false means this is for OTHER related models
3714
-     * @return bool
3715
-     */
3716
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3717
-    {
3718
-        return (
3719
-                   $for_this_model
3720
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3721
-               )
3722
-               || (
3723
-                   ! $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_minimum_others,
3728
-                           EEM_Base::default_where_conditions_minimum_all,
3729
-                       ),
3730
-                       true
3731
-                   )
3732
-               );
3733
-    }
3734
-
3735
-
3736
-    /**
3737
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3738
-     * then we also add a special where condition which allows for that model's primary key
3739
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3740
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3741
-     *
3742
-     * @param array    $default_where_conditions
3743
-     * @param array    $provided_where_conditions
3744
-     * @param EEM_Base $model
3745
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3746
-     * @return array like EEM_Base::get_all's $query_params[0]
3747
-     * @throws EE_Error
3748
-     */
3749
-    private function _override_defaults_or_make_null_friendly(
3750
-        $default_where_conditions,
3751
-        $provided_where_conditions,
3752
-        $model,
3753
-        $model_relation_path
3754
-    ) {
3755
-        $null_friendly_where_conditions = array();
3756
-        $none_overridden = true;
3757
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3758
-        foreach ($default_where_conditions as $key => $val) {
3759
-            if (isset($provided_where_conditions[$key])) {
3760
-                $none_overridden = false;
3761
-            } else {
3762
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3763
-            }
3764
-        }
3765
-        if ($none_overridden && $default_where_conditions) {
3766
-            if ($model->has_primary_key_field()) {
3767
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3768
-                                                                                . "."
3769
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3770
-            }/*else{
37
+	/**
38
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
39
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
40
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
41
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
42
+	 *
43
+	 * @var boolean
44
+	 */
45
+	private $_values_already_prepared_by_model_object = 0;
46
+
47
+	/**
48
+	 * when $_values_already_prepared_by_model_object equals this, we assume
49
+	 * the data is just like form input that needs to have the model fields'
50
+	 * prepare_for_set and prepare_for_use_in_db called on it
51
+	 */
52
+	const not_prepared_by_model_object = 0;
53
+
54
+	/**
55
+	 * when $_values_already_prepared_by_model_object equals this, we
56
+	 * assume this value is coming from a model object and doesn't need to have
57
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
58
+	 */
59
+	const prepared_by_model_object = 1;
60
+
61
+	/**
62
+	 * when $_values_already_prepared_by_model_object equals this, we assume
63
+	 * the values are already to be used in the database (ie no processing is done
64
+	 * on them by the model's fields)
65
+	 */
66
+	const prepared_for_use_in_db = 2;
67
+
68
+
69
+	protected $singular_item = 'Item';
70
+
71
+	protected $plural_item   = 'Items';
72
+
73
+	/**
74
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
75
+	 */
76
+	protected $_tables;
77
+
78
+	/**
79
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
80
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
81
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
82
+	 *
83
+	 * @var \EE_Model_Field_Base[][] $_fields
84
+	 */
85
+	protected $_fields;
86
+
87
+	/**
88
+	 * array of different kinds of relations
89
+	 *
90
+	 * @var \EE_Model_Relation_Base[] $_model_relations
91
+	 */
92
+	protected $_model_relations;
93
+
94
+	/**
95
+	 * @var \EE_Index[] $_indexes
96
+	 */
97
+	protected $_indexes = array();
98
+
99
+	/**
100
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
101
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
102
+	 * by setting the same columns as used in these queries in the query yourself.
103
+	 *
104
+	 * @var EE_Default_Where_Conditions
105
+	 */
106
+	protected $_default_where_conditions_strategy;
107
+
108
+	/**
109
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
110
+	 * This is particularly useful when you want something between 'none' and 'default'
111
+	 *
112
+	 * @var EE_Default_Where_Conditions
113
+	 */
114
+	protected $_minimum_where_conditions_strategy;
115
+
116
+	/**
117
+	 * String describing how to find the "owner" of this model's objects.
118
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
119
+	 * But when there isn't, this indicates which related model, or transiently-related model,
120
+	 * has the foreign key to the wp_users table.
121
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
122
+	 * related to events, and events have a foreign key to wp_users.
123
+	 * On EEM_Transaction, this would be 'Transaction.Event'
124
+	 *
125
+	 * @var string
126
+	 */
127
+	protected $_model_chain_to_wp_user = '';
128
+
129
+	/**
130
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
131
+	 * don't need it (particularly CPT models)
132
+	 *
133
+	 * @var bool
134
+	 */
135
+	protected $_ignore_where_strategy = false;
136
+
137
+	/**
138
+	 * String used in caps relating to this model. Eg, if the caps relating to this
139
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
140
+	 *
141
+	 * @var string. If null it hasn't been initialized yet. If false then we
142
+	 * have indicated capabilities don't apply to this
143
+	 */
144
+	protected $_caps_slug = null;
145
+
146
+	/**
147
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
148
+	 * and next-level keys are capability names, and each's value is a
149
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
150
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
151
+	 * and then each capability in the corresponding sub-array that they're missing
152
+	 * adds the where conditions onto the query.
153
+	 *
154
+	 * @var array
155
+	 */
156
+	protected $_cap_restrictions = array(
157
+		self::caps_read       => array(),
158
+		self::caps_read_admin => array(),
159
+		self::caps_edit       => array(),
160
+		self::caps_delete     => array(),
161
+	);
162
+
163
+	/**
164
+	 * Array defining which cap restriction generators to use to create default
165
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
166
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
167
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
168
+	 * automatically set this to false (not just null).
169
+	 *
170
+	 * @var EE_Restriction_Generator_Base[]
171
+	 */
172
+	protected $_cap_restriction_generators = array();
173
+
174
+	/**
175
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
176
+	 */
177
+	const caps_read       = 'read';
178
+
179
+	const caps_read_admin = 'read_admin';
180
+
181
+	const caps_edit       = 'edit';
182
+
183
+	const caps_delete     = 'delete';
184
+
185
+	/**
186
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
187
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
188
+	 * maps to 'read' because when looking for relevant permissions we're going to use
189
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
190
+	 *
191
+	 * @var array
192
+	 */
193
+	protected $_cap_contexts_to_cap_action_map = array(
194
+		self::caps_read       => 'read',
195
+		self::caps_read_admin => 'read',
196
+		self::caps_edit       => 'edit',
197
+		self::caps_delete     => 'delete',
198
+	);
199
+
200
+	/**
201
+	 * Timezone
202
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
203
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
204
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
205
+	 * EE_Datetime_Field data type will have access to it.
206
+	 *
207
+	 * @var string
208
+	 */
209
+	protected $_timezone;
210
+
211
+
212
+	/**
213
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
214
+	 * multisite.
215
+	 *
216
+	 * @var int
217
+	 */
218
+	protected static $_model_query_blog_id;
219
+
220
+	/**
221
+	 * A copy of _fields, except the array keys are the model names pointed to by
222
+	 * the field
223
+	 *
224
+	 * @var EE_Model_Field_Base[]
225
+	 */
226
+	private $_cache_foreign_key_to_fields = array();
227
+
228
+	/**
229
+	 * Cached list of all the fields on the model, indexed by their name
230
+	 *
231
+	 * @var EE_Model_Field_Base[]
232
+	 */
233
+	private $_cached_fields = null;
234
+
235
+	/**
236
+	 * Cached list of all the fields on the model, except those that are
237
+	 * marked as only pertinent to the database
238
+	 *
239
+	 * @var EE_Model_Field_Base[]
240
+	 */
241
+	private $_cached_fields_non_db_only = null;
242
+
243
+	/**
244
+	 * A cached reference to the primary key for quick lookup
245
+	 *
246
+	 * @var EE_Model_Field_Base
247
+	 */
248
+	private $_primary_key_field = null;
249
+
250
+	/**
251
+	 * Flag indicating whether this model has a primary key or not
252
+	 *
253
+	 * @var boolean
254
+	 */
255
+	protected $_has_primary_key_field = null;
256
+
257
+	/**
258
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
259
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
260
+	 * This should be true for models that deal with data that should exist independent of EE.
261
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
262
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
263
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
264
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
265
+	 * @var boolean
266
+	 */
267
+	protected $_wp_core_model = false;
268
+
269
+	/**
270
+	 *    List of valid operators that can be used for querying.
271
+	 * The keys are all operators we'll accept, the values are the real SQL
272
+	 * operators used
273
+	 *
274
+	 * @var array
275
+	 */
276
+	protected $_valid_operators = array(
277
+		'='           => '=',
278
+		'<='          => '<=',
279
+		'<'           => '<',
280
+		'>='          => '>=',
281
+		'>'           => '>',
282
+		'!='          => '!=',
283
+		'LIKE'        => 'LIKE',
284
+		'like'        => 'LIKE',
285
+		'NOT_LIKE'    => 'NOT LIKE',
286
+		'not_like'    => 'NOT LIKE',
287
+		'NOT LIKE'    => 'NOT LIKE',
288
+		'not like'    => 'NOT LIKE',
289
+		'IN'          => 'IN',
290
+		'in'          => 'IN',
291
+		'NOT_IN'      => 'NOT IN',
292
+		'not_in'      => 'NOT IN',
293
+		'NOT IN'      => 'NOT IN',
294
+		'not in'      => 'NOT IN',
295
+		'between'     => 'BETWEEN',
296
+		'BETWEEN'     => 'BETWEEN',
297
+		'IS_NOT_NULL' => 'IS NOT NULL',
298
+		'is_not_null' => 'IS NOT NULL',
299
+		'IS NOT NULL' => 'IS NOT NULL',
300
+		'is not null' => 'IS NOT NULL',
301
+		'IS_NULL'     => 'IS NULL',
302
+		'is_null'     => 'IS NULL',
303
+		'IS NULL'     => 'IS NULL',
304
+		'is null'     => 'IS NULL',
305
+		'REGEXP'      => 'REGEXP',
306
+		'regexp'      => 'REGEXP',
307
+		'NOT_REGEXP'  => 'NOT REGEXP',
308
+		'not_regexp'  => 'NOT REGEXP',
309
+		'NOT REGEXP'  => 'NOT REGEXP',
310
+		'not regexp'  => 'NOT REGEXP',
311
+	);
312
+
313
+	/**
314
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
315
+	 *
316
+	 * @var array
317
+	 */
318
+	protected $_in_style_operators = array('IN', 'NOT IN');
319
+
320
+	/**
321
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
322
+	 * '12-31-2012'"
323
+	 *
324
+	 * @var array
325
+	 */
326
+	protected $_between_style_operators = array('BETWEEN');
327
+
328
+	/**
329
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
330
+	 * @var array
331
+	 */
332
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
333
+	/**
334
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
335
+	 * on a join table.
336
+	 *
337
+	 * @var array
338
+	 */
339
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
340
+
341
+	/**
342
+	 * Allowed values for $query_params['order'] for ordering in queries
343
+	 *
344
+	 * @var array
345
+	 */
346
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
347
+
348
+	/**
349
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
350
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
351
+	 *
352
+	 * @var array
353
+	 */
354
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
355
+
356
+	/**
357
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
358
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
359
+	 *
360
+	 * @var array
361
+	 */
362
+	private $_allowed_query_params = array(
363
+		0,
364
+		'limit',
365
+		'order_by',
366
+		'group_by',
367
+		'having',
368
+		'force_join',
369
+		'order',
370
+		'on_join_limit',
371
+		'default_where_conditions',
372
+		'caps',
373
+		'extra_selects'
374
+	);
375
+
376
+	/**
377
+	 * All the data types that can be used in $wpdb->prepare statements.
378
+	 *
379
+	 * @var array
380
+	 */
381
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
382
+
383
+	/**
384
+	 * @var EE_Registry $EE
385
+	 */
386
+	protected $EE = null;
387
+
388
+
389
+	/**
390
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
391
+	 *
392
+	 * @var int
393
+	 */
394
+	protected $_show_next_x_db_queries = 0;
395
+
396
+	/**
397
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
398
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
399
+	 * WHERE, GROUP_BY, etc.
400
+	 *
401
+	 * @var CustomSelects
402
+	 */
403
+	protected $_custom_selections = array();
404
+
405
+	/**
406
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
407
+	 * caches every model object we've fetched from the DB on this request
408
+	 *
409
+	 * @var array
410
+	 */
411
+	protected $_entity_map;
412
+
413
+	/**
414
+	 * @var LoaderInterface $loader
415
+	 */
416
+	private static $loader;
417
+
418
+
419
+	/**
420
+	 * constant used to show EEM_Base has not yet verified the db on this http request
421
+	 */
422
+	const db_verified_none = 0;
423
+
424
+	/**
425
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
426
+	 * but not the addons' dbs
427
+	 */
428
+	const db_verified_core = 1;
429
+
430
+	/**
431
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
432
+	 * the EE core db too)
433
+	 */
434
+	const db_verified_addons = 2;
435
+
436
+	/**
437
+	 * indicates whether an EEM_Base child has already re-verified the DB
438
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
439
+	 * looking like EEM_Base::db_verified_*
440
+	 *
441
+	 * @var int - 0 = none, 1 = core, 2 = addons
442
+	 */
443
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
444
+
445
+	/**
446
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
447
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
448
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
449
+	 */
450
+	const default_where_conditions_all = 'all';
451
+
452
+	/**
453
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
454
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
455
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
456
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
457
+	 *        models which share tables with other models, this can return data for the wrong model.
458
+	 */
459
+	const default_where_conditions_this_only = 'this_model_only';
460
+
461
+	/**
462
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
463
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
464
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
465
+	 */
466
+	const default_where_conditions_others_only = 'other_models_only';
467
+
468
+	/**
469
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
470
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
471
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
472
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
473
+	 *        (regardless of whether those events and venues are trashed)
474
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
475
+	 *        events.
476
+	 */
477
+	const default_where_conditions_minimum_all = 'minimum';
478
+
479
+	/**
480
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
481
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
482
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
483
+	 *        not)
484
+	 */
485
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
486
+
487
+	/**
488
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
489
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
490
+	 *        it's possible it will return table entries for other models. You should use
491
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
492
+	 */
493
+	const default_where_conditions_none = 'none';
494
+
495
+
496
+
497
+	/**
498
+	 * About all child constructors:
499
+	 * they should define the _tables, _fields and _model_relations arrays.
500
+	 * Should ALWAYS be called after child constructor.
501
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
502
+	 * finalizes constructing all the object's attributes.
503
+	 * Generally, rather than requiring a child to code
504
+	 * $this->_tables = array(
505
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
506
+	 *        ...);
507
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
508
+	 * each EE_Table has a function to set the table's alias after the constructor, using
509
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
510
+	 * do something similar.
511
+	 *
512
+	 * @param null $timezone
513
+	 * @throws EE_Error
514
+	 */
515
+	protected function __construct($timezone = null)
516
+	{
517
+		// check that the model has not been loaded too soon
518
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+			throw new EE_Error (
520
+				sprintf(
521
+					__('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522
+						'event_espresso'),
523
+					get_class($this)
524
+				)
525
+			);
526
+		}
527
+		/**
528
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
529
+		 */
530
+		if (empty(EEM_Base::$_model_query_blog_id)) {
531
+			EEM_Base::set_model_query_blog_id();
532
+		}
533
+		/**
534
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
535
+		 * just use EE_Register_Model_Extension
536
+		 *
537
+		 * @var EE_Table_Base[] $_tables
538
+		 */
539
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
540
+		foreach ($this->_tables as $table_alias => $table_obj) {
541
+			/** @var $table_obj EE_Table_Base */
542
+			$table_obj->_construct_finalize_with_alias($table_alias);
543
+			if ($table_obj instanceof EE_Secondary_Table) {
544
+				/** @var $table_obj EE_Secondary_Table */
545
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
546
+			}
547
+		}
548
+		/**
549
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
550
+		 * EE_Register_Model_Extension
551
+		 *
552
+		 * @param EE_Model_Field_Base[] $_fields
553
+		 */
554
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
555
+		$this->_invalidate_field_caches();
556
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
557
+			if (! array_key_exists($table_alias, $this->_tables)) {
558
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
560
+			}
561
+			foreach ($fields_for_table as $field_name => $field_obj) {
562
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
563
+				//primary key field base has a slightly different _construct_finalize
564
+				/** @var $field_obj EE_Model_Field_Base */
565
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
566
+			}
567
+		}
568
+		// everything is related to Extra_Meta
569
+		if (get_class($this) !== 'EEM_Extra_Meta') {
570
+			//make extra meta related to everything, but don't block deleting things just
571
+			//because they have related extra meta info. For now just orphan those extra meta
572
+			//in the future we should automatically delete them
573
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		//and change logs
576
+		if (get_class($this) !== 'EEM_Change_Log') {
577
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
578
+		}
579
+		/**
580
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
581
+		 * EE_Register_Model_Extension
582
+		 *
583
+		 * @param EE_Model_Relation_Base[] $_model_relations
584
+		 */
585
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
586
+			$this->_model_relations);
587
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
588
+			/** @var $relation_obj EE_Model_Relation_Base */
589
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
590
+		}
591
+		foreach ($this->_indexes as $index_name => $index_obj) {
592
+			/** @var $index_obj EE_Index */
593
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
594
+		}
595
+		$this->set_timezone($timezone);
596
+		//finalize default where condition strategy, or set default
597
+		if (! $this->_default_where_conditions_strategy) {
598
+			//nothing was set during child constructor, so set default
599
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600
+		}
601
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
602
+		if (! $this->_minimum_where_conditions_strategy) {
603
+			//nothing was set during child constructor, so set default
604
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605
+		}
606
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
607
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
608
+		//to indicate to NOT set it, set it to the logical default
609
+		if ($this->_caps_slug === null) {
610
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
611
+		}
612
+		//initialize the standard cap restriction generators if none were specified by the child constructor
613
+		if ($this->_cap_restriction_generators !== false) {
614
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
616
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
617
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618
+						new EE_Restriction_Generator_Protected(),
619
+						$cap_context,
620
+						$this
621
+					);
622
+				}
623
+			}
624
+		}
625
+		//if there are cap restriction generators, use them to make the default cap restrictions
626
+		if ($this->_cap_restriction_generators !== false) {
627
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
+				if (! $generator_object) {
629
+					continue;
630
+				}
631
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
632
+					throw new EE_Error(
633
+						sprintf(
634
+							__('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
635
+								'event_espresso'),
636
+							$context,
637
+							$this->get_this_model_name()
638
+						)
639
+					);
640
+				}
641
+				$action = $this->cap_action_for_context($context);
642
+				if (! $generator_object->construction_finalized()) {
643
+					$generator_object->_construct_finalize($this, $action);
644
+				}
645
+			}
646
+		}
647
+		do_action('AHEE__' . get_class($this) . '__construct__end');
648
+	}
649
+
650
+
651
+
652
+	/**
653
+	 * Used to set the $_model_query_blog_id static property.
654
+	 *
655
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
656
+	 *                      value for get_current_blog_id() will be used.
657
+	 */
658
+	public static function set_model_query_blog_id($blog_id = 0)
659
+	{
660
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
661
+	}
662
+
663
+
664
+
665
+	/**
666
+	 * Returns whatever is set as the internal $model_query_blog_id.
667
+	 *
668
+	 * @return int
669
+	 */
670
+	public static function get_model_query_blog_id()
671
+	{
672
+		return EEM_Base::$_model_query_blog_id;
673
+	}
674
+
675
+
676
+
677
+	/**
678
+	 * This function is a singleton method used to instantiate the Espresso_model object
679
+	 *
680
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
681
+	 *                                (and any incoming timezone data that gets saved).
682
+	 *                                Note this just sends the timezone info to the date time model field objects.
683
+	 *                                Default is NULL
684
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
685
+	 * @return static (as in the concrete child class)
686
+	 * @throws EE_Error
687
+	 * @throws InvalidArgumentException
688
+	 * @throws InvalidDataTypeException
689
+	 * @throws InvalidInterfaceException
690
+	 */
691
+	public static function instance($timezone = null)
692
+	{
693
+		// check if instance of Espresso_model already exists
694
+		if (! static::$_instance instanceof static) {
695
+			// instantiate Espresso_model
696
+			static::$_instance = new static(
697
+				$timezone,
698
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
699
+			);
700
+		}
701
+		//we might have a timezone set, let set_timezone decide what to do with it
702
+		static::$_instance->set_timezone($timezone);
703
+		// Espresso_model object
704
+		return static::$_instance;
705
+	}
706
+
707
+
708
+
709
+	/**
710
+	 * resets the model and returns it
711
+	 *
712
+	 * @param null | string $timezone
713
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
714
+	 * all its properties reset; if it wasn't instantiated, returns null)
715
+	 * @throws EE_Error
716
+	 * @throws ReflectionException
717
+	 * @throws InvalidArgumentException
718
+	 * @throws InvalidDataTypeException
719
+	 * @throws InvalidInterfaceException
720
+	 */
721
+	public static function reset($timezone = null)
722
+	{
723
+		if (static::$_instance instanceof EEM_Base) {
724
+			//let's try to NOT swap out the current instance for a new one
725
+			//because if someone has a reference to it, we can't remove their reference
726
+			//so it's best to keep using the same reference, but change the original object
727
+			//reset all its properties to their original values as defined in the class
728
+			$r = new ReflectionClass(get_class(static::$_instance));
729
+			$static_properties = $r->getStaticProperties();
730
+			foreach ($r->getDefaultProperties() as $property => $value) {
731
+				//don't set instance to null like it was originally,
732
+				//but it's static anyways, and we're ignoring static properties (for now at least)
733
+				if (! isset($static_properties[$property])) {
734
+					static::$_instance->{$property} = $value;
735
+				}
736
+			}
737
+			//and then directly call its constructor again, like we would if we were creating a new one
738
+			static::$_instance->__construct(
739
+				$timezone,
740
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
741
+			);
742
+			return self::instance();
743
+		}
744
+		return null;
745
+	}
746
+
747
+
748
+
749
+	/**
750
+	 * @return LoaderInterface
751
+	 * @throws InvalidArgumentException
752
+	 * @throws InvalidDataTypeException
753
+	 * @throws InvalidInterfaceException
754
+	 */
755
+	private static function getLoader()
756
+	{
757
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
758
+			EEM_Base::$loader = LoaderFactory::getLoader();
759
+		}
760
+		return EEM_Base::$loader;
761
+	}
762
+
763
+
764
+
765
+	/**
766
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
767
+	 *
768
+	 * @param  boolean $translated return localized strings or JUST the array.
769
+	 * @return array
770
+	 * @throws EE_Error
771
+	 * @throws InvalidArgumentException
772
+	 * @throws InvalidDataTypeException
773
+	 * @throws InvalidInterfaceException
774
+	 */
775
+	public function status_array($translated = false)
776
+	{
777
+		if (! array_key_exists('Status', $this->_model_relations)) {
778
+			return array();
779
+		}
780
+		$model_name = $this->get_this_model_name();
781
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
782
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
783
+		$status_array = array();
784
+		foreach ($stati as $status) {
785
+			$status_array[$status->ID()] = $status->get('STS_code');
786
+		}
787
+		return $translated
788
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
789
+			: $status_array;
790
+	}
791
+
792
+
793
+
794
+	/**
795
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
796
+	 *
797
+	 * @param array $query_params             {
798
+	 * @var array $0 (where) array {
799
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
800
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
801
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
802
+	 *                                        conditions based on related models (and even
803
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
804
+	 *                                        name. Eg,
805
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
806
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
807
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
808
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
809
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
810
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
811
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
812
+	 *                                        to Venues (even when each of those models actually consisted of two
813
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
814
+	 *                                        just having
815
+	 *                                        "Venue.VNU_ID", you could have
816
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
817
+	 *                                        events are related to Registrations, which are related to Attendees). You
818
+	 *                                        can take it even further with
819
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
820
+	 *                                        (from the default of '='), change the value to an numerically-indexed
821
+	 *                                        array, where the first item in the list is the operator. eg: array(
822
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
823
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
824
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
825
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
826
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
827
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
828
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
829
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
830
+	 *                                        the value is a field, simply provide a third array item (true) to the
831
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
832
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
833
+	 *                                        Note: you can also use related model field names like you would any other
834
+	 *                                        field name. eg:
835
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
836
+	 *                                        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__>' =>
837
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
838
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
839
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
840
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
841
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
842
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
843
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
844
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
845
+	 *                                        "stick" until you specify an AND. eg
846
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
847
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
848
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
849
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
850
+	 *                                        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 >>
851
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
852
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
853
+	 *                                        too, eg:
854
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
855
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
856
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
857
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
858
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
859
+	 *                                        the OFFSET, the 2nd is the LIMIT
860
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
861
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
862
+	 *                                        following format array('on_join_limit'
863
+	 *                                        => array( 'table_alias', array(1,2) ) ).
864
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
865
+	 *                                        values are either 'ASC' or 'DESC'.
866
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
867
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
868
+	 *                                        DESC..." respectively. Like the
869
+	 *                                        'where' conditions, these fields can be on related models. Eg
870
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
871
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
872
+	 *                                        Attendee, Price, Datetime, etc.)
873
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
874
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
875
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
876
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
877
+	 *                                        order by the primary key. Eg,
878
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
879
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
880
+	 *                                        DTT_EVT_start) or
881
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
882
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
883
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
884
+	 *                                        'group_by'=>'VNU_ID', or
885
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
886
+	 *                                        if no
887
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
888
+	 *                                        model's primary key (or combined primary keys). This avoids some
889
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
890
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
891
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
892
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
893
+	 *                                        results)
894
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
895
+	 *                                        array where values are models to be joined in the query.Eg
896
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
897
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
898
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
899
+	 *                                        related models which belongs to the current model
900
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
901
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
902
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
903
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
904
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
905
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
906
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
907
+	 *                                        this model's default where conditions added to the query, use
908
+	 *                                        'this_model_only'. If you want to use all default where conditions
909
+	 *                                        (default), set to 'all'.
910
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
911
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
912
+	 *                                        everything? Or should we only show the current user items they should be
913
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
914
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
915
+	 *                                        }
916
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
917
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
918
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
919
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
920
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
921
+	 *                                        array( array(
922
+	 *                                        'OR'=>array(
923
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
924
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
925
+	 *                                        )
926
+	 *                                        ),
927
+	 *                                        'limit'=>10,
928
+	 *                                        'group_by'=>'TXN_ID'
929
+	 *                                        ));
930
+	 *                                        get all the answers to the question titled "shirt size" for event with id
931
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
932
+	 *                                        'Question.QST_display_text'=>'shirt size',
933
+	 *                                        'Registration.Event.EVT_ID'=>12
934
+	 *                                        ),
935
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
936
+	 *                                        ));
937
+	 * @throws EE_Error
938
+	 */
939
+	public function get_all($query_params = array())
940
+	{
941
+		if (isset($query_params['limit'])
942
+			&& ! isset($query_params['group_by'])
943
+		) {
944
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
945
+		}
946
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
947
+	}
948
+
949
+
950
+
951
+	/**
952
+	 * Modifies the query parameters so we only get back model objects
953
+	 * that "belong" to the current user
954
+	 *
955
+	 * @param array $query_params @see EEM_Base::get_all()
956
+	 * @return array like EEM_Base::get_all
957
+	 */
958
+	public function alter_query_params_to_only_include_mine($query_params = array())
959
+	{
960
+		$wp_user_field_name = $this->wp_user_field_name();
961
+		if ($wp_user_field_name) {
962
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
963
+		}
964
+		return $query_params;
965
+	}
966
+
967
+
968
+
969
+	/**
970
+	 * Returns the name of the field's name that points to the WP_User table
971
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
972
+	 * foreign key to the WP_User table)
973
+	 *
974
+	 * @return string|boolean string on success, boolean false when there is no
975
+	 * foreign key to the WP_User table
976
+	 */
977
+	public function wp_user_field_name()
978
+	{
979
+		try {
980
+			if (! empty($this->_model_chain_to_wp_user)) {
981
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982
+				$last_model_name = end($models_to_follow_to_wp_users);
983
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
985
+			} else {
986
+				$model_with_fk_to_wp_users = $this;
987
+				$model_chain_to_wp_user = '';
988
+			}
989
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
991
+		} catch (EE_Error $e) {
992
+			return false;
993
+		}
994
+	}
995
+
996
+
997
+
998
+	/**
999
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
1000
+	 * (or transiently-related model) has a foreign key to the wp_users table;
1001
+	 * useful for finding if model objects of this type are 'owned' by the current user.
1002
+	 * This is an empty string when the foreign key is on this model and when it isn't,
1003
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1004
+	 * (or transiently-related model)
1005
+	 *
1006
+	 * @return string
1007
+	 */
1008
+	public function model_chain_to_wp_user()
1009
+	{
1010
+		return $this->_model_chain_to_wp_user;
1011
+	}
1012
+
1013
+
1014
+
1015
+	/**
1016
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1017
+	 * like how registrations don't have a foreign key to wp_users, but the
1018
+	 * events they are for are), or is unrelated to wp users.
1019
+	 * generally available
1020
+	 *
1021
+	 * @return boolean
1022
+	 */
1023
+	public function is_owned()
1024
+	{
1025
+		if ($this->model_chain_to_wp_user()) {
1026
+			return true;
1027
+		}
1028
+		try {
1029
+			$this->get_foreign_key_to('WP_User');
1030
+			return true;
1031
+		} catch (EE_Error $e) {
1032
+			return false;
1033
+		}
1034
+	}
1035
+
1036
+
1037
+	/**
1038
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1039
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1040
+	 * the model)
1041
+	 *
1042
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1043
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1044
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1045
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1046
+	 *                                  override this and set the select to "*", or a specific column name, like
1047
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1048
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1049
+	 *                                  the aliases used to refer to this selection, and values are to be
1050
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1051
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1052
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1053
+	 * @throws EE_Error
1054
+	 * @throws InvalidArgumentException
1055
+	 */
1056
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057
+	{
1058
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1059
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1060
+		$select_expressions = $columns_to_select === null
1061
+			? $this->_construct_default_select_sql($model_query_info)
1062
+			: '';
1063
+		if ($this->_custom_selections instanceof CustomSelects) {
1064
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065
+			$select_expressions .= $select_expressions
1066
+				? ', ' . $custom_expressions
1067
+				: $custom_expressions;
1068
+		}
1069
+
1070
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1071
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1077
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1078
+	 * method of including extra select information.
1079
+	 *
1080
+	 * @param array             $query_params
1081
+	 * @param null|array|string $columns_to_select
1082
+	 * @return null|CustomSelects
1083
+	 * @throws InvalidArgumentException
1084
+	 */
1085
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086
+	{
1087
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088
+			return null;
1089
+		}
1090
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1091
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1092
+		return new CustomSelects($selects);
1093
+	}
1094
+
1095
+
1096
+
1097
+	/**
1098
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1099
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1100
+	 * take care of joins, field preparation etc.
1101
+	 *
1102
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1103
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1104
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1105
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1106
+	 *                                  override this and set the select to "*", or a specific column name, like
1107
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1108
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1109
+	 *                                  the aliases used to refer to this selection, and values are to be
1110
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1111
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1112
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1113
+	 * @throws EE_Error
1114
+	 */
1115
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1116
+	{
1117
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1118
+	}
1119
+
1120
+
1121
+
1122
+	/**
1123
+	 * For creating a custom select statement
1124
+	 *
1125
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1126
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1127
+	 *                                 SQL, and 1=>is the datatype
1128
+	 * @throws EE_Error
1129
+	 * @return string
1130
+	 */
1131
+	private function _construct_select_from_input($columns_to_select)
1132
+	{
1133
+		if (is_array($columns_to_select)) {
1134
+			$select_sql_array = array();
1135
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137
+					throw new EE_Error(
1138
+						sprintf(
1139
+							__(
1140
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1141
+								'event_espresso'
1142
+							),
1143
+							$selection_and_datatype,
1144
+							$alias
1145
+						)
1146
+					);
1147
+				}
1148
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149
+					throw new EE_Error(
1150
+						sprintf(
1151
+							esc_html__(
1152
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1153
+								'event_espresso'
1154
+							),
1155
+							$selection_and_datatype[1],
1156
+							$selection_and_datatype[0],
1157
+							$alias,
1158
+							implode(', ', $this->_valid_wpdb_data_types)
1159
+						)
1160
+					);
1161
+				}
1162
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1163
+			}
1164
+			$columns_to_select_string = implode(', ', $select_sql_array);
1165
+		} else {
1166
+			$columns_to_select_string = $columns_to_select;
1167
+		}
1168
+		return $columns_to_select_string;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1175
+	 *
1176
+	 * @return string
1177
+	 * @throws EE_Error
1178
+	 */
1179
+	public function primary_key_name()
1180
+	{
1181
+		return $this->get_primary_key_field()->get_name();
1182
+	}
1183
+
1184
+
1185
+
1186
+	/**
1187
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1188
+	 * If there is no primary key on this model, $id is treated as primary key string
1189
+	 *
1190
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1191
+	 * @return EE_Base_Class
1192
+	 */
1193
+	public function get_one_by_ID($id)
1194
+	{
1195
+		if ($this->get_from_entity_map($id)) {
1196
+			return $this->get_from_entity_map($id);
1197
+		}
1198
+		return $this->get_one(
1199
+			$this->alter_query_params_to_restrict_by_ID(
1200
+				$id,
1201
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1202
+			)
1203
+		);
1204
+	}
1205
+
1206
+
1207
+
1208
+	/**
1209
+	 * Alters query parameters to only get items with this ID are returned.
1210
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1211
+	 * or could just be a simple primary key ID
1212
+	 *
1213
+	 * @param int   $id
1214
+	 * @param array $query_params
1215
+	 * @return array of normal query params, @see EEM_Base::get_all
1216
+	 * @throws EE_Error
1217
+	 */
1218
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219
+	{
1220
+		if (! isset($query_params[0])) {
1221
+			$query_params[0] = array();
1222
+		}
1223
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1224
+		if ($conditions_from_id === null) {
1225
+			$query_params[0][$this->primary_key_name()] = $id;
1226
+		} else {
1227
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1228
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1229
+		}
1230
+		return $query_params;
1231
+	}
1232
+
1233
+
1234
+
1235
+	/**
1236
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1237
+	 * array. If no item is found, null is returned.
1238
+	 *
1239
+	 * @param array $query_params like EEM_Base's $query_params variable.
1240
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1241
+	 * @throws EE_Error
1242
+	 */
1243
+	public function get_one($query_params = array())
1244
+	{
1245
+		if (! is_array($query_params)) {
1246
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1247
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248
+					gettype($query_params)), '4.6.0');
1249
+			$query_params = array();
1250
+		}
1251
+		$query_params['limit'] = 1;
1252
+		$items = $this->get_all($query_params);
1253
+		if (empty($items)) {
1254
+			return null;
1255
+		}
1256
+		return array_shift($items);
1257
+	}
1258
+
1259
+
1260
+
1261
+	/**
1262
+	 * Returns the next x number of items in sequence from the given value as
1263
+	 * found in the database matching the given query conditions.
1264
+	 *
1265
+	 * @param mixed $current_field_value    Value used for the reference point.
1266
+	 * @param null  $field_to_order_by      What field is used for the
1267
+	 *                                      reference point.
1268
+	 * @param int   $limit                  How many to return.
1269
+	 * @param array $query_params           Extra conditions on the query.
1270
+	 * @param null  $columns_to_select      If left null, then an array of
1271
+	 *                                      EE_Base_Class objects is returned,
1272
+	 *                                      otherwise you can indicate just the
1273
+	 *                                      columns you want returned.
1274
+	 * @return EE_Base_Class[]|array
1275
+	 * @throws EE_Error
1276
+	 */
1277
+	public function next_x(
1278
+		$current_field_value,
1279
+		$field_to_order_by = null,
1280
+		$limit = 1,
1281
+		$query_params = array(),
1282
+		$columns_to_select = null
1283
+	) {
1284
+		return $this->_get_consecutive(
1285
+			$current_field_value,
1286
+			'>',
1287
+			$field_to_order_by,
1288
+			$limit,
1289
+			$query_params,
1290
+			$columns_to_select
1291
+		);
1292
+	}
1293
+
1294
+
1295
+
1296
+	/**
1297
+	 * Returns the previous x number of items in sequence from the given value
1298
+	 * as found in the database matching the given query conditions.
1299
+	 *
1300
+	 * @param mixed $current_field_value    Value used for the reference point.
1301
+	 * @param null  $field_to_order_by      What field is used for the
1302
+	 *                                      reference point.
1303
+	 * @param int   $limit                  How many to return.
1304
+	 * @param array $query_params           Extra conditions on the query.
1305
+	 * @param null  $columns_to_select      If left null, then an array of
1306
+	 *                                      EE_Base_Class objects is returned,
1307
+	 *                                      otherwise you can indicate just the
1308
+	 *                                      columns you want returned.
1309
+	 * @return EE_Base_Class[]|array
1310
+	 * @throws EE_Error
1311
+	 */
1312
+	public function previous_x(
1313
+		$current_field_value,
1314
+		$field_to_order_by = null,
1315
+		$limit = 1,
1316
+		$query_params = array(),
1317
+		$columns_to_select = null
1318
+	) {
1319
+		return $this->_get_consecutive(
1320
+			$current_field_value,
1321
+			'<',
1322
+			$field_to_order_by,
1323
+			$limit,
1324
+			$query_params,
1325
+			$columns_to_select
1326
+		);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * Returns the next item in sequence from the given value as found in the
1333
+	 * database matching the given query conditions.
1334
+	 *
1335
+	 * @param mixed $current_field_value    Value used for the reference point.
1336
+	 * @param null  $field_to_order_by      What field is used for the
1337
+	 *                                      reference point.
1338
+	 * @param array $query_params           Extra conditions on the query.
1339
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1340
+	 *                                      object is returned, otherwise you
1341
+	 *                                      can indicate just the columns you
1342
+	 *                                      want and a single array indexed by
1343
+	 *                                      the columns will be returned.
1344
+	 * @return EE_Base_Class|null|array()
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	public function next(
1348
+		$current_field_value,
1349
+		$field_to_order_by = null,
1350
+		$query_params = array(),
1351
+		$columns_to_select = null
1352
+	) {
1353
+		$results = $this->_get_consecutive(
1354
+			$current_field_value,
1355
+			'>',
1356
+			$field_to_order_by,
1357
+			1,
1358
+			$query_params,
1359
+			$columns_to_select
1360
+		);
1361
+		return empty($results) ? null : reset($results);
1362
+	}
1363
+
1364
+
1365
+
1366
+	/**
1367
+	 * Returns the previous item in sequence from the given value as found in
1368
+	 * the database matching the given query conditions.
1369
+	 *
1370
+	 * @param mixed $current_field_value    Value used for the reference point.
1371
+	 * @param null  $field_to_order_by      What field is used for the
1372
+	 *                                      reference point.
1373
+	 * @param array $query_params           Extra conditions on the query.
1374
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1375
+	 *                                      object is returned, otherwise you
1376
+	 *                                      can indicate just the columns you
1377
+	 *                                      want and a single array indexed by
1378
+	 *                                      the columns will be returned.
1379
+	 * @return EE_Base_Class|null|array()
1380
+	 * @throws EE_Error
1381
+	 */
1382
+	public function previous(
1383
+		$current_field_value,
1384
+		$field_to_order_by = null,
1385
+		$query_params = array(),
1386
+		$columns_to_select = null
1387
+	) {
1388
+		$results = $this->_get_consecutive(
1389
+			$current_field_value,
1390
+			'<',
1391
+			$field_to_order_by,
1392
+			1,
1393
+			$query_params,
1394
+			$columns_to_select
1395
+		);
1396
+		return empty($results) ? null : reset($results);
1397
+	}
1398
+
1399
+
1400
+
1401
+	/**
1402
+	 * Returns the a consecutive number of items in sequence from the given
1403
+	 * value as found in the database matching the given query conditions.
1404
+	 *
1405
+	 * @param mixed  $current_field_value   Value used for the reference point.
1406
+	 * @param string $operand               What operand is used for the sequence.
1407
+	 * @param string $field_to_order_by     What field is used for the reference point.
1408
+	 * @param int    $limit                 How many to return.
1409
+	 * @param array  $query_params          Extra conditions on the query.
1410
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1411
+	 *                                      otherwise you can indicate just the columns you want returned.
1412
+	 * @return EE_Base_Class[]|array
1413
+	 * @throws EE_Error
1414
+	 */
1415
+	protected function _get_consecutive(
1416
+		$current_field_value,
1417
+		$operand = '>',
1418
+		$field_to_order_by = null,
1419
+		$limit = 1,
1420
+		$query_params = array(),
1421
+		$columns_to_select = null
1422
+	) {
1423
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1424
+		if (empty($field_to_order_by)) {
1425
+			if ($this->has_primary_key_field()) {
1426
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1427
+			} else {
1428
+				if (WP_DEBUG) {
1429
+					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).',
1430
+						'event_espresso'));
1431
+				}
1432
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1433
+				return array();
1434
+			}
1435
+		}
1436
+		if (! is_array($query_params)) {
1437
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439
+					gettype($query_params)), '4.6.0');
1440
+			$query_params = array();
1441
+		}
1442
+		//let's add the where query param for consecutive look up.
1443
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444
+		$query_params['limit'] = $limit;
1445
+		//set direction
1446
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1447
+		$query_params['order_by'] = $operand === '>'
1448
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1449
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1450
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1451
+		if (empty($columns_to_select)) {
1452
+			return $this->get_all($query_params);
1453
+		}
1454
+		//getting just the fields
1455
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This sets the _timezone property after model object has been instantiated.
1462
+	 *
1463
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1464
+	 */
1465
+	public function set_timezone($timezone)
1466
+	{
1467
+		if ($timezone !== null) {
1468
+			$this->_timezone = $timezone;
1469
+		}
1470
+		//note we need to loop through relations and set the timezone on those objects as well.
1471
+		foreach ($this->_model_relations as $relation) {
1472
+			$relation->set_timezone($timezone);
1473
+		}
1474
+		//and finally we do the same for any datetime fields
1475
+		foreach ($this->_fields as $field) {
1476
+			if ($field instanceof EE_Datetime_Field) {
1477
+				$field->set_timezone($timezone);
1478
+			}
1479
+		}
1480
+	}
1481
+
1482
+
1483
+
1484
+	/**
1485
+	 * This just returns whatever is set for the current timezone.
1486
+	 *
1487
+	 * @access public
1488
+	 * @return string
1489
+	 */
1490
+	public function get_timezone()
1491
+	{
1492
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1493
+		if (empty($this->_timezone)) {
1494
+			foreach ($this->_fields as $field) {
1495
+				if ($field instanceof EE_Datetime_Field) {
1496
+					$this->set_timezone($field->get_timezone());
1497
+					break;
1498
+				}
1499
+			}
1500
+		}
1501
+		//if timezone STILL empty then return the default timezone for the site.
1502
+		if (empty($this->_timezone)) {
1503
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1504
+		}
1505
+		return $this->_timezone;
1506
+	}
1507
+
1508
+
1509
+
1510
+	/**
1511
+	 * This returns the date formats set for the given field name and also ensures that
1512
+	 * $this->_timezone property is set correctly.
1513
+	 *
1514
+	 * @since 4.6.x
1515
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1516
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1517
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1518
+	 * @return array formats in an array with the date format first, and the time format last.
1519
+	 */
1520
+	public function get_formats_for($field_name, $pretty = false)
1521
+	{
1522
+		$field_settings = $this->field_settings_for($field_name);
1523
+		//if not a valid EE_Datetime_Field then throw error
1524
+		if (! $field_settings instanceof EE_Datetime_Field) {
1525
+			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.',
1526
+				'event_espresso'), $field_name));
1527
+		}
1528
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1529
+		//the field.
1530
+		$this->_timezone = $field_settings->get_timezone();
1531
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1532
+	}
1533
+
1534
+
1535
+
1536
+	/**
1537
+	 * This returns the current time in a format setup for a query on this model.
1538
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1539
+	 * it will return:
1540
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1541
+	 *  NOW
1542
+	 *  - or a unix timestamp (equivalent to time())
1543
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1544
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1545
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1546
+	 * @since 4.6.x
1547
+	 * @param string $field_name       The field the current time is needed for.
1548
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1549
+	 *                                 formatted string matching the set format for the field in the set timezone will
1550
+	 *                                 be returned.
1551
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1552
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1553
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1554
+	 *                                 exception is triggered.
1555
+	 */
1556
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1557
+	{
1558
+		$formats = $this->get_formats_for($field_name);
1559
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1560
+		if ($timestamp) {
1561
+			return $DateTime->format('U');
1562
+		}
1563
+		//not returning timestamp, so return formatted string in timezone.
1564
+		switch ($what) {
1565
+			case 'time' :
1566
+				return $DateTime->format($formats[1]);
1567
+				break;
1568
+			case 'date' :
1569
+				return $DateTime->format($formats[0]);
1570
+				break;
1571
+			default :
1572
+				return $DateTime->format(implode(' ', $formats));
1573
+				break;
1574
+		}
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1581
+	 * for the model are.  Returns a DateTime object.
1582
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1583
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1584
+	 * ignored.
1585
+	 *
1586
+	 * @param string $field_name      The field being setup.
1587
+	 * @param string $timestring      The date time string being used.
1588
+	 * @param string $incoming_format The format for the time string.
1589
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1590
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1591
+	 *                                format is
1592
+	 *                                'U', this is ignored.
1593
+	 * @return DateTime
1594
+	 * @throws EE_Error
1595
+	 */
1596
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1597
+	{
1598
+		//just using this to ensure the timezone is set correctly internally
1599
+		$this->get_formats_for($field_name);
1600
+		//load EEH_DTT_Helper
1601
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1604
+	}
1605
+
1606
+
1607
+
1608
+	/**
1609
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1610
+	 *
1611
+	 * @return EE_Table_Base[]
1612
+	 */
1613
+	public function get_tables()
1614
+	{
1615
+		return $this->_tables;
1616
+	}
1617
+
1618
+
1619
+
1620
+	/**
1621
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1622
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1623
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1624
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1625
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1626
+	 * model object with EVT_ID = 1
1627
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1628
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1629
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1630
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1631
+	 * are not specified)
1632
+	 *
1633
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1634
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1635
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1636
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1637
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1638
+	 *                                         ID=34, we'd use this method as follows:
1639
+	 *                                         EEM_Transaction::instance()->update(
1640
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1641
+	 *                                         array(array('TXN_ID'=>34)));
1642
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1643
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1644
+	 *                                         consider updating Question's QST_admin_label field is of type
1645
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1646
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1647
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1648
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1649
+	 *                                         TRUE, it is assumed that you've already called
1650
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1651
+	 *                                         malicious javascript. However, if
1652
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1653
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1654
+	 *                                         and every other field, before insertion. We provide this parameter
1655
+	 *                                         because model objects perform their prepare_for_set function on all
1656
+	 *                                         their values, and so don't need to be called again (and in many cases,
1657
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1658
+	 *                                         prepare_for_set method...)
1659
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1660
+	 *                                         in this model's entity map according to $fields_n_values that match
1661
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1662
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1663
+	 *                                         could get out-of-sync with the database
1664
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1665
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1666
+	 *                                         bad)
1667
+	 * @throws EE_Error
1668
+	 */
1669
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670
+	{
1671
+		if (! is_array($query_params)) {
1672
+			EE_Error::doing_it_wrong('EEM_Base::update',
1673
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674
+					gettype($query_params)), '4.6.0');
1675
+			$query_params = array();
1676
+		}
1677
+		/**
1678
+		 * Action called before a model update call has been made.
1679
+		 *
1680
+		 * @param EEM_Base $model
1681
+		 * @param array    $fields_n_values the updated fields and their new values
1682
+		 * @param array    $query_params    @see EEM_Base::get_all()
1683
+		 */
1684
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1685
+		/**
1686
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1687
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1688
+		 *
1689
+		 * @param array    $fields_n_values fields and their new values
1690
+		 * @param EEM_Base $model           the model being queried
1691
+		 * @param array    $query_params    see EEM_Base::get_all()
1692
+		 */
1693
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694
+			$query_params);
1695
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1696
+		//to do that, for each table, verify that it's PK isn't null.
1697
+		$tables = $this->get_tables();
1698
+		//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
1699
+		//NOTE: we should make this code more efficient by NOT querying twice
1700
+		//before the real update, but that needs to first go through ALPHA testing
1701
+		//as it's dangerous. says Mike August 8 2014
1702
+		//we want to make sure the default_where strategy is ignored
1703
+		$this->_ignore_where_strategy = true;
1704
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705
+		foreach ($wpdb_select_results as $wpdb_result) {
1706
+			// type cast stdClass as array
1707
+			$wpdb_result = (array)$wpdb_result;
1708
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709
+			if ($this->has_primary_key_field()) {
1710
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1711
+			} else {
1712
+				//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)
1713
+				$main_table_pk_value = null;
1714
+			}
1715
+			//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
1716
+			//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
1717
+			if (count($tables) > 1) {
1718
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1719
+				//in that table, and so we'll want to insert one
1720
+				foreach ($tables as $table_obj) {
1721
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722
+					//if there is no private key for this table on the results, it means there's no entry
1723
+					//in this table, right? so insert a row in the current table, using any fields available
1724
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1725
+						   && $wpdb_result[$this_table_pk_column])
1726
+					) {
1727
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728
+							$main_table_pk_value);
1729
+						//if we died here, report the error
1730
+						if (! $success) {
1731
+							return false;
1732
+						}
1733
+					}
1734
+				}
1735
+			}
1736
+			//				//and now check that if we have cached any models by that ID on the model, that
1737
+			//				//they also get updated properly
1738
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1739
+			//				if( $model_object ){
1740
+			//					foreach( $fields_n_values as $field => $value ){
1741
+			//						$model_object->set($field, $value);
1742
+			//let's make sure default_where strategy is followed now
1743
+			$this->_ignore_where_strategy = false;
1744
+		}
1745
+		//if we want to keep model objects in sync, AND
1746
+		//if this wasn't called from a model object (to update itself)
1747
+		//then we want to make sure we keep all the existing
1748
+		//model objects in sync with the db
1749
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1750
+			if ($this->has_primary_key_field()) {
1751
+				$model_objs_affected_ids = $this->get_col($query_params);
1752
+			} else {
1753
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1754
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1755
+				$model_objs_affected_ids = array();
1756
+				foreach ($models_affected_key_columns as $row) {
1757
+					$combined_index_key = $this->get_index_primary_key_string($row);
1758
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759
+				}
1760
+			}
1761
+			if (! $model_objs_affected_ids) {
1762
+				//wait wait wait- if nothing was affected let's stop here
1763
+				return 0;
1764
+			}
1765
+			foreach ($model_objs_affected_ids as $id) {
1766
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1767
+				if ($model_obj_in_entity_map) {
1768
+					foreach ($fields_n_values as $field => $new_value) {
1769
+						$model_obj_in_entity_map->set($field, $new_value);
1770
+					}
1771
+				}
1772
+			}
1773
+			//if there is a primary key on this model, we can now do a slight optimization
1774
+			if ($this->has_primary_key_field()) {
1775
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1776
+				$query_params = array(
1777
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1778
+					'limit'                    => count($model_objs_affected_ids),
1779
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1780
+				);
1781
+			}
1782
+		}
1783
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1784
+		$SQL = "UPDATE "
1785
+			   . $model_query_info->get_full_join_sql()
1786
+			   . " SET "
1787
+			   . $this->_construct_update_sql($fields_n_values)
1788
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790
+		/**
1791
+		 * Action called after a model update call has been made.
1792
+		 *
1793
+		 * @param EEM_Base $model
1794
+		 * @param array    $fields_n_values the updated fields and their new values
1795
+		 * @param array    $query_params    @see EEM_Base::get_all()
1796
+		 * @param int      $rows_affected
1797
+		 */
1798
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
+		return $rows_affected;//how many supposedly got updated
1800
+	}
1801
+
1802
+
1803
+
1804
+	/**
1805
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1806
+	 * are teh values of the field specified (or by default the primary key field)
1807
+	 * that matched the query params. Note that you should pass the name of the
1808
+	 * model FIELD, not the database table's column name.
1809
+	 *
1810
+	 * @param array  $query_params @see EEM_Base::get_all()
1811
+	 * @param string $field_to_select
1812
+	 * @return array just like $wpdb->get_col()
1813
+	 * @throws EE_Error
1814
+	 */
1815
+	public function get_col($query_params = array(), $field_to_select = null)
1816
+	{
1817
+		if ($field_to_select) {
1818
+			$field = $this->field_settings_for($field_to_select);
1819
+		} elseif ($this->has_primary_key_field()) {
1820
+			$field = $this->get_primary_key_field();
1821
+		} else {
1822
+			//no primary key, just grab the first column
1823
+			$field = reset($this->field_settings());
1824
+		}
1825
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1826
+		$select_expressions = $field->get_qualified_column();
1827
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1828
+		return $this->_do_wpdb_query('get_col', array($SQL));
1829
+	}
1830
+
1831
+
1832
+
1833
+	/**
1834
+	 * Returns a single column value for a single row from the database
1835
+	 *
1836
+	 * @param array  $query_params    @see EEM_Base::get_all()
1837
+	 * @param string $field_to_select @see EEM_Base::get_col()
1838
+	 * @return string
1839
+	 * @throws EE_Error
1840
+	 */
1841
+	public function get_var($query_params = array(), $field_to_select = null)
1842
+	{
1843
+		$query_params['limit'] = 1;
1844
+		$col = $this->get_col($query_params, $field_to_select);
1845
+		if (! empty($col)) {
1846
+			return reset($col);
1847
+		}
1848
+		return null;
1849
+	}
1850
+
1851
+
1852
+
1853
+	/**
1854
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1855
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1856
+	 * injection, but currently no further filtering is done
1857
+	 *
1858
+	 * @global      $wpdb
1859
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1860
+	 *                               be updated to in the DB
1861
+	 * @return string of SQL
1862
+	 * @throws EE_Error
1863
+	 */
1864
+	public function _construct_update_sql($fields_n_values)
1865
+	{
1866
+		/** @type WPDB $wpdb */
1867
+		global $wpdb;
1868
+		$cols_n_values = array();
1869
+		foreach ($fields_n_values as $field_name => $value) {
1870
+			$field_obj = $this->field_settings_for($field_name);
1871
+			//if the value is NULL, we want to assign the value to that.
1872
+			//wpdb->prepare doesn't really handle that properly
1873
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874
+			$value_sql = $prepared_value === null ? 'NULL'
1875
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1877
+		}
1878
+		return implode(",", $cols_n_values);
1879
+	}
1880
+
1881
+
1882
+
1883
+	/**
1884
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1885
+	 * Performs a HARD delete, meaning the database row should always be removed,
1886
+	 * not just have a flag field on it switched
1887
+	 * Wrapper for EEM_Base::delete_permanently()
1888
+	 *
1889
+	 * @param mixed $id
1890
+	 * @param boolean $allow_blocking
1891
+	 * @return int the number of rows deleted
1892
+	 * @throws EE_Error
1893
+	 */
1894
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1895
+	{
1896
+		return $this->delete_permanently(
1897
+			array(
1898
+				array($this->get_primary_key_field()->get_name() => $id),
1899
+				'limit' => 1,
1900
+			),
1901
+			$allow_blocking
1902
+		);
1903
+	}
1904
+
1905
+
1906
+
1907
+	/**
1908
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1909
+	 * Wrapper for EEM_Base::delete()
1910
+	 *
1911
+	 * @param mixed $id
1912
+	 * @param boolean $allow_blocking
1913
+	 * @return int the number of rows deleted
1914
+	 * @throws EE_Error
1915
+	 */
1916
+	public function delete_by_ID($id, $allow_blocking = true)
1917
+	{
1918
+		return $this->delete(
1919
+			array(
1920
+				array($this->get_primary_key_field()->get_name() => $id),
1921
+				'limit' => 1,
1922
+			),
1923
+			$allow_blocking
1924
+		);
1925
+	}
1926
+
1927
+
1928
+
1929
+	/**
1930
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1931
+	 * meaning if the model has a field that indicates its been "trashed" or
1932
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1933
+	 *
1934
+	 * @see EEM_Base::delete_permanently
1935
+	 * @param array   $query_params
1936
+	 * @param boolean $allow_blocking
1937
+	 * @return int how many rows got deleted
1938
+	 * @throws EE_Error
1939
+	 */
1940
+	public function delete($query_params, $allow_blocking = true)
1941
+	{
1942
+		return $this->delete_permanently($query_params, $allow_blocking);
1943
+	}
1944
+
1945
+
1946
+
1947
+	/**
1948
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1949
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1950
+	 * as archived, not actually deleted
1951
+	 *
1952
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1953
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1954
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1955
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1956
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1957
+	 *                                DB
1958
+	 * @return int how many rows got deleted
1959
+	 * @throws EE_Error
1960
+	 */
1961
+	public function delete_permanently($query_params, $allow_blocking = true)
1962
+	{
1963
+		/**
1964
+		 * Action called just before performing a real deletion query. You can use the
1965
+		 * model and its $query_params to find exactly which items will be deleted
1966
+		 *
1967
+		 * @param EEM_Base $model
1968
+		 * @param array    $query_params   @see EEM_Base::get_all()
1969
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1970
+		 *                                 to block (prevent) this deletion
1971
+		 */
1972
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1973
+		//some MySQL databases may be running safe mode, which may restrict
1974
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1975
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1976
+		//to delete them
1977
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1978
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1979
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1980
+			$columns_and_ids_for_deleting
1981
+		);
1982
+		/**
1983
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1984
+		 *
1985
+		 * @param EEM_Base $this  The model instance being acted on.
1986
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1987
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1988
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1989
+		 *                                                  derived from the incoming query parameters.
1990
+		 *                                                  @see details on the structure of this array in the phpdocs
1991
+		 *                                                  for the `_get_ids_for_delete_method`
1992
+		 *
1993
+		 */
1994
+		do_action('AHEE__EEM_Base__delete__before_query',
1995
+			$this,
1996
+			$query_params,
1997
+			$allow_blocking,
1998
+			$columns_and_ids_for_deleting
1999
+		);
2000
+		if ($deletion_where_query_part) {
2001
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
2002
+			$table_aliases = array_keys($this->_tables);
2003
+			$SQL = "DELETE "
2004
+				   . implode(", ", $table_aliases)
2005
+				   . " FROM "
2006
+				   . $model_query_info->get_full_join_sql()
2007
+				   . " WHERE "
2008
+				   . $deletion_where_query_part;
2009
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
2010
+		} else {
2011
+			$rows_deleted = 0;
2012
+		}
2013
+
2014
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
2015
+		//there was no error with the delete query.
2016
+		if ($this->has_primary_key_field()
2017
+			&& $rows_deleted !== false
2018
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
2019
+		) {
2020
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
2021
+			foreach ($ids_for_removal as $id) {
2022
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
2023
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
2024
+				}
2025
+			}
2026
+
2027
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
2028
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2029
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2030
+			// (although it is possible).
2031
+			//Note this can be skipped by using the provided filter and returning false.
2032
+			if (apply_filters(
2033
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2034
+				! $this instanceof EEM_Extra_Meta,
2035
+				$this
2036
+			)) {
2037
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2038
+					0 => array(
2039
+						'EXM_type' => $this->get_this_model_name(),
2040
+						'OBJ_ID'   => array(
2041
+							'IN',
2042
+							$ids_for_removal
2043
+						)
2044
+					)
2045
+				));
2046
+			}
2047
+		}
2048
+
2049
+		/**
2050
+		 * Action called just after performing a real deletion query. Although at this point the
2051
+		 * items should have been deleted
2052
+		 *
2053
+		 * @param EEM_Base $model
2054
+		 * @param array    $query_params @see EEM_Base::get_all()
2055
+		 * @param int      $rows_deleted
2056
+		 */
2057
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
+		return $rows_deleted;//how many supposedly got deleted
2059
+	}
2060
+
2061
+
2062
+
2063
+	/**
2064
+	 * Checks all the relations that throw error messages when there are blocking related objects
2065
+	 * for related model objects. If there are any related model objects on those relations,
2066
+	 * adds an EE_Error, and return true
2067
+	 *
2068
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2069
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2070
+	 *                                                 should be ignored when determining whether there are related
2071
+	 *                                                 model objects which block this model object's deletion. Useful
2072
+	 *                                                 if you know A is related to B and are considering deleting A,
2073
+	 *                                                 but want to see if A has any other objects blocking its deletion
2074
+	 *                                                 before removing the relation between A and B
2075
+	 * @return boolean
2076
+	 * @throws EE_Error
2077
+	 */
2078
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2079
+	{
2080
+		//first, if $ignore_this_model_obj was supplied, get its model
2081
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2082
+			$ignored_model = $ignore_this_model_obj->get_model();
2083
+		} else {
2084
+			$ignored_model = null;
2085
+		}
2086
+		//now check all the relations of $this_model_obj_or_id and see if there
2087
+		//are any related model objects blocking it?
2088
+		$is_blocked = false;
2089
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2090
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2091
+				//if $ignore_this_model_obj was supplied, then for the query
2092
+				//on that model needs to be told to ignore $ignore_this_model_obj
2093
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2094
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2095
+						array(
2096
+							$ignored_model->get_primary_key_field()->get_name() => array(
2097
+								'!=',
2098
+								$ignore_this_model_obj->ID(),
2099
+							),
2100
+						),
2101
+					));
2102
+				} else {
2103
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2104
+				}
2105
+				if ($related_model_objects) {
2106
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2107
+					$is_blocked = true;
2108
+				}
2109
+			}
2110
+		}
2111
+		return $is_blocked;
2112
+	}
2113
+
2114
+
2115
+	/**
2116
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2117
+	 * @param array $row_results_for_deleting
2118
+	 * @param bool  $allow_blocking
2119
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2120
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2121
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2122
+	 *                 deleted. Example:
2123
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2124
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2125
+	 *                 where each element is a group of columns and values that get deleted. Example:
2126
+	 *                      array(
2127
+	 *                          0 => array(
2128
+	 *                              'Term_Relationship.object_id' => 1
2129
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2130
+	 *                          ),
2131
+	 *                          1 => array(
2132
+	 *                              'Term_Relationship.object_id' => 1
2133
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2134
+	 *                          )
2135
+	 *                      )
2136
+	 * @throws EE_Error
2137
+	 */
2138
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2139
+	{
2140
+		$ids_to_delete_indexed_by_column = array();
2141
+		if ($this->has_primary_key_field()) {
2142
+			$primary_table = $this->_get_main_table();
2143
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2144
+			$other_tables = $this->_get_other_tables();
2145
+			$ids_to_delete_indexed_by_column = $query = array();
2146
+			foreach ($row_results_for_deleting as $item_to_delete) {
2147
+				//before we mark this item for deletion,
2148
+				//make sure there's no related entities blocking its deletion (if we're checking)
2149
+				if (
2150
+					$allow_blocking
2151
+					&& $this->delete_is_blocked_by_related_models(
2152
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2153
+					)
2154
+				) {
2155
+					continue;
2156
+				}
2157
+				//primary table deletes
2158
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2159
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2160
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2161
+				}
2162
+			}
2163
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2164
+			$fields = $this->get_combined_primary_key_fields();
2165
+			foreach ($row_results_for_deleting as $item_to_delete) {
2166
+				$ids_to_delete_indexed_by_column_for_row = array();
2167
+				foreach ($fields as $cpk_field) {
2168
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2169
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2170
+							$item_to_delete[$cpk_field->get_qualified_column()];
2171
+					}
2172
+				}
2173
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2174
+			}
2175
+		} else {
2176
+			//so there's no primary key and no combined key...
2177
+			//sorry, can't help you
2178
+			throw new EE_Error(
2179
+				sprintf(
2180
+					__(
2181
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2182
+						"event_espresso"
2183
+					), get_class($this)
2184
+				)
2185
+			);
2186
+		}
2187
+		return $ids_to_delete_indexed_by_column;
2188
+	}
2189
+
2190
+
2191
+	/**
2192
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2193
+	 * the corresponding query_part for the query performing the delete.
2194
+	 *
2195
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2196
+	 * @return string
2197
+	 * @throws EE_Error
2198
+	 */
2199
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2200
+		$query_part = '';
2201
+		if (empty($ids_to_delete_indexed_by_column)) {
2202
+			return $query_part;
2203
+		} elseif ($this->has_primary_key_field()) {
2204
+			$query = array();
2205
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206
+				//make sure we have unique $ids
2207
+				$ids = array_unique($ids);
2208
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2209
+			}
2210
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2212
+			$ways_to_identify_a_row = array();
2213
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214
+				$values_for_each_combined_primary_key_for_a_row = array();
2215
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2217
+				}
2218
+				$ways_to_identify_a_row[] = '('
2219
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2220
+											. ')';
2221
+			}
2222
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2223
+		}
2224
+		return $query_part;
2225
+	}
2226
+
2227
+
2228
+
2229
+	/**
2230
+	 * Gets the model field by the fully qualified name
2231
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2232
+	 * @return EE_Model_Field_Base
2233
+	 */
2234
+	public function get_field_by_column($qualified_column_name)
2235
+	{
2236
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2237
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2238
+			   return $field_obj;
2239
+		   }
2240
+	   }
2241
+		throw new EE_Error(
2242
+			sprintf(
2243
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2244
+				$this->get_this_model_name(),
2245
+				$qualified_column_name
2246
+			)
2247
+		);
2248
+	}
2249
+
2250
+
2251
+
2252
+	/**
2253
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2254
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2255
+	 * column
2256
+	 *
2257
+	 * @param array  $query_params   like EEM_Base::get_all's
2258
+	 * @param string $field_to_count field on model to count by (not column name)
2259
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2260
+	 *                               that by the setting $distinct to TRUE;
2261
+	 * @return int
2262
+	 * @throws EE_Error
2263
+	 */
2264
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2265
+	{
2266
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2267
+		if ($field_to_count) {
2268
+			$field_obj = $this->field_settings_for($field_to_count);
2269
+			$column_to_count = $field_obj->get_qualified_column();
2270
+		} elseif ($this->has_primary_key_field()) {
2271
+			$pk_field_obj = $this->get_primary_key_field();
2272
+			$column_to_count = $pk_field_obj->get_qualified_column();
2273
+		} else {
2274
+			//there's no primary key
2275
+			//if we're counting distinct items, and there's no primary key,
2276
+			//we need to list out the columns for distinction;
2277
+			//otherwise we can just use star
2278
+			if ($distinct) {
2279
+				$columns_to_use = array();
2280
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2281
+					$columns_to_use[] = $field_obj->get_qualified_column();
2282
+				}
2283
+				$column_to_count = implode(',', $columns_to_use);
2284
+			} else {
2285
+				$column_to_count = '*';
2286
+			}
2287
+		}
2288
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2297
+	 *
2298
+	 * @param array  $query_params like EEM_Base::get_all
2299
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2300
+	 * @return float
2301
+	 * @throws EE_Error
2302
+	 */
2303
+	public function sum($query_params, $field_to_sum = null)
2304
+	{
2305
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2306
+		if ($field_to_sum) {
2307
+			$field_obj = $this->field_settings_for($field_to_sum);
2308
+		} else {
2309
+			$field_obj = $this->get_primary_key_field();
2310
+		}
2311
+		$column_to_count = $field_obj->get_qualified_column();
2312
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2313
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314
+		$data_type = $field_obj->get_wpdb_data_type();
2315
+		if ($data_type === '%d' || $data_type === '%s') {
2316
+			return (float)$return_value;
2317
+		}
2318
+		//must be %f
2319
+		return (float)$return_value;
2320
+	}
2321
+
2322
+
2323
+
2324
+	/**
2325
+	 * Just calls the specified method on $wpdb with the given arguments
2326
+	 * Consolidates a little extra error handling code
2327
+	 *
2328
+	 * @param string $wpdb_method
2329
+	 * @param array  $arguments_to_provide
2330
+	 * @throws EE_Error
2331
+	 * @global wpdb  $wpdb
2332
+	 * @return mixed
2333
+	 */
2334
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2335
+	{
2336
+		//if we're in maintenance mode level 2, DON'T run any queries
2337
+		//because level 2 indicates the database needs updating and
2338
+		//is probably out of sync with the code
2339
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2340
+			throw new EE_Error(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.",
2341
+				"event_espresso")));
2342
+		}
2343
+		/** @type WPDB $wpdb */
2344
+		global $wpdb;
2345
+		if (! method_exists($wpdb, $wpdb_method)) {
2346
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347
+				'event_espresso'), $wpdb_method));
2348
+		}
2349
+		if (WP_DEBUG) {
2350
+			$old_show_errors_value = $wpdb->show_errors;
2351
+			$wpdb->show_errors(false);
2352
+		}
2353
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2354
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2355
+		if (WP_DEBUG) {
2356
+			$wpdb->show_errors($old_show_errors_value);
2357
+			if (! empty($wpdb->last_error)) {
2358
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359
+			}
2360
+			if ($result === false) {
2361
+				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"',
2362
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2363
+			}
2364
+		} elseif ($result === false) {
2365
+			EE_Error::add_error(
2366
+				sprintf(
2367
+					__('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"',
2368
+						'event_espresso'),
2369
+					$wpdb_method,
2370
+					var_export($arguments_to_provide, true),
2371
+					$wpdb->last_error
2372
+				),
2373
+				__FILE__,
2374
+				__FUNCTION__,
2375
+				__LINE__
2376
+			);
2377
+		}
2378
+		return $result;
2379
+	}
2380
+
2381
+
2382
+
2383
+	/**
2384
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2385
+	 * and if there's an error tries to verify the DB is correct. Uses
2386
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2387
+	 * we should try to fix the EE core db, the addons, or just give up
2388
+	 *
2389
+	 * @param string $wpdb_method
2390
+	 * @param array  $arguments_to_provide
2391
+	 * @return mixed
2392
+	 */
2393
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2394
+	{
2395
+		/** @type WPDB $wpdb */
2396
+		global $wpdb;
2397
+		$wpdb->last_error = null;
2398
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2399
+		// was there an error running the query? but we don't care on new activations
2400
+		// (we're going to setup the DB anyway on new activations)
2401
+		if (($result === false || ! empty($wpdb->last_error))
2402
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2403
+		) {
2404
+			switch (EEM_Base::$_db_verification_level) {
2405
+				case EEM_Base::db_verified_none :
2406
+					// let's double-check core's DB
2407
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2408
+					break;
2409
+				case EEM_Base::db_verified_core :
2410
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2411
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2412
+					break;
2413
+				case EEM_Base::db_verified_addons :
2414
+					// ummmm... you in trouble
2415
+					return $result;
2416
+					break;
2417
+			}
2418
+			if (! empty($error_message)) {
2419
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420
+				trigger_error($error_message);
2421
+			}
2422
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2423
+		}
2424
+		return $result;
2425
+	}
2426
+
2427
+
2428
+
2429
+	/**
2430
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2431
+	 * EEM_Base::$_db_verification_level
2432
+	 *
2433
+	 * @param string $wpdb_method
2434
+	 * @param array  $arguments_to_provide
2435
+	 * @return string
2436
+	 */
2437
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2438
+	{
2439
+		/** @type WPDB $wpdb */
2440
+		global $wpdb;
2441
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2442
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2443
+		$error_message = sprintf(
2444
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2445
+				'event_espresso'),
2446
+			$wpdb->last_error,
2447
+			$wpdb_method,
2448
+			wp_json_encode($arguments_to_provide)
2449
+		);
2450
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2451
+		return $error_message;
2452
+	}
2453
+
2454
+
2455
+
2456
+	/**
2457
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2458
+	 * EEM_Base::$_db_verification_level
2459
+	 *
2460
+	 * @param $wpdb_method
2461
+	 * @param $arguments_to_provide
2462
+	 * @return string
2463
+	 */
2464
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2465
+	{
2466
+		/** @type WPDB $wpdb */
2467
+		global $wpdb;
2468
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2469
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2470
+		$error_message = sprintf(
2471
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2472
+				'event_espresso'),
2473
+			$wpdb->last_error,
2474
+			$wpdb_method,
2475
+			wp_json_encode($arguments_to_provide)
2476
+		);
2477
+		EE_System::instance()->initialize_addons();
2478
+		return $error_message;
2479
+	}
2480
+
2481
+
2482
+
2483
+	/**
2484
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2485
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2486
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2487
+	 * ..."
2488
+	 *
2489
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2490
+	 * @return string
2491
+	 */
2492
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493
+	{
2494
+		return " FROM " . $model_query_info->get_full_join_sql() .
2495
+			   $model_query_info->get_where_sql() .
2496
+			   $model_query_info->get_group_by_sql() .
2497
+			   $model_query_info->get_having_sql() .
2498
+			   $model_query_info->get_order_by_sql() .
2499
+			   $model_query_info->get_limit_sql();
2500
+	}
2501
+
2502
+
2503
+
2504
+	/**
2505
+	 * Set to easily debug the next X queries ran from this model.
2506
+	 *
2507
+	 * @param int $count
2508
+	 */
2509
+	public function show_next_x_db_queries($count = 1)
2510
+	{
2511
+		$this->_show_next_x_db_queries = $count;
2512
+	}
2513
+
2514
+
2515
+
2516
+	/**
2517
+	 * @param $sql_query
2518
+	 */
2519
+	public function show_db_query_if_previously_requested($sql_query)
2520
+	{
2521
+		if ($this->_show_next_x_db_queries > 0) {
2522
+			echo $sql_query;
2523
+			$this->_show_next_x_db_queries--;
2524
+		}
2525
+	}
2526
+
2527
+
2528
+
2529
+	/**
2530
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2531
+	 * There are the 3 cases:
2532
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2533
+	 * $otherModelObject has no ID, it is first saved.
2534
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2535
+	 * has no ID, it is first saved.
2536
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2537
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2538
+	 * join table
2539
+	 *
2540
+	 * @param        EE_Base_Class                     /int $thisModelObject
2541
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2542
+	 * @param string $relationName                     , key in EEM_Base::_relations
2543
+	 *                                                 an attendee to a group, you also want to specify which role they
2544
+	 *                                                 will have in that group. So you would use this parameter to
2545
+	 *                                                 specify array('role-column-name'=>'role-id')
2546
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2547
+	 *                                                 to for relation to methods that allow you to further specify
2548
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2549
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2550
+	 *                                                 because these will be inserted in any new rows created as well.
2551
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2552
+	 * @throws EE_Error
2553
+	 */
2554
+	public function add_relationship_to(
2555
+		$id_or_obj,
2556
+		$other_model_id_or_obj,
2557
+		$relationName,
2558
+		$extra_join_model_fields_n_values = array()
2559
+	) {
2560
+		$relation_obj = $this->related_settings_for($relationName);
2561
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2562
+	}
2563
+
2564
+
2565
+
2566
+	/**
2567
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2568
+	 * There are the 3 cases:
2569
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2570
+	 * error
2571
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2572
+	 * an error
2573
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2574
+	 *
2575
+	 * @param        EE_Base_Class /int $id_or_obj
2576
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2577
+	 * @param string $relationName key in EEM_Base::_relations
2578
+	 * @return boolean of success
2579
+	 * @throws EE_Error
2580
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2581
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2582
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2583
+	 *                             because these will be inserted in any new rows created as well.
2584
+	 */
2585
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2586
+	{
2587
+		$relation_obj = $this->related_settings_for($relationName);
2588
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2589
+	}
2590
+
2591
+
2592
+
2593
+	/**
2594
+	 * @param mixed           $id_or_obj
2595
+	 * @param string          $relationName
2596
+	 * @param array           $where_query_params
2597
+	 * @param EE_Base_Class[] objects to which relations were removed
2598
+	 * @return \EE_Base_Class[]
2599
+	 * @throws EE_Error
2600
+	 */
2601
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2602
+	{
2603
+		$relation_obj = $this->related_settings_for($relationName);
2604
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2605
+	}
2606
+
2607
+
2608
+
2609
+	/**
2610
+	 * Gets all the related items of the specified $model_name, using $query_params.
2611
+	 * Note: by default, we remove the "default query params"
2612
+	 * because we want to get even deleted items etc.
2613
+	 *
2614
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2615
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2616
+	 * @param array  $query_params like EEM_Base::get_all
2617
+	 * @return EE_Base_Class[]
2618
+	 * @throws EE_Error
2619
+	 */
2620
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2621
+	{
2622
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2623
+		$relation_settings = $this->related_settings_for($model_name);
2624
+		return $relation_settings->get_all_related($model_obj, $query_params);
2625
+	}
2626
+
2627
+
2628
+
2629
+	/**
2630
+	 * Deletes all the model objects across the relation indicated by $model_name
2631
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2632
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2633
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2634
+	 *
2635
+	 * @param EE_Base_Class|int|string $id_or_obj
2636
+	 * @param string                   $model_name
2637
+	 * @param array                    $query_params
2638
+	 * @return int how many deleted
2639
+	 * @throws EE_Error
2640
+	 */
2641
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2642
+	{
2643
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2644
+		$relation_settings = $this->related_settings_for($model_name);
2645
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2646
+	}
2647
+
2648
+
2649
+
2650
+	/**
2651
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2652
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2653
+	 * the model objects can't be hard deleted because of blocking related model objects,
2654
+	 * just does a soft-delete on them instead.
2655
+	 *
2656
+	 * @param EE_Base_Class|int|string $id_or_obj
2657
+	 * @param string                   $model_name
2658
+	 * @param array                    $query_params
2659
+	 * @return int how many deleted
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2663
+	{
2664
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2665
+		$relation_settings = $this->related_settings_for($model_name);
2666
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2667
+	}
2668
+
2669
+
2670
+
2671
+	/**
2672
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2673
+	 * unless otherwise specified in the $query_params
2674
+	 *
2675
+	 * @param        int             /EE_Base_Class $id_or_obj
2676
+	 * @param string $model_name     like 'Event', or 'Registration'
2677
+	 * @param array  $query_params   like EEM_Base::get_all's
2678
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2679
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2680
+	 *                               that by the setting $distinct to TRUE;
2681
+	 * @return int
2682
+	 * @throws EE_Error
2683
+	 */
2684
+	public function count_related(
2685
+		$id_or_obj,
2686
+		$model_name,
2687
+		$query_params = array(),
2688
+		$field_to_count = null,
2689
+		$distinct = false
2690
+	) {
2691
+		$related_model = $this->get_related_model_obj($model_name);
2692
+		//we're just going to use the query params on the related model's normal get_all query,
2693
+		//except add a condition to say to match the current mod
2694
+		if (! isset($query_params['default_where_conditions'])) {
2695
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696
+		}
2697
+		$this_model_name = $this->get_this_model_name();
2698
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2700
+		return $related_model->count($query_params, $field_to_count, $distinct);
2701
+	}
2702
+
2703
+
2704
+
2705
+	/**
2706
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2707
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2708
+	 *
2709
+	 * @param        int           /EE_Base_Class $id_or_obj
2710
+	 * @param string $model_name   like 'Event', or 'Registration'
2711
+	 * @param array  $query_params like EEM_Base::get_all's
2712
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2713
+	 * @return float
2714
+	 * @throws EE_Error
2715
+	 */
2716
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717
+	{
2718
+		$related_model = $this->get_related_model_obj($model_name);
2719
+		if (! is_array($query_params)) {
2720
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722
+					gettype($query_params)), '4.6.0');
2723
+			$query_params = array();
2724
+		}
2725
+		//we're just going to use the query params on the related model's normal get_all query,
2726
+		//except add a condition to say to match the current mod
2727
+		if (! isset($query_params['default_where_conditions'])) {
2728
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729
+		}
2730
+		$this_model_name = $this->get_this_model_name();
2731
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2733
+		return $related_model->sum($query_params, $field_to_sum);
2734
+	}
2735
+
2736
+
2737
+
2738
+	/**
2739
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2740
+	 * $modelObject
2741
+	 *
2742
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2743
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2744
+	 * @param array               $query_params     like EEM_Base::get_all's
2745
+	 * @return EE_Base_Class
2746
+	 * @throws EE_Error
2747
+	 */
2748
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2749
+	{
2750
+		$query_params['limit'] = 1;
2751
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2752
+		if ($results) {
2753
+			return array_shift($results);
2754
+		}
2755
+		return null;
2756
+	}
2757
+
2758
+
2759
+
2760
+	/**
2761
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2762
+	 *
2763
+	 * @return string
2764
+	 */
2765
+	public function get_this_model_name()
2766
+	{
2767
+		return str_replace("EEM_", "", get_class($this));
2768
+	}
2769
+
2770
+
2771
+
2772
+	/**
2773
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2774
+	 *
2775
+	 * @return EE_Any_Foreign_Model_Name_Field
2776
+	 * @throws EE_Error
2777
+	 */
2778
+	public function get_field_containing_related_model_name()
2779
+	{
2780
+		foreach ($this->field_settings(true) as $field) {
2781
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2782
+				$field_with_model_name = $field;
2783
+			}
2784
+		}
2785
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2786
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787
+				$this->get_this_model_name()));
2788
+		}
2789
+		return $field_with_model_name;
2790
+	}
2791
+
2792
+
2793
+
2794
+	/**
2795
+	 * Inserts a new entry into the database, for each table.
2796
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2797
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2798
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2799
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2800
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2801
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2802
+	 *
2803
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2804
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2805
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2806
+	 *                              of EEM_Base)
2807
+	 * @return int new primary key on main table that got inserted
2808
+	 * @throws EE_Error
2809
+	 */
2810
+	public function insert($field_n_values)
2811
+	{
2812
+		/**
2813
+		 * Filters the fields and their values before inserting an item using the models
2814
+		 *
2815
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2816
+		 * @param EEM_Base $model           the model used
2817
+		 */
2818
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2820
+			$main_table = $this->_get_main_table();
2821
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2822
+			if ($new_id !== false) {
2823
+				foreach ($this->_get_other_tables() as $other_table) {
2824
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2825
+				}
2826
+			}
2827
+			/**
2828
+			 * Done just after attempting to insert a new model object
2829
+			 *
2830
+			 * @param EEM_Base   $model           used
2831
+			 * @param array      $fields_n_values fields and their values
2832
+			 * @param int|string the              ID of the newly-inserted model object
2833
+			 */
2834
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2835
+			return $new_id;
2836
+		}
2837
+		return false;
2838
+	}
2839
+
2840
+
2841
+
2842
+	/**
2843
+	 * Checks that the result would satisfy the unique indexes on this model
2844
+	 *
2845
+	 * @param array  $field_n_values
2846
+	 * @param string $action
2847
+	 * @return boolean
2848
+	 * @throws EE_Error
2849
+	 */
2850
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2851
+	{
2852
+		foreach ($this->unique_indexes() as $index_name => $index) {
2853
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2854
+			if ($this->exists(array($uniqueness_where_params))) {
2855
+				EE_Error::add_error(
2856
+					sprintf(
2857
+						__(
2858
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2859
+							"event_espresso"
2860
+						),
2861
+						$action,
2862
+						$this->_get_class_name(),
2863
+						$index_name,
2864
+						implode(",", $index->field_names()),
2865
+						http_build_query($uniqueness_where_params)
2866
+					),
2867
+					__FILE__,
2868
+					__FUNCTION__,
2869
+					__LINE__
2870
+				);
2871
+				return false;
2872
+			}
2873
+		}
2874
+		return true;
2875
+	}
2876
+
2877
+
2878
+
2879
+	/**
2880
+	 * Checks the database for an item that conflicts (ie, if this item were
2881
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2882
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2883
+	 * can be either an EE_Base_Class or an array of fields n values
2884
+	 *
2885
+	 * @param EE_Base_Class|array $obj_or_fields_array
2886
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2887
+	 *                                                 when looking for conflicts
2888
+	 *                                                 (ie, if false, we ignore the model object's primary key
2889
+	 *                                                 when finding "conflicts". If true, it's also considered).
2890
+	 *                                                 Only works for INT primary key,
2891
+	 *                                                 STRING primary keys cannot be ignored
2892
+	 * @throws EE_Error
2893
+	 * @return EE_Base_Class|array
2894
+	 */
2895
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2896
+	{
2897
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2898
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2899
+		} elseif (is_array($obj_or_fields_array)) {
2900
+			$fields_n_values = $obj_or_fields_array;
2901
+		} else {
2902
+			throw new EE_Error(
2903
+				sprintf(
2904
+					__(
2905
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2906
+						"event_espresso"
2907
+					),
2908
+					get_class($this),
2909
+					$obj_or_fields_array
2910
+				)
2911
+			);
2912
+		}
2913
+		$query_params = array();
2914
+		if ($this->has_primary_key_field()
2915
+			&& ($include_primary_key
2916
+				|| $this->get_primary_key_field()
2917
+				   instanceof
2918
+				   EE_Primary_Key_String_Field)
2919
+			&& isset($fields_n_values[$this->primary_key_name()])
2920
+		) {
2921
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2922
+		}
2923
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2926
+		}
2927
+		//if there is nothing to base this search on, then we shouldn't find anything
2928
+		if (empty($query_params)) {
2929
+			return array();
2930
+		}
2931
+		return $this->get_one($query_params);
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Like count, but is optimized and returns a boolean instead of an int
2938
+	 *
2939
+	 * @param array $query_params
2940
+	 * @return boolean
2941
+	 * @throws EE_Error
2942
+	 */
2943
+	public function exists($query_params)
2944
+	{
2945
+		$query_params['limit'] = 1;
2946
+		return $this->count($query_params) > 0;
2947
+	}
2948
+
2949
+
2950
+
2951
+	/**
2952
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2953
+	 *
2954
+	 * @param int|string $id
2955
+	 * @return boolean
2956
+	 * @throws EE_Error
2957
+	 */
2958
+	public function exists_by_ID($id)
2959
+	{
2960
+		return $this->exists(
2961
+			array(
2962
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2963
+				array(
2964
+					$this->primary_key_name() => $id,
2965
+				),
2966
+			)
2967
+		);
2968
+	}
2969
+
2970
+
2971
+
2972
+	/**
2973
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2974
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2975
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2976
+	 * on the main table)
2977
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2978
+	 * cases where we want to call it directly rather than via insert().
2979
+	 *
2980
+	 * @access   protected
2981
+	 * @param EE_Table_Base $table
2982
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2983
+	 *                                       float
2984
+	 * @param int           $new_id          for now we assume only int keys
2985
+	 * @throws EE_Error
2986
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2987
+	 * @return int ID of new row inserted, or FALSE on failure
2988
+	 */
2989
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2990
+	{
2991
+		global $wpdb;
2992
+		$insertion_col_n_values = array();
2993
+		$format_for_insertion = array();
2994
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2995
+		foreach ($fields_on_table as $field_name => $field_obj) {
2996
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2997
+			if ($field_obj->is_auto_increment()) {
2998
+				continue;
2999
+			}
3000
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
3001
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
3002
+			if ($prepared_value !== null) {
3003
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
3004
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
3005
+			}
3006
+		}
3007
+		if ($table instanceof EE_Secondary_Table && $new_id) {
3008
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
3009
+			//so add the fk to the main table as a column
3010
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3012
+		}
3013
+		//insert the new entry
3014
+		$result = $this->_do_wpdb_query('insert',
3015
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
3016
+		if ($result === false) {
3017
+			return false;
3018
+		}
3019
+		//ok, now what do we return for the ID of the newly-inserted thing?
3020
+		if ($this->has_primary_key_field()) {
3021
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3022
+				return $wpdb->insert_id;
3023
+			}
3024
+			//it's not an auto-increment primary key, so
3025
+			//it must have been supplied
3026
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
3027
+		}
3028
+		//we can't return a  primary key because there is none. instead return
3029
+		//a unique string indicating this model
3030
+		return $this->get_index_primary_key_string($fields_n_values);
3031
+	}
3032
+
3033
+
3034
+
3035
+	/**
3036
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3037
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3038
+	 * and there is no default, we pass it along. WPDB will take care of it)
3039
+	 *
3040
+	 * @param EE_Model_Field_Base $field_obj
3041
+	 * @param array               $fields_n_values
3042
+	 * @return mixed string|int|float depending on what the table column will be expecting
3043
+	 * @throws EE_Error
3044
+	 */
3045
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3046
+	{
3047
+		//if this field doesn't allow nullable, don't allow it
3048
+		if (
3049
+			! $field_obj->is_nullable()
3050
+			&& (
3051
+				! isset($fields_n_values[$field_obj->get_name()])
3052
+				|| $fields_n_values[$field_obj->get_name()] === null
3053
+			)
3054
+		) {
3055
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3056
+		}
3057
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3058
+			? $fields_n_values[$field_obj->get_name()]
3059
+			: null;
3060
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3061
+	}
3062
+
3063
+
3064
+
3065
+	/**
3066
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3067
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3068
+	 * the field's prepare_for_set() method.
3069
+	 *
3070
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3071
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3072
+	 *                                   top of file)
3073
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3074
+	 *                                   $value is a custom selection
3075
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3076
+	 */
3077
+	private function _prepare_value_for_use_in_db($value, $field)
3078
+	{
3079
+		if ($field && $field instanceof EE_Model_Field_Base) {
3080
+			switch ($this->_values_already_prepared_by_model_object) {
3081
+				/** @noinspection PhpMissingBreakStatementInspection */
3082
+				case self::not_prepared_by_model_object:
3083
+					$value = $field->prepare_for_set($value);
3084
+				//purposefully left out "return"
3085
+				case self::prepared_by_model_object:
3086
+					/** @noinspection SuspiciousAssignmentsInspection */
3087
+					$value = $field->prepare_for_use_in_db($value);
3088
+				case self::prepared_for_use_in_db:
3089
+					//leave the value alone
3090
+			}
3091
+			return $value;
3092
+		}
3093
+		return $value;
3094
+	}
3095
+
3096
+
3097
+
3098
+	/**
3099
+	 * Returns the main table on this model
3100
+	 *
3101
+	 * @return EE_Primary_Table
3102
+	 * @throws EE_Error
3103
+	 */
3104
+	protected function _get_main_table()
3105
+	{
3106
+		foreach ($this->_tables as $table) {
3107
+			if ($table instanceof EE_Primary_Table) {
3108
+				return $table;
3109
+			}
3110
+		}
3111
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3112
+			'event_espresso'), get_class($this)));
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * table
3119
+	 * returns EE_Primary_Table table name
3120
+	 *
3121
+	 * @return string
3122
+	 * @throws EE_Error
3123
+	 */
3124
+	public function table()
3125
+	{
3126
+		return $this->_get_main_table()->get_table_name();
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * table
3133
+	 * returns first EE_Secondary_Table table name
3134
+	 *
3135
+	 * @return string
3136
+	 */
3137
+	public function second_table()
3138
+	{
3139
+		// grab second table from tables array
3140
+		$second_table = end($this->_tables);
3141
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3142
+	}
3143
+
3144
+
3145
+
3146
+	/**
3147
+	 * get_table_obj_by_alias
3148
+	 * returns table name given it's alias
3149
+	 *
3150
+	 * @param string $table_alias
3151
+	 * @return EE_Primary_Table | EE_Secondary_Table
3152
+	 */
3153
+	public function get_table_obj_by_alias($table_alias = '')
3154
+	{
3155
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3162
+	 *
3163
+	 * @return EE_Secondary_Table[]
3164
+	 */
3165
+	protected function _get_other_tables()
3166
+	{
3167
+		$other_tables = array();
3168
+		foreach ($this->_tables as $table_alias => $table) {
3169
+			if ($table instanceof EE_Secondary_Table) {
3170
+				$other_tables[$table_alias] = $table;
3171
+			}
3172
+		}
3173
+		return $other_tables;
3174
+	}
3175
+
3176
+
3177
+
3178
+	/**
3179
+	 * Finds all the fields that correspond to the given table
3180
+	 *
3181
+	 * @param string $table_alias , array key in EEM_Base::_tables
3182
+	 * @return EE_Model_Field_Base[]
3183
+	 */
3184
+	public function _get_fields_for_table($table_alias)
3185
+	{
3186
+		return $this->_fields[$table_alias];
3187
+	}
3188
+
3189
+
3190
+
3191
+	/**
3192
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3193
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3194
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3195
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3196
+	 * related Registration, Transaction, and Payment models.
3197
+	 *
3198
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3199
+	 * @return EE_Model_Query_Info_Carrier
3200
+	 * @throws EE_Error
3201
+	 */
3202
+	public function _extract_related_models_from_query($query_params)
3203
+	{
3204
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3205
+		if (array_key_exists(0, $query_params)) {
3206
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3207
+		}
3208
+		if (array_key_exists('group_by', $query_params)) {
3209
+			if (is_array($query_params['group_by'])) {
3210
+				$this->_extract_related_models_from_sub_params_array_values(
3211
+					$query_params['group_by'],
3212
+					$query_info_carrier,
3213
+					'group_by'
3214
+				);
3215
+			} elseif (! empty ($query_params['group_by'])) {
3216
+				$this->_extract_related_model_info_from_query_param(
3217
+					$query_params['group_by'],
3218
+					$query_info_carrier,
3219
+					'group_by'
3220
+				);
3221
+			}
3222
+		}
3223
+		if (array_key_exists('having', $query_params)) {
3224
+			$this->_extract_related_models_from_sub_params_array_keys(
3225
+				$query_params[0],
3226
+				$query_info_carrier,
3227
+				'having'
3228
+			);
3229
+		}
3230
+		if (array_key_exists('order_by', $query_params)) {
3231
+			if (is_array($query_params['order_by'])) {
3232
+				$this->_extract_related_models_from_sub_params_array_keys(
3233
+					$query_params['order_by'],
3234
+					$query_info_carrier,
3235
+					'order_by'
3236
+				);
3237
+			} elseif (! empty($query_params['order_by'])) {
3238
+				$this->_extract_related_model_info_from_query_param(
3239
+					$query_params['order_by'],
3240
+					$query_info_carrier,
3241
+					'order_by'
3242
+				);
3243
+			}
3244
+		}
3245
+		if (array_key_exists('force_join', $query_params)) {
3246
+			$this->_extract_related_models_from_sub_params_array_values(
3247
+				$query_params['force_join'],
3248
+				$query_info_carrier,
3249
+				'force_join'
3250
+			);
3251
+		}
3252
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3253
+		return $query_info_carrier;
3254
+	}
3255
+
3256
+
3257
+
3258
+	/**
3259
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3260
+	 *
3261
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3262
+	 *                                                      $query_params['having']
3263
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3264
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3265
+	 * @throws EE_Error
3266
+	 * @return \EE_Model_Query_Info_Carrier
3267
+	 */
3268
+	private function _extract_related_models_from_sub_params_array_keys(
3269
+		$sub_query_params,
3270
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271
+		$query_param_type
3272
+	) {
3273
+		if (! empty($sub_query_params)) {
3274
+			$sub_query_params = (array)$sub_query_params;
3275
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3278
+					$query_param_type);
3279
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3280
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3281
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3282
+				//of array('Registration.TXN_ID'=>23)
3283
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
+					if (! is_array($possibly_array_of_params)) {
3286
+						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'))",
3287
+							"event_espresso"),
3288
+							$param, $possibly_array_of_params));
3289
+					}
3290
+					$this->_extract_related_models_from_sub_params_array_keys(
3291
+						$possibly_array_of_params,
3292
+						$model_query_info_carrier, $query_param_type
3293
+					);
3294
+				} elseif ($query_param_type === 0 //ie WHERE
3295
+						  && is_array($possibly_array_of_params)
3296
+						  && isset($possibly_array_of_params[2])
3297
+						  && $possibly_array_of_params[2] == true
3298
+				) {
3299
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300
+					//indicating that $possible_array_of_params[1] is actually a field name,
3301
+					//from which we should extract query parameters!
3302
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305
+					}
3306
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3307
+						$model_query_info_carrier, $query_param_type);
3308
+				}
3309
+			}
3310
+		}
3311
+		return $model_query_info_carrier;
3312
+	}
3313
+
3314
+
3315
+
3316
+	/**
3317
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3318
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3319
+	 *
3320
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3321
+	 *                                                      $query_params['having']
3322
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3323
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3324
+	 * @throws EE_Error
3325
+	 * @return \EE_Model_Query_Info_Carrier
3326
+	 */
3327
+	private function _extract_related_models_from_sub_params_array_values(
3328
+		$sub_query_params,
3329
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330
+		$query_param_type
3331
+	) {
3332
+		if (! empty($sub_query_params)) {
3333
+			if (! is_array($sub_query_params)) {
3334
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335
+					$sub_query_params));
3336
+			}
3337
+			foreach ($sub_query_params as $param) {
3338
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3339
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3340
+					$query_param_type);
3341
+			}
3342
+		}
3343
+		return $model_query_info_carrier;
3344
+	}
3345
+
3346
+
3347
+
3348
+	/**
3349
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3350
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3351
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3352
+	 * but use them in a different order. Eg, we need to know what models we are querying
3353
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3354
+	 * other models before we can finalize the where clause SQL.
3355
+	 *
3356
+	 * @param array $query_params
3357
+	 * @throws EE_Error
3358
+	 * @return EE_Model_Query_Info_Carrier
3359
+	 */
3360
+	public function _create_model_query_info_carrier($query_params)
3361
+	{
3362
+		if (! is_array($query_params)) {
3363
+			EE_Error::doing_it_wrong(
3364
+				'EEM_Base::_create_model_query_info_carrier',
3365
+				sprintf(
3366
+					__(
3367
+						'$query_params should be an array, you passed a variable of type %s',
3368
+						'event_espresso'
3369
+					),
3370
+					gettype($query_params)
3371
+				),
3372
+				'4.6.0'
3373
+			);
3374
+			$query_params = array();
3375
+		}
3376
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3377
+		//first check if we should alter the query to account for caps or not
3378
+		//because the caps might require us to do extra joins
3379
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3380
+			$query_params[0] = $where_query_params = array_replace_recursive(
3381
+				$where_query_params,
3382
+				$this->caps_where_conditions(
3383
+					$query_params['caps']
3384
+				)
3385
+			);
3386
+		}
3387
+		$query_object = $this->_extract_related_models_from_query($query_params);
3388
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3389
+		foreach ($where_query_params as $key => $value) {
3390
+			if (is_int($key)) {
3391
+				throw new EE_Error(
3392
+					sprintf(
3393
+						__(
3394
+							"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.",
3395
+							"event_espresso"
3396
+						),
3397
+						$key,
3398
+						var_export($value, true),
3399
+						var_export($query_params, true),
3400
+						get_class($this)
3401
+					)
3402
+				);
3403
+			}
3404
+		}
3405
+		if (
3406
+			array_key_exists('default_where_conditions', $query_params)
3407
+			&& ! empty($query_params['default_where_conditions'])
3408
+		) {
3409
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3410
+		} else {
3411
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3412
+		}
3413
+		$where_query_params = array_merge(
3414
+			$this->_get_default_where_conditions_for_models_in_query(
3415
+				$query_object,
3416
+				$use_default_where_conditions,
3417
+				$where_query_params
3418
+			),
3419
+			$where_query_params
3420
+		);
3421
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3422
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3423
+		// So we need to setup a subquery and use that for the main join.
3424
+		// Note for now this only works on the primary table for the model.
3425
+		// So for instance, you could set the limit array like this:
3426
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3427
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3428
+			$query_object->set_main_model_join_sql(
3429
+				$this->_construct_limit_join_select(
3430
+					$query_params['on_join_limit'][0],
3431
+					$query_params['on_join_limit'][1]
3432
+				)
3433
+			);
3434
+		}
3435
+		//set limit
3436
+		if (array_key_exists('limit', $query_params)) {
3437
+			if (is_array($query_params['limit'])) {
3438
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439
+					$e = sprintf(
3440
+						__(
3441
+							"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)",
3442
+							"event_espresso"
3443
+						),
3444
+						http_build_query($query_params['limit'])
3445
+					);
3446
+					throw new EE_Error($e . "|" . $e);
3447
+				}
3448
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
+			} elseif (! empty ($query_params['limit'])) {
3451
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3452
+			}
3453
+		}
3454
+		//set order by
3455
+		if (array_key_exists('order_by', $query_params)) {
3456
+			if (is_array($query_params['order_by'])) {
3457
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3458
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3459
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3460
+				if (array_key_exists('order', $query_params)) {
3461
+					throw new EE_Error(
3462
+						sprintf(
3463
+							__(
3464
+								"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 ",
3465
+								"event_espresso"
3466
+							),
3467
+							get_class($this),
3468
+							implode(", ", array_keys($query_params['order_by'])),
3469
+							implode(", ", $query_params['order_by']),
3470
+							$query_params['order']
3471
+						)
3472
+					);
3473
+				}
3474
+				$this->_extract_related_models_from_sub_params_array_keys(
3475
+					$query_params['order_by'],
3476
+					$query_object,
3477
+					'order_by'
3478
+				);
3479
+				//assume it's an array of fields to order by
3480
+				$order_array = array();
3481
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482
+					$order = $this->_extract_order($order);
3483
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3484
+				}
3485
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
+			} elseif (! empty ($query_params['order_by'])) {
3487
+				$this->_extract_related_model_info_from_query_param(
3488
+					$query_params['order_by'],
3489
+					$query_object,
3490
+					'order',
3491
+					$query_params['order_by']
3492
+				);
3493
+				$order = isset($query_params['order'])
3494
+					? $this->_extract_order($query_params['order'])
3495
+					: 'DESC';
3496
+				$query_object->set_order_by_sql(
3497
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3498
+				);
3499
+			}
3500
+		}
3501
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
+		if (! array_key_exists('order_by', $query_params)
3503
+			&& array_key_exists('order', $query_params)
3504
+			&& ! empty($query_params['order'])
3505
+		) {
3506
+			$pk_field = $this->get_primary_key_field();
3507
+			$order = $this->_extract_order($query_params['order']);
3508
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3509
+		}
3510
+		//set group by
3511
+		if (array_key_exists('group_by', $query_params)) {
3512
+			if (is_array($query_params['group_by'])) {
3513
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3514
+				$group_by_array = array();
3515
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517
+				}
3518
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
+			} elseif (! empty ($query_params['group_by'])) {
3520
+				$query_object->set_group_by_sql(
3521
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3522
+				);
3523
+			}
3524
+		}
3525
+		//set having
3526
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3527
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3528
+		}
3529
+		//now, just verify they didn't pass anything wack
3530
+		foreach ($query_params as $query_key => $query_value) {
3531
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3532
+				throw new EE_Error(
3533
+					sprintf(
3534
+						__(
3535
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3536
+							'event_espresso'
3537
+						),
3538
+						$query_key,
3539
+						get_class($this),
3540
+						//						print_r( $this->_allowed_query_params, TRUE )
3541
+						implode(',', $this->_allowed_query_params)
3542
+					)
3543
+				);
3544
+			}
3545
+		}
3546
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3547
+		if (empty($main_model_join_sql)) {
3548
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3549
+		}
3550
+		return $query_object;
3551
+	}
3552
+
3553
+
3554
+
3555
+	/**
3556
+	 * Gets the where conditions that should be imposed on the query based on the
3557
+	 * context (eg reading frontend, backend, edit or delete).
3558
+	 *
3559
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3560
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3561
+	 * @throws EE_Error
3562
+	 */
3563
+	public function caps_where_conditions($context = self::caps_read)
3564
+	{
3565
+		EEM_Base::verify_is_valid_cap_context($context);
3566
+		$cap_where_conditions = array();
3567
+		$cap_restrictions = $this->caps_missing($context);
3568
+		/**
3569
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3570
+		 */
3571
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3572
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3573
+				$restriction_if_no_cap->get_default_where_conditions());
3574
+		}
3575
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3576
+			$cap_restrictions);
3577
+	}
3578
+
3579
+
3580
+
3581
+	/**
3582
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3583
+	 * otherwise throws an exception
3584
+	 *
3585
+	 * @param string $should_be_order_string
3586
+	 * @return string either ASC, asc, DESC or desc
3587
+	 * @throws EE_Error
3588
+	 */
3589
+	private function _extract_order($should_be_order_string)
3590
+	{
3591
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3592
+			return $should_be_order_string;
3593
+		}
3594
+		throw new EE_Error(
3595
+			sprintf(
3596
+				__(
3597
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3598
+					"event_espresso"
3599
+				), get_class($this), $should_be_order_string
3600
+			)
3601
+		);
3602
+	}
3603
+
3604
+
3605
+
3606
+	/**
3607
+	 * Looks at all the models which are included in this query, and asks each
3608
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3609
+	 * so they can be merged
3610
+	 *
3611
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3612
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3613
+	 *                                                                  'none' means NO default where conditions will
3614
+	 *                                                                  be used AT ALL during this query.
3615
+	 *                                                                  'other_models_only' means default where
3616
+	 *                                                                  conditions from other models will be used, but
3617
+	 *                                                                  not for this primary model. 'all', the default,
3618
+	 *                                                                  means default where conditions will apply as
3619
+	 *                                                                  normal
3620
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3621
+	 * @throws EE_Error
3622
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3623
+	 */
3624
+	private function _get_default_where_conditions_for_models_in_query(
3625
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3626
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3627
+		$where_query_params = array()
3628
+	) {
3629
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632
+				"event_espresso"), $use_default_where_conditions,
3633
+				implode(", ", $allowed_used_default_where_conditions_values)));
3634
+		}
3635
+		$universal_query_params = array();
3636
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3637
+			$universal_query_params = $this->_get_default_where_conditions();
3638
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3639
+			$universal_query_params = $this->_get_minimum_where_conditions();
3640
+		}
3641
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642
+			$related_model = $this->get_related_model_obj($model_name);
3643
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3644
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3646
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647
+			} else {
3648
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3649
+				continue;
3650
+			}
3651
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3652
+				$related_model_universal_where_params,
3653
+				$where_query_params,
3654
+				$related_model,
3655
+				$model_relation_path
3656
+			);
3657
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3658
+				$universal_query_params,
3659
+				$overrides
3660
+			);
3661
+		}
3662
+		return $universal_query_params;
3663
+	}
3664
+
3665
+
3666
+
3667
+	/**
3668
+	 * Determines whether or not we should use default where conditions for the model in question
3669
+	 * (this model, or other related models).
3670
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3671
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3672
+	 * We should use default where conditions on related models when they requested to use default where conditions
3673
+	 * on all models, or specifically just on other related models
3674
+	 * @param      $default_where_conditions_value
3675
+	 * @param bool $for_this_model false means this is for OTHER related models
3676
+	 * @return bool
3677
+	 */
3678
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3679
+	{
3680
+		return (
3681
+				   $for_this_model
3682
+				   && in_array(
3683
+					   $default_where_conditions_value,
3684
+					   array(
3685
+						   EEM_Base::default_where_conditions_all,
3686
+						   EEM_Base::default_where_conditions_this_only,
3687
+						   EEM_Base::default_where_conditions_minimum_others,
3688
+					   ),
3689
+					   true
3690
+				   )
3691
+			   )
3692
+			   || (
3693
+				   ! $for_this_model
3694
+				   && in_array(
3695
+					   $default_where_conditions_value,
3696
+					   array(
3697
+						   EEM_Base::default_where_conditions_all,
3698
+						   EEM_Base::default_where_conditions_others_only,
3699
+					   ),
3700
+					   true
3701
+				   )
3702
+			   );
3703
+	}
3704
+
3705
+	/**
3706
+	 * Determines whether or not we should use default minimum conditions for the model in question
3707
+	 * (this model, or other related models).
3708
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3709
+	 * where conditions.
3710
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3711
+	 * on this model or others
3712
+	 * @param      $default_where_conditions_value
3713
+	 * @param bool $for_this_model false means this is for OTHER related models
3714
+	 * @return bool
3715
+	 */
3716
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3717
+	{
3718
+		return (
3719
+				   $for_this_model
3720
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3721
+			   )
3722
+			   || (
3723
+				   ! $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_minimum_others,
3728
+						   EEM_Base::default_where_conditions_minimum_all,
3729
+					   ),
3730
+					   true
3731
+				   )
3732
+			   );
3733
+	}
3734
+
3735
+
3736
+	/**
3737
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3738
+	 * then we also add a special where condition which allows for that model's primary key
3739
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3740
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3741
+	 *
3742
+	 * @param array    $default_where_conditions
3743
+	 * @param array    $provided_where_conditions
3744
+	 * @param EEM_Base $model
3745
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3746
+	 * @return array like EEM_Base::get_all's $query_params[0]
3747
+	 * @throws EE_Error
3748
+	 */
3749
+	private function _override_defaults_or_make_null_friendly(
3750
+		$default_where_conditions,
3751
+		$provided_where_conditions,
3752
+		$model,
3753
+		$model_relation_path
3754
+	) {
3755
+		$null_friendly_where_conditions = array();
3756
+		$none_overridden = true;
3757
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3758
+		foreach ($default_where_conditions as $key => $val) {
3759
+			if (isset($provided_where_conditions[$key])) {
3760
+				$none_overridden = false;
3761
+			} else {
3762
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3763
+			}
3764
+		}
3765
+		if ($none_overridden && $default_where_conditions) {
3766
+			if ($model->has_primary_key_field()) {
3767
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3768
+																				. "."
3769
+																				. $model->primary_key_name()] = array('IS NULL');
3770
+			}/*else{
3771 3771
 				//@todo NO PK, use other defaults
3772 3772
 			}*/
3773
-        }
3774
-        return $null_friendly_where_conditions;
3775
-    }
3776
-
3777
-
3778
-
3779
-    /**
3780
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3781
-     * default where conditions on all get_all, update, and delete queries done by this model.
3782
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3783
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3784
-     *
3785
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3786
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3787
-     */
3788
-    private function _get_default_where_conditions($model_relation_path = null)
3789
-    {
3790
-        if ($this->_ignore_where_strategy) {
3791
-            return array();
3792
-        }
3793
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3794
-    }
3795
-
3796
-
3797
-
3798
-    /**
3799
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3800
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3801
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3802
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3803
-     * Similar to _get_default_where_conditions
3804
-     *
3805
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3806
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3807
-     */
3808
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3809
-    {
3810
-        if ($this->_ignore_where_strategy) {
3811
-            return array();
3812
-        }
3813
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3814
-    }
3815
-
3816
-
3817
-
3818
-    /**
3819
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3820
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3821
-     *
3822
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3823
-     * @return string
3824
-     * @throws EE_Error
3825
-     */
3826
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3827
-    {
3828
-        $selects = $this->_get_columns_to_select_for_this_model();
3829
-        foreach (
3830
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3831
-            $name_of_other_model_included
3832
-        ) {
3833
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3834
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3835
-            foreach ($other_model_selects as $key => $value) {
3836
-                $selects[] = $value;
3837
-            }
3838
-        }
3839
-        return implode(", ", $selects);
3840
-    }
3841
-
3842
-
3843
-
3844
-    /**
3845
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3846
-     * So that's going to be the columns for all the fields on the model
3847
-     *
3848
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3849
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3850
-     */
3851
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3852
-    {
3853
-        $fields = $this->field_settings();
3854
-        $selects = array();
3855
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3856
-            $this->get_this_model_name());
3857
-        foreach ($fields as $field_obj) {
3858
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3859
-                         . $field_obj->get_table_alias()
3860
-                         . "."
3861
-                         . $field_obj->get_table_column()
3862
-                         . " AS '"
3863
-                         . $table_alias_with_model_relation_chain_prefix
3864
-                         . $field_obj->get_table_alias()
3865
-                         . "."
3866
-                         . $field_obj->get_table_column()
3867
-                         . "'";
3868
-        }
3869
-        //make sure we are also getting the PKs of each table
3870
-        $tables = $this->get_tables();
3871
-        if (count($tables) > 1) {
3872
-            foreach ($tables as $table_obj) {
3873
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874
-                                       . $table_obj->get_fully_qualified_pk_column();
3875
-                if (! in_array($qualified_pk_column, $selects)) {
3876
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877
-                }
3878
-            }
3879
-        }
3880
-        return $selects;
3881
-    }
3882
-
3883
-
3884
-
3885
-    /**
3886
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3887
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3888
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3889
-     * SQL for joining, and the data types
3890
-     *
3891
-     * @param null|string                 $original_query_param
3892
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3893
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3894
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3895
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3896
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3897
-     *                                                          or 'Registration's
3898
-     * @param string                      $original_query_param what it originally was (eg
3899
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3900
-     *                                                          matches $query_param
3901
-     * @throws EE_Error
3902
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3903
-     */
3904
-    private function _extract_related_model_info_from_query_param(
3905
-        $query_param,
3906
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3907
-        $query_param_type,
3908
-        $original_query_param = null
3909
-    ) {
3910
-        if ($original_query_param === null) {
3911
-            $original_query_param = $query_param;
3912
-        }
3913
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3914
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3915
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3916
-        $allow_fields = in_array(
3917
-            $query_param_type,
3918
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3919
-            true
3920
-        );
3921
-        //check to see if we have a field on this model
3922
-        $this_model_fields = $this->field_settings(true);
3923
-        if (array_key_exists($query_param, $this_model_fields)) {
3924
-            if ($allow_fields) {
3925
-                return;
3926
-            }
3927
-            throw new EE_Error(
3928
-                sprintf(
3929
-                    __(
3930
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3931
-                        "event_espresso"
3932
-                    ),
3933
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3934
-                )
3935
-            );
3936
-        }
3937
-        //check if this is a special logic query param
3938
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3939
-            if ($allow_logic_query_params) {
3940
-                return;
3941
-            }
3942
-            throw new EE_Error(
3943
-                sprintf(
3944
-                    __(
3945
-                        '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',
3946
-                        'event_espresso'
3947
-                    ),
3948
-                    implode('", "', $this->_logic_query_param_keys),
3949
-                    $query_param,
3950
-                    get_class($this),
3951
-                    '<br />',
3952
-                    "\t"
3953
-                    . ' $passed_in_query_info = <pre>'
3954
-                    . print_r($passed_in_query_info, true)
3955
-                    . '</pre>'
3956
-                    . "\n\t"
3957
-                    . ' $query_param_type = '
3958
-                    . $query_param_type
3959
-                    . "\n\t"
3960
-                    . ' $original_query_param = '
3961
-                    . $original_query_param
3962
-                )
3963
-            );
3964
-        }
3965
-        //check if it's a custom selection
3966
-        if ($this->_custom_selections instanceof CustomSelects
3967
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
3968
-        ) {
3969
-            return;
3970
-        }
3971
-        //check if has a model name at the beginning
3972
-        //and
3973
-        //check if it's a field on a related model
3974
-        if ($this->extractJoinModelFromQueryParams(
3975
-            $passed_in_query_info,
3976
-            $query_param,
3977
-            $original_query_param,
3978
-            $query_param_type
3979
-        )) {
3980
-            return;
3981
-        }
3982
-
3983
-        //ok so $query_param didn't start with a model name
3984
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3985
-        //it's wack, that's what it is
3986
-        throw new EE_Error(
3987
-            sprintf(
3988
-                esc_html__(
3989
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3990
-                    "event_espresso"
3991
-                ),
3992
-                $query_param,
3993
-                get_class($this),
3994
-                $query_param_type,
3995
-                $original_query_param
3996
-            )
3997
-        );
3998
-    }
3999
-
4000
-
4001
-    /**
4002
-     * Extracts any possible join model information from the provided possible_join_string.
4003
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4004
-     * parts that should be added to the query.
4005
-     *
4006
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4007
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4008
-     * @param null|string                 $original_query_param
4009
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4010
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4011
-     * @return bool  returns true if a join was added and false if not.
4012
-     * @throws EE_Error
4013
-     */
4014
-    private function extractJoinModelFromQueryParams(
4015
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4016
-        $possible_join_string,
4017
-        $original_query_param,
4018
-        $query_parameter_type
4019
-    ) {
4020
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4022
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4024
-                if ($possible_join_string === '') {
4025
-                    //nothing left to $query_param
4026
-                    //we should actually end in a field name, not a model like this!
4027
-                    throw new EE_Error(
4028
-                        sprintf(
4029
-                            esc_html__(
4030
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4031
-                                "event_espresso"
4032
-                            ),
4033
-                            $possible_join_string,
4034
-                            $query_parameter_type,
4035
-                            get_class($this),
4036
-                            $valid_related_model_name
4037
-                        )
4038
-                    );
4039
-                }
4040
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4041
-                $related_model_obj->_extract_related_model_info_from_query_param(
4042
-                    $possible_join_string,
4043
-                    $query_info_carrier,
4044
-                    $query_parameter_type,
4045
-                    $original_query_param
4046
-                );
4047
-                return true;
4048
-            }
4049
-            if ($possible_join_string === $valid_related_model_name) {
4050
-                $this->_add_join_to_model(
4051
-                    $valid_related_model_name,
4052
-                    $query_info_carrier,
4053
-                    $original_query_param
4054
-                );
4055
-                return true;
4056
-            }
4057
-        }
4058
-        return false;
4059
-    }
4060
-
4061
-
4062
-    /**
4063
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4064
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4065
-     * @throws EE_Error
4066
-     */
4067
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4068
-    {
4069
-        if ($this->_custom_selections instanceof CustomSelects
4070
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4071
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4072
-            )
4073
-        ) {
4074
-            $original_selects = $this->_custom_selections->originalSelects();
4075
-            foreach ($original_selects as $alias => $select_configuration) {
4076
-                $this->extractJoinModelFromQueryParams(
4077
-                    $query_info_carrier,
4078
-                    $select_configuration[0],
4079
-                    $select_configuration[0],
4080
-                    'custom_selects'
4081
-                );
4082
-            }
4083
-        }
4084
-    }
4085
-
4086
-
4087
-
4088
-    /**
4089
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4090
-     * and store it on $passed_in_query_info
4091
-     *
4092
-     * @param string                      $model_name
4093
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4095
-     *                                                          model and $model_name. Eg, if we are querying Event,
4096
-     *                                                          and are adding a join to 'Payment' with the original
4097
-     *                                                          query param key
4098
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4099
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4100
-     *                                                          Payment wants to add default query params so that it
4101
-     *                                                          will know what models to prepend onto its default query
4102
-     *                                                          params or in case it wants to rename tables (in case
4103
-     *                                                          there are multiple joins to the same table)
4104
-     * @return void
4105
-     * @throws EE_Error
4106
-     */
4107
-    private function _add_join_to_model(
4108
-        $model_name,
4109
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4110
-        $original_query_param
4111
-    ) {
4112
-        $relation_obj = $this->related_settings_for($model_name);
4113
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4114
-        //check if the relation is HABTM, because then we're essentially doing two joins
4115
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
4116
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4117
-            $join_model_obj = $relation_obj->get_join_model();
4118
-            //replace the model specified with the join model for this relation chain, whi
4119
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4120
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4121
-            $passed_in_query_info->merge(
4122
-                new EE_Model_Query_Info_Carrier(
4123
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4124
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4125
-                )
4126
-            );
4127
-        }
4128
-        //now just join to the other table pointed to by the relation object, and add its data types
4129
-        $passed_in_query_info->merge(
4130
-            new EE_Model_Query_Info_Carrier(
4131
-                array($model_relation_chain => $model_name),
4132
-                $relation_obj->get_join_statement($model_relation_chain)
4133
-            )
4134
-        );
4135
-    }
4136
-
4137
-
4138
-
4139
-    /**
4140
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4141
-     *
4142
-     * @param array $where_params like EEM_Base::get_all
4143
-     * @return string of SQL
4144
-     * @throws EE_Error
4145
-     */
4146
-    private function _construct_where_clause($where_params)
4147
-    {
4148
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149
-        if ($SQL) {
4150
-            return " WHERE " . $SQL;
4151
-        }
4152
-        return '';
4153
-    }
4154
-
4155
-
4156
-
4157
-    /**
4158
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4159
-     * and should be passed HAVING parameters, not WHERE parameters
4160
-     *
4161
-     * @param array $having_params
4162
-     * @return string
4163
-     * @throws EE_Error
4164
-     */
4165
-    private function _construct_having_clause($having_params)
4166
-    {
4167
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168
-        if ($SQL) {
4169
-            return " HAVING " . $SQL;
4170
-        }
4171
-        return '';
4172
-    }
4173
-
4174
-
4175
-    /**
4176
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4177
-     * Event_Meta.meta_value = 'foo'))"
4178
-     *
4179
-     * @param array  $where_params see EEM_Base::get_all for documentation
4180
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4181
-     * @throws EE_Error
4182
-     * @return string of SQL
4183
-     */
4184
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4185
-    {
4186
-        $where_clauses = array();
4187
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4189
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4190
-                switch ($query_param) {
4191
-                    case 'not':
4192
-                    case 'NOT':
4193
-                        $where_clauses[] = "! ("
4194
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4195
-                                $glue)
4196
-                                           . ")";
4197
-                        break;
4198
-                    case 'and':
4199
-                    case 'AND':
4200
-                        $where_clauses[] = " ("
4201
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4202
-                                ' AND ')
4203
-                                           . ")";
4204
-                        break;
4205
-                    case 'or':
4206
-                    case 'OR':
4207
-                        $where_clauses[] = " ("
4208
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4209
-                                ' OR ')
4210
-                                           . ")";
4211
-                        break;
4212
-                }
4213
-            } else {
4214
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4215
-                //if it's not a normal field, maybe it's a custom selection?
4216
-                if (! $field_obj) {
4217
-                    if ($this->_custom_selections instanceof CustomSelects) {
4218
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219
-                    } else {
4220
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4221
-                            "event_espresso"), $query_param));
4222
-                    }
4223
-                }
4224
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4226
-            }
4227
-        }
4228
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4229
-    }
4230
-
4231
-
4232
-
4233
-    /**
4234
-     * Takes the input parameter and extract the table name (alias) and column name
4235
-     *
4236
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4237
-     * @throws EE_Error
4238
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4239
-     */
4240
-    private function _deduce_column_name_from_query_param($query_param)
4241
-    {
4242
-        $field = $this->_deduce_field_from_query_param($query_param);
4243
-        if ($field) {
4244
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245
-                $query_param);
4246
-            return $table_alias_prefix . $field->get_qualified_column();
4247
-        }
4248
-        if ($this->_custom_selections instanceof CustomSelects
4249
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4250
-        ) {
4251
-            //maybe it's custom selection item?
4252
-            //if so, just use it as the "column name"
4253
-            return $query_param;
4254
-        }
4255
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4256
-            ? implode(',', $this->_custom_selections->columnAliases())
4257
-            : '';
4258
-        throw new EE_Error(
4259
-            sprintf(
4260
-                __(
4261
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4262
-                    "event_espresso"
4263
-                ), $query_param, $custom_select_aliases
4264
-            )
4265
-        );
4266
-    }
4267
-
4268
-
4269
-
4270
-    /**
4271
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4272
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4273
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4274
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4275
-     *
4276
-     * @param string $condition_query_param_key
4277
-     * @return string
4278
-     */
4279
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4280
-    {
4281
-        $pos_of_star = strpos($condition_query_param_key, '*');
4282
-        if ($pos_of_star === false) {
4283
-            return $condition_query_param_key;
4284
-        }
4285
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4286
-        return $condition_query_param_sans_star;
4287
-    }
4288
-
4289
-
4290
-
4291
-    /**
4292
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4293
-     *
4294
-     * @param                            mixed      array | string    $op_and_value
4295
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4296
-     * @throws EE_Error
4297
-     * @return string
4298
-     */
4299
-    private function _construct_op_and_value($op_and_value, $field_obj)
4300
-    {
4301
-        if (is_array($op_and_value)) {
4302
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
-            if (! $operator) {
4304
-                $php_array_like_string = array();
4305
-                foreach ($op_and_value as $key => $value) {
4306
-                    $php_array_like_string[] = "$key=>$value";
4307
-                }
4308
-                throw new EE_Error(
4309
-                    sprintf(
4310
-                        __(
4311
-                            "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))",
4312
-                            "event_espresso"
4313
-                        ),
4314
-                        implode(",", $php_array_like_string)
4315
-                    )
4316
-                );
4317
-            }
4318
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4319
-        } else {
4320
-            $operator = '=';
4321
-            $value = $op_and_value;
4322
-        }
4323
-        //check to see if the value is actually another field
4324
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4326
-        }
4327
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328
-            //in this case, the value should be an array, or at least a comma-separated list
4329
-            //it will need to handle a little differently
4330
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4331
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4332
-            return $operator . SP . $cleaned_value;
4333
-        }
4334
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335
-            //the value should be an array with count of two.
4336
-            if (count($value) !== 2) {
4337
-                throw new EE_Error(
4338
-                    sprintf(
4339
-                        __(
4340
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4341
-                            'event_espresso'
4342
-                        ),
4343
-                        "BETWEEN"
4344
-                    )
4345
-                );
4346
-            }
4347
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
-            return $operator . SP . $cleaned_value;
4349
-        }
4350
-        if (in_array($operator, $this->valid_null_style_operators())) {
4351
-            if ($value !== null) {
4352
-                throw new EE_Error(
4353
-                    sprintf(
4354
-                        __(
4355
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4356
-                            "event_espresso"
4357
-                        ),
4358
-                        $value,
4359
-                        $operator
4360
-                    )
4361
-                );
4362
-            }
4363
-            return $operator;
4364
-        }
4365
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4367
-            //remove other junk. So just treat it as a string.
4368
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4369
-        }
4370
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4372
-        }
4373
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374
-            throw new EE_Error(
4375
-                sprintf(
4376
-                    __(
4377
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4378
-                        'event_espresso'
4379
-                    ),
4380
-                    $operator,
4381
-                    $operator
4382
-                )
4383
-            );
4384
-        }
4385
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386
-            throw new EE_Error(
4387
-                sprintf(
4388
-                    __(
4389
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4390
-                        'event_espresso'
4391
-                    ),
4392
-                    $operator,
4393
-                    $operator
4394
-                )
4395
-            );
4396
-        }
4397
-        throw new EE_Error(
4398
-            sprintf(
4399
-                __(
4400
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4401
-                    "event_espresso"
4402
-                ),
4403
-                http_build_query($op_and_value)
4404
-            )
4405
-        );
4406
-    }
4407
-
4408
-
4409
-
4410
-    /**
4411
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4412
-     *
4413
-     * @param array                      $values
4414
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4415
-     *                                              '%s'
4416
-     * @return string
4417
-     * @throws EE_Error
4418
-     */
4419
-    public function _construct_between_value($values, $field_obj)
4420
-    {
4421
-        $cleaned_values = array();
4422
-        foreach ($values as $value) {
4423
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424
-        }
4425
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4426
-    }
4427
-
4428
-
4429
-
4430
-    /**
4431
-     * Takes an array or a comma-separated list of $values and cleans them
4432
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4433
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4434
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4435
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4436
-     *
4437
-     * @param mixed                      $values    array or comma-separated string
4438
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4439
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4440
-     * @throws EE_Error
4441
-     */
4442
-    public function _construct_in_value($values, $field_obj)
4443
-    {
4444
-        //check if the value is a CSV list
4445
-        if (is_string($values)) {
4446
-            //in which case, turn it into an array
4447
-            $values = explode(",", $values);
4448
-        }
4449
-        $cleaned_values = array();
4450
-        foreach ($values as $value) {
4451
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4452
-        }
4453
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4454
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4455
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4456
-        if (empty($cleaned_values)) {
4457
-            $all_fields = $this->field_settings();
4458
-            $a_field = array_shift($all_fields);
4459
-            $main_table = $this->_get_main_table();
4460
-            $cleaned_values[] = "SELECT "
4461
-                                . $a_field->get_table_column()
4462
-                                . " FROM "
4463
-                                . $main_table->get_table_name()
4464
-                                . " WHERE FALSE";
4465
-        }
4466
-        return "(" . implode(",", $cleaned_values) . ")";
4467
-    }
4468
-
4469
-
4470
-
4471
-    /**
4472
-     * @param mixed                      $value
4473
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4474
-     * @throws EE_Error
4475
-     * @return false|null|string
4476
-     */
4477
-    private function _wpdb_prepare_using_field($value, $field_obj)
4478
-    {
4479
-        /** @type WPDB $wpdb */
4480
-        global $wpdb;
4481
-        if ($field_obj instanceof EE_Model_Field_Base) {
4482
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4484
-        } //$field_obj should really just be a data type
4485
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486
-            throw new EE_Error(
4487
-                sprintf(
4488
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4489
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4490
-                )
4491
-            );
4492
-        }
4493
-        return $wpdb->prepare($field_obj, $value);
4494
-    }
4495
-
4496
-
4497
-
4498
-    /**
4499
-     * Takes the input parameter and finds the model field that it indicates.
4500
-     *
4501
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4502
-     * @throws EE_Error
4503
-     * @return EE_Model_Field_Base
4504
-     */
4505
-    protected function _deduce_field_from_query_param($query_param_name)
4506
-    {
4507
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4508
-        //which will help us find the database table and column
4509
-        $query_param_parts = explode(".", $query_param_name);
4510
-        if (empty($query_param_parts)) {
4511
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4512
-                'event_espresso'), $query_param_name));
4513
-        }
4514
-        $number_of_parts = count($query_param_parts);
4515
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4516
-        if ($number_of_parts === 1) {
4517
-            $field_name = $last_query_param_part;
4518
-            $model_obj = $this;
4519
-        } else {// $number_of_parts >= 2
4520
-            //the last part is the column name, and there are only 2parts. therefore...
4521
-            $field_name = $last_query_param_part;
4522
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4523
-        }
4524
-        try {
4525
-            return $model_obj->field_settings_for($field_name);
4526
-        } catch (EE_Error $e) {
4527
-            return null;
4528
-        }
4529
-    }
4530
-
4531
-
4532
-
4533
-    /**
4534
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4535
-     * alias and column which corresponds to it
4536
-     *
4537
-     * @param string $field_name
4538
-     * @throws EE_Error
4539
-     * @return string
4540
-     */
4541
-    public function _get_qualified_column_for_field($field_name)
4542
-    {
4543
-        $all_fields = $this->field_settings();
4544
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4545
-        if ($field) {
4546
-            return $field->get_qualified_column();
4547
-        }
4548
-        throw new EE_Error(
4549
-            sprintf(
4550
-                __(
4551
-                    "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.",
4552
-                    'event_espresso'
4553
-                ), $field_name, get_class($this)
4554
-            )
4555
-        );
4556
-    }
4557
-
4558
-
4559
-
4560
-    /**
4561
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4562
-     * Example usage:
4563
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4564
-     *      array(),
4565
-     *      ARRAY_A,
4566
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4567
-     *  );
4568
-     * is equivalent to
4569
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4570
-     * and
4571
-     *  EEM_Event::instance()->get_all_wpdb_results(
4572
-     *      array(
4573
-     *          array(
4574
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4575
-     *          ),
4576
-     *          ARRAY_A,
4577
-     *          implode(
4578
-     *              ', ',
4579
-     *              array_merge(
4580
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4581
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4582
-     *              )
4583
-     *          )
4584
-     *      )
4585
-     *  );
4586
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4587
-     *
4588
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4589
-     *                                            and the one whose fields you are selecting for example: when querying
4590
-     *                                            tickets model and selecting fields from the tickets model you would
4591
-     *                                            leave this parameter empty, because no models are needed to join
4592
-     *                                            between the queried model and the selected one. Likewise when
4593
-     *                                            querying the datetime model and selecting fields from the tickets
4594
-     *                                            model, it would also be left empty, because there is a direct
4595
-     *                                            relation from datetimes to tickets, so no model is needed to join
4596
-     *                                            them together. However, when querying from the event model and
4597
-     *                                            selecting fields from the ticket model, you should provide the string
4598
-     *                                            'Datetime', indicating that the event model must first join to the
4599
-     *                                            datetime model in order to find its relation to ticket model.
4600
-     *                                            Also, when querying from the venue model and selecting fields from
4601
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4602
-     *                                            indicating you need to join the venue model to the event model,
4603
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4604
-     *                                            This string is used to deduce the prefix that gets added onto the
4605
-     *                                            models' tables qualified columns
4606
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4607
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4608
-     *                                            qualified column names
4609
-     * @return array|string
4610
-     */
4611
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612
-    {
4613
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4614
-        $qualified_columns = array();
4615
-        foreach ($this->field_settings() as $field_name => $field) {
4616
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4617
-        }
4618
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619
-    }
4620
-
4621
-
4622
-
4623
-    /**
4624
-     * constructs the select use on special limit joins
4625
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4626
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4627
-     * (as that is typically where the limits would be set).
4628
-     *
4629
-     * @param  string       $table_alias The table the select is being built for
4630
-     * @param  mixed|string $limit       The limit for this select
4631
-     * @return string                The final select join element for the query.
4632
-     */
4633
-    public function _construct_limit_join_select($table_alias, $limit)
4634
-    {
4635
-        $SQL = '';
4636
-        foreach ($this->_tables as $table_obj) {
4637
-            if ($table_obj instanceof EE_Primary_Table) {
4638
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4639
-                    ? $table_obj->get_select_join_limit($limit)
4640
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4641
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4642
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4643
-                    ? $table_obj->get_select_join_limit_join($limit)
4644
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4645
-            }
4646
-        }
4647
-        return $SQL;
4648
-    }
4649
-
4650
-
4651
-
4652
-    /**
4653
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4654
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4655
-     *
4656
-     * @return string SQL
4657
-     * @throws EE_Error
4658
-     */
4659
-    public function _construct_internal_join()
4660
-    {
4661
-        $SQL = $this->_get_main_table()->get_table_sql();
4662
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4663
-        return $SQL;
4664
-    }
4665
-
4666
-
4667
-
4668
-    /**
4669
-     * Constructs the SQL for joining all the tables on this model.
4670
-     * Normally $alias should be the primary table's alias, but in cases where
4671
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4672
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4673
-     * alias, this will construct SQL like:
4674
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4675
-     * With $alias being a secondary table's alias, this will construct SQL like:
4676
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4677
-     *
4678
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4679
-     * @return string
4680
-     */
4681
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4682
-    {
4683
-        $SQL = '';
4684
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4685
-        foreach ($this->_tables as $table_obj) {
4686
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4687
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4688
-                    //so we're joining to this table, meaning the table is already in
4689
-                    //the FROM statement, BUT the primary table isn't. So we want
4690
-                    //to add the inverse join sql
4691
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4692
-                } else {
4693
-                    //just add a regular JOIN to this table from the primary table
4694
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4695
-                }
4696
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4697
-        }
4698
-        return $SQL;
4699
-    }
4700
-
4701
-
4702
-
4703
-    /**
4704
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4705
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4706
-     * their data type (eg, '%s', '%d', etc)
4707
-     *
4708
-     * @return array
4709
-     */
4710
-    public function _get_data_types()
4711
-    {
4712
-        $data_types = array();
4713
-        foreach ($this->field_settings() as $field_obj) {
4714
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4715
-            /** @var $field_obj EE_Model_Field_Base */
4716
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4717
-        }
4718
-        return $data_types;
4719
-    }
4720
-
4721
-
4722
-
4723
-    /**
4724
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4725
-     *
4726
-     * @param string $model_name
4727
-     * @throws EE_Error
4728
-     * @return EEM_Base
4729
-     */
4730
-    public function get_related_model_obj($model_name)
4731
-    {
4732
-        $model_classname = "EEM_" . $model_name;
4733
-        if (! class_exists($model_classname)) {
4734
-            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",
4735
-                'event_espresso'), $model_name, $model_classname));
4736
-        }
4737
-        return call_user_func($model_classname . "::instance");
4738
-    }
4739
-
4740
-
4741
-
4742
-    /**
4743
-     * Returns the array of EE_ModelRelations for this model.
4744
-     *
4745
-     * @return EE_Model_Relation_Base[]
4746
-     */
4747
-    public function relation_settings()
4748
-    {
4749
-        return $this->_model_relations;
4750
-    }
4751
-
4752
-
4753
-
4754
-    /**
4755
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4756
-     * because without THOSE models, this model probably doesn't have much purpose.
4757
-     * (Eg, without an event, datetimes have little purpose.)
4758
-     *
4759
-     * @return EE_Belongs_To_Relation[]
4760
-     */
4761
-    public function belongs_to_relations()
4762
-    {
4763
-        $belongs_to_relations = array();
4764
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4765
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4766
-                $belongs_to_relations[$model_name] = $relation_obj;
4767
-            }
4768
-        }
4769
-        return $belongs_to_relations;
4770
-    }
4771
-
4772
-
4773
-
4774
-    /**
4775
-     * Returns the specified EE_Model_Relation, or throws an exception
4776
-     *
4777
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4778
-     * @throws EE_Error
4779
-     * @return EE_Model_Relation_Base
4780
-     */
4781
-    public function related_settings_for($relation_name)
4782
-    {
4783
-        $relatedModels = $this->relation_settings();
4784
-        if (! array_key_exists($relation_name, $relatedModels)) {
4785
-            throw new EE_Error(
4786
-                sprintf(
4787
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4788
-                        'event_espresso'),
4789
-                    $relation_name,
4790
-                    $this->_get_class_name(),
4791
-                    implode(', ', array_keys($relatedModels))
4792
-                )
4793
-            );
4794
-        }
4795
-        return $relatedModels[$relation_name];
4796
-    }
4797
-
4798
-
4799
-
4800
-    /**
4801
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4802
-     * fields
4803
-     *
4804
-     * @param string $fieldName
4805
-     * @param boolean $include_db_only_fields
4806
-     * @throws EE_Error
4807
-     * @return EE_Model_Field_Base
4808
-     */
4809
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4810
-    {
4811
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4812
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4813
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814
-                get_class($this)));
4815
-        }
4816
-        return $fieldSettings[$fieldName];
4817
-    }
4818
-
4819
-
4820
-
4821
-    /**
4822
-     * Checks if this field exists on this model
4823
-     *
4824
-     * @param string $fieldName a key in the model's _field_settings array
4825
-     * @return boolean
4826
-     */
4827
-    public function has_field($fieldName)
4828
-    {
4829
-        $fieldSettings = $this->field_settings(true);
4830
-        if (isset($fieldSettings[$fieldName])) {
4831
-            return true;
4832
-        }
4833
-        return false;
4834
-    }
4835
-
4836
-
4837
-
4838
-    /**
4839
-     * Returns whether or not this model has a relation to the specified model
4840
-     *
4841
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4842
-     * @return boolean
4843
-     */
4844
-    public function has_relation($relation_name)
4845
-    {
4846
-        $relations = $this->relation_settings();
4847
-        if (isset($relations[$relation_name])) {
4848
-            return true;
4849
-        }
4850
-        return false;
4851
-    }
4852
-
4853
-
4854
-
4855
-    /**
4856
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4857
-     * Eg, on EE_Answer that would be ANS_ID field object
4858
-     *
4859
-     * @param $field_obj
4860
-     * @return boolean
4861
-     */
4862
-    public function is_primary_key_field($field_obj)
4863
-    {
4864
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4865
-    }
4866
-
4867
-
4868
-
4869
-    /**
4870
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4871
-     * Eg, on EE_Answer that would be ANS_ID field object
4872
-     *
4873
-     * @return EE_Model_Field_Base
4874
-     * @throws EE_Error
4875
-     */
4876
-    public function get_primary_key_field()
4877
-    {
4878
-        if ($this->_primary_key_field === null) {
4879
-            foreach ($this->field_settings(true) as $field_obj) {
4880
-                if ($this->is_primary_key_field($field_obj)) {
4881
-                    $this->_primary_key_field = $field_obj;
4882
-                    break;
4883
-                }
4884
-            }
4885
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887
-                    get_class($this)));
4888
-            }
4889
-        }
4890
-        return $this->_primary_key_field;
4891
-    }
4892
-
4893
-
4894
-
4895
-    /**
4896
-     * Returns whether or not not there is a primary key on this model.
4897
-     * Internally does some caching.
4898
-     *
4899
-     * @return boolean
4900
-     */
4901
-    public function has_primary_key_field()
4902
-    {
4903
-        if ($this->_has_primary_key_field === null) {
4904
-            try {
4905
-                $this->get_primary_key_field();
4906
-                $this->_has_primary_key_field = true;
4907
-            } catch (EE_Error $e) {
4908
-                $this->_has_primary_key_field = false;
4909
-            }
4910
-        }
4911
-        return $this->_has_primary_key_field;
4912
-    }
4913
-
4914
-
4915
-
4916
-    /**
4917
-     * Finds the first field of type $field_class_name.
4918
-     *
4919
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4920
-     *                                 EE_Foreign_Key_Field, etc
4921
-     * @return EE_Model_Field_Base or null if none is found
4922
-     */
4923
-    public function get_a_field_of_type($field_class_name)
4924
-    {
4925
-        foreach ($this->field_settings() as $field) {
4926
-            if ($field instanceof $field_class_name) {
4927
-                return $field;
4928
-            }
4929
-        }
4930
-        return null;
4931
-    }
4932
-
4933
-
4934
-
4935
-    /**
4936
-     * Gets a foreign key field pointing to model.
4937
-     *
4938
-     * @param string $model_name eg Event, Registration, not EEM_Event
4939
-     * @return EE_Foreign_Key_Field_Base
4940
-     * @throws EE_Error
4941
-     */
4942
-    public function get_foreign_key_to($model_name)
4943
-    {
4944
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945
-            foreach ($this->field_settings() as $field) {
4946
-                if (
4947
-                    $field instanceof EE_Foreign_Key_Field_Base
4948
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4949
-                ) {
4950
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4951
-                    break;
4952
-                }
4953
-            }
4954
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956
-                    'event_espresso'), $model_name, get_class($this)));
4957
-            }
4958
-        }
4959
-        return $this->_cache_foreign_key_to_fields[$model_name];
4960
-    }
4961
-
4962
-
4963
-
4964
-    /**
4965
-     * Gets the table name (including $wpdb->prefix) for the table alias
4966
-     *
4967
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4968
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4969
-     *                            Either one works
4970
-     * @return string
4971
-     */
4972
-    public function get_table_for_alias($table_alias)
4973
-    {
4974
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4975
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4976
-    }
4977
-
4978
-
4979
-
4980
-    /**
4981
-     * Returns a flat array of all field son this model, instead of organizing them
4982
-     * by table_alias as they are in the constructor.
4983
-     *
4984
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4985
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4986
-     */
4987
-    public function field_settings($include_db_only_fields = false)
4988
-    {
4989
-        if ($include_db_only_fields) {
4990
-            if ($this->_cached_fields === null) {
4991
-                $this->_cached_fields = array();
4992
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4993
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4994
-                        $this->_cached_fields[$field_name] = $field_obj;
4995
-                    }
4996
-                }
4997
-            }
4998
-            return $this->_cached_fields;
4999
-        }
5000
-        if ($this->_cached_fields_non_db_only === null) {
5001
-            $this->_cached_fields_non_db_only = array();
5002
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5003
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004
-                    /** @var $field_obj EE_Model_Field_Base */
5005
-                    if (! $field_obj->is_db_only_field()) {
5006
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007
-                    }
5008
-                }
5009
-            }
5010
-        }
5011
-        return $this->_cached_fields_non_db_only;
5012
-    }
5013
-
5014
-
5015
-
5016
-    /**
5017
-     *        cycle though array of attendees and create objects out of each item
5018
-     *
5019
-     * @access        private
5020
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5021
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5022
-     *                           numerically indexed)
5023
-     * @throws EE_Error
5024
-     */
5025
-    protected function _create_objects($rows = array())
5026
-    {
5027
-        $array_of_objects = array();
5028
-        if (empty($rows)) {
5029
-            return array();
5030
-        }
5031
-        $count_if_model_has_no_primary_key = 0;
5032
-        $has_primary_key = $this->has_primary_key_field();
5033
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
-        foreach ((array)$rows as $row) {
5035
-            if (empty($row)) {
5036
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037
-                return array();
5038
-            }
5039
-            //check if we've already set this object in the results array,
5040
-            //in which case there's no need to process it further (again)
5041
-            if ($has_primary_key) {
5042
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5043
-                    $row,
5044
-                    $primary_key_field->get_qualified_column(),
5045
-                    $primary_key_field->get_table_column()
5046
-                );
5047
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5048
-                    continue;
5049
-                }
5050
-            }
5051
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5052
-            if (! $classInstance) {
5053
-                throw new EE_Error(
5054
-                    sprintf(
5055
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5056
-                        $this->get_this_model_name(),
5057
-                        http_build_query($row)
5058
-                    )
5059
-                );
5060
-            }
5061
-            //set the timezone on the instantiated objects
5062
-            $classInstance->set_timezone($this->_timezone);
5063
-            //make sure if there is any timezone setting present that we set the timezone for the object
5064
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5065
-            $array_of_objects[$key] = $classInstance;
5066
-            //also, for all the relations of type BelongsTo, see if we can cache
5067
-            //those related models
5068
-            //(we could do this for other relations too, but if there are conditions
5069
-            //that filtered out some fo the results, then we'd be caching an incomplete set
5070
-            //so it requires a little more thought than just caching them immediately...)
5071
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5072
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5073
-                    //check if this model's INFO is present. If so, cache it on the model
5074
-                    $other_model = $relation_obj->get_other_model();
5075
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5076
-                    //if we managed to make a model object from the results, cache it on the main model object
5077
-                    if ($other_model_obj_maybe) {
5078
-                        //set timezone on these other model objects if they are present
5079
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5080
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5081
-                    }
5082
-                }
5083
-            }
5084
-            //also, if this was a custom select query, let's see if there are any results for the custom select fields
5085
-            //and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5086
-            //the field in the CustomSelects object
5087
-            if ($this->_custom_selections instanceof CustomSelects) {
5088
-                $classInstance->setCustomSelectsValues(
5089
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5090
-                );
5091
-            }
5092
-        }
5093
-        return $array_of_objects;
5094
-    }
5095
-
5096
-
5097
-    /**
5098
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5099
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5100
-     *
5101
-     * @param array $db_results_row
5102
-     * @return array
5103
-     */
5104
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5105
-    {
5106
-        $results = array();
5107
-        if ($this->_custom_selections instanceof CustomSelects) {
5108
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5109
-                if (isset($db_results_row[$alias])) {
5110
-                    $results[$alias] = $this->convertValueToDataType(
5111
-                        $db_results_row[$alias],
5112
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5113
-                    );
5114
-                }
5115
-            }
5116
-        }
5117
-        return $results;
5118
-    }
5119
-
5120
-
5121
-    /**
5122
-     * This will set the value for the given alias
5123
-     * @param string $value
5124
-     * @param string $datatype (one of %d, %s, %f)
5125
-     * @return int|string|float (int for %d, string for %s, float for %f)
5126
-     */
5127
-    protected function convertValueToDataType($value, $datatype)
5128
-    {
5129
-        switch ($datatype) {
5130
-            case '%f':
5131
-                return (float) $value;
5132
-            case '%d':
5133
-                return (int) $value;
5134
-            default:
5135
-                return (string) $value;
5136
-        }
5137
-    }
5138
-
5139
-
5140
-    /**
5141
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5142
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5143
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5144
-     * object (as set in the model_field!).
5145
-     *
5146
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5147
-     */
5148
-    public function create_default_object()
5149
-    {
5150
-        $this_model_fields_and_values = array();
5151
-        //setup the row using default values;
5152
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5153
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5154
-        }
5155
-        $className = $this->_get_class_name();
5156
-        $classInstance = EE_Registry::instance()
5157
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5158
-        return $classInstance;
5159
-    }
5160
-
5161
-
5162
-
5163
-    /**
5164
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5165
-     *                             or an stdClass where each property is the name of a column,
5166
-     * @return EE_Base_Class
5167
-     * @throws EE_Error
5168
-     */
5169
-    public function instantiate_class_from_array_or_object($cols_n_values)
5170
-    {
5171
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5172
-            $cols_n_values = get_object_vars($cols_n_values);
5173
-        }
5174
-        $primary_key = null;
5175
-        //make sure the array only has keys that are fields/columns on this model
5176
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5177
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5178
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5179
-        }
5180
-        $className = $this->_get_class_name();
5181
-        //check we actually found results that we can use to build our model object
5182
-        //if not, return null
5183
-        if ($this->has_primary_key_field()) {
5184
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5185
-                return null;
5186
-            }
5187
-        } else if ($this->unique_indexes()) {
5188
-            $first_column = reset($this_model_fields_n_values);
5189
-            if (empty($first_column)) {
5190
-                return null;
5191
-            }
5192
-        }
5193
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194
-        if ($primary_key) {
5195
-            $classInstance = $this->get_from_entity_map($primary_key);
5196
-            if (! $classInstance) {
5197
-                $classInstance = EE_Registry::instance()
5198
-                                            ->load_class($className,
5199
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5200
-                // add this new object to the entity map
5201
-                $classInstance = $this->add_to_entity_map($classInstance);
5202
-            }
5203
-        } else {
5204
-            $classInstance = EE_Registry::instance()
5205
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5206
-                                            true, false);
5207
-        }
5208
-        return $classInstance;
5209
-    }
5210
-
5211
-
5212
-
5213
-    /**
5214
-     * Gets the model object from the  entity map if it exists
5215
-     *
5216
-     * @param int|string $id the ID of the model object
5217
-     * @return EE_Base_Class
5218
-     */
5219
-    public function get_from_entity_map($id)
5220
-    {
5221
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5222
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5223
-    }
5224
-
5225
-
5226
-
5227
-    /**
5228
-     * add_to_entity_map
5229
-     * Adds the object to the model's entity mappings
5230
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5231
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5232
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5233
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5234
-     *        then this method should be called immediately after the update query
5235
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5236
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5237
-     *
5238
-     * @param    EE_Base_Class $object
5239
-     * @throws EE_Error
5240
-     * @return \EE_Base_Class
5241
-     */
5242
-    public function add_to_entity_map(EE_Base_Class $object)
5243
-    {
5244
-        $className = $this->_get_class_name();
5245
-        if (! $object instanceof $className) {
5246
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247
-                is_object($object) ? get_class($object) : $object, $className));
5248
-        }
5249
-        /** @var $object EE_Base_Class */
5250
-        if (! $object->ID()) {
5251
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252
-                "event_espresso"), get_class($this)));
5253
-        }
5254
-        // double check it's not already there
5255
-        $classInstance = $this->get_from_entity_map($object->ID());
5256
-        if ($classInstance) {
5257
-            return $classInstance;
5258
-        }
5259
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5260
-        return $object;
5261
-    }
5262
-
5263
-
5264
-
5265
-    /**
5266
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5267
-     * if no identifier is provided, then the entire entity map is emptied
5268
-     *
5269
-     * @param int|string $id the ID of the model object
5270
-     * @return boolean
5271
-     */
5272
-    public function clear_entity_map($id = null)
5273
-    {
5274
-        if (empty($id)) {
5275
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5276
-            return true;
5277
-        }
5278
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5279
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5280
-            return true;
5281
-        }
5282
-        return false;
5283
-    }
5284
-
5285
-
5286
-
5287
-    /**
5288
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5289
-     * Given an array where keys are column (or column alias) names and values,
5290
-     * returns an array of their corresponding field names and database values
5291
-     *
5292
-     * @param array $cols_n_values
5293
-     * @return array
5294
-     */
5295
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5296
-    {
5297
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5298
-    }
5299
-
5300
-
5301
-
5302
-    /**
5303
-     * _deduce_fields_n_values_from_cols_n_values
5304
-     * Given an array where keys are column (or column alias) names and values,
5305
-     * returns an array of their corresponding field names and database values
5306
-     *
5307
-     * @param string $cols_n_values
5308
-     * @return array
5309
-     */
5310
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5311
-    {
5312
-        $this_model_fields_n_values = array();
5313
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5314
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5315
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5316
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5317
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
-                    if (! $field_obj->is_db_only_field()) {
5320
-                        //prepare field as if its coming from db
5321
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5323
-                    }
5324
-                }
5325
-            } else {
5326
-                //the table's rows existed. Use their values
5327
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
-                    if (! $field_obj->is_db_only_field()) {
5329
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330
-                            $cols_n_values, $field_obj->get_qualified_column(),
5331
-                            $field_obj->get_table_column()
5332
-                        );
5333
-                    }
5334
-                }
5335
-            }
5336
-        }
5337
-        return $this_model_fields_n_values;
5338
-    }
5339
-
5340
-
5341
-
5342
-    /**
5343
-     * @param $cols_n_values
5344
-     * @param $qualified_column
5345
-     * @param $regular_column
5346
-     * @return null
5347
-     */
5348
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5349
-    {
5350
-        $value = null;
5351
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5352
-        //does the field on the model relate to this column retrieved from the db?
5353
-        //or is it a db-only field? (not relating to the model)
5354
-        if (isset($cols_n_values[$qualified_column])) {
5355
-            $value = $cols_n_values[$qualified_column];
5356
-        } elseif (isset($cols_n_values[$regular_column])) {
5357
-            $value = $cols_n_values[$regular_column];
5358
-        }
5359
-        return $value;
5360
-    }
5361
-
5362
-
5363
-
5364
-    /**
5365
-     * refresh_entity_map_from_db
5366
-     * Makes sure the model object in the entity map at $id assumes the values
5367
-     * of the database (opposite of EE_base_Class::save())
5368
-     *
5369
-     * @param int|string $id
5370
-     * @return EE_Base_Class
5371
-     * @throws EE_Error
5372
-     */
5373
-    public function refresh_entity_map_from_db($id)
5374
-    {
5375
-        $obj_in_map = $this->get_from_entity_map($id);
5376
-        if ($obj_in_map) {
5377
-            $wpdb_results = $this->_get_all_wpdb_results(
5378
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5379
-            );
5380
-            if ($wpdb_results && is_array($wpdb_results)) {
5381
-                $one_row = reset($wpdb_results);
5382
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5383
-                    $obj_in_map->set_from_db($field_name, $db_value);
5384
-                }
5385
-                //clear the cache of related model objects
5386
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5387
-                    $obj_in_map->clear_cache($relation_name, null, true);
5388
-                }
5389
-            }
5390
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5391
-            return $obj_in_map;
5392
-        }
5393
-        return $this->get_one_by_ID($id);
5394
-    }
5395
-
5396
-
5397
-
5398
-    /**
5399
-     * refresh_entity_map_with
5400
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5401
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5402
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5403
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5404
-     *
5405
-     * @param int|string    $id
5406
-     * @param EE_Base_Class $replacing_model_obj
5407
-     * @return \EE_Base_Class
5408
-     * @throws EE_Error
5409
-     */
5410
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5411
-    {
5412
-        $obj_in_map = $this->get_from_entity_map($id);
5413
-        if ($obj_in_map) {
5414
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5415
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5416
-                    $obj_in_map->set($field_name, $value);
5417
-                }
5418
-                //make the model object in the entity map's cache match the $replacing_model_obj
5419
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5420
-                    $obj_in_map->clear_cache($relation_name, null, true);
5421
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5422
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5423
-                    }
5424
-                }
5425
-            }
5426
-            return $obj_in_map;
5427
-        }
5428
-        $this->add_to_entity_map($replacing_model_obj);
5429
-        return $replacing_model_obj;
5430
-    }
5431
-
5432
-
5433
-
5434
-    /**
5435
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5436
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5437
-     * require_once($this->_getClassName().".class.php");
5438
-     *
5439
-     * @return string
5440
-     */
5441
-    private function _get_class_name()
5442
-    {
5443
-        return "EE_" . $this->get_this_model_name();
5444
-    }
5445
-
5446
-
5447
-
5448
-    /**
5449
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5450
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5451
-     * it would be 'Events'.
5452
-     *
5453
-     * @param int $quantity
5454
-     * @return string
5455
-     */
5456
-    public function item_name($quantity = 1)
5457
-    {
5458
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5459
-    }
5460
-
5461
-
5462
-
5463
-    /**
5464
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5465
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5466
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5467
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5468
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5469
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5470
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5471
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5472
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5473
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5474
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5475
-     *        return $previousReturnValue.$returnString;
5476
-     * }
5477
-     * require('EEM_Answer.model.php');
5478
-     * $answer=EEM_Answer::instance();
5479
-     * echo $answer->my_callback('monkeys',100);
5480
-     * //will output "you called my_callback! and passed args:monkeys,100"
5481
-     *
5482
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5483
-     * @param array  $args       array of original arguments passed to the function
5484
-     * @throws EE_Error
5485
-     * @return mixed whatever the plugin which calls add_filter decides
5486
-     */
5487
-    public function __call($methodName, $args)
5488
-    {
5489
-        $className = get_class($this);
5490
-        $tagName = "FHEE__{$className}__{$methodName}";
5491
-        if (! has_filter($tagName)) {
5492
-            throw new EE_Error(
5493
-                sprintf(
5494
-                    __('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 );',
5495
-                        'event_espresso'),
5496
-                    $methodName,
5497
-                    $className,
5498
-                    $tagName,
5499
-                    '<br />'
5500
-                )
5501
-            );
5502
-        }
5503
-        return apply_filters($tagName, null, $this, $args);
5504
-    }
5505
-
5506
-
5507
-
5508
-    /**
5509
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5510
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5511
-     *
5512
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5513
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5514
-     *                                                       the object's class name
5515
-     *                                                       or object's ID
5516
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5517
-     *                                                       exists in the database. If it does not, we add it
5518
-     * @throws EE_Error
5519
-     * @return EE_Base_Class
5520
-     */
5521
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5522
-    {
5523
-        $className = $this->_get_class_name();
5524
-        if ($base_class_obj_or_id instanceof $className) {
5525
-            $model_object = $base_class_obj_or_id;
5526
-        } else {
5527
-            $primary_key_field = $this->get_primary_key_field();
5528
-            if (
5529
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5530
-                && (
5531
-                    is_int($base_class_obj_or_id)
5532
-                    || is_string($base_class_obj_or_id)
5533
-                )
5534
-            ) {
5535
-                // assume it's an ID.
5536
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5537
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5538
-            } else if (
5539
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5540
-                && is_string($base_class_obj_or_id)
5541
-            ) {
5542
-                // assume its a string representation of the object
5543
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5544
-            } else {
5545
-                throw new EE_Error(
5546
-                    sprintf(
5547
-                        __(
5548
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5549
-                            'event_espresso'
5550
-                        ),
5551
-                        $base_class_obj_or_id,
5552
-                        $this->_get_class_name(),
5553
-                        print_r($base_class_obj_or_id, true)
5554
-                    )
5555
-                );
5556
-            }
5557
-        }
5558
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5559
-            $model_object->save();
5560
-        }
5561
-        return $model_object;
5562
-    }
5563
-
5564
-
5565
-
5566
-    /**
5567
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5568
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5569
-     * returns it ID.
5570
-     *
5571
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5572
-     * @return int|string depending on the type of this model object's ID
5573
-     * @throws EE_Error
5574
-     */
5575
-    public function ensure_is_ID($base_class_obj_or_id)
5576
-    {
5577
-        $className = $this->_get_class_name();
5578
-        if ($base_class_obj_or_id instanceof $className) {
5579
-            /** @var $base_class_obj_or_id EE_Base_Class */
5580
-            $id = $base_class_obj_or_id->ID();
5581
-        } elseif (is_int($base_class_obj_or_id)) {
5582
-            //assume it's an ID
5583
-            $id = $base_class_obj_or_id;
5584
-        } elseif (is_string($base_class_obj_or_id)) {
5585
-            //assume its a string representation of the object
5586
-            $id = $base_class_obj_or_id;
5587
-        } else {
5588
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5589
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5590
-                print_r($base_class_obj_or_id, true)));
5591
-        }
5592
-        return $id;
5593
-    }
5594
-
5595
-
5596
-
5597
-    /**
5598
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5599
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5600
-     * been sanitized and converted into the appropriate domain.
5601
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5602
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5603
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5604
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5605
-     * $EVT = EEM_Event::instance(); $old_setting =
5606
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5607
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5608
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5609
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5610
-     *
5611
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5612
-     * @return void
5613
-     */
5614
-    public function assume_values_already_prepared_by_model_object(
5615
-        $values_already_prepared = self::not_prepared_by_model_object
5616
-    ) {
5617
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5618
-    }
5619
-
5620
-
5621
-
5622
-    /**
5623
-     * Read comments for assume_values_already_prepared_by_model_object()
5624
-     *
5625
-     * @return int
5626
-     */
5627
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5628
-    {
5629
-        return $this->_values_already_prepared_by_model_object;
5630
-    }
5631
-
5632
-
5633
-
5634
-    /**
5635
-     * Gets all the indexes on this model
5636
-     *
5637
-     * @return EE_Index[]
5638
-     */
5639
-    public function indexes()
5640
-    {
5641
-        return $this->_indexes;
5642
-    }
5643
-
5644
-
5645
-
5646
-    /**
5647
-     * Gets all the Unique Indexes on this model
5648
-     *
5649
-     * @return EE_Unique_Index[]
5650
-     */
5651
-    public function unique_indexes()
5652
-    {
5653
-        $unique_indexes = array();
5654
-        foreach ($this->_indexes as $name => $index) {
5655
-            if ($index instanceof EE_Unique_Index) {
5656
-                $unique_indexes [$name] = $index;
5657
-            }
5658
-        }
5659
-        return $unique_indexes;
5660
-    }
5661
-
5662
-
5663
-
5664
-    /**
5665
-     * Gets all the fields which, when combined, make the primary key.
5666
-     * This is usually just an array with 1 element (the primary key), but in cases
5667
-     * where there is no primary key, it's a combination of fields as defined
5668
-     * on a primary index
5669
-     *
5670
-     * @return EE_Model_Field_Base[] indexed by the field's name
5671
-     * @throws EE_Error
5672
-     */
5673
-    public function get_combined_primary_key_fields()
5674
-    {
5675
-        foreach ($this->indexes() as $index) {
5676
-            if ($index instanceof EE_Primary_Key_Index) {
5677
-                return $index->fields();
5678
-            }
5679
-        }
5680
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5681
-    }
5682
-
5683
-
5684
-
5685
-    /**
5686
-     * Used to build a primary key string (when the model has no primary key),
5687
-     * which can be used a unique string to identify this model object.
5688
-     *
5689
-     * @param array $cols_n_values keys are field names, values are their values
5690
-     * @return string
5691
-     * @throws EE_Error
5692
-     */
5693
-    public function get_index_primary_key_string($cols_n_values)
5694
-    {
5695
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5696
-            $this->get_combined_primary_key_fields());
5697
-        return http_build_query($cols_n_values_for_primary_key_index);
5698
-    }
5699
-
5700
-
5701
-
5702
-    /**
5703
-     * Gets the field values from the primary key string
5704
-     *
5705
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5706
-     * @param string $index_primary_key_string
5707
-     * @return null|array
5708
-     * @throws EE_Error
5709
-     */
5710
-    public function parse_index_primary_key_string($index_primary_key_string)
5711
-    {
5712
-        $key_fields = $this->get_combined_primary_key_fields();
5713
-        //check all of them are in the $id
5714
-        $key_vals_in_combined_pk = array();
5715
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716
-        foreach ($key_fields as $key_field_name => $field_obj) {
5717
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5718
-                return null;
5719
-            }
5720
-        }
5721
-        return $key_vals_in_combined_pk;
5722
-    }
5723
-
5724
-
5725
-
5726
-    /**
5727
-     * verifies that an array of key-value pairs for model fields has a key
5728
-     * for each field comprising the primary key index
5729
-     *
5730
-     * @param array $key_vals
5731
-     * @return boolean
5732
-     * @throws EE_Error
5733
-     */
5734
-    public function has_all_combined_primary_key_fields($key_vals)
5735
-    {
5736
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737
-        foreach ($keys_it_should_have as $key) {
5738
-            if (! isset($key_vals[$key])) {
5739
-                return false;
5740
-            }
5741
-        }
5742
-        return true;
5743
-    }
5744
-
5745
-
5746
-
5747
-    /**
5748
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5749
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5750
-     *
5751
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5752
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5753
-     * @throws EE_Error
5754
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5755
-     *                                                              indexed)
5756
-     */
5757
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5758
-    {
5759
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5760
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5761
-        } elseif (is_array($model_object_or_attributes_array)) {
5762
-            $attributes_array = $model_object_or_attributes_array;
5763
-        } else {
5764
-            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",
5765
-                "event_espresso"), $model_object_or_attributes_array));
5766
-        }
5767
-        //even copies obviously won't have the same ID, so remove the primary key
5768
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5769
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5770
-            unset($attributes_array[$this->primary_key_name()]);
5771
-        }
5772
-        if (isset($query_params[0])) {
5773
-            $query_params[0] = array_merge($attributes_array, $query_params);
5774
-        } else {
5775
-            $query_params[0] = $attributes_array;
5776
-        }
5777
-        return $this->get_all($query_params);
5778
-    }
5779
-
5780
-
5781
-
5782
-    /**
5783
-     * Gets the first copy we find. See get_all_copies for more details
5784
-     *
5785
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5786
-     * @param array $query_params
5787
-     * @return EE_Base_Class
5788
-     * @throws EE_Error
5789
-     */
5790
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791
-    {
5792
-        if (! is_array($query_params)) {
5793
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795
-                    gettype($query_params)), '4.6.0');
5796
-            $query_params = array();
5797
-        }
5798
-        $query_params['limit'] = 1;
5799
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5800
-        if (is_array($copies)) {
5801
-            return array_shift($copies);
5802
-        }
5803
-        return null;
5804
-    }
5805
-
5806
-
5807
-
5808
-    /**
5809
-     * Updates the item with the specified id. Ignores default query parameters because
5810
-     * we have specified the ID, and its assumed we KNOW what we're doing
5811
-     *
5812
-     * @param array      $fields_n_values keys are field names, values are their new values
5813
-     * @param int|string $id              the value of the primary key to update
5814
-     * @return int number of rows updated
5815
-     * @throws EE_Error
5816
-     */
5817
-    public function update_by_ID($fields_n_values, $id)
5818
-    {
5819
-        $query_params = array(
5820
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5821
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5822
-        );
5823
-        return $this->update($fields_n_values, $query_params);
5824
-    }
5825
-
5826
-
5827
-
5828
-    /**
5829
-     * Changes an operator which was supplied to the models into one usable in SQL
5830
-     *
5831
-     * @param string $operator_supplied
5832
-     * @return string an operator which can be used in SQL
5833
-     * @throws EE_Error
5834
-     */
5835
-    private function _prepare_operator_for_sql($operator_supplied)
5836
-    {
5837
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5838
-            : null;
5839
-        if ($sql_operator) {
5840
-            return $sql_operator;
5841
-        }
5842
-        throw new EE_Error(
5843
-            sprintf(
5844
-                __(
5845
-                    "The operator '%s' is not in the list of valid operators: %s",
5846
-                    "event_espresso"
5847
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5848
-            )
5849
-        );
5850
-    }
5851
-
5852
-
5853
-
5854
-    /**
5855
-     * Gets the valid operators
5856
-     * @return array keys are accepted strings, values are the SQL they are converted to
5857
-     */
5858
-    public function valid_operators(){
5859
-        return $this->_valid_operators;
5860
-    }
5861
-
5862
-
5863
-
5864
-    /**
5865
-     * Gets the between-style operators (take 2 arguments).
5866
-     * @return array keys are accepted strings, values are the SQL they are converted to
5867
-     */
5868
-    public function valid_between_style_operators()
5869
-    {
5870
-        return array_intersect(
5871
-            $this->valid_operators(),
5872
-            $this->_between_style_operators
5873
-        );
5874
-    }
5875
-
5876
-    /**
5877
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5878
-     * @return array keys are accepted strings, values are the SQL they are converted to
5879
-     */
5880
-    public function valid_like_style_operators()
5881
-    {
5882
-        return array_intersect(
5883
-            $this->valid_operators(),
5884
-            $this->_like_style_operators
5885
-        );
5886
-    }
5887
-
5888
-    /**
5889
-     * Gets the "in"-style operators
5890
-     * @return array keys are accepted strings, values are the SQL they are converted to
5891
-     */
5892
-    public function valid_in_style_operators()
5893
-    {
5894
-        return array_intersect(
5895
-            $this->valid_operators(),
5896
-            $this->_in_style_operators
5897
-        );
5898
-    }
5899
-
5900
-    /**
5901
-     * Gets the "null"-style operators (accept no arguments)
5902
-     * @return array keys are accepted strings, values are the SQL they are converted to
5903
-     */
5904
-    public function valid_null_style_operators()
5905
-    {
5906
-        return array_intersect(
5907
-            $this->valid_operators(),
5908
-            $this->_null_style_operators
5909
-        );
5910
-    }
5911
-
5912
-    /**
5913
-     * Gets an array where keys are the primary keys and values are their 'names'
5914
-     * (as determined by the model object's name() function, which is often overridden)
5915
-     *
5916
-     * @param array $query_params like get_all's
5917
-     * @return string[]
5918
-     * @throws EE_Error
5919
-     */
5920
-    public function get_all_names($query_params = array())
5921
-    {
5922
-        $objs = $this->get_all($query_params);
5923
-        $names = array();
5924
-        foreach ($objs as $obj) {
5925
-            $names[$obj->ID()] = $obj->name();
5926
-        }
5927
-        return $names;
5928
-    }
5929
-
5930
-
5931
-
5932
-    /**
5933
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5934
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5935
-     * this is duplicated effort and reduces efficiency) you would be better to use
5936
-     * array_keys() on $model_objects.
5937
-     *
5938
-     * @param \EE_Base_Class[] $model_objects
5939
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5940
-     *                                               in the returned array
5941
-     * @return array
5942
-     * @throws EE_Error
5943
-     */
5944
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945
-    {
5946
-        if (! $this->has_primary_key_field()) {
5947
-            if (WP_DEBUG) {
5948
-                EE_Error::add_error(
5949
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5950
-                    __FILE__,
5951
-                    __FUNCTION__,
5952
-                    __LINE__
5953
-                );
5954
-            }
5955
-        }
5956
-        $IDs = array();
5957
-        foreach ($model_objects as $model_object) {
5958
-            $id = $model_object->ID();
5959
-            if (! $id) {
5960
-                if ($filter_out_empty_ids) {
5961
-                    continue;
5962
-                }
5963
-                if (WP_DEBUG) {
5964
-                    EE_Error::add_error(
5965
-                        __(
5966
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5967
-                            'event_espresso'
5968
-                        ),
5969
-                        __FILE__,
5970
-                        __FUNCTION__,
5971
-                        __LINE__
5972
-                    );
5973
-                }
5974
-            }
5975
-            $IDs[] = $id;
5976
-        }
5977
-        return $IDs;
5978
-    }
5979
-
5980
-
5981
-
5982
-    /**
5983
-     * Returns the string used in capabilities relating to this model. If there
5984
-     * are no capabilities that relate to this model returns false
5985
-     *
5986
-     * @return string|false
5987
-     */
5988
-    public function cap_slug()
5989
-    {
5990
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5991
-    }
5992
-
5993
-
5994
-
5995
-    /**
5996
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5997
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5998
-     * only returns the cap restrictions array in that context (ie, the array
5999
-     * at that key)
6000
-     *
6001
-     * @param string $context
6002
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6003
-     * @throws EE_Error
6004
-     */
6005
-    public function cap_restrictions($context = EEM_Base::caps_read)
6006
-    {
6007
-        EEM_Base::verify_is_valid_cap_context($context);
6008
-        //check if we ought to run the restriction generator first
6009
-        if (
6010
-            isset($this->_cap_restriction_generators[$context])
6011
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6012
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6013
-        ) {
6014
-            $this->_cap_restrictions[$context] = array_merge(
6015
-                $this->_cap_restrictions[$context],
6016
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
6017
-            );
6018
-        }
6019
-        //and make sure we've finalized the construction of each restriction
6020
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6021
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6022
-                $where_conditions_obj->_finalize_construct($this);
6023
-            }
6024
-        }
6025
-        return $this->_cap_restrictions[$context];
6026
-    }
6027
-
6028
-
6029
-
6030
-    /**
6031
-     * Indicating whether or not this model thinks its a wp core model
6032
-     *
6033
-     * @return boolean
6034
-     */
6035
-    public function is_wp_core_model()
6036
-    {
6037
-        return $this->_wp_core_model;
6038
-    }
6039
-
6040
-
6041
-
6042
-    /**
6043
-     * Gets all the caps that are missing which impose a restriction on
6044
-     * queries made in this context
6045
-     *
6046
-     * @param string $context one of EEM_Base::caps_ constants
6047
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6048
-     * @throws EE_Error
6049
-     */
6050
-    public function caps_missing($context = EEM_Base::caps_read)
6051
-    {
6052
-        $missing_caps = array();
6053
-        $cap_restrictions = $this->cap_restrictions($context);
6054
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
-            if (! EE_Capabilities::instance()
6056
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6057
-            ) {
6058
-                $missing_caps[$cap] = $restriction_if_no_cap;
6059
-            }
6060
-        }
6061
-        return $missing_caps;
6062
-    }
6063
-
6064
-
6065
-
6066
-    /**
6067
-     * Gets the mapping from capability contexts to action strings used in capability names
6068
-     *
6069
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6070
-     * one of 'read', 'edit', or 'delete'
6071
-     */
6072
-    public function cap_contexts_to_cap_action_map()
6073
-    {
6074
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6075
-            $this);
6076
-    }
6077
-
6078
-
6079
-
6080
-    /**
6081
-     * Gets the action string for the specified capability context
6082
-     *
6083
-     * @param string $context
6084
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6085
-     * @throws EE_Error
6086
-     */
6087
-    public function cap_action_for_context($context)
6088
-    {
6089
-        $mapping = $this->cap_contexts_to_cap_action_map();
6090
-        if (isset($mapping[$context])) {
6091
-            return $mapping[$context];
6092
-        }
6093
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6094
-            return $action;
6095
-        }
6096
-        throw new EE_Error(
6097
-            sprintf(
6098
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6099
-                $context,
6100
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6101
-            )
6102
-        );
6103
-    }
6104
-
6105
-
6106
-
6107
-    /**
6108
-     * Returns all the capability contexts which are valid when querying models
6109
-     *
6110
-     * @return array
6111
-     */
6112
-    public static function valid_cap_contexts()
6113
-    {
6114
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6115
-            self::caps_read,
6116
-            self::caps_read_admin,
6117
-            self::caps_edit,
6118
-            self::caps_delete,
6119
-        ));
6120
-    }
6121
-
6122
-
6123
-
6124
-    /**
6125
-     * Returns all valid options for 'default_where_conditions'
6126
-     *
6127
-     * @return array
6128
-     */
6129
-    public static function valid_default_where_conditions()
6130
-    {
6131
-        return array(
6132
-            EEM_Base::default_where_conditions_all,
6133
-            EEM_Base::default_where_conditions_this_only,
6134
-            EEM_Base::default_where_conditions_others_only,
6135
-            EEM_Base::default_where_conditions_minimum_all,
6136
-            EEM_Base::default_where_conditions_minimum_others,
6137
-            EEM_Base::default_where_conditions_none
6138
-        );
6139
-    }
6140
-
6141
-    // public static function default_where_conditions_full
6142
-    /**
6143
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6144
-     *
6145
-     * @param string $context
6146
-     * @return bool
6147
-     * @throws EE_Error
6148
-     */
6149
-    static public function verify_is_valid_cap_context($context)
6150
-    {
6151
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6152
-        if (in_array($context, $valid_cap_contexts)) {
6153
-            return true;
6154
-        }
6155
-        throw new EE_Error(
6156
-            sprintf(
6157
-                __(
6158
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6159
-                    'event_espresso'
6160
-                ),
6161
-                $context,
6162
-                'EEM_Base',
6163
-                implode(',', $valid_cap_contexts)
6164
-            )
6165
-        );
6166
-    }
6167
-
6168
-
6169
-
6170
-    /**
6171
-     * Clears all the models field caches. This is only useful when a sub-class
6172
-     * might have added a field or something and these caches might be invalidated
6173
-     */
6174
-    protected function _invalidate_field_caches()
6175
-    {
6176
-        $this->_cache_foreign_key_to_fields = array();
6177
-        $this->_cached_fields = null;
6178
-        $this->_cached_fields_non_db_only = null;
6179
-    }
6180
-
6181
-
6182
-
6183
-    /**
6184
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6185
-     * (eg "and", "or", "not").
6186
-     *
6187
-     * @return array
6188
-     */
6189
-    public function logic_query_param_keys()
6190
-    {
6191
-        return $this->_logic_query_param_keys;
6192
-    }
6193
-
6194
-
6195
-
6196
-    /**
6197
-     * Determines whether or not the where query param array key is for a logic query param.
6198
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6199
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6200
-     *
6201
-     * @param $query_param_key
6202
-     * @return bool
6203
-     */
6204
-    public function is_logic_query_param_key($query_param_key)
6205
-    {
6206
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207
-            if ($query_param_key === $logic_query_param_key
6208
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6209
-            ) {
6210
-                return true;
6211
-            }
6212
-        }
6213
-        return false;
6214
-    }
3773
+		}
3774
+		return $null_friendly_where_conditions;
3775
+	}
3776
+
3777
+
3778
+
3779
+	/**
3780
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3781
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3782
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3783
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3784
+	 *
3785
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3786
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3787
+	 */
3788
+	private function _get_default_where_conditions($model_relation_path = null)
3789
+	{
3790
+		if ($this->_ignore_where_strategy) {
3791
+			return array();
3792
+		}
3793
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3794
+	}
3795
+
3796
+
3797
+
3798
+	/**
3799
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3800
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3801
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3802
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3803
+	 * Similar to _get_default_where_conditions
3804
+	 *
3805
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3806
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3807
+	 */
3808
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3809
+	{
3810
+		if ($this->_ignore_where_strategy) {
3811
+			return array();
3812
+		}
3813
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3814
+	}
3815
+
3816
+
3817
+
3818
+	/**
3819
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3820
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3821
+	 *
3822
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3823
+	 * @return string
3824
+	 * @throws EE_Error
3825
+	 */
3826
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3827
+	{
3828
+		$selects = $this->_get_columns_to_select_for_this_model();
3829
+		foreach (
3830
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3831
+			$name_of_other_model_included
3832
+		) {
3833
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3834
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3835
+			foreach ($other_model_selects as $key => $value) {
3836
+				$selects[] = $value;
3837
+			}
3838
+		}
3839
+		return implode(", ", $selects);
3840
+	}
3841
+
3842
+
3843
+
3844
+	/**
3845
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3846
+	 * So that's going to be the columns for all the fields on the model
3847
+	 *
3848
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3849
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3850
+	 */
3851
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3852
+	{
3853
+		$fields = $this->field_settings();
3854
+		$selects = array();
3855
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3856
+			$this->get_this_model_name());
3857
+		foreach ($fields as $field_obj) {
3858
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3859
+						 . $field_obj->get_table_alias()
3860
+						 . "."
3861
+						 . $field_obj->get_table_column()
3862
+						 . " AS '"
3863
+						 . $table_alias_with_model_relation_chain_prefix
3864
+						 . $field_obj->get_table_alias()
3865
+						 . "."
3866
+						 . $field_obj->get_table_column()
3867
+						 . "'";
3868
+		}
3869
+		//make sure we are also getting the PKs of each table
3870
+		$tables = $this->get_tables();
3871
+		if (count($tables) > 1) {
3872
+			foreach ($tables as $table_obj) {
3873
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874
+									   . $table_obj->get_fully_qualified_pk_column();
3875
+				if (! in_array($qualified_pk_column, $selects)) {
3876
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877
+				}
3878
+			}
3879
+		}
3880
+		return $selects;
3881
+	}
3882
+
3883
+
3884
+
3885
+	/**
3886
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3887
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3888
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3889
+	 * SQL for joining, and the data types
3890
+	 *
3891
+	 * @param null|string                 $original_query_param
3892
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3893
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3894
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3895
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3896
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3897
+	 *                                                          or 'Registration's
3898
+	 * @param string                      $original_query_param what it originally was (eg
3899
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3900
+	 *                                                          matches $query_param
3901
+	 * @throws EE_Error
3902
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3903
+	 */
3904
+	private function _extract_related_model_info_from_query_param(
3905
+		$query_param,
3906
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3907
+		$query_param_type,
3908
+		$original_query_param = null
3909
+	) {
3910
+		if ($original_query_param === null) {
3911
+			$original_query_param = $query_param;
3912
+		}
3913
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3914
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3915
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3916
+		$allow_fields = in_array(
3917
+			$query_param_type,
3918
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3919
+			true
3920
+		);
3921
+		//check to see if we have a field on this model
3922
+		$this_model_fields = $this->field_settings(true);
3923
+		if (array_key_exists($query_param, $this_model_fields)) {
3924
+			if ($allow_fields) {
3925
+				return;
3926
+			}
3927
+			throw new EE_Error(
3928
+				sprintf(
3929
+					__(
3930
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3931
+						"event_espresso"
3932
+					),
3933
+					$query_param, get_class($this), $query_param_type, $original_query_param
3934
+				)
3935
+			);
3936
+		}
3937
+		//check if this is a special logic query param
3938
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3939
+			if ($allow_logic_query_params) {
3940
+				return;
3941
+			}
3942
+			throw new EE_Error(
3943
+				sprintf(
3944
+					__(
3945
+						'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',
3946
+						'event_espresso'
3947
+					),
3948
+					implode('", "', $this->_logic_query_param_keys),
3949
+					$query_param,
3950
+					get_class($this),
3951
+					'<br />',
3952
+					"\t"
3953
+					. ' $passed_in_query_info = <pre>'
3954
+					. print_r($passed_in_query_info, true)
3955
+					. '</pre>'
3956
+					. "\n\t"
3957
+					. ' $query_param_type = '
3958
+					. $query_param_type
3959
+					. "\n\t"
3960
+					. ' $original_query_param = '
3961
+					. $original_query_param
3962
+				)
3963
+			);
3964
+		}
3965
+		//check if it's a custom selection
3966
+		if ($this->_custom_selections instanceof CustomSelects
3967
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
3968
+		) {
3969
+			return;
3970
+		}
3971
+		//check if has a model name at the beginning
3972
+		//and
3973
+		//check if it's a field on a related model
3974
+		if ($this->extractJoinModelFromQueryParams(
3975
+			$passed_in_query_info,
3976
+			$query_param,
3977
+			$original_query_param,
3978
+			$query_param_type
3979
+		)) {
3980
+			return;
3981
+		}
3982
+
3983
+		//ok so $query_param didn't start with a model name
3984
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3985
+		//it's wack, that's what it is
3986
+		throw new EE_Error(
3987
+			sprintf(
3988
+				esc_html__(
3989
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3990
+					"event_espresso"
3991
+				),
3992
+				$query_param,
3993
+				get_class($this),
3994
+				$query_param_type,
3995
+				$original_query_param
3996
+			)
3997
+		);
3998
+	}
3999
+
4000
+
4001
+	/**
4002
+	 * Extracts any possible join model information from the provided possible_join_string.
4003
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4004
+	 * parts that should be added to the query.
4005
+	 *
4006
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4007
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4008
+	 * @param null|string                 $original_query_param
4009
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4010
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4011
+	 * @return bool  returns true if a join was added and false if not.
4012
+	 * @throws EE_Error
4013
+	 */
4014
+	private function extractJoinModelFromQueryParams(
4015
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4016
+		$possible_join_string,
4017
+		$original_query_param,
4018
+		$query_parameter_type
4019
+	) {
4020
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4022
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4024
+				if ($possible_join_string === '') {
4025
+					//nothing left to $query_param
4026
+					//we should actually end in a field name, not a model like this!
4027
+					throw new EE_Error(
4028
+						sprintf(
4029
+							esc_html__(
4030
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4031
+								"event_espresso"
4032
+							),
4033
+							$possible_join_string,
4034
+							$query_parameter_type,
4035
+							get_class($this),
4036
+							$valid_related_model_name
4037
+						)
4038
+					);
4039
+				}
4040
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4041
+				$related_model_obj->_extract_related_model_info_from_query_param(
4042
+					$possible_join_string,
4043
+					$query_info_carrier,
4044
+					$query_parameter_type,
4045
+					$original_query_param
4046
+				);
4047
+				return true;
4048
+			}
4049
+			if ($possible_join_string === $valid_related_model_name) {
4050
+				$this->_add_join_to_model(
4051
+					$valid_related_model_name,
4052
+					$query_info_carrier,
4053
+					$original_query_param
4054
+				);
4055
+				return true;
4056
+			}
4057
+		}
4058
+		return false;
4059
+	}
4060
+
4061
+
4062
+	/**
4063
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4064
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4065
+	 * @throws EE_Error
4066
+	 */
4067
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4068
+	{
4069
+		if ($this->_custom_selections instanceof CustomSelects
4070
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4071
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4072
+			)
4073
+		) {
4074
+			$original_selects = $this->_custom_selections->originalSelects();
4075
+			foreach ($original_selects as $alias => $select_configuration) {
4076
+				$this->extractJoinModelFromQueryParams(
4077
+					$query_info_carrier,
4078
+					$select_configuration[0],
4079
+					$select_configuration[0],
4080
+					'custom_selects'
4081
+				);
4082
+			}
4083
+		}
4084
+	}
4085
+
4086
+
4087
+
4088
+	/**
4089
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4090
+	 * and store it on $passed_in_query_info
4091
+	 *
4092
+	 * @param string                      $model_name
4093
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4094
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4095
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4096
+	 *                                                          and are adding a join to 'Payment' with the original
4097
+	 *                                                          query param key
4098
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4099
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4100
+	 *                                                          Payment wants to add default query params so that it
4101
+	 *                                                          will know what models to prepend onto its default query
4102
+	 *                                                          params or in case it wants to rename tables (in case
4103
+	 *                                                          there are multiple joins to the same table)
4104
+	 * @return void
4105
+	 * @throws EE_Error
4106
+	 */
4107
+	private function _add_join_to_model(
4108
+		$model_name,
4109
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4110
+		$original_query_param
4111
+	) {
4112
+		$relation_obj = $this->related_settings_for($model_name);
4113
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4114
+		//check if the relation is HABTM, because then we're essentially doing two joins
4115
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
4116
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4117
+			$join_model_obj = $relation_obj->get_join_model();
4118
+			//replace the model specified with the join model for this relation chain, whi
4119
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4120
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4121
+			$passed_in_query_info->merge(
4122
+				new EE_Model_Query_Info_Carrier(
4123
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4124
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4125
+				)
4126
+			);
4127
+		}
4128
+		//now just join to the other table pointed to by the relation object, and add its data types
4129
+		$passed_in_query_info->merge(
4130
+			new EE_Model_Query_Info_Carrier(
4131
+				array($model_relation_chain => $model_name),
4132
+				$relation_obj->get_join_statement($model_relation_chain)
4133
+			)
4134
+		);
4135
+	}
4136
+
4137
+
4138
+
4139
+	/**
4140
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4141
+	 *
4142
+	 * @param array $where_params like EEM_Base::get_all
4143
+	 * @return string of SQL
4144
+	 * @throws EE_Error
4145
+	 */
4146
+	private function _construct_where_clause($where_params)
4147
+	{
4148
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149
+		if ($SQL) {
4150
+			return " WHERE " . $SQL;
4151
+		}
4152
+		return '';
4153
+	}
4154
+
4155
+
4156
+
4157
+	/**
4158
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4159
+	 * and should be passed HAVING parameters, not WHERE parameters
4160
+	 *
4161
+	 * @param array $having_params
4162
+	 * @return string
4163
+	 * @throws EE_Error
4164
+	 */
4165
+	private function _construct_having_clause($having_params)
4166
+	{
4167
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168
+		if ($SQL) {
4169
+			return " HAVING " . $SQL;
4170
+		}
4171
+		return '';
4172
+	}
4173
+
4174
+
4175
+	/**
4176
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4177
+	 * Event_Meta.meta_value = 'foo'))"
4178
+	 *
4179
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4180
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4181
+	 * @throws EE_Error
4182
+	 * @return string of SQL
4183
+	 */
4184
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4185
+	{
4186
+		$where_clauses = array();
4187
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4189
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4190
+				switch ($query_param) {
4191
+					case 'not':
4192
+					case 'NOT':
4193
+						$where_clauses[] = "! ("
4194
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4195
+								$glue)
4196
+										   . ")";
4197
+						break;
4198
+					case 'and':
4199
+					case 'AND':
4200
+						$where_clauses[] = " ("
4201
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4202
+								' AND ')
4203
+										   . ")";
4204
+						break;
4205
+					case 'or':
4206
+					case 'OR':
4207
+						$where_clauses[] = " ("
4208
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4209
+								' OR ')
4210
+										   . ")";
4211
+						break;
4212
+				}
4213
+			} else {
4214
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4215
+				//if it's not a normal field, maybe it's a custom selection?
4216
+				if (! $field_obj) {
4217
+					if ($this->_custom_selections instanceof CustomSelects) {
4218
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219
+					} else {
4220
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4221
+							"event_espresso"), $query_param));
4222
+					}
4223
+				}
4224
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4226
+			}
4227
+		}
4228
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4229
+	}
4230
+
4231
+
4232
+
4233
+	/**
4234
+	 * Takes the input parameter and extract the table name (alias) and column name
4235
+	 *
4236
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4237
+	 * @throws EE_Error
4238
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4239
+	 */
4240
+	private function _deduce_column_name_from_query_param($query_param)
4241
+	{
4242
+		$field = $this->_deduce_field_from_query_param($query_param);
4243
+		if ($field) {
4244
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245
+				$query_param);
4246
+			return $table_alias_prefix . $field->get_qualified_column();
4247
+		}
4248
+		if ($this->_custom_selections instanceof CustomSelects
4249
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4250
+		) {
4251
+			//maybe it's custom selection item?
4252
+			//if so, just use it as the "column name"
4253
+			return $query_param;
4254
+		}
4255
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4256
+			? implode(',', $this->_custom_selections->columnAliases())
4257
+			: '';
4258
+		throw new EE_Error(
4259
+			sprintf(
4260
+				__(
4261
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4262
+					"event_espresso"
4263
+				), $query_param, $custom_select_aliases
4264
+			)
4265
+		);
4266
+	}
4267
+
4268
+
4269
+
4270
+	/**
4271
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4272
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4273
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4274
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4275
+	 *
4276
+	 * @param string $condition_query_param_key
4277
+	 * @return string
4278
+	 */
4279
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4280
+	{
4281
+		$pos_of_star = strpos($condition_query_param_key, '*');
4282
+		if ($pos_of_star === false) {
4283
+			return $condition_query_param_key;
4284
+		}
4285
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4286
+		return $condition_query_param_sans_star;
4287
+	}
4288
+
4289
+
4290
+
4291
+	/**
4292
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4293
+	 *
4294
+	 * @param                            mixed      array | string    $op_and_value
4295
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4296
+	 * @throws EE_Error
4297
+	 * @return string
4298
+	 */
4299
+	private function _construct_op_and_value($op_and_value, $field_obj)
4300
+	{
4301
+		if (is_array($op_and_value)) {
4302
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
+			if (! $operator) {
4304
+				$php_array_like_string = array();
4305
+				foreach ($op_and_value as $key => $value) {
4306
+					$php_array_like_string[] = "$key=>$value";
4307
+				}
4308
+				throw new EE_Error(
4309
+					sprintf(
4310
+						__(
4311
+							"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))",
4312
+							"event_espresso"
4313
+						),
4314
+						implode(",", $php_array_like_string)
4315
+					)
4316
+				);
4317
+			}
4318
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4319
+		} else {
4320
+			$operator = '=';
4321
+			$value = $op_and_value;
4322
+		}
4323
+		//check to see if the value is actually another field
4324
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4326
+		}
4327
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328
+			//in this case, the value should be an array, or at least a comma-separated list
4329
+			//it will need to handle a little differently
4330
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4331
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4332
+			return $operator . SP . $cleaned_value;
4333
+		}
4334
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335
+			//the value should be an array with count of two.
4336
+			if (count($value) !== 2) {
4337
+				throw new EE_Error(
4338
+					sprintf(
4339
+						__(
4340
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4341
+							'event_espresso'
4342
+						),
4343
+						"BETWEEN"
4344
+					)
4345
+				);
4346
+			}
4347
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
+			return $operator . SP . $cleaned_value;
4349
+		}
4350
+		if (in_array($operator, $this->valid_null_style_operators())) {
4351
+			if ($value !== null) {
4352
+				throw new EE_Error(
4353
+					sprintf(
4354
+						__(
4355
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4356
+							"event_espresso"
4357
+						),
4358
+						$value,
4359
+						$operator
4360
+					)
4361
+				);
4362
+			}
4363
+			return $operator;
4364
+		}
4365
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4367
+			//remove other junk. So just treat it as a string.
4368
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4369
+		}
4370
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4372
+		}
4373
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374
+			throw new EE_Error(
4375
+				sprintf(
4376
+					__(
4377
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4378
+						'event_espresso'
4379
+					),
4380
+					$operator,
4381
+					$operator
4382
+				)
4383
+			);
4384
+		}
4385
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386
+			throw new EE_Error(
4387
+				sprintf(
4388
+					__(
4389
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4390
+						'event_espresso'
4391
+					),
4392
+					$operator,
4393
+					$operator
4394
+				)
4395
+			);
4396
+		}
4397
+		throw new EE_Error(
4398
+			sprintf(
4399
+				__(
4400
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4401
+					"event_espresso"
4402
+				),
4403
+				http_build_query($op_and_value)
4404
+			)
4405
+		);
4406
+	}
4407
+
4408
+
4409
+
4410
+	/**
4411
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4412
+	 *
4413
+	 * @param array                      $values
4414
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4415
+	 *                                              '%s'
4416
+	 * @return string
4417
+	 * @throws EE_Error
4418
+	 */
4419
+	public function _construct_between_value($values, $field_obj)
4420
+	{
4421
+		$cleaned_values = array();
4422
+		foreach ($values as $value) {
4423
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424
+		}
4425
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4426
+	}
4427
+
4428
+
4429
+
4430
+	/**
4431
+	 * Takes an array or a comma-separated list of $values and cleans them
4432
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4433
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4434
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4435
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4436
+	 *
4437
+	 * @param mixed                      $values    array or comma-separated string
4438
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4439
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4440
+	 * @throws EE_Error
4441
+	 */
4442
+	public function _construct_in_value($values, $field_obj)
4443
+	{
4444
+		//check if the value is a CSV list
4445
+		if (is_string($values)) {
4446
+			//in which case, turn it into an array
4447
+			$values = explode(",", $values);
4448
+		}
4449
+		$cleaned_values = array();
4450
+		foreach ($values as $value) {
4451
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4452
+		}
4453
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4454
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4455
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4456
+		if (empty($cleaned_values)) {
4457
+			$all_fields = $this->field_settings();
4458
+			$a_field = array_shift($all_fields);
4459
+			$main_table = $this->_get_main_table();
4460
+			$cleaned_values[] = "SELECT "
4461
+								. $a_field->get_table_column()
4462
+								. " FROM "
4463
+								. $main_table->get_table_name()
4464
+								. " WHERE FALSE";
4465
+		}
4466
+		return "(" . implode(",", $cleaned_values) . ")";
4467
+	}
4468
+
4469
+
4470
+
4471
+	/**
4472
+	 * @param mixed                      $value
4473
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4474
+	 * @throws EE_Error
4475
+	 * @return false|null|string
4476
+	 */
4477
+	private function _wpdb_prepare_using_field($value, $field_obj)
4478
+	{
4479
+		/** @type WPDB $wpdb */
4480
+		global $wpdb;
4481
+		if ($field_obj instanceof EE_Model_Field_Base) {
4482
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4484
+		} //$field_obj should really just be a data type
4485
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486
+			throw new EE_Error(
4487
+				sprintf(
4488
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4489
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4490
+				)
4491
+			);
4492
+		}
4493
+		return $wpdb->prepare($field_obj, $value);
4494
+	}
4495
+
4496
+
4497
+
4498
+	/**
4499
+	 * Takes the input parameter and finds the model field that it indicates.
4500
+	 *
4501
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4502
+	 * @throws EE_Error
4503
+	 * @return EE_Model_Field_Base
4504
+	 */
4505
+	protected function _deduce_field_from_query_param($query_param_name)
4506
+	{
4507
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4508
+		//which will help us find the database table and column
4509
+		$query_param_parts = explode(".", $query_param_name);
4510
+		if (empty($query_param_parts)) {
4511
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4512
+				'event_espresso'), $query_param_name));
4513
+		}
4514
+		$number_of_parts = count($query_param_parts);
4515
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4516
+		if ($number_of_parts === 1) {
4517
+			$field_name = $last_query_param_part;
4518
+			$model_obj = $this;
4519
+		} else {// $number_of_parts >= 2
4520
+			//the last part is the column name, and there are only 2parts. therefore...
4521
+			$field_name = $last_query_param_part;
4522
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4523
+		}
4524
+		try {
4525
+			return $model_obj->field_settings_for($field_name);
4526
+		} catch (EE_Error $e) {
4527
+			return null;
4528
+		}
4529
+	}
4530
+
4531
+
4532
+
4533
+	/**
4534
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4535
+	 * alias and column which corresponds to it
4536
+	 *
4537
+	 * @param string $field_name
4538
+	 * @throws EE_Error
4539
+	 * @return string
4540
+	 */
4541
+	public function _get_qualified_column_for_field($field_name)
4542
+	{
4543
+		$all_fields = $this->field_settings();
4544
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4545
+		if ($field) {
4546
+			return $field->get_qualified_column();
4547
+		}
4548
+		throw new EE_Error(
4549
+			sprintf(
4550
+				__(
4551
+					"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.",
4552
+					'event_espresso'
4553
+				), $field_name, get_class($this)
4554
+			)
4555
+		);
4556
+	}
4557
+
4558
+
4559
+
4560
+	/**
4561
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4562
+	 * Example usage:
4563
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4564
+	 *      array(),
4565
+	 *      ARRAY_A,
4566
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4567
+	 *  );
4568
+	 * is equivalent to
4569
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4570
+	 * and
4571
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4572
+	 *      array(
4573
+	 *          array(
4574
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4575
+	 *          ),
4576
+	 *          ARRAY_A,
4577
+	 *          implode(
4578
+	 *              ', ',
4579
+	 *              array_merge(
4580
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4581
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4582
+	 *              )
4583
+	 *          )
4584
+	 *      )
4585
+	 *  );
4586
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4587
+	 *
4588
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4589
+	 *                                            and the one whose fields you are selecting for example: when querying
4590
+	 *                                            tickets model and selecting fields from the tickets model you would
4591
+	 *                                            leave this parameter empty, because no models are needed to join
4592
+	 *                                            between the queried model and the selected one. Likewise when
4593
+	 *                                            querying the datetime model and selecting fields from the tickets
4594
+	 *                                            model, it would also be left empty, because there is a direct
4595
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4596
+	 *                                            them together. However, when querying from the event model and
4597
+	 *                                            selecting fields from the ticket model, you should provide the string
4598
+	 *                                            'Datetime', indicating that the event model must first join to the
4599
+	 *                                            datetime model in order to find its relation to ticket model.
4600
+	 *                                            Also, when querying from the venue model and selecting fields from
4601
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4602
+	 *                                            indicating you need to join the venue model to the event model,
4603
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4604
+	 *                                            This string is used to deduce the prefix that gets added onto the
4605
+	 *                                            models' tables qualified columns
4606
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4607
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4608
+	 *                                            qualified column names
4609
+	 * @return array|string
4610
+	 */
4611
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612
+	{
4613
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4614
+		$qualified_columns = array();
4615
+		foreach ($this->field_settings() as $field_name => $field) {
4616
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4617
+		}
4618
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619
+	}
4620
+
4621
+
4622
+
4623
+	/**
4624
+	 * constructs the select use on special limit joins
4625
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4626
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4627
+	 * (as that is typically where the limits would be set).
4628
+	 *
4629
+	 * @param  string       $table_alias The table the select is being built for
4630
+	 * @param  mixed|string $limit       The limit for this select
4631
+	 * @return string                The final select join element for the query.
4632
+	 */
4633
+	public function _construct_limit_join_select($table_alias, $limit)
4634
+	{
4635
+		$SQL = '';
4636
+		foreach ($this->_tables as $table_obj) {
4637
+			if ($table_obj instanceof EE_Primary_Table) {
4638
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4639
+					? $table_obj->get_select_join_limit($limit)
4640
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4641
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4642
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4643
+					? $table_obj->get_select_join_limit_join($limit)
4644
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4645
+			}
4646
+		}
4647
+		return $SQL;
4648
+	}
4649
+
4650
+
4651
+
4652
+	/**
4653
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4654
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4655
+	 *
4656
+	 * @return string SQL
4657
+	 * @throws EE_Error
4658
+	 */
4659
+	public function _construct_internal_join()
4660
+	{
4661
+		$SQL = $this->_get_main_table()->get_table_sql();
4662
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4663
+		return $SQL;
4664
+	}
4665
+
4666
+
4667
+
4668
+	/**
4669
+	 * Constructs the SQL for joining all the tables on this model.
4670
+	 * Normally $alias should be the primary table's alias, but in cases where
4671
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4672
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4673
+	 * alias, this will construct SQL like:
4674
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4675
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4676
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4677
+	 *
4678
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4679
+	 * @return string
4680
+	 */
4681
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4682
+	{
4683
+		$SQL = '';
4684
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4685
+		foreach ($this->_tables as $table_obj) {
4686
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4687
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4688
+					//so we're joining to this table, meaning the table is already in
4689
+					//the FROM statement, BUT the primary table isn't. So we want
4690
+					//to add the inverse join sql
4691
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4692
+				} else {
4693
+					//just add a regular JOIN to this table from the primary table
4694
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4695
+				}
4696
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4697
+		}
4698
+		return $SQL;
4699
+	}
4700
+
4701
+
4702
+
4703
+	/**
4704
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4705
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4706
+	 * their data type (eg, '%s', '%d', etc)
4707
+	 *
4708
+	 * @return array
4709
+	 */
4710
+	public function _get_data_types()
4711
+	{
4712
+		$data_types = array();
4713
+		foreach ($this->field_settings() as $field_obj) {
4714
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4715
+			/** @var $field_obj EE_Model_Field_Base */
4716
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4717
+		}
4718
+		return $data_types;
4719
+	}
4720
+
4721
+
4722
+
4723
+	/**
4724
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4725
+	 *
4726
+	 * @param string $model_name
4727
+	 * @throws EE_Error
4728
+	 * @return EEM_Base
4729
+	 */
4730
+	public function get_related_model_obj($model_name)
4731
+	{
4732
+		$model_classname = "EEM_" . $model_name;
4733
+		if (! class_exists($model_classname)) {
4734
+			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",
4735
+				'event_espresso'), $model_name, $model_classname));
4736
+		}
4737
+		return call_user_func($model_classname . "::instance");
4738
+	}
4739
+
4740
+
4741
+
4742
+	/**
4743
+	 * Returns the array of EE_ModelRelations for this model.
4744
+	 *
4745
+	 * @return EE_Model_Relation_Base[]
4746
+	 */
4747
+	public function relation_settings()
4748
+	{
4749
+		return $this->_model_relations;
4750
+	}
4751
+
4752
+
4753
+
4754
+	/**
4755
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4756
+	 * because without THOSE models, this model probably doesn't have much purpose.
4757
+	 * (Eg, without an event, datetimes have little purpose.)
4758
+	 *
4759
+	 * @return EE_Belongs_To_Relation[]
4760
+	 */
4761
+	public function belongs_to_relations()
4762
+	{
4763
+		$belongs_to_relations = array();
4764
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4765
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4766
+				$belongs_to_relations[$model_name] = $relation_obj;
4767
+			}
4768
+		}
4769
+		return $belongs_to_relations;
4770
+	}
4771
+
4772
+
4773
+
4774
+	/**
4775
+	 * Returns the specified EE_Model_Relation, or throws an exception
4776
+	 *
4777
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4778
+	 * @throws EE_Error
4779
+	 * @return EE_Model_Relation_Base
4780
+	 */
4781
+	public function related_settings_for($relation_name)
4782
+	{
4783
+		$relatedModels = $this->relation_settings();
4784
+		if (! array_key_exists($relation_name, $relatedModels)) {
4785
+			throw new EE_Error(
4786
+				sprintf(
4787
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4788
+						'event_espresso'),
4789
+					$relation_name,
4790
+					$this->_get_class_name(),
4791
+					implode(', ', array_keys($relatedModels))
4792
+				)
4793
+			);
4794
+		}
4795
+		return $relatedModels[$relation_name];
4796
+	}
4797
+
4798
+
4799
+
4800
+	/**
4801
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4802
+	 * fields
4803
+	 *
4804
+	 * @param string $fieldName
4805
+	 * @param boolean $include_db_only_fields
4806
+	 * @throws EE_Error
4807
+	 * @return EE_Model_Field_Base
4808
+	 */
4809
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4810
+	{
4811
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4812
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4813
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814
+				get_class($this)));
4815
+		}
4816
+		return $fieldSettings[$fieldName];
4817
+	}
4818
+
4819
+
4820
+
4821
+	/**
4822
+	 * Checks if this field exists on this model
4823
+	 *
4824
+	 * @param string $fieldName a key in the model's _field_settings array
4825
+	 * @return boolean
4826
+	 */
4827
+	public function has_field($fieldName)
4828
+	{
4829
+		$fieldSettings = $this->field_settings(true);
4830
+		if (isset($fieldSettings[$fieldName])) {
4831
+			return true;
4832
+		}
4833
+		return false;
4834
+	}
4835
+
4836
+
4837
+
4838
+	/**
4839
+	 * Returns whether or not this model has a relation to the specified model
4840
+	 *
4841
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4842
+	 * @return boolean
4843
+	 */
4844
+	public function has_relation($relation_name)
4845
+	{
4846
+		$relations = $this->relation_settings();
4847
+		if (isset($relations[$relation_name])) {
4848
+			return true;
4849
+		}
4850
+		return false;
4851
+	}
4852
+
4853
+
4854
+
4855
+	/**
4856
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4857
+	 * Eg, on EE_Answer that would be ANS_ID field object
4858
+	 *
4859
+	 * @param $field_obj
4860
+	 * @return boolean
4861
+	 */
4862
+	public function is_primary_key_field($field_obj)
4863
+	{
4864
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4865
+	}
4866
+
4867
+
4868
+
4869
+	/**
4870
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4871
+	 * Eg, on EE_Answer that would be ANS_ID field object
4872
+	 *
4873
+	 * @return EE_Model_Field_Base
4874
+	 * @throws EE_Error
4875
+	 */
4876
+	public function get_primary_key_field()
4877
+	{
4878
+		if ($this->_primary_key_field === null) {
4879
+			foreach ($this->field_settings(true) as $field_obj) {
4880
+				if ($this->is_primary_key_field($field_obj)) {
4881
+					$this->_primary_key_field = $field_obj;
4882
+					break;
4883
+				}
4884
+			}
4885
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887
+					get_class($this)));
4888
+			}
4889
+		}
4890
+		return $this->_primary_key_field;
4891
+	}
4892
+
4893
+
4894
+
4895
+	/**
4896
+	 * Returns whether or not not there is a primary key on this model.
4897
+	 * Internally does some caching.
4898
+	 *
4899
+	 * @return boolean
4900
+	 */
4901
+	public function has_primary_key_field()
4902
+	{
4903
+		if ($this->_has_primary_key_field === null) {
4904
+			try {
4905
+				$this->get_primary_key_field();
4906
+				$this->_has_primary_key_field = true;
4907
+			} catch (EE_Error $e) {
4908
+				$this->_has_primary_key_field = false;
4909
+			}
4910
+		}
4911
+		return $this->_has_primary_key_field;
4912
+	}
4913
+
4914
+
4915
+
4916
+	/**
4917
+	 * Finds the first field of type $field_class_name.
4918
+	 *
4919
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4920
+	 *                                 EE_Foreign_Key_Field, etc
4921
+	 * @return EE_Model_Field_Base or null if none is found
4922
+	 */
4923
+	public function get_a_field_of_type($field_class_name)
4924
+	{
4925
+		foreach ($this->field_settings() as $field) {
4926
+			if ($field instanceof $field_class_name) {
4927
+				return $field;
4928
+			}
4929
+		}
4930
+		return null;
4931
+	}
4932
+
4933
+
4934
+
4935
+	/**
4936
+	 * Gets a foreign key field pointing to model.
4937
+	 *
4938
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4939
+	 * @return EE_Foreign_Key_Field_Base
4940
+	 * @throws EE_Error
4941
+	 */
4942
+	public function get_foreign_key_to($model_name)
4943
+	{
4944
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945
+			foreach ($this->field_settings() as $field) {
4946
+				if (
4947
+					$field instanceof EE_Foreign_Key_Field_Base
4948
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4949
+				) {
4950
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4951
+					break;
4952
+				}
4953
+			}
4954
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956
+					'event_espresso'), $model_name, get_class($this)));
4957
+			}
4958
+		}
4959
+		return $this->_cache_foreign_key_to_fields[$model_name];
4960
+	}
4961
+
4962
+
4963
+
4964
+	/**
4965
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4966
+	 *
4967
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4968
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4969
+	 *                            Either one works
4970
+	 * @return string
4971
+	 */
4972
+	public function get_table_for_alias($table_alias)
4973
+	{
4974
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4975
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4976
+	}
4977
+
4978
+
4979
+
4980
+	/**
4981
+	 * Returns a flat array of all field son this model, instead of organizing them
4982
+	 * by table_alias as they are in the constructor.
4983
+	 *
4984
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4985
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4986
+	 */
4987
+	public function field_settings($include_db_only_fields = false)
4988
+	{
4989
+		if ($include_db_only_fields) {
4990
+			if ($this->_cached_fields === null) {
4991
+				$this->_cached_fields = array();
4992
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4993
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4994
+						$this->_cached_fields[$field_name] = $field_obj;
4995
+					}
4996
+				}
4997
+			}
4998
+			return $this->_cached_fields;
4999
+		}
5000
+		if ($this->_cached_fields_non_db_only === null) {
5001
+			$this->_cached_fields_non_db_only = array();
5002
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5003
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004
+					/** @var $field_obj EE_Model_Field_Base */
5005
+					if (! $field_obj->is_db_only_field()) {
5006
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007
+					}
5008
+				}
5009
+			}
5010
+		}
5011
+		return $this->_cached_fields_non_db_only;
5012
+	}
5013
+
5014
+
5015
+
5016
+	/**
5017
+	 *        cycle though array of attendees and create objects out of each item
5018
+	 *
5019
+	 * @access        private
5020
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5021
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5022
+	 *                           numerically indexed)
5023
+	 * @throws EE_Error
5024
+	 */
5025
+	protected function _create_objects($rows = array())
5026
+	{
5027
+		$array_of_objects = array();
5028
+		if (empty($rows)) {
5029
+			return array();
5030
+		}
5031
+		$count_if_model_has_no_primary_key = 0;
5032
+		$has_primary_key = $this->has_primary_key_field();
5033
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
+		foreach ((array)$rows as $row) {
5035
+			if (empty($row)) {
5036
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037
+				return array();
5038
+			}
5039
+			//check if we've already set this object in the results array,
5040
+			//in which case there's no need to process it further (again)
5041
+			if ($has_primary_key) {
5042
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5043
+					$row,
5044
+					$primary_key_field->get_qualified_column(),
5045
+					$primary_key_field->get_table_column()
5046
+				);
5047
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5048
+					continue;
5049
+				}
5050
+			}
5051
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5052
+			if (! $classInstance) {
5053
+				throw new EE_Error(
5054
+					sprintf(
5055
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5056
+						$this->get_this_model_name(),
5057
+						http_build_query($row)
5058
+					)
5059
+				);
5060
+			}
5061
+			//set the timezone on the instantiated objects
5062
+			$classInstance->set_timezone($this->_timezone);
5063
+			//make sure if there is any timezone setting present that we set the timezone for the object
5064
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5065
+			$array_of_objects[$key] = $classInstance;
5066
+			//also, for all the relations of type BelongsTo, see if we can cache
5067
+			//those related models
5068
+			//(we could do this for other relations too, but if there are conditions
5069
+			//that filtered out some fo the results, then we'd be caching an incomplete set
5070
+			//so it requires a little more thought than just caching them immediately...)
5071
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5072
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5073
+					//check if this model's INFO is present. If so, cache it on the model
5074
+					$other_model = $relation_obj->get_other_model();
5075
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5076
+					//if we managed to make a model object from the results, cache it on the main model object
5077
+					if ($other_model_obj_maybe) {
5078
+						//set timezone on these other model objects if they are present
5079
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5080
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5081
+					}
5082
+				}
5083
+			}
5084
+			//also, if this was a custom select query, let's see if there are any results for the custom select fields
5085
+			//and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5086
+			//the field in the CustomSelects object
5087
+			if ($this->_custom_selections instanceof CustomSelects) {
5088
+				$classInstance->setCustomSelectsValues(
5089
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5090
+				);
5091
+			}
5092
+		}
5093
+		return $array_of_objects;
5094
+	}
5095
+
5096
+
5097
+	/**
5098
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5099
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5100
+	 *
5101
+	 * @param array $db_results_row
5102
+	 * @return array
5103
+	 */
5104
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5105
+	{
5106
+		$results = array();
5107
+		if ($this->_custom_selections instanceof CustomSelects) {
5108
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5109
+				if (isset($db_results_row[$alias])) {
5110
+					$results[$alias] = $this->convertValueToDataType(
5111
+						$db_results_row[$alias],
5112
+						$this->_custom_selections->getDataTypeForAlias($alias)
5113
+					);
5114
+				}
5115
+			}
5116
+		}
5117
+		return $results;
5118
+	}
5119
+
5120
+
5121
+	/**
5122
+	 * This will set the value for the given alias
5123
+	 * @param string $value
5124
+	 * @param string $datatype (one of %d, %s, %f)
5125
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5126
+	 */
5127
+	protected function convertValueToDataType($value, $datatype)
5128
+	{
5129
+		switch ($datatype) {
5130
+			case '%f':
5131
+				return (float) $value;
5132
+			case '%d':
5133
+				return (int) $value;
5134
+			default:
5135
+				return (string) $value;
5136
+		}
5137
+	}
5138
+
5139
+
5140
+	/**
5141
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5142
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5143
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5144
+	 * object (as set in the model_field!).
5145
+	 *
5146
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5147
+	 */
5148
+	public function create_default_object()
5149
+	{
5150
+		$this_model_fields_and_values = array();
5151
+		//setup the row using default values;
5152
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5153
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5154
+		}
5155
+		$className = $this->_get_class_name();
5156
+		$classInstance = EE_Registry::instance()
5157
+									->load_class($className, array($this_model_fields_and_values), false, false);
5158
+		return $classInstance;
5159
+	}
5160
+
5161
+
5162
+
5163
+	/**
5164
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5165
+	 *                             or an stdClass where each property is the name of a column,
5166
+	 * @return EE_Base_Class
5167
+	 * @throws EE_Error
5168
+	 */
5169
+	public function instantiate_class_from_array_or_object($cols_n_values)
5170
+	{
5171
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5172
+			$cols_n_values = get_object_vars($cols_n_values);
5173
+		}
5174
+		$primary_key = null;
5175
+		//make sure the array only has keys that are fields/columns on this model
5176
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5177
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5178
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5179
+		}
5180
+		$className = $this->_get_class_name();
5181
+		//check we actually found results that we can use to build our model object
5182
+		//if not, return null
5183
+		if ($this->has_primary_key_field()) {
5184
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5185
+				return null;
5186
+			}
5187
+		} else if ($this->unique_indexes()) {
5188
+			$first_column = reset($this_model_fields_n_values);
5189
+			if (empty($first_column)) {
5190
+				return null;
5191
+			}
5192
+		}
5193
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194
+		if ($primary_key) {
5195
+			$classInstance = $this->get_from_entity_map($primary_key);
5196
+			if (! $classInstance) {
5197
+				$classInstance = EE_Registry::instance()
5198
+											->load_class($className,
5199
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5200
+				// add this new object to the entity map
5201
+				$classInstance = $this->add_to_entity_map($classInstance);
5202
+			}
5203
+		} else {
5204
+			$classInstance = EE_Registry::instance()
5205
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5206
+											true, false);
5207
+		}
5208
+		return $classInstance;
5209
+	}
5210
+
5211
+
5212
+
5213
+	/**
5214
+	 * Gets the model object from the  entity map if it exists
5215
+	 *
5216
+	 * @param int|string $id the ID of the model object
5217
+	 * @return EE_Base_Class
5218
+	 */
5219
+	public function get_from_entity_map($id)
5220
+	{
5221
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5222
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5223
+	}
5224
+
5225
+
5226
+
5227
+	/**
5228
+	 * add_to_entity_map
5229
+	 * Adds the object to the model's entity mappings
5230
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5231
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5232
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5233
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5234
+	 *        then this method should be called immediately after the update query
5235
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5236
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5237
+	 *
5238
+	 * @param    EE_Base_Class $object
5239
+	 * @throws EE_Error
5240
+	 * @return \EE_Base_Class
5241
+	 */
5242
+	public function add_to_entity_map(EE_Base_Class $object)
5243
+	{
5244
+		$className = $this->_get_class_name();
5245
+		if (! $object instanceof $className) {
5246
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247
+				is_object($object) ? get_class($object) : $object, $className));
5248
+		}
5249
+		/** @var $object EE_Base_Class */
5250
+		if (! $object->ID()) {
5251
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252
+				"event_espresso"), get_class($this)));
5253
+		}
5254
+		// double check it's not already there
5255
+		$classInstance = $this->get_from_entity_map($object->ID());
5256
+		if ($classInstance) {
5257
+			return $classInstance;
5258
+		}
5259
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5260
+		return $object;
5261
+	}
5262
+
5263
+
5264
+
5265
+	/**
5266
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5267
+	 * if no identifier is provided, then the entire entity map is emptied
5268
+	 *
5269
+	 * @param int|string $id the ID of the model object
5270
+	 * @return boolean
5271
+	 */
5272
+	public function clear_entity_map($id = null)
5273
+	{
5274
+		if (empty($id)) {
5275
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5276
+			return true;
5277
+		}
5278
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5279
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5280
+			return true;
5281
+		}
5282
+		return false;
5283
+	}
5284
+
5285
+
5286
+
5287
+	/**
5288
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5289
+	 * Given an array where keys are column (or column alias) names and values,
5290
+	 * returns an array of their corresponding field names and database values
5291
+	 *
5292
+	 * @param array $cols_n_values
5293
+	 * @return array
5294
+	 */
5295
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5296
+	{
5297
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5298
+	}
5299
+
5300
+
5301
+
5302
+	/**
5303
+	 * _deduce_fields_n_values_from_cols_n_values
5304
+	 * Given an array where keys are column (or column alias) names and values,
5305
+	 * returns an array of their corresponding field names and database values
5306
+	 *
5307
+	 * @param string $cols_n_values
5308
+	 * @return array
5309
+	 */
5310
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5311
+	{
5312
+		$this_model_fields_n_values = array();
5313
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5314
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5315
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5316
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5317
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
+					if (! $field_obj->is_db_only_field()) {
5320
+						//prepare field as if its coming from db
5321
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5323
+					}
5324
+				}
5325
+			} else {
5326
+				//the table's rows existed. Use their values
5327
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
+					if (! $field_obj->is_db_only_field()) {
5329
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330
+							$cols_n_values, $field_obj->get_qualified_column(),
5331
+							$field_obj->get_table_column()
5332
+						);
5333
+					}
5334
+				}
5335
+			}
5336
+		}
5337
+		return $this_model_fields_n_values;
5338
+	}
5339
+
5340
+
5341
+
5342
+	/**
5343
+	 * @param $cols_n_values
5344
+	 * @param $qualified_column
5345
+	 * @param $regular_column
5346
+	 * @return null
5347
+	 */
5348
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5349
+	{
5350
+		$value = null;
5351
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5352
+		//does the field on the model relate to this column retrieved from the db?
5353
+		//or is it a db-only field? (not relating to the model)
5354
+		if (isset($cols_n_values[$qualified_column])) {
5355
+			$value = $cols_n_values[$qualified_column];
5356
+		} elseif (isset($cols_n_values[$regular_column])) {
5357
+			$value = $cols_n_values[$regular_column];
5358
+		}
5359
+		return $value;
5360
+	}
5361
+
5362
+
5363
+
5364
+	/**
5365
+	 * refresh_entity_map_from_db
5366
+	 * Makes sure the model object in the entity map at $id assumes the values
5367
+	 * of the database (opposite of EE_base_Class::save())
5368
+	 *
5369
+	 * @param int|string $id
5370
+	 * @return EE_Base_Class
5371
+	 * @throws EE_Error
5372
+	 */
5373
+	public function refresh_entity_map_from_db($id)
5374
+	{
5375
+		$obj_in_map = $this->get_from_entity_map($id);
5376
+		if ($obj_in_map) {
5377
+			$wpdb_results = $this->_get_all_wpdb_results(
5378
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5379
+			);
5380
+			if ($wpdb_results && is_array($wpdb_results)) {
5381
+				$one_row = reset($wpdb_results);
5382
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5383
+					$obj_in_map->set_from_db($field_name, $db_value);
5384
+				}
5385
+				//clear the cache of related model objects
5386
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5387
+					$obj_in_map->clear_cache($relation_name, null, true);
5388
+				}
5389
+			}
5390
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5391
+			return $obj_in_map;
5392
+		}
5393
+		return $this->get_one_by_ID($id);
5394
+	}
5395
+
5396
+
5397
+
5398
+	/**
5399
+	 * refresh_entity_map_with
5400
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5401
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5402
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5403
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5404
+	 *
5405
+	 * @param int|string    $id
5406
+	 * @param EE_Base_Class $replacing_model_obj
5407
+	 * @return \EE_Base_Class
5408
+	 * @throws EE_Error
5409
+	 */
5410
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5411
+	{
5412
+		$obj_in_map = $this->get_from_entity_map($id);
5413
+		if ($obj_in_map) {
5414
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5415
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5416
+					$obj_in_map->set($field_name, $value);
5417
+				}
5418
+				//make the model object in the entity map's cache match the $replacing_model_obj
5419
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5420
+					$obj_in_map->clear_cache($relation_name, null, true);
5421
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5422
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5423
+					}
5424
+				}
5425
+			}
5426
+			return $obj_in_map;
5427
+		}
5428
+		$this->add_to_entity_map($replacing_model_obj);
5429
+		return $replacing_model_obj;
5430
+	}
5431
+
5432
+
5433
+
5434
+	/**
5435
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5436
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5437
+	 * require_once($this->_getClassName().".class.php");
5438
+	 *
5439
+	 * @return string
5440
+	 */
5441
+	private function _get_class_name()
5442
+	{
5443
+		return "EE_" . $this->get_this_model_name();
5444
+	}
5445
+
5446
+
5447
+
5448
+	/**
5449
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5450
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5451
+	 * it would be 'Events'.
5452
+	 *
5453
+	 * @param int $quantity
5454
+	 * @return string
5455
+	 */
5456
+	public function item_name($quantity = 1)
5457
+	{
5458
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5459
+	}
5460
+
5461
+
5462
+
5463
+	/**
5464
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5465
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5466
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5467
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5468
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5469
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5470
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5471
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5472
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5473
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5474
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5475
+	 *        return $previousReturnValue.$returnString;
5476
+	 * }
5477
+	 * require('EEM_Answer.model.php');
5478
+	 * $answer=EEM_Answer::instance();
5479
+	 * echo $answer->my_callback('monkeys',100);
5480
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5481
+	 *
5482
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5483
+	 * @param array  $args       array of original arguments passed to the function
5484
+	 * @throws EE_Error
5485
+	 * @return mixed whatever the plugin which calls add_filter decides
5486
+	 */
5487
+	public function __call($methodName, $args)
5488
+	{
5489
+		$className = get_class($this);
5490
+		$tagName = "FHEE__{$className}__{$methodName}";
5491
+		if (! has_filter($tagName)) {
5492
+			throw new EE_Error(
5493
+				sprintf(
5494
+					__('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 );',
5495
+						'event_espresso'),
5496
+					$methodName,
5497
+					$className,
5498
+					$tagName,
5499
+					'<br />'
5500
+				)
5501
+			);
5502
+		}
5503
+		return apply_filters($tagName, null, $this, $args);
5504
+	}
5505
+
5506
+
5507
+
5508
+	/**
5509
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5510
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5511
+	 *
5512
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5513
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5514
+	 *                                                       the object's class name
5515
+	 *                                                       or object's ID
5516
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5517
+	 *                                                       exists in the database. If it does not, we add it
5518
+	 * @throws EE_Error
5519
+	 * @return EE_Base_Class
5520
+	 */
5521
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5522
+	{
5523
+		$className = $this->_get_class_name();
5524
+		if ($base_class_obj_or_id instanceof $className) {
5525
+			$model_object = $base_class_obj_or_id;
5526
+		} else {
5527
+			$primary_key_field = $this->get_primary_key_field();
5528
+			if (
5529
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5530
+				&& (
5531
+					is_int($base_class_obj_or_id)
5532
+					|| is_string($base_class_obj_or_id)
5533
+				)
5534
+			) {
5535
+				// assume it's an ID.
5536
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5537
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5538
+			} else if (
5539
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5540
+				&& is_string($base_class_obj_or_id)
5541
+			) {
5542
+				// assume its a string representation of the object
5543
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5544
+			} else {
5545
+				throw new EE_Error(
5546
+					sprintf(
5547
+						__(
5548
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5549
+							'event_espresso'
5550
+						),
5551
+						$base_class_obj_or_id,
5552
+						$this->_get_class_name(),
5553
+						print_r($base_class_obj_or_id, true)
5554
+					)
5555
+				);
5556
+			}
5557
+		}
5558
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5559
+			$model_object->save();
5560
+		}
5561
+		return $model_object;
5562
+	}
5563
+
5564
+
5565
+
5566
+	/**
5567
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5568
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5569
+	 * returns it ID.
5570
+	 *
5571
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5572
+	 * @return int|string depending on the type of this model object's ID
5573
+	 * @throws EE_Error
5574
+	 */
5575
+	public function ensure_is_ID($base_class_obj_or_id)
5576
+	{
5577
+		$className = $this->_get_class_name();
5578
+		if ($base_class_obj_or_id instanceof $className) {
5579
+			/** @var $base_class_obj_or_id EE_Base_Class */
5580
+			$id = $base_class_obj_or_id->ID();
5581
+		} elseif (is_int($base_class_obj_or_id)) {
5582
+			//assume it's an ID
5583
+			$id = $base_class_obj_or_id;
5584
+		} elseif (is_string($base_class_obj_or_id)) {
5585
+			//assume its a string representation of the object
5586
+			$id = $base_class_obj_or_id;
5587
+		} else {
5588
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5589
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5590
+				print_r($base_class_obj_or_id, true)));
5591
+		}
5592
+		return $id;
5593
+	}
5594
+
5595
+
5596
+
5597
+	/**
5598
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5599
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5600
+	 * been sanitized and converted into the appropriate domain.
5601
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5602
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5603
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5604
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5605
+	 * $EVT = EEM_Event::instance(); $old_setting =
5606
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5607
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5608
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5609
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5610
+	 *
5611
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5612
+	 * @return void
5613
+	 */
5614
+	public function assume_values_already_prepared_by_model_object(
5615
+		$values_already_prepared = self::not_prepared_by_model_object
5616
+	) {
5617
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5618
+	}
5619
+
5620
+
5621
+
5622
+	/**
5623
+	 * Read comments for assume_values_already_prepared_by_model_object()
5624
+	 *
5625
+	 * @return int
5626
+	 */
5627
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5628
+	{
5629
+		return $this->_values_already_prepared_by_model_object;
5630
+	}
5631
+
5632
+
5633
+
5634
+	/**
5635
+	 * Gets all the indexes on this model
5636
+	 *
5637
+	 * @return EE_Index[]
5638
+	 */
5639
+	public function indexes()
5640
+	{
5641
+		return $this->_indexes;
5642
+	}
5643
+
5644
+
5645
+
5646
+	/**
5647
+	 * Gets all the Unique Indexes on this model
5648
+	 *
5649
+	 * @return EE_Unique_Index[]
5650
+	 */
5651
+	public function unique_indexes()
5652
+	{
5653
+		$unique_indexes = array();
5654
+		foreach ($this->_indexes as $name => $index) {
5655
+			if ($index instanceof EE_Unique_Index) {
5656
+				$unique_indexes [$name] = $index;
5657
+			}
5658
+		}
5659
+		return $unique_indexes;
5660
+	}
5661
+
5662
+
5663
+
5664
+	/**
5665
+	 * Gets all the fields which, when combined, make the primary key.
5666
+	 * This is usually just an array with 1 element (the primary key), but in cases
5667
+	 * where there is no primary key, it's a combination of fields as defined
5668
+	 * on a primary index
5669
+	 *
5670
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5671
+	 * @throws EE_Error
5672
+	 */
5673
+	public function get_combined_primary_key_fields()
5674
+	{
5675
+		foreach ($this->indexes() as $index) {
5676
+			if ($index instanceof EE_Primary_Key_Index) {
5677
+				return $index->fields();
5678
+			}
5679
+		}
5680
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5681
+	}
5682
+
5683
+
5684
+
5685
+	/**
5686
+	 * Used to build a primary key string (when the model has no primary key),
5687
+	 * which can be used a unique string to identify this model object.
5688
+	 *
5689
+	 * @param array $cols_n_values keys are field names, values are their values
5690
+	 * @return string
5691
+	 * @throws EE_Error
5692
+	 */
5693
+	public function get_index_primary_key_string($cols_n_values)
5694
+	{
5695
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5696
+			$this->get_combined_primary_key_fields());
5697
+		return http_build_query($cols_n_values_for_primary_key_index);
5698
+	}
5699
+
5700
+
5701
+
5702
+	/**
5703
+	 * Gets the field values from the primary key string
5704
+	 *
5705
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5706
+	 * @param string $index_primary_key_string
5707
+	 * @return null|array
5708
+	 * @throws EE_Error
5709
+	 */
5710
+	public function parse_index_primary_key_string($index_primary_key_string)
5711
+	{
5712
+		$key_fields = $this->get_combined_primary_key_fields();
5713
+		//check all of them are in the $id
5714
+		$key_vals_in_combined_pk = array();
5715
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716
+		foreach ($key_fields as $key_field_name => $field_obj) {
5717
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5718
+				return null;
5719
+			}
5720
+		}
5721
+		return $key_vals_in_combined_pk;
5722
+	}
5723
+
5724
+
5725
+
5726
+	/**
5727
+	 * verifies that an array of key-value pairs for model fields has a key
5728
+	 * for each field comprising the primary key index
5729
+	 *
5730
+	 * @param array $key_vals
5731
+	 * @return boolean
5732
+	 * @throws EE_Error
5733
+	 */
5734
+	public function has_all_combined_primary_key_fields($key_vals)
5735
+	{
5736
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737
+		foreach ($keys_it_should_have as $key) {
5738
+			if (! isset($key_vals[$key])) {
5739
+				return false;
5740
+			}
5741
+		}
5742
+		return true;
5743
+	}
5744
+
5745
+
5746
+
5747
+	/**
5748
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5749
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5750
+	 *
5751
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5752
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5753
+	 * @throws EE_Error
5754
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5755
+	 *                                                              indexed)
5756
+	 */
5757
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5758
+	{
5759
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5760
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5761
+		} elseif (is_array($model_object_or_attributes_array)) {
5762
+			$attributes_array = $model_object_or_attributes_array;
5763
+		} else {
5764
+			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",
5765
+				"event_espresso"), $model_object_or_attributes_array));
5766
+		}
5767
+		//even copies obviously won't have the same ID, so remove the primary key
5768
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5769
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5770
+			unset($attributes_array[$this->primary_key_name()]);
5771
+		}
5772
+		if (isset($query_params[0])) {
5773
+			$query_params[0] = array_merge($attributes_array, $query_params);
5774
+		} else {
5775
+			$query_params[0] = $attributes_array;
5776
+		}
5777
+		return $this->get_all($query_params);
5778
+	}
5779
+
5780
+
5781
+
5782
+	/**
5783
+	 * Gets the first copy we find. See get_all_copies for more details
5784
+	 *
5785
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5786
+	 * @param array $query_params
5787
+	 * @return EE_Base_Class
5788
+	 * @throws EE_Error
5789
+	 */
5790
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791
+	{
5792
+		if (! is_array($query_params)) {
5793
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795
+					gettype($query_params)), '4.6.0');
5796
+			$query_params = array();
5797
+		}
5798
+		$query_params['limit'] = 1;
5799
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5800
+		if (is_array($copies)) {
5801
+			return array_shift($copies);
5802
+		}
5803
+		return null;
5804
+	}
5805
+
5806
+
5807
+
5808
+	/**
5809
+	 * Updates the item with the specified id. Ignores default query parameters because
5810
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5811
+	 *
5812
+	 * @param array      $fields_n_values keys are field names, values are their new values
5813
+	 * @param int|string $id              the value of the primary key to update
5814
+	 * @return int number of rows updated
5815
+	 * @throws EE_Error
5816
+	 */
5817
+	public function update_by_ID($fields_n_values, $id)
5818
+	{
5819
+		$query_params = array(
5820
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5821
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5822
+		);
5823
+		return $this->update($fields_n_values, $query_params);
5824
+	}
5825
+
5826
+
5827
+
5828
+	/**
5829
+	 * Changes an operator which was supplied to the models into one usable in SQL
5830
+	 *
5831
+	 * @param string $operator_supplied
5832
+	 * @return string an operator which can be used in SQL
5833
+	 * @throws EE_Error
5834
+	 */
5835
+	private function _prepare_operator_for_sql($operator_supplied)
5836
+	{
5837
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5838
+			: null;
5839
+		if ($sql_operator) {
5840
+			return $sql_operator;
5841
+		}
5842
+		throw new EE_Error(
5843
+			sprintf(
5844
+				__(
5845
+					"The operator '%s' is not in the list of valid operators: %s",
5846
+					"event_espresso"
5847
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5848
+			)
5849
+		);
5850
+	}
5851
+
5852
+
5853
+
5854
+	/**
5855
+	 * Gets the valid operators
5856
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5857
+	 */
5858
+	public function valid_operators(){
5859
+		return $this->_valid_operators;
5860
+	}
5861
+
5862
+
5863
+
5864
+	/**
5865
+	 * Gets the between-style operators (take 2 arguments).
5866
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5867
+	 */
5868
+	public function valid_between_style_operators()
5869
+	{
5870
+		return array_intersect(
5871
+			$this->valid_operators(),
5872
+			$this->_between_style_operators
5873
+		);
5874
+	}
5875
+
5876
+	/**
5877
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5878
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5879
+	 */
5880
+	public function valid_like_style_operators()
5881
+	{
5882
+		return array_intersect(
5883
+			$this->valid_operators(),
5884
+			$this->_like_style_operators
5885
+		);
5886
+	}
5887
+
5888
+	/**
5889
+	 * Gets the "in"-style operators
5890
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5891
+	 */
5892
+	public function valid_in_style_operators()
5893
+	{
5894
+		return array_intersect(
5895
+			$this->valid_operators(),
5896
+			$this->_in_style_operators
5897
+		);
5898
+	}
5899
+
5900
+	/**
5901
+	 * Gets the "null"-style operators (accept no arguments)
5902
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5903
+	 */
5904
+	public function valid_null_style_operators()
5905
+	{
5906
+		return array_intersect(
5907
+			$this->valid_operators(),
5908
+			$this->_null_style_operators
5909
+		);
5910
+	}
5911
+
5912
+	/**
5913
+	 * Gets an array where keys are the primary keys and values are their 'names'
5914
+	 * (as determined by the model object's name() function, which is often overridden)
5915
+	 *
5916
+	 * @param array $query_params like get_all's
5917
+	 * @return string[]
5918
+	 * @throws EE_Error
5919
+	 */
5920
+	public function get_all_names($query_params = array())
5921
+	{
5922
+		$objs = $this->get_all($query_params);
5923
+		$names = array();
5924
+		foreach ($objs as $obj) {
5925
+			$names[$obj->ID()] = $obj->name();
5926
+		}
5927
+		return $names;
5928
+	}
5929
+
5930
+
5931
+
5932
+	/**
5933
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5934
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5935
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5936
+	 * array_keys() on $model_objects.
5937
+	 *
5938
+	 * @param \EE_Base_Class[] $model_objects
5939
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5940
+	 *                                               in the returned array
5941
+	 * @return array
5942
+	 * @throws EE_Error
5943
+	 */
5944
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945
+	{
5946
+		if (! $this->has_primary_key_field()) {
5947
+			if (WP_DEBUG) {
5948
+				EE_Error::add_error(
5949
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5950
+					__FILE__,
5951
+					__FUNCTION__,
5952
+					__LINE__
5953
+				);
5954
+			}
5955
+		}
5956
+		$IDs = array();
5957
+		foreach ($model_objects as $model_object) {
5958
+			$id = $model_object->ID();
5959
+			if (! $id) {
5960
+				if ($filter_out_empty_ids) {
5961
+					continue;
5962
+				}
5963
+				if (WP_DEBUG) {
5964
+					EE_Error::add_error(
5965
+						__(
5966
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5967
+							'event_espresso'
5968
+						),
5969
+						__FILE__,
5970
+						__FUNCTION__,
5971
+						__LINE__
5972
+					);
5973
+				}
5974
+			}
5975
+			$IDs[] = $id;
5976
+		}
5977
+		return $IDs;
5978
+	}
5979
+
5980
+
5981
+
5982
+	/**
5983
+	 * Returns the string used in capabilities relating to this model. If there
5984
+	 * are no capabilities that relate to this model returns false
5985
+	 *
5986
+	 * @return string|false
5987
+	 */
5988
+	public function cap_slug()
5989
+	{
5990
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5991
+	}
5992
+
5993
+
5994
+
5995
+	/**
5996
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5997
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5998
+	 * only returns the cap restrictions array in that context (ie, the array
5999
+	 * at that key)
6000
+	 *
6001
+	 * @param string $context
6002
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6003
+	 * @throws EE_Error
6004
+	 */
6005
+	public function cap_restrictions($context = EEM_Base::caps_read)
6006
+	{
6007
+		EEM_Base::verify_is_valid_cap_context($context);
6008
+		//check if we ought to run the restriction generator first
6009
+		if (
6010
+			isset($this->_cap_restriction_generators[$context])
6011
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6012
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6013
+		) {
6014
+			$this->_cap_restrictions[$context] = array_merge(
6015
+				$this->_cap_restrictions[$context],
6016
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
6017
+			);
6018
+		}
6019
+		//and make sure we've finalized the construction of each restriction
6020
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6021
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6022
+				$where_conditions_obj->_finalize_construct($this);
6023
+			}
6024
+		}
6025
+		return $this->_cap_restrictions[$context];
6026
+	}
6027
+
6028
+
6029
+
6030
+	/**
6031
+	 * Indicating whether or not this model thinks its a wp core model
6032
+	 *
6033
+	 * @return boolean
6034
+	 */
6035
+	public function is_wp_core_model()
6036
+	{
6037
+		return $this->_wp_core_model;
6038
+	}
6039
+
6040
+
6041
+
6042
+	/**
6043
+	 * Gets all the caps that are missing which impose a restriction on
6044
+	 * queries made in this context
6045
+	 *
6046
+	 * @param string $context one of EEM_Base::caps_ constants
6047
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6048
+	 * @throws EE_Error
6049
+	 */
6050
+	public function caps_missing($context = EEM_Base::caps_read)
6051
+	{
6052
+		$missing_caps = array();
6053
+		$cap_restrictions = $this->cap_restrictions($context);
6054
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
+			if (! EE_Capabilities::instance()
6056
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6057
+			) {
6058
+				$missing_caps[$cap] = $restriction_if_no_cap;
6059
+			}
6060
+		}
6061
+		return $missing_caps;
6062
+	}
6063
+
6064
+
6065
+
6066
+	/**
6067
+	 * Gets the mapping from capability contexts to action strings used in capability names
6068
+	 *
6069
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6070
+	 * one of 'read', 'edit', or 'delete'
6071
+	 */
6072
+	public function cap_contexts_to_cap_action_map()
6073
+	{
6074
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
6075
+			$this);
6076
+	}
6077
+
6078
+
6079
+
6080
+	/**
6081
+	 * Gets the action string for the specified capability context
6082
+	 *
6083
+	 * @param string $context
6084
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6085
+	 * @throws EE_Error
6086
+	 */
6087
+	public function cap_action_for_context($context)
6088
+	{
6089
+		$mapping = $this->cap_contexts_to_cap_action_map();
6090
+		if (isset($mapping[$context])) {
6091
+			return $mapping[$context];
6092
+		}
6093
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6094
+			return $action;
6095
+		}
6096
+		throw new EE_Error(
6097
+			sprintf(
6098
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6099
+				$context,
6100
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6101
+			)
6102
+		);
6103
+	}
6104
+
6105
+
6106
+
6107
+	/**
6108
+	 * Returns all the capability contexts which are valid when querying models
6109
+	 *
6110
+	 * @return array
6111
+	 */
6112
+	public static function valid_cap_contexts()
6113
+	{
6114
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6115
+			self::caps_read,
6116
+			self::caps_read_admin,
6117
+			self::caps_edit,
6118
+			self::caps_delete,
6119
+		));
6120
+	}
6121
+
6122
+
6123
+
6124
+	/**
6125
+	 * Returns all valid options for 'default_where_conditions'
6126
+	 *
6127
+	 * @return array
6128
+	 */
6129
+	public static function valid_default_where_conditions()
6130
+	{
6131
+		return array(
6132
+			EEM_Base::default_where_conditions_all,
6133
+			EEM_Base::default_where_conditions_this_only,
6134
+			EEM_Base::default_where_conditions_others_only,
6135
+			EEM_Base::default_where_conditions_minimum_all,
6136
+			EEM_Base::default_where_conditions_minimum_others,
6137
+			EEM_Base::default_where_conditions_none
6138
+		);
6139
+	}
6140
+
6141
+	// public static function default_where_conditions_full
6142
+	/**
6143
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6144
+	 *
6145
+	 * @param string $context
6146
+	 * @return bool
6147
+	 * @throws EE_Error
6148
+	 */
6149
+	static public function verify_is_valid_cap_context($context)
6150
+	{
6151
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6152
+		if (in_array($context, $valid_cap_contexts)) {
6153
+			return true;
6154
+		}
6155
+		throw new EE_Error(
6156
+			sprintf(
6157
+				__(
6158
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6159
+					'event_espresso'
6160
+				),
6161
+				$context,
6162
+				'EEM_Base',
6163
+				implode(',', $valid_cap_contexts)
6164
+			)
6165
+		);
6166
+	}
6167
+
6168
+
6169
+
6170
+	/**
6171
+	 * Clears all the models field caches. This is only useful when a sub-class
6172
+	 * might have added a field or something and these caches might be invalidated
6173
+	 */
6174
+	protected function _invalidate_field_caches()
6175
+	{
6176
+		$this->_cache_foreign_key_to_fields = array();
6177
+		$this->_cached_fields = null;
6178
+		$this->_cached_fields_non_db_only = null;
6179
+	}
6180
+
6181
+
6182
+
6183
+	/**
6184
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6185
+	 * (eg "and", "or", "not").
6186
+	 *
6187
+	 * @return array
6188
+	 */
6189
+	public function logic_query_param_keys()
6190
+	{
6191
+		return $this->_logic_query_param_keys;
6192
+	}
6193
+
6194
+
6195
+
6196
+	/**
6197
+	 * Determines whether or not the where query param array key is for a logic query param.
6198
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6199
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6200
+	 *
6201
+	 * @param $query_param_key
6202
+	 * @return bool
6203
+	 */
6204
+	public function is_logic_query_param_key($query_param_key)
6205
+	{
6206
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207
+			if ($query_param_key === $logic_query_param_key
6208
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6209
+			) {
6210
+				return true;
6211
+			}
6212
+		}
6213
+		return false;
6214
+	}
6215 6215
 
6216 6216
 
6217 6217
 
Please login to merge, or discard this patch.
Spacing   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -515,8 +515,8 @@  discard block
 block discarded – undo
515 515
     protected function __construct($timezone = null)
516 516
     {
517 517
         // check that the model has not been loaded too soon
518
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
519
-            throw new EE_Error (
518
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
519
+            throw new EE_Error(
520 520
                 sprintf(
521 521
                     __('The %1$s model can not be loaded before the "AHEE__EE_System__load_espresso_addons" hook has been called. This gives other addons a chance to extend this model.',
522 522
                         'event_espresso'),
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
          *
537 537
          * @var EE_Table_Base[] $_tables
538 538
          */
539
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
539
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
540 540
         foreach ($this->_tables as $table_alias => $table_obj) {
541 541
             /** @var $table_obj EE_Table_Base */
542 542
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -551,10 +551,10 @@  discard block
 block discarded – undo
551 551
          *
552 552
          * @param EE_Model_Field_Base[] $_fields
553 553
          */
554
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
554
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
555 555
         $this->_invalidate_field_caches();
556 556
         foreach ($this->_fields as $table_alias => $fields_for_table) {
557
-            if (! array_key_exists($table_alias, $this->_tables)) {
557
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
558 558
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
559 559
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
560 560
             }
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
          *
583 583
          * @param EE_Model_Relation_Base[] $_model_relations
584 584
          */
585
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
585
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
586 586
             $this->_model_relations);
587 587
         foreach ($this->_model_relations as $model_name => $relation_obj) {
588 588
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -594,12 +594,12 @@  discard block
 block discarded – undo
594 594
         }
595 595
         $this->set_timezone($timezone);
596 596
         //finalize default where condition strategy, or set default
597
-        if (! $this->_default_where_conditions_strategy) {
597
+        if ( ! $this->_default_where_conditions_strategy) {
598 598
             //nothing was set during child constructor, so set default
599 599
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
600 600
         }
601 601
         $this->_default_where_conditions_strategy->_finalize_construct($this);
602
-        if (! $this->_minimum_where_conditions_strategy) {
602
+        if ( ! $this->_minimum_where_conditions_strategy) {
603 603
             //nothing was set during child constructor, so set default
604 604
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
605 605
         }
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
         //initialize the standard cap restriction generators if none were specified by the child constructor
613 613
         if ($this->_cap_restriction_generators !== false) {
614 614
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
615
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
615
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
616 616
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
617 617
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
618 618
                         new EE_Restriction_Generator_Protected(),
@@ -625,10 +625,10 @@  discard block
 block discarded – undo
625 625
         //if there are cap restriction generators, use them to make the default cap restrictions
626 626
         if ($this->_cap_restriction_generators !== false) {
627 627
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
628
-                if (! $generator_object) {
628
+                if ( ! $generator_object) {
629 629
                     continue;
630 630
                 }
631
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
631
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
632 632
                     throw new EE_Error(
633 633
                         sprintf(
634 634
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
                     );
640 640
                 }
641 641
                 $action = $this->cap_action_for_context($context);
642
-                if (! $generator_object->construction_finalized()) {
642
+                if ( ! $generator_object->construction_finalized()) {
643 643
                     $generator_object->_construct_finalize($this, $action);
644 644
                 }
645 645
             }
646 646
         }
647
-        do_action('AHEE__' . get_class($this) . '__construct__end');
647
+        do_action('AHEE__'.get_class($this).'__construct__end');
648 648
     }
649 649
 
650 650
 
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
      */
658 658
     public static function set_model_query_blog_id($blog_id = 0)
659 659
     {
660
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
660
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
661 661
     }
662 662
 
663 663
 
@@ -691,7 +691,7 @@  discard block
 block discarded – undo
691 691
     public static function instance($timezone = null)
692 692
     {
693 693
         // check if instance of Espresso_model already exists
694
-        if (! static::$_instance instanceof static) {
694
+        if ( ! static::$_instance instanceof static) {
695 695
             // instantiate Espresso_model
696 696
             static::$_instance = new static(
697 697
                 $timezone,
@@ -730,7 +730,7 @@  discard block
 block discarded – undo
730 730
             foreach ($r->getDefaultProperties() as $property => $value) {
731 731
                 //don't set instance to null like it was originally,
732 732
                 //but it's static anyways, and we're ignoring static properties (for now at least)
733
-                if (! isset($static_properties[$property])) {
733
+                if ( ! isset($static_properties[$property])) {
734 734
                     static::$_instance->{$property} = $value;
735 735
                 }
736 736
             }
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
      */
755 755
     private static function getLoader()
756 756
     {
757
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
757
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
758 758
             EEM_Base::$loader = LoaderFactory::getLoader();
759 759
         }
760 760
         return EEM_Base::$loader;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
      */
775 775
     public function status_array($translated = false)
776 776
     {
777
-        if (! array_key_exists('Status', $this->_model_relations)) {
777
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
778 778
             return array();
779 779
         }
780 780
         $model_name = $this->get_this_model_name();
@@ -977,17 +977,17 @@  discard block
 block discarded – undo
977 977
     public function wp_user_field_name()
978 978
     {
979 979
         try {
980
-            if (! empty($this->_model_chain_to_wp_user)) {
980
+            if ( ! empty($this->_model_chain_to_wp_user)) {
981 981
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
982 982
                 $last_model_name = end($models_to_follow_to_wp_users);
983 983
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
984
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
984
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
985 985
             } else {
986 986
                 $model_with_fk_to_wp_users = $this;
987 987
                 $model_chain_to_wp_user = '';
988 988
             }
989 989
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
990
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
990
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
991 991
         } catch (EE_Error $e) {
992 992
             return false;
993 993
         }
@@ -1055,7 +1055,7 @@  discard block
 block discarded – undo
1055 1055
      */
1056 1056
     protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1057 1057
     {
1058
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);;
1058
+        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select); ;
1059 1059
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1060 1060
         $select_expressions = $columns_to_select === null
1061 1061
             ? $this->_construct_default_select_sql($model_query_info)
@@ -1063,11 +1063,11 @@  discard block
 block discarded – undo
1063 1063
         if ($this->_custom_selections instanceof CustomSelects) {
1064 1064
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
1065 1065
             $select_expressions .= $select_expressions
1066
-                ? ', ' . $custom_expressions
1066
+                ? ', '.$custom_expressions
1067 1067
                 : $custom_expressions;
1068 1068
         }
1069 1069
 
1070
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1070
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1071 1071
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1072 1072
     }
1073 1073
 
@@ -1084,7 +1084,7 @@  discard block
 block discarded – undo
1084 1084
      */
1085 1085
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1086 1086
     {
1087
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1087
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1088 1088
             return null;
1089 1089
         }
1090 1090
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1133,7 +1133,7 @@  discard block
 block discarded – undo
1133 1133
         if (is_array($columns_to_select)) {
1134 1134
             $select_sql_array = array();
1135 1135
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1136
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1136
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1137 1137
                     throw new EE_Error(
1138 1138
                         sprintf(
1139 1139
                             __(
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
                         )
1146 1146
                     );
1147 1147
                 }
1148
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1148
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1149 1149
                     throw new EE_Error(
1150 1150
                         sprintf(
1151 1151
                             esc_html__(
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
      */
1218 1218
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1219 1219
     {
1220
-        if (! isset($query_params[0])) {
1220
+        if ( ! isset($query_params[0])) {
1221 1221
             $query_params[0] = array();
1222 1222
         }
1223 1223
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
      */
1243 1243
     public function get_one($query_params = array())
1244 1244
     {
1245
-        if (! is_array($query_params)) {
1245
+        if ( ! is_array($query_params)) {
1246 1246
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1247 1247
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1248 1248
                     gettype($query_params)), '4.6.0');
@@ -1433,7 +1433,7 @@  discard block
 block discarded – undo
1433 1433
                 return array();
1434 1434
             }
1435 1435
         }
1436
-        if (! is_array($query_params)) {
1436
+        if ( ! is_array($query_params)) {
1437 1437
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1438 1438
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1439 1439
                     gettype($query_params)), '4.6.0');
@@ -1443,7 +1443,7 @@  discard block
 block discarded – undo
1443 1443
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1444 1444
         $query_params['limit'] = $limit;
1445 1445
         //set direction
1446
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1446
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1447 1447
         $query_params['order_by'] = $operand === '>'
1448 1448
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1449 1449
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
     {
1522 1522
         $field_settings = $this->field_settings_for($field_name);
1523 1523
         //if not a valid EE_Datetime_Field then throw error
1524
-        if (! $field_settings instanceof EE_Datetime_Field) {
1524
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1525 1525
             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.',
1526 1526
                 'event_espresso'), $field_name));
1527 1527
         }
@@ -1600,7 +1600,7 @@  discard block
 block discarded – undo
1600 1600
         //load EEH_DTT_Helper
1601 1601
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1602 1602
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1603
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1603
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1604 1604
     }
1605 1605
 
1606 1606
 
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
      */
1669 1669
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1670 1670
     {
1671
-        if (! is_array($query_params)) {
1671
+        if ( ! is_array($query_params)) {
1672 1672
             EE_Error::doing_it_wrong('EEM_Base::update',
1673 1673
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1674 1674
                     gettype($query_params)), '4.6.0');
@@ -1690,7 +1690,7 @@  discard block
 block discarded – undo
1690 1690
          * @param EEM_Base $model           the model being queried
1691 1691
          * @param array    $query_params    see EEM_Base::get_all()
1692 1692
          */
1693
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1693
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1694 1694
             $query_params);
1695 1695
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1696 1696
         //to do that, for each table, verify that it's PK isn't null.
@@ -1704,7 +1704,7 @@  discard block
 block discarded – undo
1704 1704
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1705 1705
         foreach ($wpdb_select_results as $wpdb_result) {
1706 1706
             // type cast stdClass as array
1707
-            $wpdb_result = (array)$wpdb_result;
1707
+            $wpdb_result = (array) $wpdb_result;
1708 1708
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1709 1709
             if ($this->has_primary_key_field()) {
1710 1710
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1721,13 +1721,13 @@  discard block
 block discarded – undo
1721 1721
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1722 1722
                     //if there is no private key for this table on the results, it means there's no entry
1723 1723
                     //in this table, right? so insert a row in the current table, using any fields available
1724
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1724
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1725 1725
                            && $wpdb_result[$this_table_pk_column])
1726 1726
                     ) {
1727 1727
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1728 1728
                             $main_table_pk_value);
1729 1729
                         //if we died here, report the error
1730
-                        if (! $success) {
1730
+                        if ( ! $success) {
1731 1731
                             return false;
1732 1732
                         }
1733 1733
                     }
@@ -1758,7 +1758,7 @@  discard block
 block discarded – undo
1758 1758
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1759 1759
                 }
1760 1760
             }
1761
-            if (! $model_objs_affected_ids) {
1761
+            if ( ! $model_objs_affected_ids) {
1762 1762
                 //wait wait wait- if nothing was affected let's stop here
1763 1763
                 return 0;
1764 1764
             }
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
                . $model_query_info->get_full_join_sql()
1786 1786
                . " SET "
1787 1787
                . $this->_construct_update_sql($fields_n_values)
1788
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1788
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1789 1789
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1790 1790
         /**
1791 1791
          * Action called after a model update call has been made.
@@ -1796,7 +1796,7 @@  discard block
 block discarded – undo
1796 1796
          * @param int      $rows_affected
1797 1797
          */
1798 1798
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1799
-        return $rows_affected;//how many supposedly got updated
1799
+        return $rows_affected; //how many supposedly got updated
1800 1800
     }
1801 1801
 
1802 1802
 
@@ -1824,7 +1824,7 @@  discard block
 block discarded – undo
1824 1824
         }
1825 1825
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1826 1826
         $select_expressions = $field->get_qualified_column();
1827
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1827
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1828 1828
         return $this->_do_wpdb_query('get_col', array($SQL));
1829 1829
     }
1830 1830
 
@@ -1842,7 +1842,7 @@  discard block
 block discarded – undo
1842 1842
     {
1843 1843
         $query_params['limit'] = 1;
1844 1844
         $col = $this->get_col($query_params, $field_to_select);
1845
-        if (! empty($col)) {
1845
+        if ( ! empty($col)) {
1846 1846
             return reset($col);
1847 1847
         }
1848 1848
         return null;
@@ -1873,7 +1873,7 @@  discard block
 block discarded – undo
1873 1873
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1874 1874
             $value_sql = $prepared_value === null ? 'NULL'
1875 1875
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1876
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1876
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1877 1877
         }
1878 1878
         return implode(",", $cols_n_values);
1879 1879
     }
@@ -2055,7 +2055,7 @@  discard block
 block discarded – undo
2055 2055
          * @param int      $rows_deleted
2056 2056
          */
2057 2057
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2058
-        return $rows_deleted;//how many supposedly got deleted
2058
+        return $rows_deleted; //how many supposedly got deleted
2059 2059
     }
2060 2060
 
2061 2061
 
@@ -2205,7 +2205,7 @@  discard block
 block discarded – undo
2205 2205
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2206 2206
                 //make sure we have unique $ids
2207 2207
                 $ids = array_unique($ids);
2208
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2208
+                $query[] = $column.' IN('.implode(',', $ids).')';
2209 2209
             }
2210 2210
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2211 2211
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2213,7 +2213,7 @@  discard block
 block discarded – undo
2213 2213
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2214 2214
                 $values_for_each_combined_primary_key_for_a_row = array();
2215 2215
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2216
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2216
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2217 2217
                 }
2218 2218
                 $ways_to_identify_a_row[] = '('
2219 2219
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2233,8 +2233,8 @@  discard block
 block discarded – undo
2233 2233
      */
2234 2234
     public function get_field_by_column($qualified_column_name)
2235 2235
     {
2236
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2237
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2236
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2237
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2238 2238
                return $field_obj;
2239 2239
            }
2240 2240
        }
@@ -2285,9 +2285,9 @@  discard block
 block discarded – undo
2285 2285
                 $column_to_count = '*';
2286 2286
             }
2287 2287
         }
2288
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2289
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2290
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2288
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2289
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2290
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2291 2291
     }
2292 2292
 
2293 2293
 
@@ -2309,14 +2309,14 @@  discard block
 block discarded – undo
2309 2309
             $field_obj = $this->get_primary_key_field();
2310 2310
         }
2311 2311
         $column_to_count = $field_obj->get_qualified_column();
2312
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2312
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2313 2313
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2314 2314
         $data_type = $field_obj->get_wpdb_data_type();
2315 2315
         if ($data_type === '%d' || $data_type === '%s') {
2316
-            return (float)$return_value;
2316
+            return (float) $return_value;
2317 2317
         }
2318 2318
         //must be %f
2319
-        return (float)$return_value;
2319
+        return (float) $return_value;
2320 2320
     }
2321 2321
 
2322 2322
 
@@ -2336,13 +2336,13 @@  discard block
 block discarded – undo
2336 2336
         //if we're in maintenance mode level 2, DON'T run any queries
2337 2337
         //because level 2 indicates the database needs updating and
2338 2338
         //is probably out of sync with the code
2339
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2339
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2340 2340
             throw new EE_Error(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.",
2341 2341
                 "event_espresso")));
2342 2342
         }
2343 2343
         /** @type WPDB $wpdb */
2344 2344
         global $wpdb;
2345
-        if (! method_exists($wpdb, $wpdb_method)) {
2345
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2346 2346
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2347 2347
                 'event_espresso'), $wpdb_method));
2348 2348
         }
@@ -2354,7 +2354,7 @@  discard block
 block discarded – undo
2354 2354
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2355 2355
         if (WP_DEBUG) {
2356 2356
             $wpdb->show_errors($old_show_errors_value);
2357
-            if (! empty($wpdb->last_error)) {
2357
+            if ( ! empty($wpdb->last_error)) {
2358 2358
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2359 2359
             }
2360 2360
             if ($result === false) {
@@ -2415,7 +2415,7 @@  discard block
 block discarded – undo
2415 2415
                     return $result;
2416 2416
                     break;
2417 2417
             }
2418
-            if (! empty($error_message)) {
2418
+            if ( ! empty($error_message)) {
2419 2419
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2420 2420
                 trigger_error($error_message);
2421 2421
             }
@@ -2491,11 +2491,11 @@  discard block
 block discarded – undo
2491 2491
      */
2492 2492
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2493 2493
     {
2494
-        return " FROM " . $model_query_info->get_full_join_sql() .
2495
-               $model_query_info->get_where_sql() .
2496
-               $model_query_info->get_group_by_sql() .
2497
-               $model_query_info->get_having_sql() .
2498
-               $model_query_info->get_order_by_sql() .
2494
+        return " FROM ".$model_query_info->get_full_join_sql().
2495
+               $model_query_info->get_where_sql().
2496
+               $model_query_info->get_group_by_sql().
2497
+               $model_query_info->get_having_sql().
2498
+               $model_query_info->get_order_by_sql().
2499 2499
                $model_query_info->get_limit_sql();
2500 2500
     }
2501 2501
 
@@ -2691,12 +2691,12 @@  discard block
 block discarded – undo
2691 2691
         $related_model = $this->get_related_model_obj($model_name);
2692 2692
         //we're just going to use the query params on the related model's normal get_all query,
2693 2693
         //except add a condition to say to match the current mod
2694
-        if (! isset($query_params['default_where_conditions'])) {
2694
+        if ( ! isset($query_params['default_where_conditions'])) {
2695 2695
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2696 2696
         }
2697 2697
         $this_model_name = $this->get_this_model_name();
2698 2698
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2699
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2699
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2700 2700
         return $related_model->count($query_params, $field_to_count, $distinct);
2701 2701
     }
2702 2702
 
@@ -2716,7 +2716,7 @@  discard block
 block discarded – undo
2716 2716
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2717 2717
     {
2718 2718
         $related_model = $this->get_related_model_obj($model_name);
2719
-        if (! is_array($query_params)) {
2719
+        if ( ! is_array($query_params)) {
2720 2720
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2721 2721
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2722 2722
                     gettype($query_params)), '4.6.0');
@@ -2724,12 +2724,12 @@  discard block
 block discarded – undo
2724 2724
         }
2725 2725
         //we're just going to use the query params on the related model's normal get_all query,
2726 2726
         //except add a condition to say to match the current mod
2727
-        if (! isset($query_params['default_where_conditions'])) {
2727
+        if ( ! isset($query_params['default_where_conditions'])) {
2728 2728
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2729 2729
         }
2730 2730
         $this_model_name = $this->get_this_model_name();
2731 2731
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2732
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2732
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2733 2733
         return $related_model->sum($query_params, $field_to_sum);
2734 2734
     }
2735 2735
 
@@ -2782,7 +2782,7 @@  discard block
 block discarded – undo
2782 2782
                 $field_with_model_name = $field;
2783 2783
             }
2784 2784
         }
2785
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2785
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2786 2786
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2787 2787
                 $this->get_this_model_name()));
2788 2788
         }
@@ -2815,7 +2815,7 @@  discard block
 block discarded – undo
2815 2815
          * @param array    $fields_n_values keys are the fields and values are their new values
2816 2816
          * @param EEM_Base $model           the model used
2817 2817
          */
2818
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2818
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2819 2819
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2820 2820
             $main_table = $this->_get_main_table();
2821 2821
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2922,7 +2922,7 @@  discard block
 block discarded – undo
2922 2922
         }
2923 2923
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2924 2924
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2925
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2925
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2926 2926
         }
2927 2927
         //if there is nothing to base this search on, then we shouldn't find anything
2928 2928
         if (empty($query_params)) {
@@ -3008,7 +3008,7 @@  discard block
 block discarded – undo
3008 3008
             //its not the main table, so we should have already saved the main table's PK which we just inserted
3009 3009
             //so add the fk to the main table as a column
3010 3010
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
3011
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
3011
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
3012 3012
         }
3013 3013
         //insert the new entry
3014 3014
         $result = $this->_do_wpdb_query('insert',
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
                     $query_info_carrier,
3213 3213
                     'group_by'
3214 3214
                 );
3215
-            } elseif (! empty ($query_params['group_by'])) {
3215
+            } elseif ( ! empty ($query_params['group_by'])) {
3216 3216
                 $this->_extract_related_model_info_from_query_param(
3217 3217
                     $query_params['group_by'],
3218 3218
                     $query_info_carrier,
@@ -3234,7 +3234,7 @@  discard block
 block discarded – undo
3234 3234
                     $query_info_carrier,
3235 3235
                     'order_by'
3236 3236
                 );
3237
-            } elseif (! empty($query_params['order_by'])) {
3237
+            } elseif ( ! empty($query_params['order_by'])) {
3238 3238
                 $this->_extract_related_model_info_from_query_param(
3239 3239
                     $query_params['order_by'],
3240 3240
                     $query_info_carrier,
@@ -3270,8 +3270,8 @@  discard block
 block discarded – undo
3270 3270
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3271 3271
         $query_param_type
3272 3272
     ) {
3273
-        if (! empty($sub_query_params)) {
3274
-            $sub_query_params = (array)$sub_query_params;
3273
+        if ( ! empty($sub_query_params)) {
3274
+            $sub_query_params = (array) $sub_query_params;
3275 3275
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3276 3276
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3277 3277
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
                 //of array('Registration.TXN_ID'=>23)
3283 3283
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3284 3284
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3285
-                    if (! is_array($possibly_array_of_params)) {
3285
+                    if ( ! is_array($possibly_array_of_params)) {
3286 3286
                         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'))",
3287 3287
                             "event_espresso"),
3288 3288
                             $param, $possibly_array_of_params));
@@ -3299,7 +3299,7 @@  discard block
 block discarded – undo
3299 3299
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3300 3300
                     //indicating that $possible_array_of_params[1] is actually a field name,
3301 3301
                     //from which we should extract query parameters!
3302
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3302
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3303 3303
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3304 3304
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3305 3305
                     }
@@ -3329,8 +3329,8 @@  discard block
 block discarded – undo
3329 3329
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3330 3330
         $query_param_type
3331 3331
     ) {
3332
-        if (! empty($sub_query_params)) {
3333
-            if (! is_array($sub_query_params)) {
3332
+        if ( ! empty($sub_query_params)) {
3333
+            if ( ! is_array($sub_query_params)) {
3334 3334
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3335 3335
                     $sub_query_params));
3336 3336
             }
@@ -3359,7 +3359,7 @@  discard block
 block discarded – undo
3359 3359
      */
3360 3360
     public function _create_model_query_info_carrier($query_params)
3361 3361
     {
3362
-        if (! is_array($query_params)) {
3362
+        if ( ! is_array($query_params)) {
3363 3363
             EE_Error::doing_it_wrong(
3364 3364
                 'EEM_Base::_create_model_query_info_carrier',
3365 3365
                 sprintf(
@@ -3435,7 +3435,7 @@  discard block
 block discarded – undo
3435 3435
         //set limit
3436 3436
         if (array_key_exists('limit', $query_params)) {
3437 3437
             if (is_array($query_params['limit'])) {
3438
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3438
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3439 3439
                     $e = sprintf(
3440 3440
                         __(
3441 3441
                             "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)",
@@ -3443,12 +3443,12 @@  discard block
 block discarded – undo
3443 3443
                         ),
3444 3444
                         http_build_query($query_params['limit'])
3445 3445
                     );
3446
-                    throw new EE_Error($e . "|" . $e);
3446
+                    throw new EE_Error($e."|".$e);
3447 3447
                 }
3448 3448
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3449
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3450
-            } elseif (! empty ($query_params['limit'])) {
3451
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3449
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3450
+            } elseif ( ! empty ($query_params['limit'])) {
3451
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3452 3452
             }
3453 3453
         }
3454 3454
         //set order by
@@ -3480,10 +3480,10 @@  discard block
 block discarded – undo
3480 3480
                 $order_array = array();
3481 3481
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3482 3482
                     $order = $this->_extract_order($order);
3483
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3483
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3484 3484
                 }
3485
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3486
-            } elseif (! empty ($query_params['order_by'])) {
3485
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3486
+            } elseif ( ! empty ($query_params['order_by'])) {
3487 3487
                 $this->_extract_related_model_info_from_query_param(
3488 3488
                     $query_params['order_by'],
3489 3489
                     $query_object,
@@ -3494,18 +3494,18 @@  discard block
 block discarded – undo
3494 3494
                     ? $this->_extract_order($query_params['order'])
3495 3495
                     : 'DESC';
3496 3496
                 $query_object->set_order_by_sql(
3497
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3497
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3498 3498
                 );
3499 3499
             }
3500 3500
         }
3501 3501
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3502
-        if (! array_key_exists('order_by', $query_params)
3502
+        if ( ! array_key_exists('order_by', $query_params)
3503 3503
             && array_key_exists('order', $query_params)
3504 3504
             && ! empty($query_params['order'])
3505 3505
         ) {
3506 3506
             $pk_field = $this->get_primary_key_field();
3507 3507
             $order = $this->_extract_order($query_params['order']);
3508
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3508
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3509 3509
         }
3510 3510
         //set group by
3511 3511
         if (array_key_exists('group_by', $query_params)) {
@@ -3515,10 +3515,10 @@  discard block
 block discarded – undo
3515 3515
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3516 3516
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3517 3517
                 }
3518
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3519
-            } elseif (! empty ($query_params['group_by'])) {
3518
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3519
+            } elseif ( ! empty ($query_params['group_by'])) {
3520 3520
                 $query_object->set_group_by_sql(
3521
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3521
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3522 3522
                 );
3523 3523
             }
3524 3524
         }
@@ -3528,7 +3528,7 @@  discard block
 block discarded – undo
3528 3528
         }
3529 3529
         //now, just verify they didn't pass anything wack
3530 3530
         foreach ($query_params as $query_key => $query_value) {
3531
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3531
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3532 3532
                 throw new EE_Error(
3533 3533
                     sprintf(
3534 3534
                         __(
@@ -3627,22 +3627,22 @@  discard block
 block discarded – undo
3627 3627
         $where_query_params = array()
3628 3628
     ) {
3629 3629
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3630
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3630
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3631 3631
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3632 3632
                 "event_espresso"), $use_default_where_conditions,
3633 3633
                 implode(", ", $allowed_used_default_where_conditions_values)));
3634 3634
         }
3635 3635
         $universal_query_params = array();
3636
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3636
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3637 3637
             $universal_query_params = $this->_get_default_where_conditions();
3638
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3638
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3639 3639
             $universal_query_params = $this->_get_minimum_where_conditions();
3640 3640
         }
3641 3641
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3642 3642
             $related_model = $this->get_related_model_obj($model_name);
3643
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3643
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3644 3644
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3645
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3645
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3646 3646
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3647 3647
             } else {
3648 3648
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3675,7 +3675,7 @@  discard block
 block discarded – undo
3675 3675
      * @param bool $for_this_model false means this is for OTHER related models
3676 3676
      * @return bool
3677 3677
      */
3678
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3678
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3679 3679
     {
3680 3680
         return (
3681 3681
                    $for_this_model
@@ -3754,7 +3754,7 @@  discard block
 block discarded – undo
3754 3754
     ) {
3755 3755
         $null_friendly_where_conditions = array();
3756 3756
         $none_overridden = true;
3757
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3757
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3758 3758
         foreach ($default_where_conditions as $key => $val) {
3759 3759
             if (isset($provided_where_conditions[$key])) {
3760 3760
                 $none_overridden = false;
@@ -3872,7 +3872,7 @@  discard block
 block discarded – undo
3872 3872
             foreach ($tables as $table_obj) {
3873 3873
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3874 3874
                                        . $table_obj->get_fully_qualified_pk_column();
3875
-                if (! in_array($qualified_pk_column, $selects)) {
3875
+                if ( ! in_array($qualified_pk_column, $selects)) {
3876 3876
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3877 3877
                 }
3878 3878
             }
@@ -4018,9 +4018,9 @@  discard block
 block discarded – undo
4018 4018
         $query_parameter_type
4019 4019
     ) {
4020 4020
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4021
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4021
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4022 4022
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4023
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4023
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4024 4024
                 if ($possible_join_string === '') {
4025 4025
                     //nothing left to $query_param
4026 4026
                     //we should actually end in a field name, not a model like this!
@@ -4147,7 +4147,7 @@  discard block
 block discarded – undo
4147 4147
     {
4148 4148
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4149 4149
         if ($SQL) {
4150
-            return " WHERE " . $SQL;
4150
+            return " WHERE ".$SQL;
4151 4151
         }
4152 4152
         return '';
4153 4153
     }
@@ -4166,7 +4166,7 @@  discard block
 block discarded – undo
4166 4166
     {
4167 4167
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4168 4168
         if ($SQL) {
4169
-            return " HAVING " . $SQL;
4169
+            return " HAVING ".$SQL;
4170 4170
         }
4171 4171
         return '';
4172 4172
     }
@@ -4185,7 +4185,7 @@  discard block
 block discarded – undo
4185 4185
     {
4186 4186
         $where_clauses = array();
4187 4187
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4188
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4188
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4189 4189
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4190 4190
                 switch ($query_param) {
4191 4191
                     case 'not':
@@ -4213,7 +4213,7 @@  discard block
 block discarded – undo
4213 4213
             } else {
4214 4214
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4215 4215
                 //if it's not a normal field, maybe it's a custom selection?
4216
-                if (! $field_obj) {
4216
+                if ( ! $field_obj) {
4217 4217
                     if ($this->_custom_selections instanceof CustomSelects) {
4218 4218
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4219 4219
                     } else {
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
                     }
4223 4223
                 }
4224 4224
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4225
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4225
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4226 4226
             }
4227 4227
         }
4228 4228
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4243,7 +4243,7 @@  discard block
 block discarded – undo
4243 4243
         if ($field) {
4244 4244
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4245 4245
                 $query_param);
4246
-            return $table_alias_prefix . $field->get_qualified_column();
4246
+            return $table_alias_prefix.$field->get_qualified_column();
4247 4247
         }
4248 4248
         if ($this->_custom_selections instanceof CustomSelects
4249 4249
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4300,7 +4300,7 @@  discard block
 block discarded – undo
4300 4300
     {
4301 4301
         if (is_array($op_and_value)) {
4302 4302
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4303
-            if (! $operator) {
4303
+            if ( ! $operator) {
4304 4304
                 $php_array_like_string = array();
4305 4305
                 foreach ($op_and_value as $key => $value) {
4306 4306
                     $php_array_like_string[] = "$key=>$value";
@@ -4322,14 +4322,14 @@  discard block
 block discarded – undo
4322 4322
         }
4323 4323
         //check to see if the value is actually another field
4324 4324
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4325
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4325
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4326 4326
         }
4327 4327
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4328 4328
             //in this case, the value should be an array, or at least a comma-separated list
4329 4329
             //it will need to handle a little differently
4330 4330
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4331 4331
             //note: $cleaned_value has already been run through $wpdb->prepare()
4332
-            return $operator . SP . $cleaned_value;
4332
+            return $operator.SP.$cleaned_value;
4333 4333
         }
4334 4334
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4335 4335
             //the value should be an array with count of two.
@@ -4345,7 +4345,7 @@  discard block
 block discarded – undo
4345 4345
                 );
4346 4346
             }
4347 4347
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4348
-            return $operator . SP . $cleaned_value;
4348
+            return $operator.SP.$cleaned_value;
4349 4349
         }
4350 4350
         if (in_array($operator, $this->valid_null_style_operators())) {
4351 4351
             if ($value !== null) {
@@ -4365,10 +4365,10 @@  discard block
 block discarded – undo
4365 4365
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4366 4366
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4367 4367
             //remove other junk. So just treat it as a string.
4368
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4368
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4369 4369
         }
4370
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4370
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4371
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4372 4372
         }
4373 4373
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4374 4374
             throw new EE_Error(
@@ -4382,7 +4382,7 @@  discard block
 block discarded – undo
4382 4382
                 )
4383 4383
             );
4384 4384
         }
4385
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4385
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4386 4386
             throw new EE_Error(
4387 4387
                 sprintf(
4388 4388
                     __(
@@ -4422,7 +4422,7 @@  discard block
 block discarded – undo
4422 4422
         foreach ($values as $value) {
4423 4423
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4424 4424
         }
4425
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4425
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4426 4426
     }
4427 4427
 
4428 4428
 
@@ -4463,7 +4463,7 @@  discard block
 block discarded – undo
4463 4463
                                 . $main_table->get_table_name()
4464 4464
                                 . " WHERE FALSE";
4465 4465
         }
4466
-        return "(" . implode(",", $cleaned_values) . ")";
4466
+        return "(".implode(",", $cleaned_values).")";
4467 4467
     }
4468 4468
 
4469 4469
 
@@ -4482,7 +4482,7 @@  discard block
 block discarded – undo
4482 4482
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4483 4483
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4484 4484
         } //$field_obj should really just be a data type
4485
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4485
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4486 4486
             throw new EE_Error(
4487 4487
                 sprintf(
4488 4488
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4610,10 +4610,10 @@  discard block
 block discarded – undo
4610 4610
      */
4611 4611
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4612 4612
     {
4613
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4613
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4614 4614
         $qualified_columns = array();
4615 4615
         foreach ($this->field_settings() as $field_name => $field) {
4616
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4616
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4617 4617
         }
4618 4618
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4619 4619
     }
@@ -4637,11 +4637,11 @@  discard block
 block discarded – undo
4637 4637
             if ($table_obj instanceof EE_Primary_Table) {
4638 4638
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4639 4639
                     ? $table_obj->get_select_join_limit($limit)
4640
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4640
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4641 4641
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4642 4642
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4643 4643
                     ? $table_obj->get_select_join_limit_join($limit)
4644
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4644
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4645 4645
             }
4646 4646
         }
4647 4647
         return $SQL;
@@ -4729,12 +4729,12 @@  discard block
 block discarded – undo
4729 4729
      */
4730 4730
     public function get_related_model_obj($model_name)
4731 4731
     {
4732
-        $model_classname = "EEM_" . $model_name;
4733
-        if (! class_exists($model_classname)) {
4732
+        $model_classname = "EEM_".$model_name;
4733
+        if ( ! class_exists($model_classname)) {
4734 4734
             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",
4735 4735
                 'event_espresso'), $model_name, $model_classname));
4736 4736
         }
4737
-        return call_user_func($model_classname . "::instance");
4737
+        return call_user_func($model_classname."::instance");
4738 4738
     }
4739 4739
 
4740 4740
 
@@ -4781,7 +4781,7 @@  discard block
 block discarded – undo
4781 4781
     public function related_settings_for($relation_name)
4782 4782
     {
4783 4783
         $relatedModels = $this->relation_settings();
4784
-        if (! array_key_exists($relation_name, $relatedModels)) {
4784
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4785 4785
             throw new EE_Error(
4786 4786
                 sprintf(
4787 4787
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4809,7 +4809,7 @@  discard block
 block discarded – undo
4809 4809
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4810 4810
     {
4811 4811
         $fieldSettings = $this->field_settings($include_db_only_fields);
4812
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4812
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4813 4813
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4814 4814
                 get_class($this)));
4815 4815
         }
@@ -4882,7 +4882,7 @@  discard block
 block discarded – undo
4882 4882
                     break;
4883 4883
                 }
4884 4884
             }
4885
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4885
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4886 4886
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4887 4887
                     get_class($this)));
4888 4888
             }
@@ -4941,7 +4941,7 @@  discard block
 block discarded – undo
4941 4941
      */
4942 4942
     public function get_foreign_key_to($model_name)
4943 4943
     {
4944
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4944
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4945 4945
             foreach ($this->field_settings() as $field) {
4946 4946
                 if (
4947 4947
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4951,7 +4951,7 @@  discard block
 block discarded – undo
4951 4951
                     break;
4952 4952
                 }
4953 4953
             }
4954
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4954
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4955 4955
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4956 4956
                     'event_espresso'), $model_name, get_class($this)));
4957 4957
             }
@@ -5002,7 +5002,7 @@  discard block
 block discarded – undo
5002 5002
             foreach ($this->_fields as $fields_corresponding_to_table) {
5003 5003
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5004 5004
                     /** @var $field_obj EE_Model_Field_Base */
5005
-                    if (! $field_obj->is_db_only_field()) {
5005
+                    if ( ! $field_obj->is_db_only_field()) {
5006 5006
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5007 5007
                     }
5008 5008
                 }
@@ -5031,7 +5031,7 @@  discard block
 block discarded – undo
5031 5031
         $count_if_model_has_no_primary_key = 0;
5032 5032
         $has_primary_key = $this->has_primary_key_field();
5033 5033
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5034
-        foreach ((array)$rows as $row) {
5034
+        foreach ((array) $rows as $row) {
5035 5035
             if (empty($row)) {
5036 5036
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5037 5037
                 return array();
@@ -5049,7 +5049,7 @@  discard block
 block discarded – undo
5049 5049
                 }
5050 5050
             }
5051 5051
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5052
-            if (! $classInstance) {
5052
+            if ( ! $classInstance) {
5053 5053
                 throw new EE_Error(
5054 5054
                     sprintf(
5055 5055
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5168,7 +5168,7 @@  discard block
 block discarded – undo
5168 5168
      */
5169 5169
     public function instantiate_class_from_array_or_object($cols_n_values)
5170 5170
     {
5171
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5171
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5172 5172
             $cols_n_values = get_object_vars($cols_n_values);
5173 5173
         }
5174 5174
         $primary_key = null;
@@ -5193,7 +5193,7 @@  discard block
 block discarded – undo
5193 5193
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5194 5194
         if ($primary_key) {
5195 5195
             $classInstance = $this->get_from_entity_map($primary_key);
5196
-            if (! $classInstance) {
5196
+            if ( ! $classInstance) {
5197 5197
                 $classInstance = EE_Registry::instance()
5198 5198
                                             ->load_class($className,
5199 5199
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5242,12 +5242,12 @@  discard block
 block discarded – undo
5242 5242
     public function add_to_entity_map(EE_Base_Class $object)
5243 5243
     {
5244 5244
         $className = $this->_get_class_name();
5245
-        if (! $object instanceof $className) {
5245
+        if ( ! $object instanceof $className) {
5246 5246
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5247 5247
                 is_object($object) ? get_class($object) : $object, $className));
5248 5248
         }
5249 5249
         /** @var $object EE_Base_Class */
5250
-        if (! $object->ID()) {
5250
+        if ( ! $object->ID()) {
5251 5251
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5252 5252
                 "event_espresso"), get_class($this)));
5253 5253
         }
@@ -5316,7 +5316,7 @@  discard block
 block discarded – undo
5316 5316
             //there is a primary key on this table and its not set. Use defaults for all its columns
5317 5317
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5318 5318
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5319
-                    if (! $field_obj->is_db_only_field()) {
5319
+                    if ( ! $field_obj->is_db_only_field()) {
5320 5320
                         //prepare field as if its coming from db
5321 5321
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5322 5322
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5325,7 +5325,7 @@  discard block
 block discarded – undo
5325 5325
             } else {
5326 5326
                 //the table's rows existed. Use their values
5327 5327
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5328
-                    if (! $field_obj->is_db_only_field()) {
5328
+                    if ( ! $field_obj->is_db_only_field()) {
5329 5329
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5330 5330
                             $cols_n_values, $field_obj->get_qualified_column(),
5331 5331
                             $field_obj->get_table_column()
@@ -5440,7 +5440,7 @@  discard block
 block discarded – undo
5440 5440
      */
5441 5441
     private function _get_class_name()
5442 5442
     {
5443
-        return "EE_" . $this->get_this_model_name();
5443
+        return "EE_".$this->get_this_model_name();
5444 5444
     }
5445 5445
 
5446 5446
 
@@ -5455,7 +5455,7 @@  discard block
 block discarded – undo
5455 5455
      */
5456 5456
     public function item_name($quantity = 1)
5457 5457
     {
5458
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5458
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5459 5459
     }
5460 5460
 
5461 5461
 
@@ -5488,7 +5488,7 @@  discard block
 block discarded – undo
5488 5488
     {
5489 5489
         $className = get_class($this);
5490 5490
         $tagName = "FHEE__{$className}__{$methodName}";
5491
-        if (! has_filter($tagName)) {
5491
+        if ( ! has_filter($tagName)) {
5492 5492
             throw new EE_Error(
5493 5493
                 sprintf(
5494 5494
                     __('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 );',
@@ -5714,7 +5714,7 @@  discard block
 block discarded – undo
5714 5714
         $key_vals_in_combined_pk = array();
5715 5715
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5716 5716
         foreach ($key_fields as $key_field_name => $field_obj) {
5717
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5717
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5718 5718
                 return null;
5719 5719
             }
5720 5720
         }
@@ -5735,7 +5735,7 @@  discard block
 block discarded – undo
5735 5735
     {
5736 5736
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5737 5737
         foreach ($keys_it_should_have as $key) {
5738
-            if (! isset($key_vals[$key])) {
5738
+            if ( ! isset($key_vals[$key])) {
5739 5739
                 return false;
5740 5740
             }
5741 5741
         }
@@ -5789,7 +5789,7 @@  discard block
 block discarded – undo
5789 5789
      */
5790 5790
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5791 5791
     {
5792
-        if (! is_array($query_params)) {
5792
+        if ( ! is_array($query_params)) {
5793 5793
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5794 5794
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5795 5795
                     gettype($query_params)), '4.6.0');
@@ -5855,7 +5855,7 @@  discard block
 block discarded – undo
5855 5855
      * Gets the valid operators
5856 5856
      * @return array keys are accepted strings, values are the SQL they are converted to
5857 5857
      */
5858
-    public function valid_operators(){
5858
+    public function valid_operators() {
5859 5859
         return $this->_valid_operators;
5860 5860
     }
5861 5861
 
@@ -5943,7 +5943,7 @@  discard block
 block discarded – undo
5943 5943
      */
5944 5944
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5945 5945
     {
5946
-        if (! $this->has_primary_key_field()) {
5946
+        if ( ! $this->has_primary_key_field()) {
5947 5947
             if (WP_DEBUG) {
5948 5948
                 EE_Error::add_error(
5949 5949
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5956,7 +5956,7 @@  discard block
 block discarded – undo
5956 5956
         $IDs = array();
5957 5957
         foreach ($model_objects as $model_object) {
5958 5958
             $id = $model_object->ID();
5959
-            if (! $id) {
5959
+            if ( ! $id) {
5960 5960
                 if ($filter_out_empty_ids) {
5961 5961
                     continue;
5962 5962
                 }
@@ -6052,8 +6052,8 @@  discard block
 block discarded – undo
6052 6052
         $missing_caps = array();
6053 6053
         $cap_restrictions = $this->cap_restrictions($context);
6054 6054
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6055
-            if (! EE_Capabilities::instance()
6056
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6055
+            if ( ! EE_Capabilities::instance()
6056
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6057 6057
             ) {
6058 6058
                 $missing_caps[$cap] = $restriction_if_no_cap;
6059 6059
             }
@@ -6205,7 +6205,7 @@  discard block
 block discarded – undo
6205 6205
     {
6206 6206
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6207 6207
             if ($query_param_key === $logic_query_param_key
6208
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6208
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6209 6209
             ) {
6210 6210
                 return true;
6211 6211
             }
Please login to merge, or discard this patch.
core/domain/values/model/CustomSelects.php 2 patches
Indentation   +322 added lines, -322 removed lines patch added patch discarded remove patch
@@ -14,326 +14,326 @@
 block discarded – undo
14 14
  */
15 15
 class CustomSelects
16 16
 {
17
-    const TYPE_SIMPLE = 'simple';
18
-    const TYPE_COMPLEX = 'complex';
19
-    const TYPE_STRUCTURED = 'structured';
20
-
21
-    private $valid_operators = array('COUNT', 'SUM');
22
-
23
-
24
-    /**
25
-     * Original incoming select array
26
-     * @var array
27
-     */
28
-    private $original_selects;
29
-
30
-    /**
31
-     * Select string that can be added to the query
32
-     * @var string
33
-     */
34
-    private $columns_to_select_expression;
35
-
36
-
37
-    /**
38
-     * An array of aliases for the columns included in the incoming select array.
39
-     * @var array
40
-     */
41
-    private $column_aliases_in_select;
42
-
43
-
44
-    /**
45
-     * Enum representation of the "type" of array coming into this value object.
46
-     * @var string
47
-     *
48
-     */
49
-    private $type = '';
50
-
51
-
52
-    /**
53
-     * CustomSelects constructor.
54
-     * Incoming selects can be in one of the following formats:
55
-     * ---- self::TYPE_SIMPLE array ----
56
-     * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
57
-     * multiple columns to select as the values.
58
-     * eg. array( 'ATT_ID', 'REG_ID' )
59
-     * eg. array( '*' )
60
-     * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
61
-     * "structured" method.
62
-     * ---- self::TYPE_COMPLEX array ----
63
-     * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
64
-     * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
65
-     * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
66
-     * EEM_Base::$_valid_wpdb_data_types.
67
-     * eg. array( 'count' => array('count(REG_ID)', '%d') )
68
-     * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
69
-     * ---- self::TYPE_STRUCTURED array ---
70
-     * This is considered the "structured" type. This type is similar to the complex type except that the array attached
71
-     * to the column alias contains three values.  The first value is the qualified column name (which can include
72
-     * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
73
-     * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
74
-     * the second value.
75
-     * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
76
-     * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
77
-     *
78
-     * NOTE: mixing array types in the incoming $select will cause errors.
79
-     *
80
-     * @param array $selects
81
-     * @throws InvalidArgumentException
82
-     */
83
-    public function __construct(array $selects)
84
-    {
85
-        $this->original_selects = $selects;
86
-        $this->deriveType($selects);
87
-        $this->deriveParts($selects);
88
-    }
89
-
90
-
91
-    /**
92
-     * Derives what type of custom select has been sent in.
93
-     * @param array $selects
94
-     * @throws InvalidArgumentException
95
-     */
96
-    private function deriveType(array $selects)
97
-    {
98
-        //first if the first key for this array is an integer then its coming in as a simple format, so we'll also
99
-        // ensure all elements of the array are simple.
100
-        if (is_int(key($selects))) {
101
-            //let's ensure all keys are ints
102
-            $invalid_keys = array_filter(
103
-                array_keys($selects),
104
-                function ($value) {
105
-                    return ! is_int($value);
106
-                }
107
-            );
108
-            if (! empty($invalid_keys)) {
109
-                throw new InvalidArgumentException(
110
-                    sprintf(
111
-                        esc_html__(
112
-                            'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
113
-                            'event_espresso'
114
-                        ),
115
-                        self::TYPE_SIMPLE
116
-                    )
117
-                );
118
-            }
119
-            $this->type = self::TYPE_SIMPLE;
120
-            return;
121
-        }
122
-        //made it here so that means we've got either complex or structured selects.  Let's find out which by popping
123
-        //the first array element off.
124
-        $first_element = reset($selects);
125
-
126
-        if (! is_array($first_element)) {
127
-            throw new InvalidArgumentException(
128
-                sprintf(
129
-                    esc_html__(
130
-                        'Incoming array looks like its formatted as a "%1$s" or "%2$%s" type.  However, the values in the array must be arrays themselves and they are not.',
131
-                        'event_espresso'
132
-                    ),
133
-                    self::TYPE_COMPLEX,
134
-                    self::TYPE_STRUCTURED
135
-                )
136
-            );
137
-        }
138
-        $this->type = count($first_element) === 2
139
-            ? self::TYPE_COMPLEX
140
-            : self::TYPE_STRUCTURED;
141
-    }
142
-
143
-
144
-    /**
145
-     * Sets up the various properties for the vo depending on type.
146
-     * @param array $selects
147
-     * @throws InvalidArgumentException
148
-     */
149
-    private function deriveParts(array $selects)
150
-    {
151
-        $column_parts = array();
152
-        switch ($this->type) {
153
-            case self::TYPE_SIMPLE:
154
-                $column_parts = $selects;
155
-                $this->column_aliases_in_select = $selects;
156
-                break;
157
-            case self::TYPE_COMPLEX:
158
-                foreach ($selects as $alias => $parts) {
159
-                    $this->validateSelectValueForType($parts, $alias);
160
-                    $column_parts[] = "{$parts[0]} AS {$alias}";
161
-                    $this->column_aliases_in_select[] = $alias;
162
-                }
163
-                break;
164
-            case self::TYPE_STRUCTURED:
165
-                foreach ($selects as $alias => $parts) {
166
-                    $this->validateSelectValueForType($parts, $alias);
167
-                    $column_parts[] = $parts[1] !== ''
168
-                        ? $this->assembleSelectStringWithOperator($parts, $alias)
169
-                        : "{$parts[0]} AS {$alias}";
170
-                    $this->column_aliases_in_select[] = $alias;
171
-                }
172
-                break;
173
-        }
174
-        $this->columns_to_select_expression = implode(', ', $column_parts);
175
-    }
176
-
177
-
178
-    /**
179
-     * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
180
-     * @param array $select_parts
181
-     * @param string      $alias
182
-     * @throws InvalidArgumentException
183
-     */
184
-    private function validateSelectValueForType(array $select_parts, $alias)
185
-    {
186
-        $valid_data_types = array('%d', '%s', '%f');
187
-        if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
188
-            throw new InvalidArgumentException(
189
-                sprintf(
190
-                    esc_html__(
191
-                        'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
192
-                        'event_espresso'
193
-                    ),
194
-                    $alias,
195
-                    $this->expectedSelectPartCountForType(),
196
-                    $this->type,
197
-                    count($select_parts)
198
-                )
199
-            );
200
-        }
201
-        //validate data type.
202
-        $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203
-        $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204
-
205
-        if (! in_array($data_type, $valid_data_types, true)) {
206
-            throw new InvalidArgumentException(
207
-                sprintf(
208
-                    esc_html__(
209
-                        'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
210
-                        'event_espresso'
211
-                    ),
212
-                    $data_type,
213
-                    $select_parts[0],
214
-                    $alias,
215
-                    implode(', ', $valid_data_types)
216
-                )
217
-            );
218
-        }
219
-    }
220
-
221
-
222
-    /**
223
-     * Each type will have an expected count of array elements, this returns what that expected count is.
224
-     * @param string $type
225
-     * @return int
226
-     */
227
-    private function expectedSelectPartCountForType($type = '') {
228
-        $type = $type === '' ? $this->type : $type;
229
-        $types_count_map = array(
230
-            self::TYPE_COMPLEX => 2,
231
-            self::TYPE_STRUCTURED => 3
232
-        );
233
-        return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
234
-    }
235
-
236
-
237
-    /**
238
-     * Prepares the select statement part for for structured type selects.
239
-     * @param array  $select_parts
240
-     * @param string $alias
241
-     * @return string
242
-     * @throws InvalidArgumentException
243
-     */
244
-    private function assembleSelectStringWithOperator(array $select_parts, $alias)
245
-    {
246
-        $operator = strtoupper($select_parts[1]);
247
-        //validate operator
248
-        if (! in_array($operator, $this->valid_operators, true)) {
249
-            throw new InvalidArgumentException(
250
-                sprintf(
251
-                    esc_html__(
252
-                        'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
253
-                        'event_espresso'
254
-                    ),
255
-                    $operator,
256
-                    $alias,
257
-                    implode(', ', $this->valid_operators)
258
-                )
259
-            );
260
-        }
261
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
262
-    }
263
-
264
-
265
-    /**
266
-     * Return the datatype from the given select part.
267
-     * Remember the select_part has already been validated on object instantiation.
268
-     * @param array $select_part
269
-     * @return string
270
-     */
271
-    private function getDataTypeForSelectType(array $select_part)
272
-    {
273
-        switch ($this->type) {
274
-            case self::TYPE_COMPLEX:
275
-                return $select_part[1];
276
-            case self::TYPE_STRUCTURED:
277
-                return $select_part[2];
278
-            default:
279
-                return '';
280
-        }
281
-    }
282
-
283
-
284
-    /**
285
-     * Returns the original select array sent into the VO.
286
-     * @return array
287
-     */
288
-    public function originalSelects()
289
-    {
290
-        return $this->original_selects;
291
-    }
292
-
293
-
294
-    /**
295
-     * Returns the final assembled select expression derived from the incoming select array.
296
-     * @return string
297
-     */
298
-    public function columnsToSelectExpression()
299
-    {
300
-        return $this->columns_to_select_expression;
301
-    }
302
-
303
-
304
-    /**
305
-     * Returns all the column aliases derived from the incoming select array.
306
-     * @return array
307
-     */
308
-    public function columnAliases()
309
-    {
310
-        return $this->column_aliases_in_select;
311
-    }
312
-
313
-
314
-    /**
315
-     * Returns the enum type for the incoming select array.
316
-     * @return string
317
-     */
318
-    public function type()
319
-    {
320
-        return $this->type;
321
-    }
322
-
323
-
324
-
325
-    /**
326
-     * Return the datatype for the given column_alias
327
-     * @param string $column_alias
328
-     * @return string  (if there's no data type we return string as the default).
329
-     */
330
-    public function getDataTypeForAlias($column_alias)
331
-    {
332
-        if (isset($this->original_selects[$column_alias])
333
-            && in_array($column_alias, $this->columnAliases(), true)
334
-        ) {
335
-            return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
336
-        }
337
-        return '%s';
338
-    }
17
+	const TYPE_SIMPLE = 'simple';
18
+	const TYPE_COMPLEX = 'complex';
19
+	const TYPE_STRUCTURED = 'structured';
20
+
21
+	private $valid_operators = array('COUNT', 'SUM');
22
+
23
+
24
+	/**
25
+	 * Original incoming select array
26
+	 * @var array
27
+	 */
28
+	private $original_selects;
29
+
30
+	/**
31
+	 * Select string that can be added to the query
32
+	 * @var string
33
+	 */
34
+	private $columns_to_select_expression;
35
+
36
+
37
+	/**
38
+	 * An array of aliases for the columns included in the incoming select array.
39
+	 * @var array
40
+	 */
41
+	private $column_aliases_in_select;
42
+
43
+
44
+	/**
45
+	 * Enum representation of the "type" of array coming into this value object.
46
+	 * @var string
47
+	 *
48
+	 */
49
+	private $type = '';
50
+
51
+
52
+	/**
53
+	 * CustomSelects constructor.
54
+	 * Incoming selects can be in one of the following formats:
55
+	 * ---- self::TYPE_SIMPLE array ----
56
+	 * This is considered the "simple" type. In this case the array is an numerically indexed array with single or
57
+	 * multiple columns to select as the values.
58
+	 * eg. array( 'ATT_ID', 'REG_ID' )
59
+	 * eg. array( '*' )
60
+	 * If you want to use the columns in any WHERE, GROUP BY, or HAVING clauses, you must instead use the "complex" or
61
+	 * "structured" method.
62
+	 * ---- self::TYPE_COMPLEX array ----
63
+	 * This is considered the "complex" type.  In this case the array is indexed by arbitrary strings that serve as
64
+	 * column alias, and the value is an numerically indexed array where there are two values.  The first value (0) is
65
+	 * the selection and the second value (1) is the data type.  Data types must be one of the types defined in
66
+	 * EEM_Base::$_valid_wpdb_data_types.
67
+	 * eg. array( 'count' => array('count(REG_ID)', '%d') )
68
+	 * Complex array configuration allows for using the column alias in any WHERE, GROUP BY, or HAVING clauses.
69
+	 * ---- self::TYPE_STRUCTURED array ---
70
+	 * This is considered the "structured" type. This type is similar to the complex type except that the array attached
71
+	 * to the column alias contains three values.  The first value is the qualified column name (which can include
72
+	 * join syntax for models).  The second value is the operator performed on the column (i.e. 'COUNT', 'SUM' etc).,
73
+	 * the third value is the data type.  Note, if the select does not have an operator, you can use an empty string for
74
+	 * the second value.
75
+	 * Note: for now SUM is only for simple single column expressions (i.e. SUM(Transaction.TXN_total))
76
+	 * eg. array( 'registration_count' => array('Registration.REG_ID', 'count', '%d') );
77
+	 *
78
+	 * NOTE: mixing array types in the incoming $select will cause errors.
79
+	 *
80
+	 * @param array $selects
81
+	 * @throws InvalidArgumentException
82
+	 */
83
+	public function __construct(array $selects)
84
+	{
85
+		$this->original_selects = $selects;
86
+		$this->deriveType($selects);
87
+		$this->deriveParts($selects);
88
+	}
89
+
90
+
91
+	/**
92
+	 * Derives what type of custom select has been sent in.
93
+	 * @param array $selects
94
+	 * @throws InvalidArgumentException
95
+	 */
96
+	private function deriveType(array $selects)
97
+	{
98
+		//first if the first key for this array is an integer then its coming in as a simple format, so we'll also
99
+		// ensure all elements of the array are simple.
100
+		if (is_int(key($selects))) {
101
+			//let's ensure all keys are ints
102
+			$invalid_keys = array_filter(
103
+				array_keys($selects),
104
+				function ($value) {
105
+					return ! is_int($value);
106
+				}
107
+			);
108
+			if (! empty($invalid_keys)) {
109
+				throw new InvalidArgumentException(
110
+					sprintf(
111
+						esc_html__(
112
+							'Incoming array looks like its formatted for "%1$s" type selects, however it has elements that are not indexed numerically',
113
+							'event_espresso'
114
+						),
115
+						self::TYPE_SIMPLE
116
+					)
117
+				);
118
+			}
119
+			$this->type = self::TYPE_SIMPLE;
120
+			return;
121
+		}
122
+		//made it here so that means we've got either complex or structured selects.  Let's find out which by popping
123
+		//the first array element off.
124
+		$first_element = reset($selects);
125
+
126
+		if (! is_array($first_element)) {
127
+			throw new InvalidArgumentException(
128
+				sprintf(
129
+					esc_html__(
130
+						'Incoming array looks like its formatted as a "%1$s" or "%2$%s" type.  However, the values in the array must be arrays themselves and they are not.',
131
+						'event_espresso'
132
+					),
133
+					self::TYPE_COMPLEX,
134
+					self::TYPE_STRUCTURED
135
+				)
136
+			);
137
+		}
138
+		$this->type = count($first_element) === 2
139
+			? self::TYPE_COMPLEX
140
+			: self::TYPE_STRUCTURED;
141
+	}
142
+
143
+
144
+	/**
145
+	 * Sets up the various properties for the vo depending on type.
146
+	 * @param array $selects
147
+	 * @throws InvalidArgumentException
148
+	 */
149
+	private function deriveParts(array $selects)
150
+	{
151
+		$column_parts = array();
152
+		switch ($this->type) {
153
+			case self::TYPE_SIMPLE:
154
+				$column_parts = $selects;
155
+				$this->column_aliases_in_select = $selects;
156
+				break;
157
+			case self::TYPE_COMPLEX:
158
+				foreach ($selects as $alias => $parts) {
159
+					$this->validateSelectValueForType($parts, $alias);
160
+					$column_parts[] = "{$parts[0]} AS {$alias}";
161
+					$this->column_aliases_in_select[] = $alias;
162
+				}
163
+				break;
164
+			case self::TYPE_STRUCTURED:
165
+				foreach ($selects as $alias => $parts) {
166
+					$this->validateSelectValueForType($parts, $alias);
167
+					$column_parts[] = $parts[1] !== ''
168
+						? $this->assembleSelectStringWithOperator($parts, $alias)
169
+						: "{$parts[0]} AS {$alias}";
170
+					$this->column_aliases_in_select[] = $alias;
171
+				}
172
+				break;
173
+		}
174
+		$this->columns_to_select_expression = implode(', ', $column_parts);
175
+	}
176
+
177
+
178
+	/**
179
+	 * Validates self::TYPE_COMPLEX and self::TYPE_STRUCTURED select statement parts.
180
+	 * @param array $select_parts
181
+	 * @param string      $alias
182
+	 * @throws InvalidArgumentException
183
+	 */
184
+	private function validateSelectValueForType(array $select_parts, $alias)
185
+	{
186
+		$valid_data_types = array('%d', '%s', '%f');
187
+		if (count($select_parts) !== $this->expectedSelectPartCountForType()) {
188
+			throw new InvalidArgumentException(
189
+				sprintf(
190
+					esc_html__(
191
+						'The provided select part array for the %1$s column is expected to have a count of %2$d because the incoming select array is of type %3$s.  However the count was %4$d.',
192
+						'event_espresso'
193
+					),
194
+					$alias,
195
+					$this->expectedSelectPartCountForType(),
196
+					$this->type,
197
+					count($select_parts)
198
+				)
199
+			);
200
+		}
201
+		//validate data type.
202
+		$data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203
+		$data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204
+
205
+		if (! in_array($data_type, $valid_data_types, true)) {
206
+			throw new InvalidArgumentException(
207
+				sprintf(
208
+					esc_html__(
209
+						'Datatype %1$s (for selection "%2$s" and alias "%3$s") is not a valid wpdb datatype (eg %%s)',
210
+						'event_espresso'
211
+					),
212
+					$data_type,
213
+					$select_parts[0],
214
+					$alias,
215
+					implode(', ', $valid_data_types)
216
+				)
217
+			);
218
+		}
219
+	}
220
+
221
+
222
+	/**
223
+	 * Each type will have an expected count of array elements, this returns what that expected count is.
224
+	 * @param string $type
225
+	 * @return int
226
+	 */
227
+	private function expectedSelectPartCountForType($type = '') {
228
+		$type = $type === '' ? $this->type : $type;
229
+		$types_count_map = array(
230
+			self::TYPE_COMPLEX => 2,
231
+			self::TYPE_STRUCTURED => 3
232
+		);
233
+		return isset($types_count_map[$type]) ? $types_count_map[$type] : 0;
234
+	}
235
+
236
+
237
+	/**
238
+	 * Prepares the select statement part for for structured type selects.
239
+	 * @param array  $select_parts
240
+	 * @param string $alias
241
+	 * @return string
242
+	 * @throws InvalidArgumentException
243
+	 */
244
+	private function assembleSelectStringWithOperator(array $select_parts, $alias)
245
+	{
246
+		$operator = strtoupper($select_parts[1]);
247
+		//validate operator
248
+		if (! in_array($operator, $this->valid_operators, true)) {
249
+			throw new InvalidArgumentException(
250
+				sprintf(
251
+					esc_html__(
252
+						'An invalid operator has been provided (%1$s) for the column %2$s.  Valid operators must be one of the following: %3$s.',
253
+						'event_espresso'
254
+					),
255
+					$operator,
256
+					$alias,
257
+					implode(', ', $this->valid_operators)
258
+				)
259
+			);
260
+		}
261
+		return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
262
+	}
263
+
264
+
265
+	/**
266
+	 * Return the datatype from the given select part.
267
+	 * Remember the select_part has already been validated on object instantiation.
268
+	 * @param array $select_part
269
+	 * @return string
270
+	 */
271
+	private function getDataTypeForSelectType(array $select_part)
272
+	{
273
+		switch ($this->type) {
274
+			case self::TYPE_COMPLEX:
275
+				return $select_part[1];
276
+			case self::TYPE_STRUCTURED:
277
+				return $select_part[2];
278
+			default:
279
+				return '';
280
+		}
281
+	}
282
+
283
+
284
+	/**
285
+	 * Returns the original select array sent into the VO.
286
+	 * @return array
287
+	 */
288
+	public function originalSelects()
289
+	{
290
+		return $this->original_selects;
291
+	}
292
+
293
+
294
+	/**
295
+	 * Returns the final assembled select expression derived from the incoming select array.
296
+	 * @return string
297
+	 */
298
+	public function columnsToSelectExpression()
299
+	{
300
+		return $this->columns_to_select_expression;
301
+	}
302
+
303
+
304
+	/**
305
+	 * Returns all the column aliases derived from the incoming select array.
306
+	 * @return array
307
+	 */
308
+	public function columnAliases()
309
+	{
310
+		return $this->column_aliases_in_select;
311
+	}
312
+
313
+
314
+	/**
315
+	 * Returns the enum type for the incoming select array.
316
+	 * @return string
317
+	 */
318
+	public function type()
319
+	{
320
+		return $this->type;
321
+	}
322
+
323
+
324
+
325
+	/**
326
+	 * Return the datatype for the given column_alias
327
+	 * @param string $column_alias
328
+	 * @return string  (if there's no data type we return string as the default).
329
+	 */
330
+	public function getDataTypeForAlias($column_alias)
331
+	{
332
+		if (isset($this->original_selects[$column_alias])
333
+			&& in_array($column_alias, $this->columnAliases(), true)
334
+		) {
335
+			return $this->getDataTypeForSelectType($this->original_selects[$column_alias]);
336
+		}
337
+		return '%s';
338
+	}
339 339
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -101,11 +101,11 @@  discard block
 block discarded – undo
101 101
             //let's ensure all keys are ints
102 102
             $invalid_keys = array_filter(
103 103
                 array_keys($selects),
104
-                function ($value) {
104
+                function($value) {
105 105
                     return ! is_int($value);
106 106
                 }
107 107
             );
108
-            if (! empty($invalid_keys)) {
108
+            if ( ! empty($invalid_keys)) {
109 109
                 throw new InvalidArgumentException(
110 110
                     sprintf(
111 111
                         esc_html__(
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
         //the first array element off.
124 124
         $first_element = reset($selects);
125 125
 
126
-        if (! is_array($first_element)) {
126
+        if ( ! is_array($first_element)) {
127 127
             throw new InvalidArgumentException(
128 128
                 sprintf(
129 129
                     esc_html__(
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
         $data_type = $this->type === self::TYPE_COMPLEX ? $select_parts[1] : '';
203 203
         $data_type = $this->type === self::TYPE_STRUCTURED ? $select_parts[2] : $data_type;
204 204
 
205
-        if (! in_array($data_type, $valid_data_types, true)) {
205
+        if ( ! in_array($data_type, $valid_data_types, true)) {
206 206
             throw new InvalidArgumentException(
207 207
                 sprintf(
208 208
                     esc_html__(
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
     {
246 246
         $operator = strtoupper($select_parts[1]);
247 247
         //validate operator
248
-        if (! in_array($operator, $this->valid_operators, true)) {
248
+        if ( ! in_array($operator, $this->valid_operators, true)) {
249 249
             throw new InvalidArgumentException(
250 250
                 sprintf(
251 251
                     esc_html__(
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
                 )
259 259
             );
260 260
         }
261
-        return $operator . '(' . $select_parts[0] . ') AS ' . $alias;
261
+        return $operator.'('.$select_parts[0].') AS '.$alias;
262 262
     }
263 263
 
264 264
 
Please login to merge, or discard this patch.
core/db_classes/EE_Base_Class.class.php 1 patch
Indentation   +2766 added lines, -2766 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 do_action('AHEE_log', __FILE__, ' FILE LOADED', '');
5 5
 
@@ -25,2771 +25,2771 @@  discard block
 block discarded – undo
25 25
 abstract class EE_Base_Class
26 26
 {
27 27
 
28
-    /**
29
-     * This is an array of the original properties and values provided during construction
30
-     * of this model object. (keys are model field names, values are their values).
31
-     * This list is important to remember so that when we are merging data from the db, we know
32
-     * which values to override and which to not override.
33
-     *
34
-     * @var array
35
-     */
36
-    protected $_props_n_values_provided_in_constructor;
37
-
38
-    /**
39
-     * Timezone
40
-     * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
-     * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
-     * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
-     * access to it.
44
-     *
45
-     * @var string
46
-     */
47
-    protected $_timezone;
48
-
49
-
50
-
51
-    /**
52
-     * date format
53
-     * pattern or format for displaying dates
54
-     *
55
-     * @var string $_dt_frmt
56
-     */
57
-    protected $_dt_frmt;
58
-
59
-
60
-
61
-    /**
62
-     * time format
63
-     * pattern or format for displaying time
64
-     *
65
-     * @var string $_tm_frmt
66
-     */
67
-    protected $_tm_frmt;
68
-
69
-
70
-
71
-    /**
72
-     * This property is for holding a cached array of object properties indexed by property name as the key.
73
-     * The purpose of this is for setting a cache on properties that may have calculated values after a
74
-     * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
-     * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
-     *
77
-     * @var array
78
-     */
79
-    protected $_cached_properties = array();
80
-
81
-    /**
82
-     * An array containing keys of the related model, and values are either an array of related mode objects or a
83
-     * single
84
-     * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
-     * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
-     * all others have an array)
87
-     *
88
-     * @var array
89
-     */
90
-    protected $_model_relations = array();
91
-
92
-    /**
93
-     * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
-     * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
-     *
96
-     * @var array
97
-     */
98
-    protected $_fields = array();
99
-
100
-    /**
101
-     * @var boolean indicating whether or not this model object is intended to ever be saved
102
-     * For example, we might create model objects intended to only be used for the duration
103
-     * of this request and to be thrown away, and if they were accidentally saved
104
-     * it would be a bug.
105
-     */
106
-    protected $_allow_persist = true;
107
-
108
-    /**
109
-     * @var boolean indicating whether or not this model object's properties have changed since construction
110
-     */
111
-    protected $_has_changes = false;
112
-
113
-    /**
114
-     * @var EEM_Base
115
-     */
116
-    protected $_model;
117
-
118
-
119
-    /**
120
-     * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
121
-     * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
122
-     * the db.  They also do not automatically update if there are any changes to the data that produced their results.
123
-     * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
124
-     * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
125
-     * array as:
126
-     * array(
127
-     *  'Registration_Count' => 24
128
-     * );
129
-     * Note: if the custom select configuration for the query included a data type, the value will be in the data type
130
-     * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
131
-     * info)
132
-     *
133
-     * @var array
134
-     */
135
-    protected $custom_selection_results = array();
136
-
137
-
138
-
139
-    /**
140
-     * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
141
-     * play nice
142
-     *
143
-     * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
144
-     *                                                         layer of the model's _fields array, (eg, EVT_ID,
145
-     *                                                         TXN_amount, QST_name, etc) and values are their values
146
-     * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
147
-     *                                                         corresponding db model or not.
148
-     * @param string  $timezone                                indicate what timezone you want any datetime fields to
149
-     *                                                         be in when instantiating a EE_Base_Class object.
150
-     * @param array   $date_formats                            An array of date formats to set on construct where first
151
-     *                                                         value is the date_format and second value is the time
152
-     *                                                         format.
153
-     * @throws EE_Error
154
-     */
155
-    protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
156
-    {
157
-        $className = get_class($this);
158
-        do_action("AHEE__{$className}__construct", $this, $fieldValues);
159
-        $model = $this->get_model();
160
-        $model_fields = $model->field_settings(false);
161
-        // ensure $fieldValues is an array
162
-        $fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
163
-        // EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
164
-        // verify client code has not passed any invalid field names
165
-        foreach ($fieldValues as $field_name => $field_value) {
166
-            if ( ! isset($model_fields[$field_name])) {
167
-                throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
168
-                    "event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
169
-            }
170
-        }
171
-        // EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
172
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
173
-        if ( ! empty($date_formats) && is_array($date_formats)) {
174
-            list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
175
-        } else {
176
-            //set default formats for date and time
177
-            $this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
178
-            $this->_tm_frmt = (string)get_option('time_format', 'g:i a');
179
-        }
180
-        //if db model is instantiating
181
-        if ($bydb) {
182
-            //client code has indicated these field values are from the database
183
-            foreach ($model_fields as $fieldName => $field) {
184
-                $this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
185
-            }
186
-        } else {
187
-            //we're constructing a brand
188
-            //new instance of the model object. Generally, this means we'll need to do more field validation
189
-            foreach ($model_fields as $fieldName => $field) {
190
-                $this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
191
-            }
192
-        }
193
-        //remember what values were passed to this constructor
194
-        $this->_props_n_values_provided_in_constructor = $fieldValues;
195
-        //remember in entity mapper
196
-        if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
197
-            $model->add_to_entity_map($this);
198
-        }
199
-        //setup all the relations
200
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
201
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
202
-                $this->_model_relations[$relation_name] = null;
203
-            } else {
204
-                $this->_model_relations[$relation_name] = array();
205
-            }
206
-        }
207
-        /**
208
-         * Action done at the end of each model object construction
209
-         *
210
-         * @param EE_Base_Class $this the model object just created
211
-         */
212
-        do_action('AHEE__EE_Base_Class__construct__finished', $this);
213
-    }
214
-
215
-
216
-
217
-    /**
218
-     * Gets whether or not this model object is allowed to persist/be saved to the database.
219
-     *
220
-     * @return boolean
221
-     */
222
-    public function allow_persist()
223
-    {
224
-        return $this->_allow_persist;
225
-    }
226
-
227
-
228
-
229
-    /**
230
-     * Sets whether or not this model object should be allowed to be saved to the DB.
231
-     * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
232
-     * you got new information that somehow made you change your mind.
233
-     *
234
-     * @param boolean $allow_persist
235
-     * @return boolean
236
-     */
237
-    public function set_allow_persist($allow_persist)
238
-    {
239
-        return $this->_allow_persist = $allow_persist;
240
-    }
241
-
242
-
243
-
244
-    /**
245
-     * Gets the field's original value when this object was constructed during this request.
246
-     * This can be helpful when determining if a model object has changed or not
247
-     *
248
-     * @param string $field_name
249
-     * @return mixed|null
250
-     * @throws \EE_Error
251
-     */
252
-    public function get_original($field_name)
253
-    {
254
-        if (isset($this->_props_n_values_provided_in_constructor[$field_name])
255
-            && $field_settings = $this->get_model()->field_settings_for($field_name)
256
-        ) {
257
-            return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258
-        } else {
259
-            return null;
260
-        }
261
-    }
262
-
263
-
264
-
265
-    /**
266
-     * @param EE_Base_Class $obj
267
-     * @return string
268
-     */
269
-    public function get_class($obj)
270
-    {
271
-        return get_class($obj);
272
-    }
273
-
274
-
275
-
276
-    /**
277
-     * Overrides parent because parent expects old models.
278
-     * This also doesn't do any validation, and won't work for serialized arrays
279
-     *
280
-     * @param    string $field_name
281
-     * @param    mixed  $field_value
282
-     * @param bool      $use_default
283
-     * @throws \EE_Error
284
-     */
285
-    public function set($field_name, $field_value, $use_default = false)
286
-    {
287
-        // if not using default and nothing has changed, and object has already been setup (has ID),
288
-        // then don't do anything
289
-        if (
290
-            ! $use_default
291
-            && $this->_fields[$field_name] === $field_value
292
-            && $this->ID()
293
-        ) {
294
-            return;
295
-        }
296
-        $model = $this->get_model();
297
-        $this->_has_changes = true;
298
-        $field_obj = $model->field_settings_for($field_name);
299
-        if ($field_obj instanceof EE_Model_Field_Base) {
300
-            //			if ( method_exists( $field_obj, 'set_timezone' )) {
301
-            if ($field_obj instanceof EE_Datetime_Field) {
302
-                $field_obj->set_timezone($this->_timezone);
303
-                $field_obj->set_date_format($this->_dt_frmt);
304
-                $field_obj->set_time_format($this->_tm_frmt);
305
-            }
306
-            $holder_of_value = $field_obj->prepare_for_set($field_value);
307
-            //should the value be null?
308
-            if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
309
-                $this->_fields[$field_name] = $field_obj->get_default_value();
310
-                /**
311
-                 * To save having to refactor all the models, if a default value is used for a
312
-                 * EE_Datetime_Field, and that value is not null nor is it a DateTime
313
-                 * object.  Then let's do a set again to ensure that it becomes a DateTime
314
-                 * object.
315
-                 *
316
-                 * @since 4.6.10+
317
-                 */
318
-                if (
319
-                    $field_obj instanceof EE_Datetime_Field
320
-                    && $this->_fields[$field_name] !== null
321
-                    && ! $this->_fields[$field_name] instanceof DateTime
322
-                ) {
323
-                    empty($this->_fields[$field_name])
324
-                        ? $this->set($field_name, time())
325
-                        : $this->set($field_name, $this->_fields[$field_name]);
326
-                }
327
-            } else {
328
-                $this->_fields[$field_name] = $holder_of_value;
329
-            }
330
-            //if we're not in the constructor...
331
-            //now check if what we set was a primary key
332
-            if (
333
-                //note: props_n_values_provided_in_constructor is only set at the END of the constructor
334
-                $this->_props_n_values_provided_in_constructor
335
-                && $field_value
336
-                && $field_name === $model->primary_key_name()
337
-            ) {
338
-                //if so, we want all this object's fields to be filled either with
339
-                //what we've explicitly set on this model
340
-                //or what we have in the db
341
-                // echo "setting primary key!";
342
-                $fields_on_model = self::_get_model(get_class($this))->field_settings();
343
-                $obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
344
-                foreach ($fields_on_model as $field_obj) {
345
-                    if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
-                         && $field_obj->get_name() !== $field_name
347
-                    ) {
348
-                        $this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
-                    }
350
-                }
351
-                //oh this model object has an ID? well make sure its in the entity mapper
352
-                $model->add_to_entity_map($this);
353
-            }
354
-            //let's unset any cache for this field_name from the $_cached_properties property.
355
-            $this->_clear_cached_property($field_name);
356
-        } else {
357
-            throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
358
-                "event_espresso"), $field_name));
359
-        }
360
-    }
361
-
362
-
363
-    /**
364
-     * Set custom select values for model.
365
-     * @param array $custom_select_values
366
-     */
367
-    public function setCustomSelectsValues(array $custom_select_values)
368
-    {
369
-        $this->custom_selection_results = $custom_select_values;
370
-    }
371
-
372
-
373
-    /**
374
-     * Returns the custom select value for the provided alias if its set.
375
-     * If not set, returns null.
376
-     * @param string $alias
377
-     * @return string|int|float|null
378
-     */
379
-    public function getCustomSelect($alias)
380
-    {
381
-        return isset($this->custom_selection_results[$alias])
382
-            ? $this->custom_selection_results[$alias]
383
-            : null;
384
-    }
385
-
386
-
387
-
388
-    /**
389
-     * This sets the field value on the db column if it exists for the given $column_name or
390
-     * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
391
-     *
392
-     * @see EE_message::get_column_value for related documentation on the necessity of this method.
393
-     * @param string $field_name  Must be the exact column name.
394
-     * @param mixed  $field_value The value to set.
395
-     * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
396
-     * @throws \EE_Error
397
-     */
398
-    public function set_field_or_extra_meta($field_name, $field_value)
399
-    {
400
-        if ($this->get_model()->has_field($field_name)) {
401
-            $this->set($field_name, $field_value);
402
-            return true;
403
-        } else {
404
-            //ensure this object is saved first so that extra meta can be properly related.
405
-            $this->save();
406
-            return $this->update_extra_meta($field_name, $field_value);
407
-        }
408
-    }
409
-
410
-
411
-
412
-    /**
413
-     * This retrieves the value of the db column set on this class or if that's not present
414
-     * it will attempt to retrieve from extra_meta if found.
415
-     * Example Usage:
416
-     * Via EE_Message child class:
417
-     * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
418
-     * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
419
-     * also have additional main fields specific to the messenger.  The system accommodates those extra
420
-     * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
421
-     * value for those extra fields dynamically via the EE_message object.
422
-     *
423
-     * @param  string $field_name expecting the fully qualified field name.
424
-     * @return mixed|null  value for the field if found.  null if not found.
425
-     * @throws \EE_Error
426
-     */
427
-    public function get_field_or_extra_meta($field_name)
428
-    {
429
-        if ($this->get_model()->has_field($field_name)) {
430
-            $column_value = $this->get($field_name);
431
-        } else {
432
-            //This isn't a column in the main table, let's see if it is in the extra meta.
433
-            $column_value = $this->get_extra_meta($field_name, true, null);
434
-        }
435
-        return $column_value;
436
-    }
437
-
438
-
439
-
440
-    /**
441
-     * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
442
-     * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
443
-     * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
444
-     * available to all child classes that may be using the EE_Datetime_Field for a field data type.
445
-     *
446
-     * @access public
447
-     * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
448
-     * @return void
449
-     * @throws \EE_Error
450
-     */
451
-    public function set_timezone($timezone = '')
452
-    {
453
-        $this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
454
-        //make sure we clear all cached properties because they won't be relevant now
455
-        $this->_clear_cached_properties();
456
-        //make sure we update field settings and the date for all EE_Datetime_Fields
457
-        $model_fields = $this->get_model()->field_settings(false);
458
-        foreach ($model_fields as $field_name => $field_obj) {
459
-            if ($field_obj instanceof EE_Datetime_Field) {
460
-                $field_obj->set_timezone($this->_timezone);
461
-                if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
462
-                    $this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
463
-                }
464
-            }
465
-        }
466
-    }
467
-
468
-
469
-
470
-    /**
471
-     * This just returns whatever is set for the current timezone.
472
-     *
473
-     * @access public
474
-     * @return string timezone string
475
-     */
476
-    public function get_timezone()
477
-    {
478
-        return $this->_timezone;
479
-    }
480
-
481
-
482
-
483
-    /**
484
-     * This sets the internal date format to what is sent in to be used as the new default for the class
485
-     * internally instead of wp set date format options
486
-     *
487
-     * @since 4.6
488
-     * @param string $format should be a format recognizable by PHP date() functions.
489
-     */
490
-    public function set_date_format($format)
491
-    {
492
-        $this->_dt_frmt = $format;
493
-        //clear cached_properties because they won't be relevant now.
494
-        $this->_clear_cached_properties();
495
-    }
496
-
497
-
498
-
499
-    /**
500
-     * This sets the internal time format string to what is sent in to be used as the new default for the
501
-     * class internally instead of wp set time format options.
502
-     *
503
-     * @since 4.6
504
-     * @param string $format should be a format recognizable by PHP date() functions.
505
-     */
506
-    public function set_time_format($format)
507
-    {
508
-        $this->_tm_frmt = $format;
509
-        //clear cached_properties because they won't be relevant now.
510
-        $this->_clear_cached_properties();
511
-    }
512
-
513
-
514
-
515
-    /**
516
-     * This returns the current internal set format for the date and time formats.
517
-     *
518
-     * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
519
-     *                             where the first value is the date format and the second value is the time format.
520
-     * @return mixed string|array
521
-     */
522
-    public function get_format($full = true)
523
-    {
524
-        return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
525
-    }
526
-
527
-
528
-
529
-    /**
530
-     * cache
531
-     * stores the passed model object on the current model object.
532
-     * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
533
-     *
534
-     * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
535
-     *                                       'Registration' associated with this model object
536
-     * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
537
-     *                                       that could be a payment or a registration)
538
-     * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
539
-     *                                       items which will be stored in an array on this object
540
-     * @throws EE_Error
541
-     * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
542
-     *                  related thing, no array)
543
-     */
544
-    public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
545
-    {
546
-        // its entirely possible that there IS no related object yet in which case there is nothing to cache.
547
-        if ( ! $object_to_cache instanceof EE_Base_Class) {
548
-            return false;
549
-        }
550
-        // also get "how" the object is related, or throw an error
551
-        if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
552
-            throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
553
-                $relationName, get_class($this)));
554
-        }
555
-        // how many things are related ?
556
-        if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
557
-            // if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
558
-            // so for these model objects just set it to be cached
559
-            $this->_model_relations[$relationName] = $object_to_cache;
560
-            $return = true;
561
-        } else {
562
-            // otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
563
-            // eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
564
-            if ( ! is_array($this->_model_relations[$relationName])) {
565
-                // if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
566
-                $this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
567
-                    ? array($this->_model_relations[$relationName]) : array();
568
-            }
569
-            // first check for a cache_id which is normally empty
570
-            if ( ! empty($cache_id)) {
571
-                // if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
572
-                $this->_model_relations[$relationName][$cache_id] = $object_to_cache;
573
-                $return = $cache_id;
574
-            } elseif ($object_to_cache->ID()) {
575
-                // OR the cached object originally came from the db, so let's just use it's PK for an ID
576
-                $this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
577
-                $return = $object_to_cache->ID();
578
-            } else {
579
-                // OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
580
-                $this->_model_relations[$relationName][] = $object_to_cache;
581
-                // move the internal pointer to the end of the array
582
-                end($this->_model_relations[$relationName]);
583
-                // and grab the key so that we can return it
584
-                $return = key($this->_model_relations[$relationName]);
585
-            }
586
-        }
587
-        return $return;
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * For adding an item to the cached_properties property.
594
-     *
595
-     * @access protected
596
-     * @param string      $fieldname the property item the corresponding value is for.
597
-     * @param mixed       $value     The value we are caching.
598
-     * @param string|null $cache_type
599
-     * @return void
600
-     * @throws \EE_Error
601
-     */
602
-    protected function _set_cached_property($fieldname, $value, $cache_type = null)
603
-    {
604
-        //first make sure this property exists
605
-        $this->get_model()->field_settings_for($fieldname);
606
-        $cache_type = empty($cache_type) ? 'standard' : $cache_type;
607
-        $this->_cached_properties[$fieldname][$cache_type] = $value;
608
-    }
609
-
610
-
611
-
612
-    /**
613
-     * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
614
-     * This also SETS the cache if we return the actual property!
615
-     *
616
-     * @param string $fieldname        the name of the property we're trying to retrieve
617
-     * @param bool   $pretty
618
-     * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
619
-     *                                 (in cases where the same property may be used for different outputs
620
-     *                                 - i.e. datetime, money etc.)
621
-     *                                 It can also accept certain pre-defined "schema" strings
622
-     *                                 to define how to output the property.
623
-     *                                 see the field's prepare_for_pretty_echoing for what strings can be used
624
-     * @return mixed                   whatever the value for the property is we're retrieving
625
-     * @throws \EE_Error
626
-     */
627
-    protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
628
-    {
629
-        //verify the field exists
630
-        $model = $this->get_model();
631
-        $model->field_settings_for($fieldname);
632
-        $cache_type = $pretty ? 'pretty' : 'standard';
633
-        $cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
634
-        if (isset($this->_cached_properties[$fieldname][$cache_type])) {
635
-            return $this->_cached_properties[$fieldname][$cache_type];
636
-        }
637
-        $value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
638
-        $this->_set_cached_property($fieldname, $value, $cache_type);
639
-        return $value;
640
-    }
641
-
642
-
643
-
644
-    /**
645
-     * If the cache didn't fetch the needed item, this fetches it.
646
-     * @param string $fieldname
647
-     * @param bool $pretty
648
-     * @param string $extra_cache_ref
649
-     * @return mixed
650
-     */
651
-    protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
652
-    {
653
-        $field_obj = $this->get_model()->field_settings_for($fieldname);
654
-        // If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
655
-        if ($field_obj instanceof EE_Datetime_Field) {
656
-            $this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
657
-        }
658
-        if ( ! isset($this->_fields[$fieldname])) {
659
-            $this->_fields[$fieldname] = null;
660
-        }
661
-        $value = $pretty
662
-            ? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
663
-            : $field_obj->prepare_for_get($this->_fields[$fieldname]);
664
-        return $value;
665
-    }
666
-
667
-
668
-
669
-    /**
670
-     * set timezone, formats, and output for EE_Datetime_Field objects
671
-     *
672
-     * @param \EE_Datetime_Field $datetime_field
673
-     * @param bool               $pretty
674
-     * @param null $date_or_time
675
-     * @return void
676
-     * @throws \EE_Error
677
-     */
678
-    protected function _prepare_datetime_field(
679
-        EE_Datetime_Field $datetime_field,
680
-        $pretty = false,
681
-        $date_or_time = null
682
-    ) {
683
-        $datetime_field->set_timezone($this->_timezone);
684
-        $datetime_field->set_date_format($this->_dt_frmt, $pretty);
685
-        $datetime_field->set_time_format($this->_tm_frmt, $pretty);
686
-        //set the output returned
687
-        switch ($date_or_time) {
688
-            case 'D' :
689
-                $datetime_field->set_date_time_output('date');
690
-                break;
691
-            case 'T' :
692
-                $datetime_field->set_date_time_output('time');
693
-                break;
694
-            default :
695
-                $datetime_field->set_date_time_output();
696
-        }
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * This just takes care of clearing out the cached_properties
703
-     *
704
-     * @return void
705
-     */
706
-    protected function _clear_cached_properties()
707
-    {
708
-        $this->_cached_properties = array();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * This just clears out ONE property if it exists in the cache
715
-     *
716
-     * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
717
-     * @return void
718
-     */
719
-    protected function _clear_cached_property($property_name)
720
-    {
721
-        if (isset($this->_cached_properties[$property_name])) {
722
-            unset($this->_cached_properties[$property_name]);
723
-        }
724
-    }
725
-
726
-
727
-
728
-    /**
729
-     * Ensures that this related thing is a model object.
730
-     *
731
-     * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
732
-     * @param string $model_name   name of the related thing, eg 'Attendee',
733
-     * @return EE_Base_Class
734
-     * @throws \EE_Error
735
-     */
736
-    protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
737
-    {
738
-        $other_model_instance = self::_get_model_instance_with_name(
739
-            self::_get_model_classname($model_name),
740
-            $this->_timezone
741
-        );
742
-        return $other_model_instance->ensure_is_obj($object_or_id);
743
-    }
744
-
745
-
746
-
747
-    /**
748
-     * Forgets the cached model of the given relation Name. So the next time we request it,
749
-     * we will fetch it again from the database. (Handy if you know it's changed somehow).
750
-     * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
751
-     * then only remove that one object from our cached array. Otherwise, clear the entire list
752
-     *
753
-     * @param string $relationName                         one of the keys in the _model_relations array on the model.
754
-     *                                                     Eg 'Registration'
755
-     * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
756
-     *                                                     if you intend to use $clear_all = TRUE, or the relation only
757
-     *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
758
-     * @param bool   $clear_all                            This flags clearing the entire cache relation property if
759
-     *                                                     this is HasMany or HABTM.
760
-     * @throws EE_Error
761
-     * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
762
-     *                       relation from all
763
-     */
764
-    public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
765
-    {
766
-        $relationship_to_model = $this->get_model()->related_settings_for($relationName);
767
-        $index_in_cache = '';
768
-        if ( ! $relationship_to_model) {
769
-            throw new EE_Error(
770
-                sprintf(
771
-                    __("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
772
-                    $relationName,
773
-                    get_class($this)
774
-                )
775
-            );
776
-        }
777
-        if ($clear_all) {
778
-            $obj_removed = true;
779
-            $this->_model_relations[$relationName] = null;
780
-        } elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
781
-            $obj_removed = $this->_model_relations[$relationName];
782
-            $this->_model_relations[$relationName] = null;
783
-        } else {
784
-            if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
785
-                && $object_to_remove_or_index_into_array->ID()
786
-            ) {
787
-                $index_in_cache = $object_to_remove_or_index_into_array->ID();
788
-                if (is_array($this->_model_relations[$relationName])
789
-                    && ! isset($this->_model_relations[$relationName][$index_in_cache])
790
-                ) {
791
-                    $index_found_at = null;
792
-                    //find this object in the array even though it has a different key
793
-                    foreach ($this->_model_relations[$relationName] as $index => $obj) {
794
-                        if (
795
-                            $obj instanceof EE_Base_Class
796
-                            && (
797
-                                $obj == $object_to_remove_or_index_into_array
798
-                                || $obj->ID() === $object_to_remove_or_index_into_array->ID()
799
-                            )
800
-                        ) {
801
-                            $index_found_at = $index;
802
-                            break;
803
-                        }
804
-                    }
805
-                    if ($index_found_at) {
806
-                        $index_in_cache = $index_found_at;
807
-                    } else {
808
-                        //it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
809
-                        //if it wasn't in it to begin with. So we're done
810
-                        return $object_to_remove_or_index_into_array;
811
-                    }
812
-                }
813
-            } elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
814
-                //so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
815
-                foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
816
-                    if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
817
-                        $index_in_cache = $index;
818
-                    }
819
-                }
820
-            } else {
821
-                $index_in_cache = $object_to_remove_or_index_into_array;
822
-            }
823
-            //supposedly we've found it. But it could just be that the client code
824
-            //provided a bad index/object
825
-            if (
826
-            isset(
827
-                $this->_model_relations[$relationName],
828
-                $this->_model_relations[$relationName][$index_in_cache]
829
-            )
830
-            ) {
831
-                $obj_removed = $this->_model_relations[$relationName][$index_in_cache];
832
-                unset($this->_model_relations[$relationName][$index_in_cache]);
833
-            } else {
834
-                //that thing was never cached anyways.
835
-                $obj_removed = null;
836
-            }
837
-        }
838
-        return $obj_removed;
839
-    }
840
-
841
-
842
-
843
-    /**
844
-     * update_cache_after_object_save
845
-     * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
846
-     * obtained after being saved to the db
847
-     *
848
-     * @param string         $relationName       - the type of object that is cached
849
-     * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
850
-     * @param string         $current_cache_id   - the ID that was used when originally caching the object
851
-     * @return boolean TRUE on success, FALSE on fail
852
-     * @throws \EE_Error
853
-     */
854
-    public function update_cache_after_object_save(
855
-        $relationName,
856
-        EE_Base_Class $newly_saved_object,
857
-        $current_cache_id = ''
858
-    ) {
859
-        // verify that incoming object is of the correct type
860
-        $obj_class = 'EE_' . $relationName;
861
-        if ($newly_saved_object instanceof $obj_class) {
862
-            /* @type EE_Base_Class $newly_saved_object */
863
-            // now get the type of relation
864
-            $relationship_to_model = $this->get_model()->related_settings_for($relationName);
865
-            // if this is a 1:1 relationship
866
-            if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
867
-                // then just replace the cached object with the newly saved object
868
-                $this->_model_relations[$relationName] = $newly_saved_object;
869
-                return true;
870
-                // or if it's some kind of sordid feral polyamorous relationship...
871
-            } elseif (is_array($this->_model_relations[$relationName])
872
-                      && isset($this->_model_relations[$relationName][$current_cache_id])
873
-            ) {
874
-                // then remove the current cached item
875
-                unset($this->_model_relations[$relationName][$current_cache_id]);
876
-                // and cache the newly saved object using it's new ID
877
-                $this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
878
-                return true;
879
-            }
880
-        }
881
-        return false;
882
-    }
883
-
884
-
885
-
886
-    /**
887
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
888
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
889
-     *
890
-     * @param string $relationName
891
-     * @return EE_Base_Class
892
-     */
893
-    public function get_one_from_cache($relationName)
894
-    {
895
-        $cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
896
-            : null;
897
-        if (is_array($cached_array_or_object)) {
898
-            return array_shift($cached_array_or_object);
899
-        } else {
900
-            return $cached_array_or_object;
901
-        }
902
-    }
903
-
904
-
905
-
906
-    /**
907
-     * Fetches a single EE_Base_Class on that relation. (If the relation is of type
908
-     * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
909
-     *
910
-     * @param string $relationName
911
-     * @throws \EE_Error
912
-     * @return EE_Base_Class[] NOT necessarily indexed by primary keys
913
-     */
914
-    public function get_all_from_cache($relationName)
915
-    {
916
-        $objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
917
-        // if the result is not an array, but exists, make it an array
918
-        $objects = is_array($objects) ? $objects : array($objects);
919
-        //bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
920
-        //basically, if this model object was stored in the session, and these cached model objects
921
-        //already have IDs, let's make sure they're in their model's entity mapper
922
-        //otherwise we will have duplicates next time we call
923
-        // EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
924
-        $model = EE_Registry::instance()->load_model($relationName);
925
-        foreach ($objects as $model_object) {
926
-            if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
927
-                //ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
928
-                if ($model_object->ID()) {
929
-                    $model->add_to_entity_map($model_object);
930
-                }
931
-            } else {
932
-                throw new EE_Error(
933
-                    sprintf(
934
-                        __(
935
-                            'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
936
-                            'event_espresso'
937
-                        ),
938
-                        $relationName,
939
-                        gettype($model_object)
940
-                    )
941
-                );
942
-            }
943
-        }
944
-        return $objects;
945
-    }
946
-
947
-
948
-
949
-    /**
950
-     * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
951
-     * matching the given query conditions.
952
-     *
953
-     * @param null  $field_to_order_by  What field is being used as the reference point.
954
-     * @param int   $limit              How many objects to return.
955
-     * @param array $query_params       Any additional conditions on the query.
956
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
957
-     *                                  you can indicate just the columns you want returned
958
-     * @return array|EE_Base_Class[]
959
-     * @throws \EE_Error
960
-     */
961
-    public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
962
-    {
963
-        $model = $this->get_model();
964
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
965
-            ? $model->get_primary_key_field()->get_name()
966
-            : $field_to_order_by;
967
-        $current_value = ! empty($field) ? $this->get($field) : null;
968
-        if (empty($field) || empty($current_value)) {
969
-            return array();
970
-        }
971
-        return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
972
-    }
973
-
974
-
975
-
976
-    /**
977
-     * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
978
-     * matching the given query conditions.
979
-     *
980
-     * @param null  $field_to_order_by  What field is being used as the reference point.
981
-     * @param int   $limit              How many objects to return.
982
-     * @param array $query_params       Any additional conditions on the query.
983
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
984
-     *                                  you can indicate just the columns you want returned
985
-     * @return array|EE_Base_Class[]
986
-     * @throws \EE_Error
987
-     */
988
-    public function previous_x(
989
-        $field_to_order_by = null,
990
-        $limit = 1,
991
-        $query_params = array(),
992
-        $columns_to_select = null
993
-    ) {
994
-        $model = $this->get_model();
995
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
996
-            ? $model->get_primary_key_field()->get_name()
997
-            : $field_to_order_by;
998
-        $current_value = ! empty($field) ? $this->get($field) : null;
999
-        if (empty($field) || empty($current_value)) {
1000
-            return array();
1001
-        }
1002
-        return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1003
-    }
1004
-
1005
-
1006
-
1007
-    /**
1008
-     * Returns the next EE_Base_Class object in sequence from this object as found in the database
1009
-     * matching the given query conditions.
1010
-     *
1011
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1012
-     * @param array $query_params       Any additional conditions on the query.
1013
-     * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1014
-     *                                  you can indicate just the columns you want returned
1015
-     * @return array|EE_Base_Class
1016
-     * @throws \EE_Error
1017
-     */
1018
-    public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1019
-    {
1020
-        $model = $this->get_model();
1021
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1022
-            ? $model->get_primary_key_field()->get_name()
1023
-            : $field_to_order_by;
1024
-        $current_value = ! empty($field) ? $this->get($field) : null;
1025
-        if (empty($field) || empty($current_value)) {
1026
-            return array();
1027
-        }
1028
-        return $model->next($current_value, $field, $query_params, $columns_to_select);
1029
-    }
1030
-
1031
-
1032
-
1033
-    /**
1034
-     * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1035
-     * matching the given query conditions.
1036
-     *
1037
-     * @param null  $field_to_order_by  What field is being used as the reference point.
1038
-     * @param array $query_params       Any additional conditions on the query.
1039
-     * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1040
-     *                                  you can indicate just the column you want returned
1041
-     * @return array|EE_Base_Class
1042
-     * @throws \EE_Error
1043
-     */
1044
-    public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1045
-    {
1046
-        $model = $this->get_model();
1047
-        $field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
-            ? $model->get_primary_key_field()->get_name()
1049
-            : $field_to_order_by;
1050
-        $current_value = ! empty($field) ? $this->get($field) : null;
1051
-        if (empty($field) || empty($current_value)) {
1052
-            return array();
1053
-        }
1054
-        return $model->previous($current_value, $field, $query_params, $columns_to_select);
1055
-    }
1056
-
1057
-
1058
-
1059
-    /**
1060
-     * Overrides parent because parent expects old models.
1061
-     * This also doesn't do any validation, and won't work for serialized arrays
1062
-     *
1063
-     * @param string $field_name
1064
-     * @param mixed  $field_value_from_db
1065
-     * @throws \EE_Error
1066
-     */
1067
-    public function set_from_db($field_name, $field_value_from_db)
1068
-    {
1069
-        $field_obj = $this->get_model()->field_settings_for($field_name);
1070
-        if ($field_obj instanceof EE_Model_Field_Base) {
1071
-            //you would think the DB has no NULLs for non-null label fields right? wrong!
1072
-            //eg, a CPT model object could have an entry in the posts table, but no
1073
-            //entry in the meta table. Meaning that all its columns in the meta table
1074
-            //are null! yikes! so when we find one like that, use defaults for its meta columns
1075
-            if ($field_value_from_db === null) {
1076
-                if ($field_obj->is_nullable()) {
1077
-                    //if the field allows nulls, then let it be null
1078
-                    $field_value = null;
1079
-                } else {
1080
-                    $field_value = $field_obj->get_default_value();
1081
-                }
1082
-            } else {
1083
-                $field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1084
-            }
1085
-            $this->_fields[$field_name] = $field_value;
1086
-            $this->_clear_cached_property($field_name);
1087
-        }
1088
-    }
1089
-
1090
-
1091
-
1092
-    /**
1093
-     * verifies that the specified field is of the correct type
1094
-     *
1095
-     * @param string $field_name
1096
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1097
-     *                                (in cases where the same property may be used for different outputs
1098
-     *                                - i.e. datetime, money etc.)
1099
-     * @return mixed
1100
-     * @throws \EE_Error
1101
-     */
1102
-    public function get($field_name, $extra_cache_ref = null)
1103
-    {
1104
-        return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1105
-    }
1106
-
1107
-
1108
-
1109
-    /**
1110
-     * This method simply returns the RAW unprocessed value for the given property in this class
1111
-     *
1112
-     * @param  string $field_name A valid fieldname
1113
-     * @return mixed              Whatever the raw value stored on the property is.
1114
-     * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1115
-     */
1116
-    public function get_raw($field_name)
1117
-    {
1118
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1119
-        return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1120
-            ? $this->_fields[$field_name]->format('U')
1121
-            : $this->_fields[$field_name];
1122
-    }
1123
-
1124
-
1125
-
1126
-    /**
1127
-     * This is used to return the internal DateTime object used for a field that is a
1128
-     * EE_Datetime_Field.
1129
-     *
1130
-     * @param string $field_name               The field name retrieving the DateTime object.
1131
-     * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1132
-     * @throws \EE_Error
1133
-     *                                         an error is set and false returned.  If the field IS an
1134
-     *                                         EE_Datetime_Field and but the field value is null, then
1135
-     *                                         just null is returned (because that indicates that likely
1136
-     *                                         this field is nullable).
1137
-     */
1138
-    public function get_DateTime_object($field_name)
1139
-    {
1140
-        $field_settings = $this->get_model()->field_settings_for($field_name);
1141
-        if ( ! $field_settings instanceof EE_Datetime_Field) {
1142
-            EE_Error::add_error(
1143
-                sprintf(
1144
-                    __(
1145
-                        'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1146
-                        'event_espresso'
1147
-                    ),
1148
-                    $field_name
1149
-                ),
1150
-                __FILE__,
1151
-                __FUNCTION__,
1152
-                __LINE__
1153
-            );
1154
-            return false;
1155
-        }
1156
-        return $this->_fields[$field_name];
1157
-    }
1158
-
1159
-
1160
-
1161
-    /**
1162
-     * To be used in template to immediately echo out the value, and format it for output.
1163
-     * Eg, should call stripslashes and whatnot before echoing
1164
-     *
1165
-     * @param string $field_name      the name of the field as it appears in the DB
1166
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
-     *                                (in cases where the same property may be used for different outputs
1168
-     *                                - i.e. datetime, money etc.)
1169
-     * @return void
1170
-     * @throws \EE_Error
1171
-     */
1172
-    public function e($field_name, $extra_cache_ref = null)
1173
-    {
1174
-        echo $this->get_pretty($field_name, $extra_cache_ref);
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1181
-     * can be easily used as the value of form input.
1182
-     *
1183
-     * @param string $field_name
1184
-     * @return void
1185
-     * @throws \EE_Error
1186
-     */
1187
-    public function f($field_name)
1188
-    {
1189
-        $this->e($field_name, 'form_input');
1190
-    }
1191
-
1192
-    /**
1193
-     * Same as `f()` but just returns the value instead of echoing it
1194
-     * @param string $field_name
1195
-     * @return string
1196
-     */
1197
-    public function get_f($field_name)
1198
-    {
1199
-        return (string)$this->get_pretty($field_name,'form_input');
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1206
-     * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1207
-     * to see what options are available.
1208
-     * @param string $field_name
1209
-     * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1210
-     *                                (in cases where the same property may be used for different outputs
1211
-     *                                - i.e. datetime, money etc.)
1212
-     * @return mixed
1213
-     * @throws \EE_Error
1214
-     */
1215
-    public function get_pretty($field_name, $extra_cache_ref = null)
1216
-    {
1217
-        return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1218
-    }
1219
-
1220
-
1221
-
1222
-    /**
1223
-     * This simply returns the datetime for the given field name
1224
-     * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1225
-     * (and the equivalent e_date, e_time, e_datetime).
1226
-     *
1227
-     * @access   protected
1228
-     * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1229
-     * @param string   $dt_frmt      valid datetime format used for date
1230
-     *                               (if '' then we just use the default on the field,
1231
-     *                               if NULL we use the last-used format)
1232
-     * @param string   $tm_frmt      Same as above except this is for time format
1233
-     * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1234
-     * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1235
-     * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1236
-     *                               if field is not a valid dtt field, or void if echoing
1237
-     * @throws \EE_Error
1238
-     */
1239
-    protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1240
-    {
1241
-        // clear cached property
1242
-        $this->_clear_cached_property($field_name);
1243
-        //reset format properties because they are used in get()
1244
-        $this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1245
-        $this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1246
-        if ($echo) {
1247
-            $this->e($field_name, $date_or_time);
1248
-            return '';
1249
-        }
1250
-        return $this->get($field_name, $date_or_time);
1251
-    }
1252
-
1253
-
1254
-
1255
-    /**
1256
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1257
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1258
-     * other echoes the pretty value for dtt)
1259
-     *
1260
-     * @param  string $field_name name of model object datetime field holding the value
1261
-     * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1262
-     * @return string            datetime value formatted
1263
-     * @throws \EE_Error
1264
-     */
1265
-    public function get_date($field_name, $format = '')
1266
-    {
1267
-        return $this->_get_datetime($field_name, $format, null, 'D');
1268
-    }
1269
-
1270
-
1271
-
1272
-    /**
1273
-     * @param      $field_name
1274
-     * @param string $format
1275
-     * @throws \EE_Error
1276
-     */
1277
-    public function e_date($field_name, $format = '')
1278
-    {
1279
-        $this->_get_datetime($field_name, $format, null, 'D', true);
1280
-    }
1281
-
1282
-
1283
-
1284
-    /**
1285
-     * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1286
-     * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1287
-     * other echoes the pretty value for dtt)
1288
-     *
1289
-     * @param  string $field_name name of model object datetime field holding the value
1290
-     * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1291
-     * @return string             datetime value formatted
1292
-     * @throws \EE_Error
1293
-     */
1294
-    public function get_time($field_name, $format = '')
1295
-    {
1296
-        return $this->_get_datetime($field_name, null, $format, 'T');
1297
-    }
1298
-
1299
-
1300
-
1301
-    /**
1302
-     * @param      $field_name
1303
-     * @param string $format
1304
-     * @throws \EE_Error
1305
-     */
1306
-    public function e_time($field_name, $format = '')
1307
-    {
1308
-        $this->_get_datetime($field_name, null, $format, 'T', true);
1309
-    }
1310
-
1311
-
1312
-
1313
-    /**
1314
-     * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1315
-     * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1316
-     * other echoes the pretty value for dtt)
1317
-     *
1318
-     * @param  string $field_name name of model object datetime field holding the value
1319
-     * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1320
-     * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1321
-     * @return string             datetime value formatted
1322
-     * @throws \EE_Error
1323
-     */
1324
-    public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
-    {
1326
-        return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1327
-    }
1328
-
1329
-
1330
-
1331
-    /**
1332
-     * @param string $field_name
1333
-     * @param string $dt_frmt
1334
-     * @param string $tm_frmt
1335
-     * @throws \EE_Error
1336
-     */
1337
-    public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1338
-    {
1339
-        $this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Get the i8ln value for a date using the WordPress @see date_i18n function.
1346
-     *
1347
-     * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1348
-     * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1349
-     *                           on the object will be used.
1350
-     * @return string Date and time string in set locale or false if no field exists for the given
1351
-     * @throws \EE_Error
1352
-     *                           field name.
1353
-     */
1354
-    public function get_i18n_datetime($field_name, $format = '')
1355
-    {
1356
-        $format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1357
-        return date_i18n(
1358
-            $format,
1359
-            EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1360
-        );
1361
-    }
1362
-
1363
-
1364
-
1365
-    /**
1366
-     * This method validates whether the given field name is a valid field on the model object as well as it is of a
1367
-     * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1368
-     * thrown.
1369
-     *
1370
-     * @param  string $field_name The field name being checked
1371
-     * @throws EE_Error
1372
-     * @return EE_Datetime_Field
1373
-     */
1374
-    protected function _get_dtt_field_settings($field_name)
1375
-    {
1376
-        $field = $this->get_model()->field_settings_for($field_name);
1377
-        //check if field is dtt
1378
-        if ($field instanceof EE_Datetime_Field) {
1379
-            return $field;
1380
-        } else {
1381
-            throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1382
-                'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1383
-        }
1384
-    }
1385
-
1386
-
1387
-
1388
-
1389
-    /**
1390
-     * NOTE ABOUT BELOW:
1391
-     * These convenience date and time setters are for setting date and time independently.  In other words you might
1392
-     * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1393
-     * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1394
-     * method and make sure you send the entire datetime value for setting.
1395
-     */
1396
-    /**
1397
-     * sets the time on a datetime property
1398
-     *
1399
-     * @access protected
1400
-     * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1401
-     * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1402
-     * @throws \EE_Error
1403
-     */
1404
-    protected function _set_time_for($time, $fieldname)
1405
-    {
1406
-        $this->_set_date_time('T', $time, $fieldname);
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * sets the date on a datetime property
1413
-     *
1414
-     * @access protected
1415
-     * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1416
-     * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1417
-     * @throws \EE_Error
1418
-     */
1419
-    protected function _set_date_for($date, $fieldname)
1420
-    {
1421
-        $this->_set_date_time('D', $date, $fieldname);
1422
-    }
1423
-
1424
-
1425
-
1426
-    /**
1427
-     * This takes care of setting a date or time independently on a given model object property. This method also
1428
-     * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1429
-     *
1430
-     * @access protected
1431
-     * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1432
-     * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1433
-     * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1434
-     *                                        EE_Datetime_Field property)
1435
-     * @throws \EE_Error
1436
-     */
1437
-    protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1438
-    {
1439
-        $field = $this->_get_dtt_field_settings($fieldname);
1440
-        $field->set_timezone($this->_timezone);
1441
-        $field->set_date_format($this->_dt_frmt);
1442
-        $field->set_time_format($this->_tm_frmt);
1443
-        switch ($what) {
1444
-            case 'T' :
1445
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1446
-                    $datetime_value,
1447
-                    $this->_fields[$fieldname]
1448
-                );
1449
-                break;
1450
-            case 'D' :
1451
-                $this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1452
-                    $datetime_value,
1453
-                    $this->_fields[$fieldname]
1454
-                );
1455
-                break;
1456
-            case 'B' :
1457
-                $this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1458
-                break;
1459
-        }
1460
-        $this->_clear_cached_property($fieldname);
1461
-    }
1462
-
1463
-
1464
-
1465
-    /**
1466
-     * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1467
-     * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1468
-     * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1469
-     * that could lead to some unexpected results!
1470
-     *
1471
-     * @access public
1472
-     * @param string               $field_name This is the name of the field on the object that contains the date/time
1473
-     *                                         value being returned.
1474
-     * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1475
-     * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1476
-     * @param string               $prepend    You can include something to prepend on the timestamp
1477
-     * @param string               $append     You can include something to append on the timestamp
1478
-     * @throws EE_Error
1479
-     * @return string timestamp
1480
-     */
1481
-    public function display_in_my_timezone(
1482
-        $field_name,
1483
-        $callback = 'get_datetime',
1484
-        $args = null,
1485
-        $prepend = '',
1486
-        $append = ''
1487
-    ) {
1488
-        $timezone = EEH_DTT_Helper::get_timezone();
1489
-        if ($timezone === $this->_timezone) {
1490
-            return '';
1491
-        }
1492
-        $original_timezone = $this->_timezone;
1493
-        $this->set_timezone($timezone);
1494
-        $fn = (array)$field_name;
1495
-        $args = array_merge($fn, (array)$args);
1496
-        if ( ! method_exists($this, $callback)) {
1497
-            throw new EE_Error(
1498
-                sprintf(
1499
-                    __(
1500
-                        'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1501
-                        'event_espresso'
1502
-                    ),
1503
-                    $callback
1504
-                )
1505
-            );
1506
-        }
1507
-        $args = (array)$args;
1508
-        $return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1509
-        $this->set_timezone($original_timezone);
1510
-        return $return;
1511
-    }
1512
-
1513
-
1514
-
1515
-    /**
1516
-     * Deletes this model object.
1517
-     * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1518
-     * override
1519
-     * `EE_Base_Class::_delete` NOT this class.
1520
-     *
1521
-     * @return boolean | int
1522
-     * @throws \EE_Error
1523
-     */
1524
-    public function delete()
1525
-    {
1526
-        /**
1527
-         * Called just before the `EE_Base_Class::_delete` method call.
1528
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1529
-         * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1530
-         * soft deletes (trash) the object and does not permanently delete it.
1531
-         *
1532
-         * @param EE_Base_Class $model_object about to be 'deleted'
1533
-         */
1534
-        do_action('AHEE__EE_Base_Class__delete__before', $this);
1535
-        $result = $this->_delete();
1536
-        /**
1537
-         * Called just after the `EE_Base_Class::_delete` method call.
1538
-         * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1539
-         * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1540
-         * soft deletes (trash) the object and does not permanently delete it.
1541
-         *
1542
-         * @param EE_Base_Class $model_object that was just 'deleted'
1543
-         * @param boolean       $result
1544
-         */
1545
-        do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1546
-        return $result;
1547
-    }
1548
-
1549
-
1550
-
1551
-    /**
1552
-     * Calls the specific delete method for the instantiated class.
1553
-     * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1554
-     * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1555
-     * `EE_Base_Class::delete`
1556
-     *
1557
-     * @return bool|int
1558
-     * @throws \EE_Error
1559
-     */
1560
-    protected function _delete()
1561
-    {
1562
-        return $this->delete_permanently();
1563
-    }
1564
-
1565
-
1566
-
1567
-    /**
1568
-     * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1569
-     * error)
1570
-     *
1571
-     * @return bool | int
1572
-     * @throws \EE_Error
1573
-     */
1574
-    public function delete_permanently()
1575
-    {
1576
-        /**
1577
-         * Called just before HARD deleting a model object
1578
-         *
1579
-         * @param EE_Base_Class $model_object about to be 'deleted'
1580
-         */
1581
-        do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1582
-        $model = $this->get_model();
1583
-        $result = $model->delete_permanently_by_ID($this->ID());
1584
-        $this->refresh_cache_of_related_objects();
1585
-        /**
1586
-         * Called just after HARD deleting a model object
1587
-         *
1588
-         * @param EE_Base_Class $model_object that was just 'deleted'
1589
-         * @param boolean       $result
1590
-         */
1591
-        do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1592
-        return $result;
1593
-    }
1594
-
1595
-
1596
-
1597
-    /**
1598
-     * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1599
-     * related model objects
1600
-     *
1601
-     * @throws \EE_Error
1602
-     */
1603
-    public function refresh_cache_of_related_objects()
1604
-    {
1605
-        $model = $this->get_model();
1606
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1607
-            if ( ! empty($this->_model_relations[$relation_name])) {
1608
-                $related_objects = $this->_model_relations[$relation_name];
1609
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
1610
-                    //this relation only stores a single model object, not an array
1611
-                    //but let's make it consistent
1612
-                    $related_objects = array($related_objects);
1613
-                }
1614
-                foreach ($related_objects as $related_object) {
1615
-                    //only refresh their cache if they're in memory
1616
-                    if ($related_object instanceof EE_Base_Class) {
1617
-                        $related_object->clear_cache($model->get_this_model_name(), $this);
1618
-                    }
1619
-                }
1620
-            }
1621
-        }
1622
-    }
1623
-
1624
-
1625
-
1626
-    /**
1627
-     *        Saves this object to the database. An array may be supplied to set some values on this
1628
-     * object just before saving.
1629
-     *
1630
-     * @access public
1631
-     * @param array $set_cols_n_values keys are field names, values are their new values,
1632
-     *                                 if provided during the save() method (often client code will change the fields'
1633
-     *                                 values before calling save)
1634
-     * @throws \EE_Error
1635
-     * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1636
-     *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1637
-     */
1638
-    public function save($set_cols_n_values = array())
1639
-    {
1640
-        $model = $this->get_model();
1641
-        /**
1642
-         * Filters the fields we're about to save on the model object
1643
-         *
1644
-         * @param array         $set_cols_n_values
1645
-         * @param EE_Base_Class $model_object
1646
-         */
1647
-        $set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1648
-            $this);
1649
-        //set attributes as provided in $set_cols_n_values
1650
-        foreach ($set_cols_n_values as $column => $value) {
1651
-            $this->set($column, $value);
1652
-        }
1653
-        // no changes ? then don't do anything
1654
-        if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1655
-            return 0;
1656
-        }
1657
-        /**
1658
-         * Saving a model object.
1659
-         * Before we perform a save, this action is fired.
1660
-         *
1661
-         * @param EE_Base_Class $model_object the model object about to be saved.
1662
-         */
1663
-        do_action('AHEE__EE_Base_Class__save__begin', $this);
1664
-        if ( ! $this->allow_persist()) {
1665
-            return 0;
1666
-        }
1667
-        //now get current attribute values
1668
-        $save_cols_n_values = $this->_fields;
1669
-        //if the object already has an ID, update it. Otherwise, insert it
1670
-        //also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1671
-        $old_assumption_concerning_value_preparation = $model
1672
-                                                            ->get_assumption_concerning_values_already_prepared_by_model_object();
1673
-        $model->assume_values_already_prepared_by_model_object(true);
1674
-        //does this model have an autoincrement PK?
1675
-        if ($model->has_primary_key_field()) {
1676
-            if ($model->get_primary_key_field()->is_auto_increment()) {
1677
-                //ok check if it's set, if so: update; if not, insert
1678
-                if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1679
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1680
-                } else {
1681
-                    unset($save_cols_n_values[$model->primary_key_name()]);
1682
-                    $results = $model->insert($save_cols_n_values);
1683
-                    if ($results) {
1684
-                        //if successful, set the primary key
1685
-                        //but don't use the normal SET method, because it will check if
1686
-                        //an item with the same ID exists in the mapper & db, then
1687
-                        //will find it in the db (because we just added it) and THAT object
1688
-                        //will get added to the mapper before we can add this one!
1689
-                        //but if we just avoid using the SET method, all that headache can be avoided
1690
-                        $pk_field_name = $model->primary_key_name();
1691
-                        $this->_fields[$pk_field_name] = $results;
1692
-                        $this->_clear_cached_property($pk_field_name);
1693
-                        $model->add_to_entity_map($this);
1694
-                        $this->_update_cached_related_model_objs_fks();
1695
-                    }
1696
-                }
1697
-            } else {//PK is NOT auto-increment
1698
-                //so check if one like it already exists in the db
1699
-                if ($model->exists_by_ID($this->ID())) {
1700
-                    if (WP_DEBUG && ! $this->in_entity_map()) {
1701
-                        throw new EE_Error(
1702
-                            sprintf(
1703
-                                __('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1704
-                                    'event_espresso'),
1705
-                                get_class($this),
1706
-                                get_class($model) . '::instance()->add_to_entity_map()',
1707
-                                get_class($model) . '::instance()->get_one_by_ID()',
1708
-                                '<br />'
1709
-                            )
1710
-                        );
1711
-                    }
1712
-                    $results = $model->update_by_ID($save_cols_n_values, $this->ID());
1713
-                } else {
1714
-                    $results = $model->insert($save_cols_n_values);
1715
-                    $this->_update_cached_related_model_objs_fks();
1716
-                }
1717
-            }
1718
-        } else {//there is NO primary key
1719
-            $already_in_db = false;
1720
-            foreach ($model->unique_indexes() as $index) {
1721
-                $uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1722
-                if ($model->exists(array($uniqueness_where_params))) {
1723
-                    $already_in_db = true;
1724
-                }
1725
-            }
1726
-            if ($already_in_db) {
1727
-                $combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1728
-                    $model->get_combined_primary_key_fields());
1729
-                $results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1730
-            } else {
1731
-                $results = $model->insert($save_cols_n_values);
1732
-            }
1733
-        }
1734
-        //restore the old assumption about values being prepared by the model object
1735
-        $model
1736
-             ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1737
-        /**
1738
-         * After saving the model object this action is called
1739
-         *
1740
-         * @param EE_Base_Class $model_object which was just saved
1741
-         * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1742
-         *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1743
-         */
1744
-        do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1745
-        $this->_has_changes = false;
1746
-        return $results;
1747
-    }
1748
-
1749
-
1750
-
1751
-    /**
1752
-     * Updates the foreign key on related models objects pointing to this to have this model object's ID
1753
-     * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1754
-     * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1755
-     * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1756
-     * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1757
-     * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1758
-     * or not they exist in the DB (if they do, their DB records will be automatically updated)
1759
-     *
1760
-     * @return void
1761
-     * @throws \EE_Error
1762
-     */
1763
-    protected function _update_cached_related_model_objs_fks()
1764
-    {
1765
-        $model = $this->get_model();
1766
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1767
-            if ($relation_obj instanceof EE_Has_Many_Relation) {
1768
-                foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1769
-                    $fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1770
-                        $model->get_this_model_name()
1771
-                    );
1772
-                    $related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1773
-                    if ($related_model_obj_in_cache->ID()) {
1774
-                        $related_model_obj_in_cache->save();
1775
-                    }
1776
-                }
1777
-            }
1778
-        }
1779
-    }
1780
-
1781
-
1782
-
1783
-    /**
1784
-     * Saves this model object and its NEW cached relations to the database.
1785
-     * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1786
-     * In order for that to work, we would need to mark model objects as dirty/clean...
1787
-     * because otherwise, there's a potential for infinite looping of saving
1788
-     * Saves the cached related model objects, and ensures the relation between them
1789
-     * and this object and properly setup
1790
-     *
1791
-     * @return int ID of new model object on save; 0 on failure+
1792
-     * @throws \EE_Error
1793
-     */
1794
-    public function save_new_cached_related_model_objs()
1795
-    {
1796
-        //make sure this has been saved
1797
-        if ( ! $this->ID()) {
1798
-            $id = $this->save();
1799
-        } else {
1800
-            $id = $this->ID();
1801
-        }
1802
-        //now save all the NEW cached model objects  (ie they don't exist in the DB)
1803
-        foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1804
-            if ($this->_model_relations[$relationName]) {
1805
-                //is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1806
-                //or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1807
-                if ($relationObj instanceof EE_Belongs_To_Relation) {
1808
-                    //add a relation to that relation type (which saves the appropriate thing in the process)
1809
-                    //but ONLY if it DOES NOT exist in the DB
1810
-                    /* @var $related_model_obj EE_Base_Class */
1811
-                    $related_model_obj = $this->_model_relations[$relationName];
1812
-                    //					if( ! $related_model_obj->ID()){
1813
-                    $this->_add_relation_to($related_model_obj, $relationName);
1814
-                    $related_model_obj->save_new_cached_related_model_objs();
1815
-                    //					}
1816
-                } else {
1817
-                    foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1818
-                        //add a relation to that relation type (which saves the appropriate thing in the process)
1819
-                        //but ONLY if it DOES NOT exist in the DB
1820
-                        //						if( ! $related_model_obj->ID()){
1821
-                        $this->_add_relation_to($related_model_obj, $relationName);
1822
-                        $related_model_obj->save_new_cached_related_model_objs();
1823
-                        //						}
1824
-                    }
1825
-                }
1826
-            }
1827
-        }
1828
-        return $id;
1829
-    }
1830
-
1831
-
1832
-
1833
-    /**
1834
-     * for getting a model while instantiated.
1835
-     *
1836
-     * @return \EEM_Base | \EEM_CPT_Base
1837
-     */
1838
-    public function get_model()
1839
-    {
1840
-        if( ! $this->_model){
1841
-            $modelName = self::_get_model_classname(get_class($this));
1842
-            $this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1843
-        } else {
1844
-            $this->_model->set_timezone($this->_timezone);
1845
-        }
1846
-
1847
-        return $this->_model;
1848
-    }
1849
-
1850
-
1851
-
1852
-    /**
1853
-     * @param $props_n_values
1854
-     * @param $classname
1855
-     * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1856
-     * @throws \EE_Error
1857
-     */
1858
-    protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1859
-    {
1860
-        //TODO: will not work for Term_Relationships because they have no PK!
1861
-        $primary_id_ref = self::_get_primary_key_name($classname);
1862
-        if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1863
-            $id = $props_n_values[$primary_id_ref];
1864
-            return self::_get_model($classname)->get_from_entity_map($id);
1865
-        }
1866
-        return false;
1867
-    }
1868
-
1869
-
1870
-
1871
-    /**
1872
-     * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1873
-     * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1874
-     * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1875
-     * we return false.
1876
-     *
1877
-     * @param  array  $props_n_values   incoming array of properties and their values
1878
-     * @param  string $classname        the classname of the child class
1879
-     * @param null    $timezone
1880
-     * @param array   $date_formats     incoming date_formats in an array where the first value is the
1881
-     *                                  date_format and the second value is the time format
1882
-     * @return mixed (EE_Base_Class|bool)
1883
-     * @throws \EE_Error
1884
-     */
1885
-    protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1886
-    {
1887
-        $existing = null;
1888
-        $model = self::_get_model($classname, $timezone);
1889
-        if ($model->has_primary_key_field()) {
1890
-            $primary_id_ref = self::_get_primary_key_name($classname);
1891
-            if (array_key_exists($primary_id_ref, $props_n_values)
1892
-                && ! empty($props_n_values[$primary_id_ref])
1893
-            ) {
1894
-                $existing = $model->get_one_by_ID(
1895
-                    $props_n_values[$primary_id_ref]
1896
-                );
1897
-            }
1898
-        } elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1899
-            //no primary key on this model, but there's still a matching item in the DB
1900
-            $existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1901
-                self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1902
-            );
1903
-        }
1904
-        if ($existing) {
1905
-            //set date formats if present before setting values
1906
-            if ( ! empty($date_formats) && is_array($date_formats)) {
1907
-                $existing->set_date_format($date_formats[0]);
1908
-                $existing->set_time_format($date_formats[1]);
1909
-            } else {
1910
-                //set default formats for date and time
1911
-                $existing->set_date_format(get_option('date_format'));
1912
-                $existing->set_time_format(get_option('time_format'));
1913
-            }
1914
-            foreach ($props_n_values as $property => $field_value) {
1915
-                $existing->set($property, $field_value);
1916
-            }
1917
-            return $existing;
1918
-        } else {
1919
-            return false;
1920
-        }
1921
-    }
1922
-
1923
-
1924
-
1925
-    /**
1926
-     * Gets the EEM_*_Model for this class
1927
-     *
1928
-     * @access public now, as this is more convenient
1929
-     * @param      $classname
1930
-     * @param null $timezone
1931
-     * @throws EE_Error
1932
-     * @return EEM_Base
1933
-     */
1934
-    protected static function _get_model($classname, $timezone = null)
1935
-    {
1936
-        //find model for this class
1937
-        if ( ! $classname) {
1938
-            throw new EE_Error(
1939
-                sprintf(
1940
-                    __(
1941
-                        "What were you thinking calling _get_model(%s)?? You need to specify the class name",
1942
-                        "event_espresso"
1943
-                    ),
1944
-                    $classname
1945
-                )
1946
-            );
1947
-        }
1948
-        $modelName = self::_get_model_classname($classname);
1949
-        return self::_get_model_instance_with_name($modelName, $timezone);
1950
-    }
1951
-
1952
-
1953
-
1954
-    /**
1955
-     * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1956
-     *
1957
-     * @param string $model_classname
1958
-     * @param null   $timezone
1959
-     * @return EEM_Base
1960
-     */
1961
-    protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1962
-    {
1963
-        $model_classname = str_replace('EEM_', '', $model_classname);
1964
-        $model = EE_Registry::instance()->load_model($model_classname);
1965
-        $model->set_timezone($timezone);
1966
-        return $model;
1967
-    }
1968
-
1969
-
1970
-
1971
-    /**
1972
-     * If a model name is provided (eg Registration), gets the model classname for that model.
1973
-     * Also works if a model class's classname is provided (eg EE_Registration).
1974
-     *
1975
-     * @param null $model_name
1976
-     * @return string like EEM_Attendee
1977
-     */
1978
-    private static function _get_model_classname($model_name = null)
1979
-    {
1980
-        if (strpos($model_name, "EE_") === 0) {
1981
-            $model_classname = str_replace("EE_", "EEM_", $model_name);
1982
-        } else {
1983
-            $model_classname = "EEM_" . $model_name;
1984
-        }
1985
-        return $model_classname;
1986
-    }
1987
-
1988
-
1989
-
1990
-    /**
1991
-     * returns the name of the primary key attribute
1992
-     *
1993
-     * @param null $classname
1994
-     * @throws EE_Error
1995
-     * @return string
1996
-     */
1997
-    protected static function _get_primary_key_name($classname = null)
1998
-    {
1999
-        if ( ! $classname) {
2000
-            throw new EE_Error(
2001
-                sprintf(
2002
-                    __("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2003
-                    $classname
2004
-                )
2005
-            );
2006
-        }
2007
-        return self::_get_model($classname)->get_primary_key_field()->get_name();
2008
-    }
2009
-
2010
-
2011
-
2012
-    /**
2013
-     * Gets the value of the primary key.
2014
-     * If the object hasn't yet been saved, it should be whatever the model field's default was
2015
-     * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2016
-     * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2017
-     *
2018
-     * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2019
-     * @throws \EE_Error
2020
-     */
2021
-    public function ID()
2022
-    {
2023
-        $model = $this->get_model();
2024
-        //now that we know the name of the variable, use a variable variable to get its value and return its
2025
-        if ($model->has_primary_key_field()) {
2026
-            return $this->_fields[$model->primary_key_name()];
2027
-        } else {
2028
-            return $model->get_index_primary_key_string($this->_fields);
2029
-        }
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2036
-     * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2037
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2038
-     *
2039
-     * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2040
-     * @param string $relationName                     eg 'Events','Question',etc.
2041
-     *                                                 an attendee to a group, you also want to specify which role they
2042
-     *                                                 will have in that group. So you would use this parameter to
2043
-     *                                                 specify array('role-column-name'=>'role-id')
2044
-     * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2045
-     *                                                 allow you to further constrict the relation to being added.
2046
-     *                                                 However, keep in mind that the columns (keys) given must match a
2047
-     *                                                 column on the JOIN table and currently only the HABTM models
2048
-     *                                                 accept these additional conditions.  Also remember that if an
2049
-     *                                                 exact match isn't found for these extra cols/val pairs, then a
2050
-     *                                                 NEW row is created in the join table.
2051
-     * @param null   $cache_id
2052
-     * @throws EE_Error
2053
-     * @return EE_Base_Class the object the relation was added to
2054
-     */
2055
-    public function _add_relation_to(
2056
-        $otherObjectModelObjectOrID,
2057
-        $relationName,
2058
-        $extra_join_model_fields_n_values = array(),
2059
-        $cache_id = null
2060
-    ) {
2061
-        $model = $this->get_model();
2062
-        //if this thing exists in the DB, save the relation to the DB
2063
-        if ($this->ID()) {
2064
-            $otherObject = $model
2065
-                                ->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2066
-                                    $extra_join_model_fields_n_values);
2067
-            //clear cache so future get_many_related and get_first_related() return new results.
2068
-            $this->clear_cache($relationName, $otherObject, true);
2069
-            if ($otherObject instanceof EE_Base_Class) {
2070
-                $otherObject->clear_cache($model->get_this_model_name(), $this);
2071
-            }
2072
-        } else {
2073
-            //this thing doesn't exist in the DB,  so just cache it
2074
-            if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2075
-                throw new EE_Error(sprintf(
2076
-                    __('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2077
-                        'event_espresso'),
2078
-                    $otherObjectModelObjectOrID,
2079
-                    get_class($this)
2080
-                ));
2081
-            } else {
2082
-                $otherObject = $otherObjectModelObjectOrID;
2083
-            }
2084
-            $this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2085
-        }
2086
-        if ($otherObject instanceof EE_Base_Class) {
2087
-            //fix the reciprocal relation too
2088
-            if ($otherObject->ID()) {
2089
-                //its saved so assumed relations exist in the DB, so we can just
2090
-                //clear the cache so future queries use the updated info in the DB
2091
-                $otherObject->clear_cache($model->get_this_model_name(), null, true);
2092
-            } else {
2093
-                //it's not saved, so it caches relations like this
2094
-                $otherObject->cache($model->get_this_model_name(), $this);
2095
-            }
2096
-        }
2097
-        return $otherObject;
2098
-    }
2099
-
2100
-
2101
-
2102
-    /**
2103
-     * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2104
-     * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2105
-     * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2106
-     * from the cache
2107
-     *
2108
-     * @param mixed  $otherObjectModelObjectOrID
2109
-     *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2110
-     *                to the DB yet
2111
-     * @param string $relationName
2112
-     * @param array  $where_query
2113
-     *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2114
-     *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2115
-     *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2116
-     *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2117
-     *                created in the join table.
2118
-     * @return EE_Base_Class the relation was removed from
2119
-     * @throws \EE_Error
2120
-     */
2121
-    public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2122
-    {
2123
-        if ($this->ID()) {
2124
-            //if this exists in the DB, save the relation change to the DB too
2125
-            $otherObject = $this->get_model()
2126
-                                ->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2127
-                                    $where_query);
2128
-            $this->clear_cache($relationName, $otherObject);
2129
-        } else {
2130
-            //this doesn't exist in the DB, just remove it from the cache
2131
-            $otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2132
-        }
2133
-        if ($otherObject instanceof EE_Base_Class) {
2134
-            $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2135
-        }
2136
-        return $otherObject;
2137
-    }
2138
-
2139
-
2140
-
2141
-    /**
2142
-     * Removes ALL the related things for the $relationName.
2143
-     *
2144
-     * @param string $relationName
2145
-     * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2146
-     * @return EE_Base_Class
2147
-     * @throws \EE_Error
2148
-     */
2149
-    public function _remove_relations($relationName, $where_query_params = array())
2150
-    {
2151
-        if ($this->ID()) {
2152
-            //if this exists in the DB, save the relation change to the DB too
2153
-            $otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2154
-            $this->clear_cache($relationName, null, true);
2155
-        } else {
2156
-            //this doesn't exist in the DB, just remove it from the cache
2157
-            $otherObjects = $this->clear_cache($relationName, null, true);
2158
-        }
2159
-        if (is_array($otherObjects)) {
2160
-            foreach ($otherObjects as $otherObject) {
2161
-                $otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2162
-            }
2163
-        }
2164
-        return $otherObjects;
2165
-    }
2166
-
2167
-
2168
-
2169
-    /**
2170
-     * Gets all the related model objects of the specified type. Eg, if the current class if
2171
-     * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2172
-     * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2173
-     * because we want to get even deleted items etc.
2174
-     *
2175
-     * @param string $relationName key in the model's _model_relations array
2176
-     * @param array  $query_params like EEM_Base::get_all
2177
-     * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2178
-     * @throws \EE_Error
2179
-     *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2180
-     *                             you want IDs
2181
-     */
2182
-    public function get_many_related($relationName, $query_params = array())
2183
-    {
2184
-        if ($this->ID()) {
2185
-            //this exists in the DB, so get the related things from either the cache or the DB
2186
-            //if there are query parameters, forget about caching the related model objects.
2187
-            if ($query_params) {
2188
-                $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2189
-            } else {
2190
-                //did we already cache the result of this query?
2191
-                $cached_results = $this->get_all_from_cache($relationName);
2192
-                if ( ! $cached_results) {
2193
-                    $related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2194
-                    //if no query parameters were passed, then we got all the related model objects
2195
-                    //for that relation. We can cache them then.
2196
-                    foreach ($related_model_objects as $related_model_object) {
2197
-                        $this->cache($relationName, $related_model_object);
2198
-                    }
2199
-                } else {
2200
-                    $related_model_objects = $cached_results;
2201
-                }
2202
-            }
2203
-        } else {
2204
-            //this doesn't exist in the DB, so just get the related things from the cache
2205
-            $related_model_objects = $this->get_all_from_cache($relationName);
2206
-        }
2207
-        return $related_model_objects;
2208
-    }
2209
-
2210
-
2211
-
2212
-    /**
2213
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2214
-     * unless otherwise specified in the $query_params
2215
-     *
2216
-     * @param string $relation_name  model_name like 'Event', or 'Registration'
2217
-     * @param array  $query_params   like EEM_Base::get_all's
2218
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2219
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2220
-     *                               that by the setting $distinct to TRUE;
2221
-     * @return int
2222
-     */
2223
-    public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2224
-    {
2225
-        return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2226
-    }
2227
-
2228
-
2229
-
2230
-    /**
2231
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2232
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2233
-     *
2234
-     * @param string $relation_name model_name like 'Event', or 'Registration'
2235
-     * @param array  $query_params  like EEM_Base::get_all's
2236
-     * @param string $field_to_sum  name of field to count by.
2237
-     *                              By default, uses primary key (which doesn't make much sense, so you should probably
2238
-     *                              change it)
2239
-     * @return int
2240
-     */
2241
-    public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2242
-    {
2243
-        return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2244
-    }
2245
-
2246
-
2247
-
2248
-    /**
2249
-     * Gets the first (ie, one) related model object of the specified type.
2250
-     *
2251
-     * @param string $relationName key in the model's _model_relations array
2252
-     * @param array  $query_params like EEM_Base::get_all
2253
-     * @return EE_Base_Class (not an array, a single object)
2254
-     * @throws \EE_Error
2255
-     */
2256
-    public function get_first_related($relationName, $query_params = array())
2257
-    {
2258
-        $model = $this->get_model();
2259
-        if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2260
-            //if they've provided some query parameters, don't bother trying to cache the result
2261
-            //also make sure we're not caching the result of get_first_related
2262
-            //on a relation which should have an array of objects (because the cache might have an array of objects)
2263
-            if ($query_params
2264
-                || ! $model->related_settings_for($relationName)
2265
-                     instanceof
2266
-                     EE_Belongs_To_Relation
2267
-            ) {
2268
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2269
-            } else {
2270
-                //first, check if we've already cached the result of this query
2271
-                $cached_result = $this->get_one_from_cache($relationName);
2272
-                if ( ! $cached_result) {
2273
-                    $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2274
-                    $this->cache($relationName, $related_model_object);
2275
-                } else {
2276
-                    $related_model_object = $cached_result;
2277
-                }
2278
-            }
2279
-        } else {
2280
-            $related_model_object = null;
2281
-            //this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2282
-            if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2283
-                $related_model_object = $model->get_first_related($this, $relationName, $query_params);
2284
-            }
2285
-            //this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2286
-            if ( ! $related_model_object) {
2287
-                $related_model_object = $this->get_one_from_cache($relationName);
2288
-            }
2289
-        }
2290
-        return $related_model_object;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Does a delete on all related objects of type $relationName and removes
2297
-     * the current model object's relation to them. If they can't be deleted (because
2298
-     * of blocking related model objects) does nothing. If the related model objects are
2299
-     * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2300
-     * If this model object doesn't exist yet in the DB, just removes its related things
2301
-     *
2302
-     * @param string $relationName
2303
-     * @param array  $query_params like EEM_Base::get_all's
2304
-     * @return int how many deleted
2305
-     * @throws \EE_Error
2306
-     */
2307
-    public function delete_related($relationName, $query_params = array())
2308
-    {
2309
-        if ($this->ID()) {
2310
-            $count = $this->get_model()->delete_related($this, $relationName, $query_params);
2311
-        } else {
2312
-            $count = count($this->get_all_from_cache($relationName));
2313
-            $this->clear_cache($relationName, null, true);
2314
-        }
2315
-        return $count;
2316
-    }
2317
-
2318
-
2319
-
2320
-    /**
2321
-     * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2322
-     * the current model object's relation to them. If they can't be deleted (because
2323
-     * of blocking related model objects) just does a soft delete on it instead, if possible.
2324
-     * If the related thing isn't a soft-deletable model object, this function is identical
2325
-     * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2326
-     *
2327
-     * @param string $relationName
2328
-     * @param array  $query_params like EEM_Base::get_all's
2329
-     * @return int how many deleted (including those soft deleted)
2330
-     * @throws \EE_Error
2331
-     */
2332
-    public function delete_related_permanently($relationName, $query_params = array())
2333
-    {
2334
-        if ($this->ID()) {
2335
-            $count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2336
-        } else {
2337
-            $count = count($this->get_all_from_cache($relationName));
2338
-        }
2339
-        $this->clear_cache($relationName, null, true);
2340
-        return $count;
2341
-    }
2342
-
2343
-
2344
-
2345
-    /**
2346
-     * is_set
2347
-     * Just a simple utility function children can use for checking if property exists
2348
-     *
2349
-     * @access  public
2350
-     * @param  string $field_name property to check
2351
-     * @return bool                              TRUE if existing,FALSE if not.
2352
-     */
2353
-    public function is_set($field_name)
2354
-    {
2355
-        return isset($this->_fields[$field_name]);
2356
-    }
2357
-
2358
-
2359
-
2360
-    /**
2361
-     * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2362
-     * EE_Error exception if they don't
2363
-     *
2364
-     * @param  mixed (string|array) $properties properties to check
2365
-     * @throws EE_Error
2366
-     * @return bool                              TRUE if existing, throw EE_Error if not.
2367
-     */
2368
-    protected function _property_exists($properties)
2369
-    {
2370
-        foreach ((array)$properties as $property_name) {
2371
-            //first make sure this property exists
2372
-            if ( ! $this->_fields[$property_name]) {
2373
-                throw new EE_Error(
2374
-                    sprintf(
2375
-                        __(
2376
-                            'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2377
-                            'event_espresso'
2378
-                        ),
2379
-                        $property_name
2380
-                    )
2381
-                );
2382
-            }
2383
-        }
2384
-        return true;
2385
-    }
2386
-
2387
-
2388
-
2389
-    /**
2390
-     * This simply returns an array of model fields for this object
2391
-     *
2392
-     * @return array
2393
-     * @throws \EE_Error
2394
-     */
2395
-    public function model_field_array()
2396
-    {
2397
-        $fields = $this->get_model()->field_settings(false);
2398
-        $properties = array();
2399
-        //remove prepended underscore
2400
-        foreach ($fields as $field_name => $settings) {
2401
-            $properties[$field_name] = $this->get($field_name);
2402
-        }
2403
-        return $properties;
2404
-    }
2405
-
2406
-
2407
-
2408
-    /**
2409
-     * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2410
-     * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2411
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2412
-     * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2413
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2414
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2415
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
2416
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
2417
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2418
-     * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2419
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2420
-     *        return $previousReturnValue.$returnString;
2421
-     * }
2422
-     * require('EE_Answer.class.php');
2423
-     * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2424
-     * echo $answer->my_callback('monkeys',100);
2425
-     * //will output "you called my_callback! and passed args:monkeys,100"
2426
-     *
2427
-     * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2428
-     * @param array  $args       array of original arguments passed to the function
2429
-     * @throws EE_Error
2430
-     * @return mixed whatever the plugin which calls add_filter decides
2431
-     */
2432
-    public function __call($methodName, $args)
2433
-    {
2434
-        $className = get_class($this);
2435
-        $tagName = "FHEE__{$className}__{$methodName}";
2436
-        if ( ! has_filter($tagName)) {
2437
-            throw new EE_Error(
2438
-                sprintf(
2439
-                    __(
2440
-                        "Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2441
-                        "event_espresso"
2442
-                    ),
2443
-                    $methodName,
2444
-                    $className,
2445
-                    $tagName
2446
-                )
2447
-            );
2448
-        }
2449
-        return apply_filters($tagName, null, $this, $args);
2450
-    }
2451
-
2452
-
2453
-
2454
-    /**
2455
-     * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2456
-     * A $previous_value can be specified in case there are many meta rows with the same key
2457
-     *
2458
-     * @param string $meta_key
2459
-     * @param mixed  $meta_value
2460
-     * @param mixed  $previous_value
2461
-     * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2462
-     * @throws \EE_Error
2463
-     * NOTE: if the values haven't changed, returns 0
2464
-     */
2465
-    public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2466
-    {
2467
-        $query_params = array(
2468
-            array(
2469
-                'EXM_key'  => $meta_key,
2470
-                'OBJ_ID'   => $this->ID(),
2471
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2472
-            ),
2473
-        );
2474
-        if ($previous_value !== null) {
2475
-            $query_params[0]['EXM_value'] = $meta_value;
2476
-        }
2477
-        $existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2478
-        if ( ! $existing_rows_like_that) {
2479
-            return $this->add_extra_meta($meta_key, $meta_value);
2480
-        }
2481
-        foreach ($existing_rows_like_that as $existing_row) {
2482
-            $existing_row->save(array('EXM_value' => $meta_value));
2483
-        }
2484
-        return count($existing_rows_like_that);
2485
-    }
2486
-
2487
-
2488
-
2489
-    /**
2490
-     * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2491
-     * no other extra meta for this model object have the same key. Returns TRUE if the
2492
-     * extra meta row was entered, false if not
2493
-     *
2494
-     * @param string  $meta_key
2495
-     * @param mixed   $meta_value
2496
-     * @param boolean $unique
2497
-     * @return boolean
2498
-     * @throws \EE_Error
2499
-     */
2500
-    public function add_extra_meta($meta_key, $meta_value, $unique = false)
2501
-    {
2502
-        if ($unique) {
2503
-            $existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2504
-                array(
2505
-                    array(
2506
-                        'EXM_key'  => $meta_key,
2507
-                        'OBJ_ID'   => $this->ID(),
2508
-                        'EXM_type' => $this->get_model()->get_this_model_name(),
2509
-                    ),
2510
-                )
2511
-            );
2512
-            if ($existing_extra_meta) {
2513
-                return false;
2514
-            }
2515
-        }
2516
-        $new_extra_meta = EE_Extra_Meta::new_instance(
2517
-            array(
2518
-                'EXM_key'   => $meta_key,
2519
-                'EXM_value' => $meta_value,
2520
-                'OBJ_ID'    => $this->ID(),
2521
-                'EXM_type'  => $this->get_model()->get_this_model_name(),
2522
-            )
2523
-        );
2524
-        $new_extra_meta->save();
2525
-        return true;
2526
-    }
2527
-
2528
-
2529
-
2530
-    /**
2531
-     * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2532
-     * is specified, only deletes extra meta records with that value.
2533
-     *
2534
-     * @param string $meta_key
2535
-     * @param mixed  $meta_value
2536
-     * @return int number of extra meta rows deleted
2537
-     * @throws \EE_Error
2538
-     */
2539
-    public function delete_extra_meta($meta_key, $meta_value = null)
2540
-    {
2541
-        $query_params = array(
2542
-            array(
2543
-                'EXM_key'  => $meta_key,
2544
-                'OBJ_ID'   => $this->ID(),
2545
-                'EXM_type' => $this->get_model()->get_this_model_name(),
2546
-            ),
2547
-        );
2548
-        if ($meta_value !== null) {
2549
-            $query_params[0]['EXM_value'] = $meta_value;
2550
-        }
2551
-        return EEM_Extra_Meta::instance()->delete($query_params);
2552
-    }
2553
-
2554
-
2555
-
2556
-    /**
2557
-     * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2558
-     * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2559
-     * You can specify $default is case you haven't found the extra meta
2560
-     *
2561
-     * @param string  $meta_key
2562
-     * @param boolean $single
2563
-     * @param mixed   $default if we don't find anything, what should we return?
2564
-     * @return mixed single value if $single; array if ! $single
2565
-     * @throws \EE_Error
2566
-     */
2567
-    public function get_extra_meta($meta_key, $single = false, $default = null)
2568
-    {
2569
-        if ($single) {
2570
-            $result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2571
-            if ($result instanceof EE_Extra_Meta) {
2572
-                return $result->value();
2573
-            }
2574
-        } else {
2575
-            $results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2576
-            if ($results) {
2577
-                $values = array();
2578
-                foreach ($results as $result) {
2579
-                    if ($result instanceof EE_Extra_Meta) {
2580
-                        $values[$result->ID()] = $result->value();
2581
-                    }
2582
-                }
2583
-                return $values;
2584
-            }
2585
-        }
2586
-        //if nothing discovered yet return default.
2587
-        return apply_filters(
2588
-            'FHEE__EE_Base_Class__get_extra_meta__default_value',
2589
-            $default,
2590
-            $meta_key,
2591
-            $single,
2592
-            $this
2593
-            );
2594
-    }
2595
-
2596
-
2597
-
2598
-    /**
2599
-     * Returns a simple array of all the extra meta associated with this model object.
2600
-     * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2601
-     * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2602
-     * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2603
-     * If $one_of_each_key is false, it will return an array with the top-level keys being
2604
-     * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2605
-     * finally the extra meta's value as each sub-value. (eg
2606
-     * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2607
-     *
2608
-     * @param boolean $one_of_each_key
2609
-     * @return array
2610
-     * @throws \EE_Error
2611
-     */
2612
-    public function all_extra_meta_array($one_of_each_key = true)
2613
-    {
2614
-        $return_array = array();
2615
-        if ($one_of_each_key) {
2616
-            $extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2617
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2618
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2619
-                    $return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2620
-                }
2621
-            }
2622
-        } else {
2623
-            $extra_meta_objs = $this->get_many_related('Extra_Meta');
2624
-            foreach ($extra_meta_objs as $extra_meta_obj) {
2625
-                if ($extra_meta_obj instanceof EE_Extra_Meta) {
2626
-                    if ( ! isset($return_array[$extra_meta_obj->key()])) {
2627
-                        $return_array[$extra_meta_obj->key()] = array();
2628
-                    }
2629
-                    $return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2630
-                }
2631
-            }
2632
-        }
2633
-        return $return_array;
2634
-    }
2635
-
2636
-
2637
-
2638
-    /**
2639
-     * Gets a pretty nice displayable nice for this model object. Often overridden
2640
-     *
2641
-     * @return string
2642
-     * @throws \EE_Error
2643
-     */
2644
-    public function name()
2645
-    {
2646
-        //find a field that's not a text field
2647
-        $field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2648
-        if ($field_we_can_use) {
2649
-            return $this->get($field_we_can_use->get_name());
2650
-        } else {
2651
-            $first_few_properties = $this->model_field_array();
2652
-            $first_few_properties = array_slice($first_few_properties, 0, 3);
2653
-            $name_parts = array();
2654
-            foreach ($first_few_properties as $name => $value) {
2655
-                $name_parts[] = "$name:$value";
2656
-            }
2657
-            return implode(",", $name_parts);
2658
-        }
2659
-    }
2660
-
2661
-
2662
-
2663
-    /**
2664
-     * in_entity_map
2665
-     * Checks if this model object has been proven to already be in the entity map
2666
-     *
2667
-     * @return boolean
2668
-     * @throws \EE_Error
2669
-     */
2670
-    public function in_entity_map()
2671
-    {
2672
-        if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2673
-            //well, if we looked, did we find it in the entity map?
2674
-            return true;
2675
-        } else {
2676
-            return false;
2677
-        }
2678
-    }
2679
-
2680
-
2681
-
2682
-    /**
2683
-     * refresh_from_db
2684
-     * Makes sure the fields and values on this model object are in-sync with what's in the database.
2685
-     *
2686
-     * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2687
-     * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2688
-     */
2689
-    public function refresh_from_db()
2690
-    {
2691
-        if ($this->ID() && $this->in_entity_map()) {
2692
-            $this->get_model()->refresh_entity_map_from_db($this->ID());
2693
-        } else {
2694
-            //if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2695
-            //if it has an ID but it's not in the map, and you're asking me to refresh it
2696
-            //that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2697
-            //absolutely nothing in it for this ID
2698
-            if (WP_DEBUG) {
2699
-                throw new EE_Error(
2700
-                    sprintf(
2701
-                        __('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2702
-                            'event_espresso'),
2703
-                        $this->ID(),
2704
-                        get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2705
-                        get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2706
-                    )
2707
-                );
2708
-            }
2709
-        }
2710
-    }
2711
-
2712
-
2713
-
2714
-    /**
2715
-     * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2716
-     * (probably a bad assumption they have made, oh well)
2717
-     *
2718
-     * @return string
2719
-     */
2720
-    public function __toString()
2721
-    {
2722
-        try {
2723
-            return sprintf('%s (%s)', $this->name(), $this->ID());
2724
-        } catch (Exception $e) {
2725
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2726
-            return '';
2727
-        }
2728
-    }
2729
-
2730
-
2731
-
2732
-    /**
2733
-     * Clear related model objects if they're already in the DB, because otherwise when we
2734
-     * UN-serialize this model object we'll need to be careful to add them to the entity map.
2735
-     * This means if we have made changes to those related model objects, and want to unserialize
2736
-     * the this model object on a subsequent request, changes to those related model objects will be lost.
2737
-     * Instead, those related model objects should be directly serialized and stored.
2738
-     * Eg, the following won't work:
2739
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2740
-     * $att = $reg->attendee();
2741
-     * $att->set( 'ATT_fname', 'Dirk' );
2742
-     * update_option( 'my_option', serialize( $reg ) );
2743
-     * //END REQUEST
2744
-     * //START NEXT REQUEST
2745
-     * $reg = get_option( 'my_option' );
2746
-     * $reg->attendee()->save();
2747
-     * And would need to be replace with:
2748
-     * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2749
-     * $att = $reg->attendee();
2750
-     * $att->set( 'ATT_fname', 'Dirk' );
2751
-     * update_option( 'my_option', serialize( $reg ) );
2752
-     * //END REQUEST
2753
-     * //START NEXT REQUEST
2754
-     * $att = get_option( 'my_option' );
2755
-     * $att->save();
2756
-     *
2757
-     * @return array
2758
-     * @throws \EE_Error
2759
-     */
2760
-    public function __sleep()
2761
-    {
2762
-        $model = $this->get_model();
2763
-        foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2764
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
2765
-                $classname = 'EE_' . $model->get_this_model_name();
2766
-                if (
2767
-                    $this->get_one_from_cache($relation_name) instanceof $classname
2768
-                    && $this->get_one_from_cache($relation_name)->ID()
2769
-                ) {
2770
-                    $this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2771
-                }
2772
-            }
2773
-        }
2774
-        $this->_props_n_values_provided_in_constructor = array();
2775
-        $properties_to_serialize = get_object_vars($this);
2776
-        //don't serialize the model. It's big and that risks recursion
2777
-        unset($properties_to_serialize['_model']);
2778
-        return array_keys($properties_to_serialize);
2779
-    }
2780
-
2781
-
2782
-
2783
-    /**
2784
-     * restore _props_n_values_provided_in_constructor
2785
-     * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2786
-     * and therefore should NOT be used to determine if state change has occurred since initial construction.
2787
-     * At best, you would only be able to detect if state change has occurred during THIS request.
2788
-     */
2789
-    public function __wakeup()
2790
-    {
2791
-        $this->_props_n_values_provided_in_constructor = $this->_fields;
2792
-    }
28
+	/**
29
+	 * This is an array of the original properties and values provided during construction
30
+	 * of this model object. (keys are model field names, values are their values).
31
+	 * This list is important to remember so that when we are merging data from the db, we know
32
+	 * which values to override and which to not override.
33
+	 *
34
+	 * @var array
35
+	 */
36
+	protected $_props_n_values_provided_in_constructor;
37
+
38
+	/**
39
+	 * Timezone
40
+	 * This gets set by the "set_timezone()" method so that we know what timezone incoming strings|timestamps are in.
41
+	 * This can also be used before a get to set what timezone you want strings coming out of the object to be in.  NOT
42
+	 * all EE_Base_Class child classes use this property but any that use a EE_Datetime_Field data type will have
43
+	 * access to it.
44
+	 *
45
+	 * @var string
46
+	 */
47
+	protected $_timezone;
48
+
49
+
50
+
51
+	/**
52
+	 * date format
53
+	 * pattern or format for displaying dates
54
+	 *
55
+	 * @var string $_dt_frmt
56
+	 */
57
+	protected $_dt_frmt;
58
+
59
+
60
+
61
+	/**
62
+	 * time format
63
+	 * pattern or format for displaying time
64
+	 *
65
+	 * @var string $_tm_frmt
66
+	 */
67
+	protected $_tm_frmt;
68
+
69
+
70
+
71
+	/**
72
+	 * This property is for holding a cached array of object properties indexed by property name as the key.
73
+	 * The purpose of this is for setting a cache on properties that may have calculated values after a
74
+	 * prepare_for_get.  That way the cache can be checked first and the calculated property returned instead of having
75
+	 * to recalculate. Used by _set_cached_property() and _get_cached_property() methods.
76
+	 *
77
+	 * @var array
78
+	 */
79
+	protected $_cached_properties = array();
80
+
81
+	/**
82
+	 * An array containing keys of the related model, and values are either an array of related mode objects or a
83
+	 * single
84
+	 * related model object. see the model's _model_relations. The keys should match those specified. And if the
85
+	 * relation is of type EE_Belongs_To (or one of its children), then there should only be ONE related model object,
86
+	 * all others have an array)
87
+	 *
88
+	 * @var array
89
+	 */
90
+	protected $_model_relations = array();
91
+
92
+	/**
93
+	 * Array where keys are field names (see the model's _fields property) and values are their values. To see what
94
+	 * their types should be, look at what that field object returns on its prepare_for_get and prepare_for_set methods)
95
+	 *
96
+	 * @var array
97
+	 */
98
+	protected $_fields = array();
99
+
100
+	/**
101
+	 * @var boolean indicating whether or not this model object is intended to ever be saved
102
+	 * For example, we might create model objects intended to only be used for the duration
103
+	 * of this request and to be thrown away, and if they were accidentally saved
104
+	 * it would be a bug.
105
+	 */
106
+	protected $_allow_persist = true;
107
+
108
+	/**
109
+	 * @var boolean indicating whether or not this model object's properties have changed since construction
110
+	 */
111
+	protected $_has_changes = false;
112
+
113
+	/**
114
+	 * @var EEM_Base
115
+	 */
116
+	protected $_model;
117
+
118
+
119
+	/**
120
+	 * This is a cache of results from custom selections done on a query that constructs this entity. The only purpose
121
+	 * for these values is for retrieval of the results, they are not further queryable and they are not persisted to
122
+	 * the db.  They also do not automatically update if there are any changes to the data that produced their results.
123
+	 * The format is a simple array of field_alias => field_value.  So for instance if a custom select was something
124
+	 * like,  "Select COUNT(Registration.REG_ID) as Registration_Count ...", then the resulting value will be in this
125
+	 * array as:
126
+	 * array(
127
+	 *  'Registration_Count' => 24
128
+	 * );
129
+	 * Note: if the custom select configuration for the query included a data type, the value will be in the data type
130
+	 * provided for the query (@see EventEspresso\core\domain\values\model\CustomSelects::__construct phpdocs for more
131
+	 * info)
132
+	 *
133
+	 * @var array
134
+	 */
135
+	protected $custom_selection_results = array();
136
+
137
+
138
+
139
+	/**
140
+	 * basic constructor for Event Espresso classes, performs any necessary initialization, and verifies it's children
141
+	 * play nice
142
+	 *
143
+	 * @param array   $fieldValues                             where each key is a field (ie, array key in the 2nd
144
+	 *                                                         layer of the model's _fields array, (eg, EVT_ID,
145
+	 *                                                         TXN_amount, QST_name, etc) and values are their values
146
+	 * @param boolean $bydb                                    a flag for setting if the class is instantiated by the
147
+	 *                                                         corresponding db model or not.
148
+	 * @param string  $timezone                                indicate what timezone you want any datetime fields to
149
+	 *                                                         be in when instantiating a EE_Base_Class object.
150
+	 * @param array   $date_formats                            An array of date formats to set on construct where first
151
+	 *                                                         value is the date_format and second value is the time
152
+	 *                                                         format.
153
+	 * @throws EE_Error
154
+	 */
155
+	protected function __construct($fieldValues = array(), $bydb = false, $timezone = '', $date_formats = array())
156
+	{
157
+		$className = get_class($this);
158
+		do_action("AHEE__{$className}__construct", $this, $fieldValues);
159
+		$model = $this->get_model();
160
+		$model_fields = $model->field_settings(false);
161
+		// ensure $fieldValues is an array
162
+		$fieldValues = is_array($fieldValues) ? $fieldValues : array($fieldValues);
163
+		// EEH_Debug_Tools::printr( $fieldValues, '$fieldValues  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
164
+		// verify client code has not passed any invalid field names
165
+		foreach ($fieldValues as $field_name => $field_value) {
166
+			if ( ! isset($model_fields[$field_name])) {
167
+				throw new EE_Error(sprintf(__("Invalid field (%s) passed to constructor of %s. Allowed fields are :%s",
168
+					"event_espresso"), $field_name, get_class($this), implode(", ", array_keys($model_fields))));
169
+			}
170
+		}
171
+		// EEH_Debug_Tools::printr( $model_fields, '$model_fields  <br /><span style="font-size:10px;font-weight:normal;">' . __FILE__ . '<br />line no: ' . __LINE__ . '</span>', 'auto' );
172
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
173
+		if ( ! empty($date_formats) && is_array($date_formats)) {
174
+			list($this->_dt_frmt, $this->_tm_frmt) = $date_formats;
175
+		} else {
176
+			//set default formats for date and time
177
+			$this->_dt_frmt = (string)get_option('date_format', 'Y-m-d');
178
+			$this->_tm_frmt = (string)get_option('time_format', 'g:i a');
179
+		}
180
+		//if db model is instantiating
181
+		if ($bydb) {
182
+			//client code has indicated these field values are from the database
183
+			foreach ($model_fields as $fieldName => $field) {
184
+				$this->set_from_db($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null);
185
+			}
186
+		} else {
187
+			//we're constructing a brand
188
+			//new instance of the model object. Generally, this means we'll need to do more field validation
189
+			foreach ($model_fields as $fieldName => $field) {
190
+				$this->set($fieldName, isset($fieldValues[$fieldName]) ? $fieldValues[$fieldName] : null, true);
191
+			}
192
+		}
193
+		//remember what values were passed to this constructor
194
+		$this->_props_n_values_provided_in_constructor = $fieldValues;
195
+		//remember in entity mapper
196
+		if ( ! $bydb && $model->has_primary_key_field() && $this->ID()) {
197
+			$model->add_to_entity_map($this);
198
+		}
199
+		//setup all the relations
200
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
201
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
202
+				$this->_model_relations[$relation_name] = null;
203
+			} else {
204
+				$this->_model_relations[$relation_name] = array();
205
+			}
206
+		}
207
+		/**
208
+		 * Action done at the end of each model object construction
209
+		 *
210
+		 * @param EE_Base_Class $this the model object just created
211
+		 */
212
+		do_action('AHEE__EE_Base_Class__construct__finished', $this);
213
+	}
214
+
215
+
216
+
217
+	/**
218
+	 * Gets whether or not this model object is allowed to persist/be saved to the database.
219
+	 *
220
+	 * @return boolean
221
+	 */
222
+	public function allow_persist()
223
+	{
224
+		return $this->_allow_persist;
225
+	}
226
+
227
+
228
+
229
+	/**
230
+	 * Sets whether or not this model object should be allowed to be saved to the DB.
231
+	 * Normally once this is set to FALSE you wouldn't set it back to TRUE, unless
232
+	 * you got new information that somehow made you change your mind.
233
+	 *
234
+	 * @param boolean $allow_persist
235
+	 * @return boolean
236
+	 */
237
+	public function set_allow_persist($allow_persist)
238
+	{
239
+		return $this->_allow_persist = $allow_persist;
240
+	}
241
+
242
+
243
+
244
+	/**
245
+	 * Gets the field's original value when this object was constructed during this request.
246
+	 * This can be helpful when determining if a model object has changed or not
247
+	 *
248
+	 * @param string $field_name
249
+	 * @return mixed|null
250
+	 * @throws \EE_Error
251
+	 */
252
+	public function get_original($field_name)
253
+	{
254
+		if (isset($this->_props_n_values_provided_in_constructor[$field_name])
255
+			&& $field_settings = $this->get_model()->field_settings_for($field_name)
256
+		) {
257
+			return $field_settings->prepare_for_get($this->_props_n_values_provided_in_constructor[$field_name]);
258
+		} else {
259
+			return null;
260
+		}
261
+	}
262
+
263
+
264
+
265
+	/**
266
+	 * @param EE_Base_Class $obj
267
+	 * @return string
268
+	 */
269
+	public function get_class($obj)
270
+	{
271
+		return get_class($obj);
272
+	}
273
+
274
+
275
+
276
+	/**
277
+	 * Overrides parent because parent expects old models.
278
+	 * This also doesn't do any validation, and won't work for serialized arrays
279
+	 *
280
+	 * @param    string $field_name
281
+	 * @param    mixed  $field_value
282
+	 * @param bool      $use_default
283
+	 * @throws \EE_Error
284
+	 */
285
+	public function set($field_name, $field_value, $use_default = false)
286
+	{
287
+		// if not using default and nothing has changed, and object has already been setup (has ID),
288
+		// then don't do anything
289
+		if (
290
+			! $use_default
291
+			&& $this->_fields[$field_name] === $field_value
292
+			&& $this->ID()
293
+		) {
294
+			return;
295
+		}
296
+		$model = $this->get_model();
297
+		$this->_has_changes = true;
298
+		$field_obj = $model->field_settings_for($field_name);
299
+		if ($field_obj instanceof EE_Model_Field_Base) {
300
+			//			if ( method_exists( $field_obj, 'set_timezone' )) {
301
+			if ($field_obj instanceof EE_Datetime_Field) {
302
+				$field_obj->set_timezone($this->_timezone);
303
+				$field_obj->set_date_format($this->_dt_frmt);
304
+				$field_obj->set_time_format($this->_tm_frmt);
305
+			}
306
+			$holder_of_value = $field_obj->prepare_for_set($field_value);
307
+			//should the value be null?
308
+			if (($field_value === null || $holder_of_value === null || $holder_of_value === '') && $use_default) {
309
+				$this->_fields[$field_name] = $field_obj->get_default_value();
310
+				/**
311
+				 * To save having to refactor all the models, if a default value is used for a
312
+				 * EE_Datetime_Field, and that value is not null nor is it a DateTime
313
+				 * object.  Then let's do a set again to ensure that it becomes a DateTime
314
+				 * object.
315
+				 *
316
+				 * @since 4.6.10+
317
+				 */
318
+				if (
319
+					$field_obj instanceof EE_Datetime_Field
320
+					&& $this->_fields[$field_name] !== null
321
+					&& ! $this->_fields[$field_name] instanceof DateTime
322
+				) {
323
+					empty($this->_fields[$field_name])
324
+						? $this->set($field_name, time())
325
+						: $this->set($field_name, $this->_fields[$field_name]);
326
+				}
327
+			} else {
328
+				$this->_fields[$field_name] = $holder_of_value;
329
+			}
330
+			//if we're not in the constructor...
331
+			//now check if what we set was a primary key
332
+			if (
333
+				//note: props_n_values_provided_in_constructor is only set at the END of the constructor
334
+				$this->_props_n_values_provided_in_constructor
335
+				&& $field_value
336
+				&& $field_name === $model->primary_key_name()
337
+			) {
338
+				//if so, we want all this object's fields to be filled either with
339
+				//what we've explicitly set on this model
340
+				//or what we have in the db
341
+				// echo "setting primary key!";
342
+				$fields_on_model = self::_get_model(get_class($this))->field_settings();
343
+				$obj_in_db = self::_get_model(get_class($this))->get_one_by_ID($field_value);
344
+				foreach ($fields_on_model as $field_obj) {
345
+					if ( ! array_key_exists($field_obj->get_name(), $this->_props_n_values_provided_in_constructor)
346
+						 && $field_obj->get_name() !== $field_name
347
+					) {
348
+						$this->set($field_obj->get_name(), $obj_in_db->get($field_obj->get_name()));
349
+					}
350
+				}
351
+				//oh this model object has an ID? well make sure its in the entity mapper
352
+				$model->add_to_entity_map($this);
353
+			}
354
+			//let's unset any cache for this field_name from the $_cached_properties property.
355
+			$this->_clear_cached_property($field_name);
356
+		} else {
357
+			throw new EE_Error(sprintf(__("A valid EE_Model_Field_Base could not be found for the given field name: %s",
358
+				"event_espresso"), $field_name));
359
+		}
360
+	}
361
+
362
+
363
+	/**
364
+	 * Set custom select values for model.
365
+	 * @param array $custom_select_values
366
+	 */
367
+	public function setCustomSelectsValues(array $custom_select_values)
368
+	{
369
+		$this->custom_selection_results = $custom_select_values;
370
+	}
371
+
372
+
373
+	/**
374
+	 * Returns the custom select value for the provided alias if its set.
375
+	 * If not set, returns null.
376
+	 * @param string $alias
377
+	 * @return string|int|float|null
378
+	 */
379
+	public function getCustomSelect($alias)
380
+	{
381
+		return isset($this->custom_selection_results[$alias])
382
+			? $this->custom_selection_results[$alias]
383
+			: null;
384
+	}
385
+
386
+
387
+
388
+	/**
389
+	 * This sets the field value on the db column if it exists for the given $column_name or
390
+	 * saves it to EE_Extra_Meta if the given $column_name does not match a db column.
391
+	 *
392
+	 * @see EE_message::get_column_value for related documentation on the necessity of this method.
393
+	 * @param string $field_name  Must be the exact column name.
394
+	 * @param mixed  $field_value The value to set.
395
+	 * @return int|bool @see EE_Base_Class::update_extra_meta() for return docs.
396
+	 * @throws \EE_Error
397
+	 */
398
+	public function set_field_or_extra_meta($field_name, $field_value)
399
+	{
400
+		if ($this->get_model()->has_field($field_name)) {
401
+			$this->set($field_name, $field_value);
402
+			return true;
403
+		} else {
404
+			//ensure this object is saved first so that extra meta can be properly related.
405
+			$this->save();
406
+			return $this->update_extra_meta($field_name, $field_value);
407
+		}
408
+	}
409
+
410
+
411
+
412
+	/**
413
+	 * This retrieves the value of the db column set on this class or if that's not present
414
+	 * it will attempt to retrieve from extra_meta if found.
415
+	 * Example Usage:
416
+	 * Via EE_Message child class:
417
+	 * Due to the dynamic nature of the EE_messages system, EE_messengers will always have a "to",
418
+	 * "from", "subject", and "content" field (as represented in the EE_Message schema), however they may
419
+	 * also have additional main fields specific to the messenger.  The system accommodates those extra
420
+	 * fields through the EE_Extra_Meta table.  This method allows for EE_messengers to retrieve the
421
+	 * value for those extra fields dynamically via the EE_message object.
422
+	 *
423
+	 * @param  string $field_name expecting the fully qualified field name.
424
+	 * @return mixed|null  value for the field if found.  null if not found.
425
+	 * @throws \EE_Error
426
+	 */
427
+	public function get_field_or_extra_meta($field_name)
428
+	{
429
+		if ($this->get_model()->has_field($field_name)) {
430
+			$column_value = $this->get($field_name);
431
+		} else {
432
+			//This isn't a column in the main table, let's see if it is in the extra meta.
433
+			$column_value = $this->get_extra_meta($field_name, true, null);
434
+		}
435
+		return $column_value;
436
+	}
437
+
438
+
439
+
440
+	/**
441
+	 * See $_timezone property for description of what the timezone property is for.  This SETS the timezone internally
442
+	 * for being able to reference what timezone we are running conversions on when converting TO the internal timezone
443
+	 * (UTC Unix Timestamp) for the object OR when converting FROM the internal timezone (UTC Unix Timestamp). This is
444
+	 * available to all child classes that may be using the EE_Datetime_Field for a field data type.
445
+	 *
446
+	 * @access public
447
+	 * @param string $timezone A valid timezone string as described by @link http://www.php.net/manual/en/timezones.php
448
+	 * @return void
449
+	 * @throws \EE_Error
450
+	 */
451
+	public function set_timezone($timezone = '')
452
+	{
453
+		$this->_timezone = EEH_DTT_Helper::get_valid_timezone_string($timezone);
454
+		//make sure we clear all cached properties because they won't be relevant now
455
+		$this->_clear_cached_properties();
456
+		//make sure we update field settings and the date for all EE_Datetime_Fields
457
+		$model_fields = $this->get_model()->field_settings(false);
458
+		foreach ($model_fields as $field_name => $field_obj) {
459
+			if ($field_obj instanceof EE_Datetime_Field) {
460
+				$field_obj->set_timezone($this->_timezone);
461
+				if (isset($this->_fields[$field_name]) && $this->_fields[$field_name] instanceof DateTime) {
462
+					$this->_fields[$field_name]->setTimezone(new DateTimeZone($this->_timezone));
463
+				}
464
+			}
465
+		}
466
+	}
467
+
468
+
469
+
470
+	/**
471
+	 * This just returns whatever is set for the current timezone.
472
+	 *
473
+	 * @access public
474
+	 * @return string timezone string
475
+	 */
476
+	public function get_timezone()
477
+	{
478
+		return $this->_timezone;
479
+	}
480
+
481
+
482
+
483
+	/**
484
+	 * This sets the internal date format to what is sent in to be used as the new default for the class
485
+	 * internally instead of wp set date format options
486
+	 *
487
+	 * @since 4.6
488
+	 * @param string $format should be a format recognizable by PHP date() functions.
489
+	 */
490
+	public function set_date_format($format)
491
+	{
492
+		$this->_dt_frmt = $format;
493
+		//clear cached_properties because they won't be relevant now.
494
+		$this->_clear_cached_properties();
495
+	}
496
+
497
+
498
+
499
+	/**
500
+	 * This sets the internal time format string to what is sent in to be used as the new default for the
501
+	 * class internally instead of wp set time format options.
502
+	 *
503
+	 * @since 4.6
504
+	 * @param string $format should be a format recognizable by PHP date() functions.
505
+	 */
506
+	public function set_time_format($format)
507
+	{
508
+		$this->_tm_frmt = $format;
509
+		//clear cached_properties because they won't be relevant now.
510
+		$this->_clear_cached_properties();
511
+	}
512
+
513
+
514
+
515
+	/**
516
+	 * This returns the current internal set format for the date and time formats.
517
+	 *
518
+	 * @param bool $full           if true (default), then return the full format.  Otherwise will return an array
519
+	 *                             where the first value is the date format and the second value is the time format.
520
+	 * @return mixed string|array
521
+	 */
522
+	public function get_format($full = true)
523
+	{
524
+		return $full ? $this->_dt_frmt . ' ' . $this->_tm_frmt : array($this->_dt_frmt, $this->_tm_frmt);
525
+	}
526
+
527
+
528
+
529
+	/**
530
+	 * cache
531
+	 * stores the passed model object on the current model object.
532
+	 * In certain circumstances, we can use this cached model object instead of querying for another one entirely.
533
+	 *
534
+	 * @param string        $relationName    one of the keys in the _model_relations array on the model. Eg
535
+	 *                                       'Registration' associated with this model object
536
+	 * @param EE_Base_Class $object_to_cache that has a relation to this model object. (Eg, if this is a Transaction,
537
+	 *                                       that could be a payment or a registration)
538
+	 * @param null          $cache_id        a string or number that will be used as the key for any Belongs_To_Many
539
+	 *                                       items which will be stored in an array on this object
540
+	 * @throws EE_Error
541
+	 * @return mixed    index into cache, or just TRUE if the relation is of type Belongs_To (because there's only one
542
+	 *                  related thing, no array)
543
+	 */
544
+	public function cache($relationName = '', $object_to_cache = null, $cache_id = null)
545
+	{
546
+		// its entirely possible that there IS no related object yet in which case there is nothing to cache.
547
+		if ( ! $object_to_cache instanceof EE_Base_Class) {
548
+			return false;
549
+		}
550
+		// also get "how" the object is related, or throw an error
551
+		if ( ! $relationship_to_model = $this->get_model()->related_settings_for($relationName)) {
552
+			throw new EE_Error(sprintf(__('There is no relationship to %s on a %s. Cannot cache it', 'event_espresso'),
553
+				$relationName, get_class($this)));
554
+		}
555
+		// how many things are related ?
556
+		if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
557
+			// if it's a "belongs to" relationship, then there's only one related model object  eg, if this is a registration, there's only 1 attendee for it
558
+			// so for these model objects just set it to be cached
559
+			$this->_model_relations[$relationName] = $object_to_cache;
560
+			$return = true;
561
+		} else {
562
+			// otherwise, this is the "many" side of a one to many relationship, so we'll add the object to the array of related objects for that type.
563
+			// eg: if this is an event, there are many registrations for that event, so we cache the registrations in an array
564
+			if ( ! is_array($this->_model_relations[$relationName])) {
565
+				// if for some reason, the cached item is a model object, then stick that in the array, otherwise start with an empty array
566
+				$this->_model_relations[$relationName] = $this->_model_relations[$relationName] instanceof EE_Base_Class
567
+					? array($this->_model_relations[$relationName]) : array();
568
+			}
569
+			// first check for a cache_id which is normally empty
570
+			if ( ! empty($cache_id)) {
571
+				// if the cache_id exists, then it means we are purposely trying to cache this with a known key that can then be used to retrieve the object later on
572
+				$this->_model_relations[$relationName][$cache_id] = $object_to_cache;
573
+				$return = $cache_id;
574
+			} elseif ($object_to_cache->ID()) {
575
+				// OR the cached object originally came from the db, so let's just use it's PK for an ID
576
+				$this->_model_relations[$relationName][$object_to_cache->ID()] = $object_to_cache;
577
+				$return = $object_to_cache->ID();
578
+			} else {
579
+				// OR it's a new object with no ID, so just throw it in the array with an auto-incremented ID
580
+				$this->_model_relations[$relationName][] = $object_to_cache;
581
+				// move the internal pointer to the end of the array
582
+				end($this->_model_relations[$relationName]);
583
+				// and grab the key so that we can return it
584
+				$return = key($this->_model_relations[$relationName]);
585
+			}
586
+		}
587
+		return $return;
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * For adding an item to the cached_properties property.
594
+	 *
595
+	 * @access protected
596
+	 * @param string      $fieldname the property item the corresponding value is for.
597
+	 * @param mixed       $value     The value we are caching.
598
+	 * @param string|null $cache_type
599
+	 * @return void
600
+	 * @throws \EE_Error
601
+	 */
602
+	protected function _set_cached_property($fieldname, $value, $cache_type = null)
603
+	{
604
+		//first make sure this property exists
605
+		$this->get_model()->field_settings_for($fieldname);
606
+		$cache_type = empty($cache_type) ? 'standard' : $cache_type;
607
+		$this->_cached_properties[$fieldname][$cache_type] = $value;
608
+	}
609
+
610
+
611
+
612
+	/**
613
+	 * This returns the value cached property if it exists OR the actual property value if the cache doesn't exist.
614
+	 * This also SETS the cache if we return the actual property!
615
+	 *
616
+	 * @param string $fieldname        the name of the property we're trying to retrieve
617
+	 * @param bool   $pretty
618
+	 * @param string $extra_cache_ref  This allows the user to specify an extra cache ref for the given property
619
+	 *                                 (in cases where the same property may be used for different outputs
620
+	 *                                 - i.e. datetime, money etc.)
621
+	 *                                 It can also accept certain pre-defined "schema" strings
622
+	 *                                 to define how to output the property.
623
+	 *                                 see the field's prepare_for_pretty_echoing for what strings can be used
624
+	 * @return mixed                   whatever the value for the property is we're retrieving
625
+	 * @throws \EE_Error
626
+	 */
627
+	protected function _get_cached_property($fieldname, $pretty = false, $extra_cache_ref = null)
628
+	{
629
+		//verify the field exists
630
+		$model = $this->get_model();
631
+		$model->field_settings_for($fieldname);
632
+		$cache_type = $pretty ? 'pretty' : 'standard';
633
+		$cache_type .= ! empty($extra_cache_ref) ? '_' . $extra_cache_ref : '';
634
+		if (isset($this->_cached_properties[$fieldname][$cache_type])) {
635
+			return $this->_cached_properties[$fieldname][$cache_type];
636
+		}
637
+		$value = $this->_get_fresh_property($fieldname, $pretty, $extra_cache_ref);
638
+		$this->_set_cached_property($fieldname, $value, $cache_type);
639
+		return $value;
640
+	}
641
+
642
+
643
+
644
+	/**
645
+	 * If the cache didn't fetch the needed item, this fetches it.
646
+	 * @param string $fieldname
647
+	 * @param bool $pretty
648
+	 * @param string $extra_cache_ref
649
+	 * @return mixed
650
+	 */
651
+	protected function _get_fresh_property($fieldname, $pretty = false, $extra_cache_ref = null)
652
+	{
653
+		$field_obj = $this->get_model()->field_settings_for($fieldname);
654
+		// If this is an EE_Datetime_Field we need to make sure timezone, formats, and output are correct
655
+		if ($field_obj instanceof EE_Datetime_Field) {
656
+			$this->_prepare_datetime_field($field_obj, $pretty, $extra_cache_ref);
657
+		}
658
+		if ( ! isset($this->_fields[$fieldname])) {
659
+			$this->_fields[$fieldname] = null;
660
+		}
661
+		$value = $pretty
662
+			? $field_obj->prepare_for_pretty_echoing($this->_fields[$fieldname], $extra_cache_ref)
663
+			: $field_obj->prepare_for_get($this->_fields[$fieldname]);
664
+		return $value;
665
+	}
666
+
667
+
668
+
669
+	/**
670
+	 * set timezone, formats, and output for EE_Datetime_Field objects
671
+	 *
672
+	 * @param \EE_Datetime_Field $datetime_field
673
+	 * @param bool               $pretty
674
+	 * @param null $date_or_time
675
+	 * @return void
676
+	 * @throws \EE_Error
677
+	 */
678
+	protected function _prepare_datetime_field(
679
+		EE_Datetime_Field $datetime_field,
680
+		$pretty = false,
681
+		$date_or_time = null
682
+	) {
683
+		$datetime_field->set_timezone($this->_timezone);
684
+		$datetime_field->set_date_format($this->_dt_frmt, $pretty);
685
+		$datetime_field->set_time_format($this->_tm_frmt, $pretty);
686
+		//set the output returned
687
+		switch ($date_or_time) {
688
+			case 'D' :
689
+				$datetime_field->set_date_time_output('date');
690
+				break;
691
+			case 'T' :
692
+				$datetime_field->set_date_time_output('time');
693
+				break;
694
+			default :
695
+				$datetime_field->set_date_time_output();
696
+		}
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * This just takes care of clearing out the cached_properties
703
+	 *
704
+	 * @return void
705
+	 */
706
+	protected function _clear_cached_properties()
707
+	{
708
+		$this->_cached_properties = array();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * This just clears out ONE property if it exists in the cache
715
+	 *
716
+	 * @param  string $property_name the property to remove if it exists (from the _cached_properties array)
717
+	 * @return void
718
+	 */
719
+	protected function _clear_cached_property($property_name)
720
+	{
721
+		if (isset($this->_cached_properties[$property_name])) {
722
+			unset($this->_cached_properties[$property_name]);
723
+		}
724
+	}
725
+
726
+
727
+
728
+	/**
729
+	 * Ensures that this related thing is a model object.
730
+	 *
731
+	 * @param mixed  $object_or_id EE_base_Class/int/string either a related model object, or its ID
732
+	 * @param string $model_name   name of the related thing, eg 'Attendee',
733
+	 * @return EE_Base_Class
734
+	 * @throws \EE_Error
735
+	 */
736
+	protected function ensure_related_thing_is_model_obj($object_or_id, $model_name)
737
+	{
738
+		$other_model_instance = self::_get_model_instance_with_name(
739
+			self::_get_model_classname($model_name),
740
+			$this->_timezone
741
+		);
742
+		return $other_model_instance->ensure_is_obj($object_or_id);
743
+	}
744
+
745
+
746
+
747
+	/**
748
+	 * Forgets the cached model of the given relation Name. So the next time we request it,
749
+	 * we will fetch it again from the database. (Handy if you know it's changed somehow).
750
+	 * If a specific object is supplied, and the relationship to it is either a HasMany or HABTM,
751
+	 * then only remove that one object from our cached array. Otherwise, clear the entire list
752
+	 *
753
+	 * @param string $relationName                         one of the keys in the _model_relations array on the model.
754
+	 *                                                     Eg 'Registration'
755
+	 * @param mixed  $object_to_remove_or_index_into_array or an index into the array of cached things, or NULL
756
+	 *                                                     if you intend to use $clear_all = TRUE, or the relation only
757
+	 *                                                     has 1 object anyways (ie, it's a BelongsToRelation)
758
+	 * @param bool   $clear_all                            This flags clearing the entire cache relation property if
759
+	 *                                                     this is HasMany or HABTM.
760
+	 * @throws EE_Error
761
+	 * @return EE_Base_Class | boolean from which was cleared from the cache, or true if we requested to remove a
762
+	 *                       relation from all
763
+	 */
764
+	public function clear_cache($relationName, $object_to_remove_or_index_into_array = null, $clear_all = false)
765
+	{
766
+		$relationship_to_model = $this->get_model()->related_settings_for($relationName);
767
+		$index_in_cache = '';
768
+		if ( ! $relationship_to_model) {
769
+			throw new EE_Error(
770
+				sprintf(
771
+					__("There is no relationship to %s on a %s. Cannot clear that cache", 'event_espresso'),
772
+					$relationName,
773
+					get_class($this)
774
+				)
775
+			);
776
+		}
777
+		if ($clear_all) {
778
+			$obj_removed = true;
779
+			$this->_model_relations[$relationName] = null;
780
+		} elseif ($relationship_to_model instanceof EE_Belongs_To_Relation) {
781
+			$obj_removed = $this->_model_relations[$relationName];
782
+			$this->_model_relations[$relationName] = null;
783
+		} else {
784
+			if ($object_to_remove_or_index_into_array instanceof EE_Base_Class
785
+				&& $object_to_remove_or_index_into_array->ID()
786
+			) {
787
+				$index_in_cache = $object_to_remove_or_index_into_array->ID();
788
+				if (is_array($this->_model_relations[$relationName])
789
+					&& ! isset($this->_model_relations[$relationName][$index_in_cache])
790
+				) {
791
+					$index_found_at = null;
792
+					//find this object in the array even though it has a different key
793
+					foreach ($this->_model_relations[$relationName] as $index => $obj) {
794
+						if (
795
+							$obj instanceof EE_Base_Class
796
+							&& (
797
+								$obj == $object_to_remove_or_index_into_array
798
+								|| $obj->ID() === $object_to_remove_or_index_into_array->ID()
799
+							)
800
+						) {
801
+							$index_found_at = $index;
802
+							break;
803
+						}
804
+					}
805
+					if ($index_found_at) {
806
+						$index_in_cache = $index_found_at;
807
+					} else {
808
+						//it wasn't found. huh. well obviously it doesn't need to be removed from teh cache
809
+						//if it wasn't in it to begin with. So we're done
810
+						return $object_to_remove_or_index_into_array;
811
+					}
812
+				}
813
+			} elseif ($object_to_remove_or_index_into_array instanceof EE_Base_Class) {
814
+				//so they provided a model object, but it's not yet saved to the DB... so let's go hunting for it!
815
+				foreach ($this->get_all_from_cache($relationName) as $index => $potentially_obj_we_want) {
816
+					if ($potentially_obj_we_want == $object_to_remove_or_index_into_array) {
817
+						$index_in_cache = $index;
818
+					}
819
+				}
820
+			} else {
821
+				$index_in_cache = $object_to_remove_or_index_into_array;
822
+			}
823
+			//supposedly we've found it. But it could just be that the client code
824
+			//provided a bad index/object
825
+			if (
826
+			isset(
827
+				$this->_model_relations[$relationName],
828
+				$this->_model_relations[$relationName][$index_in_cache]
829
+			)
830
+			) {
831
+				$obj_removed = $this->_model_relations[$relationName][$index_in_cache];
832
+				unset($this->_model_relations[$relationName][$index_in_cache]);
833
+			} else {
834
+				//that thing was never cached anyways.
835
+				$obj_removed = null;
836
+			}
837
+		}
838
+		return $obj_removed;
839
+	}
840
+
841
+
842
+
843
+	/**
844
+	 * update_cache_after_object_save
845
+	 * Allows a cached item to have it's cache ID (within the array of cached items) reset using the new ID it has
846
+	 * obtained after being saved to the db
847
+	 *
848
+	 * @param string         $relationName       - the type of object that is cached
849
+	 * @param \EE_Base_Class $newly_saved_object - the newly saved object to be re-cached
850
+	 * @param string         $current_cache_id   - the ID that was used when originally caching the object
851
+	 * @return boolean TRUE on success, FALSE on fail
852
+	 * @throws \EE_Error
853
+	 */
854
+	public function update_cache_after_object_save(
855
+		$relationName,
856
+		EE_Base_Class $newly_saved_object,
857
+		$current_cache_id = ''
858
+	) {
859
+		// verify that incoming object is of the correct type
860
+		$obj_class = 'EE_' . $relationName;
861
+		if ($newly_saved_object instanceof $obj_class) {
862
+			/* @type EE_Base_Class $newly_saved_object */
863
+			// now get the type of relation
864
+			$relationship_to_model = $this->get_model()->related_settings_for($relationName);
865
+			// if this is a 1:1 relationship
866
+			if ($relationship_to_model instanceof EE_Belongs_To_Relation) {
867
+				// then just replace the cached object with the newly saved object
868
+				$this->_model_relations[$relationName] = $newly_saved_object;
869
+				return true;
870
+				// or if it's some kind of sordid feral polyamorous relationship...
871
+			} elseif (is_array($this->_model_relations[$relationName])
872
+					  && isset($this->_model_relations[$relationName][$current_cache_id])
873
+			) {
874
+				// then remove the current cached item
875
+				unset($this->_model_relations[$relationName][$current_cache_id]);
876
+				// and cache the newly saved object using it's new ID
877
+				$this->_model_relations[$relationName][$newly_saved_object->ID()] = $newly_saved_object;
878
+				return true;
879
+			}
880
+		}
881
+		return false;
882
+	}
883
+
884
+
885
+
886
+	/**
887
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
888
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
889
+	 *
890
+	 * @param string $relationName
891
+	 * @return EE_Base_Class
892
+	 */
893
+	public function get_one_from_cache($relationName)
894
+	{
895
+		$cached_array_or_object = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName]
896
+			: null;
897
+		if (is_array($cached_array_or_object)) {
898
+			return array_shift($cached_array_or_object);
899
+		} else {
900
+			return $cached_array_or_object;
901
+		}
902
+	}
903
+
904
+
905
+
906
+	/**
907
+	 * Fetches a single EE_Base_Class on that relation. (If the relation is of type
908
+	 * BelongsTo, it will only ever have 1 object. However, other relations could have an array of objects)
909
+	 *
910
+	 * @param string $relationName
911
+	 * @throws \EE_Error
912
+	 * @return EE_Base_Class[] NOT necessarily indexed by primary keys
913
+	 */
914
+	public function get_all_from_cache($relationName)
915
+	{
916
+		$objects = isset($this->_model_relations[$relationName]) ? $this->_model_relations[$relationName] : array();
917
+		// if the result is not an array, but exists, make it an array
918
+		$objects = is_array($objects) ? $objects : array($objects);
919
+		//bugfix for https://events.codebasehq.com/projects/event-espresso/tickets/7143
920
+		//basically, if this model object was stored in the session, and these cached model objects
921
+		//already have IDs, let's make sure they're in their model's entity mapper
922
+		//otherwise we will have duplicates next time we call
923
+		// EE_Registry::instance()->load_model( $relationName )->get_one_by_ID( $result->ID() );
924
+		$model = EE_Registry::instance()->load_model($relationName);
925
+		foreach ($objects as $model_object) {
926
+			if ($model instanceof EEM_Base && $model_object instanceof EE_Base_Class) {
927
+				//ensure its in the map if it has an ID; otherwise it will be added to the map when its saved
928
+				if ($model_object->ID()) {
929
+					$model->add_to_entity_map($model_object);
930
+				}
931
+			} else {
932
+				throw new EE_Error(
933
+					sprintf(
934
+						__(
935
+							'Error retrieving related model objects. Either $1%s is not a model or $2%s is not a model object',
936
+							'event_espresso'
937
+						),
938
+						$relationName,
939
+						gettype($model_object)
940
+					)
941
+				);
942
+			}
943
+		}
944
+		return $objects;
945
+	}
946
+
947
+
948
+
949
+	/**
950
+	 * Returns the next x number of EE_Base_Class objects in sequence from this object as found in the database
951
+	 * matching the given query conditions.
952
+	 *
953
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
954
+	 * @param int   $limit              How many objects to return.
955
+	 * @param array $query_params       Any additional conditions on the query.
956
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
957
+	 *                                  you can indicate just the columns you want returned
958
+	 * @return array|EE_Base_Class[]
959
+	 * @throws \EE_Error
960
+	 */
961
+	public function next_x($field_to_order_by = null, $limit = 1, $query_params = array(), $columns_to_select = null)
962
+	{
963
+		$model = $this->get_model();
964
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
965
+			? $model->get_primary_key_field()->get_name()
966
+			: $field_to_order_by;
967
+		$current_value = ! empty($field) ? $this->get($field) : null;
968
+		if (empty($field) || empty($current_value)) {
969
+			return array();
970
+		}
971
+		return $model->next_x($current_value, $field, $limit, $query_params, $columns_to_select);
972
+	}
973
+
974
+
975
+
976
+	/**
977
+	 * Returns the previous x number of EE_Base_Class objects in sequence from this object as found in the database
978
+	 * matching the given query conditions.
979
+	 *
980
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
981
+	 * @param int   $limit              How many objects to return.
982
+	 * @param array $query_params       Any additional conditions on the query.
983
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
984
+	 *                                  you can indicate just the columns you want returned
985
+	 * @return array|EE_Base_Class[]
986
+	 * @throws \EE_Error
987
+	 */
988
+	public function previous_x(
989
+		$field_to_order_by = null,
990
+		$limit = 1,
991
+		$query_params = array(),
992
+		$columns_to_select = null
993
+	) {
994
+		$model = $this->get_model();
995
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
996
+			? $model->get_primary_key_field()->get_name()
997
+			: $field_to_order_by;
998
+		$current_value = ! empty($field) ? $this->get($field) : null;
999
+		if (empty($field) || empty($current_value)) {
1000
+			return array();
1001
+		}
1002
+		return $model->previous_x($current_value, $field, $limit, $query_params, $columns_to_select);
1003
+	}
1004
+
1005
+
1006
+
1007
+	/**
1008
+	 * Returns the next EE_Base_Class object in sequence from this object as found in the database
1009
+	 * matching the given query conditions.
1010
+	 *
1011
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1012
+	 * @param array $query_params       Any additional conditions on the query.
1013
+	 * @param null  $columns_to_select  If left null, then an array of EE_Base_Class objects is returned, otherwise
1014
+	 *                                  you can indicate just the columns you want returned
1015
+	 * @return array|EE_Base_Class
1016
+	 * @throws \EE_Error
1017
+	 */
1018
+	public function next($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1019
+	{
1020
+		$model = $this->get_model();
1021
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1022
+			? $model->get_primary_key_field()->get_name()
1023
+			: $field_to_order_by;
1024
+		$current_value = ! empty($field) ? $this->get($field) : null;
1025
+		if (empty($field) || empty($current_value)) {
1026
+			return array();
1027
+		}
1028
+		return $model->next($current_value, $field, $query_params, $columns_to_select);
1029
+	}
1030
+
1031
+
1032
+
1033
+	/**
1034
+	 * Returns the previous EE_Base_Class object in sequence from this object as found in the database
1035
+	 * matching the given query conditions.
1036
+	 *
1037
+	 * @param null  $field_to_order_by  What field is being used as the reference point.
1038
+	 * @param array $query_params       Any additional conditions on the query.
1039
+	 * @param null  $columns_to_select  If left null, then an EE_Base_Class object is returned, otherwise
1040
+	 *                                  you can indicate just the column you want returned
1041
+	 * @return array|EE_Base_Class
1042
+	 * @throws \EE_Error
1043
+	 */
1044
+	public function previous($field_to_order_by = null, $query_params = array(), $columns_to_select = null)
1045
+	{
1046
+		$model = $this->get_model();
1047
+		$field = empty($field_to_order_by) && $model->has_primary_key_field()
1048
+			? $model->get_primary_key_field()->get_name()
1049
+			: $field_to_order_by;
1050
+		$current_value = ! empty($field) ? $this->get($field) : null;
1051
+		if (empty($field) || empty($current_value)) {
1052
+			return array();
1053
+		}
1054
+		return $model->previous($current_value, $field, $query_params, $columns_to_select);
1055
+	}
1056
+
1057
+
1058
+
1059
+	/**
1060
+	 * Overrides parent because parent expects old models.
1061
+	 * This also doesn't do any validation, and won't work for serialized arrays
1062
+	 *
1063
+	 * @param string $field_name
1064
+	 * @param mixed  $field_value_from_db
1065
+	 * @throws \EE_Error
1066
+	 */
1067
+	public function set_from_db($field_name, $field_value_from_db)
1068
+	{
1069
+		$field_obj = $this->get_model()->field_settings_for($field_name);
1070
+		if ($field_obj instanceof EE_Model_Field_Base) {
1071
+			//you would think the DB has no NULLs for non-null label fields right? wrong!
1072
+			//eg, a CPT model object could have an entry in the posts table, but no
1073
+			//entry in the meta table. Meaning that all its columns in the meta table
1074
+			//are null! yikes! so when we find one like that, use defaults for its meta columns
1075
+			if ($field_value_from_db === null) {
1076
+				if ($field_obj->is_nullable()) {
1077
+					//if the field allows nulls, then let it be null
1078
+					$field_value = null;
1079
+				} else {
1080
+					$field_value = $field_obj->get_default_value();
1081
+				}
1082
+			} else {
1083
+				$field_value = $field_obj->prepare_for_set_from_db($field_value_from_db);
1084
+			}
1085
+			$this->_fields[$field_name] = $field_value;
1086
+			$this->_clear_cached_property($field_name);
1087
+		}
1088
+	}
1089
+
1090
+
1091
+
1092
+	/**
1093
+	 * verifies that the specified field is of the correct type
1094
+	 *
1095
+	 * @param string $field_name
1096
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1097
+	 *                                (in cases where the same property may be used for different outputs
1098
+	 *                                - i.e. datetime, money etc.)
1099
+	 * @return mixed
1100
+	 * @throws \EE_Error
1101
+	 */
1102
+	public function get($field_name, $extra_cache_ref = null)
1103
+	{
1104
+		return $this->_get_cached_property($field_name, false, $extra_cache_ref);
1105
+	}
1106
+
1107
+
1108
+
1109
+	/**
1110
+	 * This method simply returns the RAW unprocessed value for the given property in this class
1111
+	 *
1112
+	 * @param  string $field_name A valid fieldname
1113
+	 * @return mixed              Whatever the raw value stored on the property is.
1114
+	 * @throws EE_Error if fieldSettings is misconfigured or the field doesn't exist.
1115
+	 */
1116
+	public function get_raw($field_name)
1117
+	{
1118
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1119
+		return $field_settings instanceof EE_Datetime_Field && $this->_fields[$field_name] instanceof DateTime
1120
+			? $this->_fields[$field_name]->format('U')
1121
+			: $this->_fields[$field_name];
1122
+	}
1123
+
1124
+
1125
+
1126
+	/**
1127
+	 * This is used to return the internal DateTime object used for a field that is a
1128
+	 * EE_Datetime_Field.
1129
+	 *
1130
+	 * @param string $field_name               The field name retrieving the DateTime object.
1131
+	 * @return mixed null | false | DateTime  If the requested field is NOT a EE_Datetime_Field then
1132
+	 * @throws \EE_Error
1133
+	 *                                         an error is set and false returned.  If the field IS an
1134
+	 *                                         EE_Datetime_Field and but the field value is null, then
1135
+	 *                                         just null is returned (because that indicates that likely
1136
+	 *                                         this field is nullable).
1137
+	 */
1138
+	public function get_DateTime_object($field_name)
1139
+	{
1140
+		$field_settings = $this->get_model()->field_settings_for($field_name);
1141
+		if ( ! $field_settings instanceof EE_Datetime_Field) {
1142
+			EE_Error::add_error(
1143
+				sprintf(
1144
+					__(
1145
+						'The field %s is not an EE_Datetime_Field field.  There is no DateTime object stored on this field type.',
1146
+						'event_espresso'
1147
+					),
1148
+					$field_name
1149
+				),
1150
+				__FILE__,
1151
+				__FUNCTION__,
1152
+				__LINE__
1153
+			);
1154
+			return false;
1155
+		}
1156
+		return $this->_fields[$field_name];
1157
+	}
1158
+
1159
+
1160
+
1161
+	/**
1162
+	 * To be used in template to immediately echo out the value, and format it for output.
1163
+	 * Eg, should call stripslashes and whatnot before echoing
1164
+	 *
1165
+	 * @param string $field_name      the name of the field as it appears in the DB
1166
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1167
+	 *                                (in cases where the same property may be used for different outputs
1168
+	 *                                - i.e. datetime, money etc.)
1169
+	 * @return void
1170
+	 * @throws \EE_Error
1171
+	 */
1172
+	public function e($field_name, $extra_cache_ref = null)
1173
+	{
1174
+		echo $this->get_pretty($field_name, $extra_cache_ref);
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * Exactly like e(), echoes out the field, but sets its schema to 'form_input', so that it
1181
+	 * can be easily used as the value of form input.
1182
+	 *
1183
+	 * @param string $field_name
1184
+	 * @return void
1185
+	 * @throws \EE_Error
1186
+	 */
1187
+	public function f($field_name)
1188
+	{
1189
+		$this->e($field_name, 'form_input');
1190
+	}
1191
+
1192
+	/**
1193
+	 * Same as `f()` but just returns the value instead of echoing it
1194
+	 * @param string $field_name
1195
+	 * @return string
1196
+	 */
1197
+	public function get_f($field_name)
1198
+	{
1199
+		return (string)$this->get_pretty($field_name,'form_input');
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Gets a pretty view of the field's value. $extra_cache_ref can specify different formats for this.
1206
+	 * The $extra_cache_ref will be passed to the model field's prepare_for_pretty_echoing, so consult the field's class
1207
+	 * to see what options are available.
1208
+	 * @param string $field_name
1209
+	 * @param string $extra_cache_ref This allows the user to specify an extra cache ref for the given property
1210
+	 *                                (in cases where the same property may be used for different outputs
1211
+	 *                                - i.e. datetime, money etc.)
1212
+	 * @return mixed
1213
+	 * @throws \EE_Error
1214
+	 */
1215
+	public function get_pretty($field_name, $extra_cache_ref = null)
1216
+	{
1217
+		return $this->_get_cached_property($field_name, true, $extra_cache_ref);
1218
+	}
1219
+
1220
+
1221
+
1222
+	/**
1223
+	 * This simply returns the datetime for the given field name
1224
+	 * Note: this protected function is called by the wrapper get_date or get_time or get_datetime functions
1225
+	 * (and the equivalent e_date, e_time, e_datetime).
1226
+	 *
1227
+	 * @access   protected
1228
+	 * @param string   $field_name   Field on the instantiated EE_Base_Class child object
1229
+	 * @param string   $dt_frmt      valid datetime format used for date
1230
+	 *                               (if '' then we just use the default on the field,
1231
+	 *                               if NULL we use the last-used format)
1232
+	 * @param string   $tm_frmt      Same as above except this is for time format
1233
+	 * @param string   $date_or_time if NULL then both are returned, otherwise "D" = only date and "T" = only time.
1234
+	 * @param  boolean $echo         Whether the dtt is echoing using pretty echoing or just returned using vanilla get
1235
+	 * @return string|bool|EE_Error string on success, FALSE on fail, or EE_Error Exception is thrown
1236
+	 *                               if field is not a valid dtt field, or void if echoing
1237
+	 * @throws \EE_Error
1238
+	 */
1239
+	protected function _get_datetime($field_name, $dt_frmt = '', $tm_frmt = '', $date_or_time = '', $echo = false)
1240
+	{
1241
+		// clear cached property
1242
+		$this->_clear_cached_property($field_name);
1243
+		//reset format properties because they are used in get()
1244
+		$this->_dt_frmt = $dt_frmt !== '' ? $dt_frmt : $this->_dt_frmt;
1245
+		$this->_tm_frmt = $tm_frmt !== '' ? $tm_frmt : $this->_tm_frmt;
1246
+		if ($echo) {
1247
+			$this->e($field_name, $date_or_time);
1248
+			return '';
1249
+		}
1250
+		return $this->get($field_name, $date_or_time);
1251
+	}
1252
+
1253
+
1254
+
1255
+	/**
1256
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the date
1257
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1258
+	 * other echoes the pretty value for dtt)
1259
+	 *
1260
+	 * @param  string $field_name name of model object datetime field holding the value
1261
+	 * @param  string $format     format for the date returned (if NULL we use default in dt_frmt property)
1262
+	 * @return string            datetime value formatted
1263
+	 * @throws \EE_Error
1264
+	 */
1265
+	public function get_date($field_name, $format = '')
1266
+	{
1267
+		return $this->_get_datetime($field_name, $format, null, 'D');
1268
+	}
1269
+
1270
+
1271
+
1272
+	/**
1273
+	 * @param      $field_name
1274
+	 * @param string $format
1275
+	 * @throws \EE_Error
1276
+	 */
1277
+	public function e_date($field_name, $format = '')
1278
+	{
1279
+		$this->_get_datetime($field_name, $format, null, 'D', true);
1280
+	}
1281
+
1282
+
1283
+
1284
+	/**
1285
+	 * below are wrapper functions for the various datetime outputs that can be obtained for JUST returning the time
1286
+	 * portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1287
+	 * other echoes the pretty value for dtt)
1288
+	 *
1289
+	 * @param  string $field_name name of model object datetime field holding the value
1290
+	 * @param  string $format     format for the time returned ( if NULL we use default in tm_frmt property)
1291
+	 * @return string             datetime value formatted
1292
+	 * @throws \EE_Error
1293
+	 */
1294
+	public function get_time($field_name, $format = '')
1295
+	{
1296
+		return $this->_get_datetime($field_name, null, $format, 'T');
1297
+	}
1298
+
1299
+
1300
+
1301
+	/**
1302
+	 * @param      $field_name
1303
+	 * @param string $format
1304
+	 * @throws \EE_Error
1305
+	 */
1306
+	public function e_time($field_name, $format = '')
1307
+	{
1308
+		$this->_get_datetime($field_name, null, $format, 'T', true);
1309
+	}
1310
+
1311
+
1312
+
1313
+	/**
1314
+	 * below are wrapper functions for the various datetime outputs that can be obtained for returning the date AND
1315
+	 * time portion of a datetime value. (note the only difference between get_ and e_ is one returns the value and the
1316
+	 * other echoes the pretty value for dtt)
1317
+	 *
1318
+	 * @param  string $field_name name of model object datetime field holding the value
1319
+	 * @param  string $dt_frmt    format for the date returned (if NULL we use default in dt_frmt property)
1320
+	 * @param  string $tm_frmt    format for the time returned (if NULL we use default in tm_frmt property)
1321
+	 * @return string             datetime value formatted
1322
+	 * @throws \EE_Error
1323
+	 */
1324
+	public function get_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1325
+	{
1326
+		return $this->_get_datetime($field_name, $dt_frmt, $tm_frmt);
1327
+	}
1328
+
1329
+
1330
+
1331
+	/**
1332
+	 * @param string $field_name
1333
+	 * @param string $dt_frmt
1334
+	 * @param string $tm_frmt
1335
+	 * @throws \EE_Error
1336
+	 */
1337
+	public function e_datetime($field_name, $dt_frmt = '', $tm_frmt = '')
1338
+	{
1339
+		$this->_get_datetime($field_name, $dt_frmt, $tm_frmt, null, true);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Get the i8ln value for a date using the WordPress @see date_i18n function.
1346
+	 *
1347
+	 * @param string $field_name The EE_Datetime_Field reference for the date being retrieved.
1348
+	 * @param string $format     PHP valid date/time string format.  If none is provided then the internal set format
1349
+	 *                           on the object will be used.
1350
+	 * @return string Date and time string in set locale or false if no field exists for the given
1351
+	 * @throws \EE_Error
1352
+	 *                           field name.
1353
+	 */
1354
+	public function get_i18n_datetime($field_name, $format = '')
1355
+	{
1356
+		$format = empty($format) ? $this->_dt_frmt . ' ' . $this->_tm_frmt : $format;
1357
+		return date_i18n(
1358
+			$format,
1359
+			EEH_DTT_Helper::get_timestamp_with_offset($this->get_raw($field_name), $this->_timezone)
1360
+		);
1361
+	}
1362
+
1363
+
1364
+
1365
+	/**
1366
+	 * This method validates whether the given field name is a valid field on the model object as well as it is of a
1367
+	 * type EE_Datetime_Field.  On success there will be returned the field settings.  On fail an EE_Error exception is
1368
+	 * thrown.
1369
+	 *
1370
+	 * @param  string $field_name The field name being checked
1371
+	 * @throws EE_Error
1372
+	 * @return EE_Datetime_Field
1373
+	 */
1374
+	protected function _get_dtt_field_settings($field_name)
1375
+	{
1376
+		$field = $this->get_model()->field_settings_for($field_name);
1377
+		//check if field is dtt
1378
+		if ($field instanceof EE_Datetime_Field) {
1379
+			return $field;
1380
+		} else {
1381
+			throw new EE_Error(sprintf(__('The field name "%s" has been requested for the EE_Base_Class datetime functions and it is not a valid EE_Datetime_Field.  Please check the spelling of the field and make sure it has been setup as a EE_Datetime_Field in the %s model constructor',
1382
+				'event_espresso'), $field_name, self::_get_model_classname(get_class($this))));
1383
+		}
1384
+	}
1385
+
1386
+
1387
+
1388
+
1389
+	/**
1390
+	 * NOTE ABOUT BELOW:
1391
+	 * These convenience date and time setters are for setting date and time independently.  In other words you might
1392
+	 * want to change the time on a datetime_field but leave the date the same (or vice versa). IF on the other hand
1393
+	 * you want to set both date and time at the same time, you can just use the models default set($fieldname,$value)
1394
+	 * method and make sure you send the entire datetime value for setting.
1395
+	 */
1396
+	/**
1397
+	 * sets the time on a datetime property
1398
+	 *
1399
+	 * @access protected
1400
+	 * @param string|Datetime $time      a valid time string for php datetime functions (or DateTime object)
1401
+	 * @param string          $fieldname the name of the field the time is being set on (must match a EE_Datetime_Field)
1402
+	 * @throws \EE_Error
1403
+	 */
1404
+	protected function _set_time_for($time, $fieldname)
1405
+	{
1406
+		$this->_set_date_time('T', $time, $fieldname);
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * sets the date on a datetime property
1413
+	 *
1414
+	 * @access protected
1415
+	 * @param string|DateTime $date      a valid date string for php datetime functions ( or DateTime object)
1416
+	 * @param string          $fieldname the name of the field the date is being set on (must match a EE_Datetime_Field)
1417
+	 * @throws \EE_Error
1418
+	 */
1419
+	protected function _set_date_for($date, $fieldname)
1420
+	{
1421
+		$this->_set_date_time('D', $date, $fieldname);
1422
+	}
1423
+
1424
+
1425
+
1426
+	/**
1427
+	 * This takes care of setting a date or time independently on a given model object property. This method also
1428
+	 * verifies that the given fieldname matches a model object property and is for a EE_Datetime_Field field
1429
+	 *
1430
+	 * @access protected
1431
+	 * @param string          $what           "T" for time, 'B' for both, 'D' for Date.
1432
+	 * @param string|DateTime $datetime_value A valid Date or Time string (or DateTime object)
1433
+	 * @param string          $fieldname      the name of the field the date OR time is being set on (must match a
1434
+	 *                                        EE_Datetime_Field property)
1435
+	 * @throws \EE_Error
1436
+	 */
1437
+	protected function _set_date_time($what = 'T', $datetime_value, $fieldname)
1438
+	{
1439
+		$field = $this->_get_dtt_field_settings($fieldname);
1440
+		$field->set_timezone($this->_timezone);
1441
+		$field->set_date_format($this->_dt_frmt);
1442
+		$field->set_time_format($this->_tm_frmt);
1443
+		switch ($what) {
1444
+			case 'T' :
1445
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_time(
1446
+					$datetime_value,
1447
+					$this->_fields[$fieldname]
1448
+				);
1449
+				break;
1450
+			case 'D' :
1451
+				$this->_fields[$fieldname] = $field->prepare_for_set_with_new_date(
1452
+					$datetime_value,
1453
+					$this->_fields[$fieldname]
1454
+				);
1455
+				break;
1456
+			case 'B' :
1457
+				$this->_fields[$fieldname] = $field->prepare_for_set($datetime_value);
1458
+				break;
1459
+		}
1460
+		$this->_clear_cached_property($fieldname);
1461
+	}
1462
+
1463
+
1464
+
1465
+	/**
1466
+	 * This will return a timestamp for the website timezone but ONLY when the current website timezone is different
1467
+	 * than the timezone set for the website. NOTE, this currently only works well with methods that return values.  If
1468
+	 * you use it with methods that echo values the $_timestamp property may not get reset to its original value and
1469
+	 * that could lead to some unexpected results!
1470
+	 *
1471
+	 * @access public
1472
+	 * @param string               $field_name This is the name of the field on the object that contains the date/time
1473
+	 *                                         value being returned.
1474
+	 * @param string               $callback   must match a valid method in this class (defaults to get_datetime)
1475
+	 * @param mixed (array|string) $args       This is the arguments that will be passed to the callback.
1476
+	 * @param string               $prepend    You can include something to prepend on the timestamp
1477
+	 * @param string               $append     You can include something to append on the timestamp
1478
+	 * @throws EE_Error
1479
+	 * @return string timestamp
1480
+	 */
1481
+	public function display_in_my_timezone(
1482
+		$field_name,
1483
+		$callback = 'get_datetime',
1484
+		$args = null,
1485
+		$prepend = '',
1486
+		$append = ''
1487
+	) {
1488
+		$timezone = EEH_DTT_Helper::get_timezone();
1489
+		if ($timezone === $this->_timezone) {
1490
+			return '';
1491
+		}
1492
+		$original_timezone = $this->_timezone;
1493
+		$this->set_timezone($timezone);
1494
+		$fn = (array)$field_name;
1495
+		$args = array_merge($fn, (array)$args);
1496
+		if ( ! method_exists($this, $callback)) {
1497
+			throw new EE_Error(
1498
+				sprintf(
1499
+					__(
1500
+						'The method named "%s" given as the callback param in "display_in_my_timezone" does not exist.  Please check your spelling',
1501
+						'event_espresso'
1502
+					),
1503
+					$callback
1504
+				)
1505
+			);
1506
+		}
1507
+		$args = (array)$args;
1508
+		$return = $prepend . call_user_func_array(array($this, $callback), $args) . $append;
1509
+		$this->set_timezone($original_timezone);
1510
+		return $return;
1511
+	}
1512
+
1513
+
1514
+
1515
+	/**
1516
+	 * Deletes this model object.
1517
+	 * This calls the `EE_Base_Class::_delete` method.  Child classes wishing to change default behaviour should
1518
+	 * override
1519
+	 * `EE_Base_Class::_delete` NOT this class.
1520
+	 *
1521
+	 * @return boolean | int
1522
+	 * @throws \EE_Error
1523
+	 */
1524
+	public function delete()
1525
+	{
1526
+		/**
1527
+		 * Called just before the `EE_Base_Class::_delete` method call.
1528
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1529
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example, `EE_Soft_Delete_Base_Class::_delete`
1530
+		 * soft deletes (trash) the object and does not permanently delete it.
1531
+		 *
1532
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1533
+		 */
1534
+		do_action('AHEE__EE_Base_Class__delete__before', $this);
1535
+		$result = $this->_delete();
1536
+		/**
1537
+		 * Called just after the `EE_Base_Class::_delete` method call.
1538
+		 * Note: `EE_Base_Class::_delete` might be overridden by child classes so any client code hooking into these actions
1539
+		 * should be aware that `_delete` may not always result in a permanent delete.  For example `EE_Soft_Base_Class::_delete`
1540
+		 * soft deletes (trash) the object and does not permanently delete it.
1541
+		 *
1542
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1543
+		 * @param boolean       $result
1544
+		 */
1545
+		do_action('AHEE__EE_Base_Class__delete__end', $this, $result);
1546
+		return $result;
1547
+	}
1548
+
1549
+
1550
+
1551
+	/**
1552
+	 * Calls the specific delete method for the instantiated class.
1553
+	 * This method is called by the public `EE_Base_Class::delete` method.  Any child classes desiring to override
1554
+	 * default functionality for "delete" (which is to call `permanently_delete`) should override this method NOT
1555
+	 * `EE_Base_Class::delete`
1556
+	 *
1557
+	 * @return bool|int
1558
+	 * @throws \EE_Error
1559
+	 */
1560
+	protected function _delete()
1561
+	{
1562
+		return $this->delete_permanently();
1563
+	}
1564
+
1565
+
1566
+
1567
+	/**
1568
+	 * Deletes this model object permanently from db (but keep in mind related models my block the delete and return an
1569
+	 * error)
1570
+	 *
1571
+	 * @return bool | int
1572
+	 * @throws \EE_Error
1573
+	 */
1574
+	public function delete_permanently()
1575
+	{
1576
+		/**
1577
+		 * Called just before HARD deleting a model object
1578
+		 *
1579
+		 * @param EE_Base_Class $model_object about to be 'deleted'
1580
+		 */
1581
+		do_action('AHEE__EE_Base_Class__delete_permanently__before', $this);
1582
+		$model = $this->get_model();
1583
+		$result = $model->delete_permanently_by_ID($this->ID());
1584
+		$this->refresh_cache_of_related_objects();
1585
+		/**
1586
+		 * Called just after HARD deleting a model object
1587
+		 *
1588
+		 * @param EE_Base_Class $model_object that was just 'deleted'
1589
+		 * @param boolean       $result
1590
+		 */
1591
+		do_action('AHEE__EE_Base_Class__delete_permanently__end', $this, $result);
1592
+		return $result;
1593
+	}
1594
+
1595
+
1596
+
1597
+	/**
1598
+	 * When this model object is deleted, it may still be cached on related model objects. This clears the cache of
1599
+	 * related model objects
1600
+	 *
1601
+	 * @throws \EE_Error
1602
+	 */
1603
+	public function refresh_cache_of_related_objects()
1604
+	{
1605
+		$model = $this->get_model();
1606
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1607
+			if ( ! empty($this->_model_relations[$relation_name])) {
1608
+				$related_objects = $this->_model_relations[$relation_name];
1609
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
1610
+					//this relation only stores a single model object, not an array
1611
+					//but let's make it consistent
1612
+					$related_objects = array($related_objects);
1613
+				}
1614
+				foreach ($related_objects as $related_object) {
1615
+					//only refresh their cache if they're in memory
1616
+					if ($related_object instanceof EE_Base_Class) {
1617
+						$related_object->clear_cache($model->get_this_model_name(), $this);
1618
+					}
1619
+				}
1620
+			}
1621
+		}
1622
+	}
1623
+
1624
+
1625
+
1626
+	/**
1627
+	 *        Saves this object to the database. An array may be supplied to set some values on this
1628
+	 * object just before saving.
1629
+	 *
1630
+	 * @access public
1631
+	 * @param array $set_cols_n_values keys are field names, values are their new values,
1632
+	 *                                 if provided during the save() method (often client code will change the fields'
1633
+	 *                                 values before calling save)
1634
+	 * @throws \EE_Error
1635
+	 * @return int , 1 on a successful update, the ID of the new entry on insert; 0 on failure or if the model object
1636
+	 *                                 isn't allowed to persist (as determined by EE_Base_Class::allow_persist())
1637
+	 */
1638
+	public function save($set_cols_n_values = array())
1639
+	{
1640
+		$model = $this->get_model();
1641
+		/**
1642
+		 * Filters the fields we're about to save on the model object
1643
+		 *
1644
+		 * @param array         $set_cols_n_values
1645
+		 * @param EE_Base_Class $model_object
1646
+		 */
1647
+		$set_cols_n_values = (array)apply_filters('FHEE__EE_Base_Class__save__set_cols_n_values', $set_cols_n_values,
1648
+			$this);
1649
+		//set attributes as provided in $set_cols_n_values
1650
+		foreach ($set_cols_n_values as $column => $value) {
1651
+			$this->set($column, $value);
1652
+		}
1653
+		// no changes ? then don't do anything
1654
+		if (! $this->_has_changes && $this->ID() && $model->get_primary_key_field()->is_auto_increment()) {
1655
+			return 0;
1656
+		}
1657
+		/**
1658
+		 * Saving a model object.
1659
+		 * Before we perform a save, this action is fired.
1660
+		 *
1661
+		 * @param EE_Base_Class $model_object the model object about to be saved.
1662
+		 */
1663
+		do_action('AHEE__EE_Base_Class__save__begin', $this);
1664
+		if ( ! $this->allow_persist()) {
1665
+			return 0;
1666
+		}
1667
+		//now get current attribute values
1668
+		$save_cols_n_values = $this->_fields;
1669
+		//if the object already has an ID, update it. Otherwise, insert it
1670
+		//also: change the assumption about values passed to the model NOT being prepare dby the model object. They have been
1671
+		$old_assumption_concerning_value_preparation = $model
1672
+															->get_assumption_concerning_values_already_prepared_by_model_object();
1673
+		$model->assume_values_already_prepared_by_model_object(true);
1674
+		//does this model have an autoincrement PK?
1675
+		if ($model->has_primary_key_field()) {
1676
+			if ($model->get_primary_key_field()->is_auto_increment()) {
1677
+				//ok check if it's set, if so: update; if not, insert
1678
+				if ( ! empty($save_cols_n_values[$model->primary_key_name()])) {
1679
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1680
+				} else {
1681
+					unset($save_cols_n_values[$model->primary_key_name()]);
1682
+					$results = $model->insert($save_cols_n_values);
1683
+					if ($results) {
1684
+						//if successful, set the primary key
1685
+						//but don't use the normal SET method, because it will check if
1686
+						//an item with the same ID exists in the mapper & db, then
1687
+						//will find it in the db (because we just added it) and THAT object
1688
+						//will get added to the mapper before we can add this one!
1689
+						//but if we just avoid using the SET method, all that headache can be avoided
1690
+						$pk_field_name = $model->primary_key_name();
1691
+						$this->_fields[$pk_field_name] = $results;
1692
+						$this->_clear_cached_property($pk_field_name);
1693
+						$model->add_to_entity_map($this);
1694
+						$this->_update_cached_related_model_objs_fks();
1695
+					}
1696
+				}
1697
+			} else {//PK is NOT auto-increment
1698
+				//so check if one like it already exists in the db
1699
+				if ($model->exists_by_ID($this->ID())) {
1700
+					if (WP_DEBUG && ! $this->in_entity_map()) {
1701
+						throw new EE_Error(
1702
+							sprintf(
1703
+								__('Using a model object %1$s that is NOT in the entity map, can lead to unexpected errors. You should either: %4$s 1. Put it in the entity mapper by calling %2$s %4$s 2. Discard this model object and use what is in the entity mapper %4$s 3. Fetch from the database using %3$s',
1704
+									'event_espresso'),
1705
+								get_class($this),
1706
+								get_class($model) . '::instance()->add_to_entity_map()',
1707
+								get_class($model) . '::instance()->get_one_by_ID()',
1708
+								'<br />'
1709
+							)
1710
+						);
1711
+					}
1712
+					$results = $model->update_by_ID($save_cols_n_values, $this->ID());
1713
+				} else {
1714
+					$results = $model->insert($save_cols_n_values);
1715
+					$this->_update_cached_related_model_objs_fks();
1716
+				}
1717
+			}
1718
+		} else {//there is NO primary key
1719
+			$already_in_db = false;
1720
+			foreach ($model->unique_indexes() as $index) {
1721
+				$uniqueness_where_params = array_intersect_key($save_cols_n_values, $index->fields());
1722
+				if ($model->exists(array($uniqueness_where_params))) {
1723
+					$already_in_db = true;
1724
+				}
1725
+			}
1726
+			if ($already_in_db) {
1727
+				$combined_pk_fields_n_values = array_intersect_key($save_cols_n_values,
1728
+					$model->get_combined_primary_key_fields());
1729
+				$results = $model->update($save_cols_n_values, $combined_pk_fields_n_values);
1730
+			} else {
1731
+				$results = $model->insert($save_cols_n_values);
1732
+			}
1733
+		}
1734
+		//restore the old assumption about values being prepared by the model object
1735
+		$model
1736
+			 ->assume_values_already_prepared_by_model_object($old_assumption_concerning_value_preparation);
1737
+		/**
1738
+		 * After saving the model object this action is called
1739
+		 *
1740
+		 * @param EE_Base_Class $model_object which was just saved
1741
+		 * @param boolean|int   $results      if it were updated, TRUE or FALSE; if it were newly inserted
1742
+		 *                                    the new ID (or 0 if an error occurred and it wasn't updated)
1743
+		 */
1744
+		do_action('AHEE__EE_Base_Class__save__end', $this, $results);
1745
+		$this->_has_changes = false;
1746
+		return $results;
1747
+	}
1748
+
1749
+
1750
+
1751
+	/**
1752
+	 * Updates the foreign key on related models objects pointing to this to have this model object's ID
1753
+	 * as their foreign key.  If the cached related model objects already exist in the db, saves them (so that the DB
1754
+	 * is consistent) Especially useful in case we JUST added this model object ot the database and we want to let its
1755
+	 * cached relations with foreign keys to it know about that change. Eg: we've created a transaction but haven't
1756
+	 * saved it to the db. We also create a registration and don't save it to the DB, but we DO cache it on the
1757
+	 * transaction. Now, when we save the transaction, the registration's TXN_ID will be automatically updated, whether
1758
+	 * or not they exist in the DB (if they do, their DB records will be automatically updated)
1759
+	 *
1760
+	 * @return void
1761
+	 * @throws \EE_Error
1762
+	 */
1763
+	protected function _update_cached_related_model_objs_fks()
1764
+	{
1765
+		$model = $this->get_model();
1766
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
1767
+			if ($relation_obj instanceof EE_Has_Many_Relation) {
1768
+				foreach ($this->get_all_from_cache($relation_name) as $related_model_obj_in_cache) {
1769
+					$fk_to_this = $related_model_obj_in_cache->get_model()->get_foreign_key_to(
1770
+						$model->get_this_model_name()
1771
+					);
1772
+					$related_model_obj_in_cache->set($fk_to_this->get_name(), $this->ID());
1773
+					if ($related_model_obj_in_cache->ID()) {
1774
+						$related_model_obj_in_cache->save();
1775
+					}
1776
+				}
1777
+			}
1778
+		}
1779
+	}
1780
+
1781
+
1782
+
1783
+	/**
1784
+	 * Saves this model object and its NEW cached relations to the database.
1785
+	 * (Meaning, for now, IT DOES NOT WORK if the cached items already exist in the DB.
1786
+	 * In order for that to work, we would need to mark model objects as dirty/clean...
1787
+	 * because otherwise, there's a potential for infinite looping of saving
1788
+	 * Saves the cached related model objects, and ensures the relation between them
1789
+	 * and this object and properly setup
1790
+	 *
1791
+	 * @return int ID of new model object on save; 0 on failure+
1792
+	 * @throws \EE_Error
1793
+	 */
1794
+	public function save_new_cached_related_model_objs()
1795
+	{
1796
+		//make sure this has been saved
1797
+		if ( ! $this->ID()) {
1798
+			$id = $this->save();
1799
+		} else {
1800
+			$id = $this->ID();
1801
+		}
1802
+		//now save all the NEW cached model objects  (ie they don't exist in the DB)
1803
+		foreach ($this->get_model()->relation_settings() as $relationName => $relationObj) {
1804
+			if ($this->_model_relations[$relationName]) {
1805
+				//is this a relation where we should expect just ONE related object (ie, EE_Belongs_To_relation)
1806
+				//or MANY related objects (ie, EE_HABTM_Relation or EE_Has_Many_Relation)?
1807
+				if ($relationObj instanceof EE_Belongs_To_Relation) {
1808
+					//add a relation to that relation type (which saves the appropriate thing in the process)
1809
+					//but ONLY if it DOES NOT exist in the DB
1810
+					/* @var $related_model_obj EE_Base_Class */
1811
+					$related_model_obj = $this->_model_relations[$relationName];
1812
+					//					if( ! $related_model_obj->ID()){
1813
+					$this->_add_relation_to($related_model_obj, $relationName);
1814
+					$related_model_obj->save_new_cached_related_model_objs();
1815
+					//					}
1816
+				} else {
1817
+					foreach ($this->_model_relations[$relationName] as $related_model_obj) {
1818
+						//add a relation to that relation type (which saves the appropriate thing in the process)
1819
+						//but ONLY if it DOES NOT exist in the DB
1820
+						//						if( ! $related_model_obj->ID()){
1821
+						$this->_add_relation_to($related_model_obj, $relationName);
1822
+						$related_model_obj->save_new_cached_related_model_objs();
1823
+						//						}
1824
+					}
1825
+				}
1826
+			}
1827
+		}
1828
+		return $id;
1829
+	}
1830
+
1831
+
1832
+
1833
+	/**
1834
+	 * for getting a model while instantiated.
1835
+	 *
1836
+	 * @return \EEM_Base | \EEM_CPT_Base
1837
+	 */
1838
+	public function get_model()
1839
+	{
1840
+		if( ! $this->_model){
1841
+			$modelName = self::_get_model_classname(get_class($this));
1842
+			$this->_model = self::_get_model_instance_with_name($modelName, $this->_timezone);
1843
+		} else {
1844
+			$this->_model->set_timezone($this->_timezone);
1845
+		}
1846
+
1847
+		return $this->_model;
1848
+	}
1849
+
1850
+
1851
+
1852
+	/**
1853
+	 * @param $props_n_values
1854
+	 * @param $classname
1855
+	 * @return mixed bool|EE_Base_Class|EEM_CPT_Base
1856
+	 * @throws \EE_Error
1857
+	 */
1858
+	protected static function _get_object_from_entity_mapper($props_n_values, $classname)
1859
+	{
1860
+		//TODO: will not work for Term_Relationships because they have no PK!
1861
+		$primary_id_ref = self::_get_primary_key_name($classname);
1862
+		if (array_key_exists($primary_id_ref, $props_n_values) && ! empty($props_n_values[$primary_id_ref])) {
1863
+			$id = $props_n_values[$primary_id_ref];
1864
+			return self::_get_model($classname)->get_from_entity_map($id);
1865
+		}
1866
+		return false;
1867
+	}
1868
+
1869
+
1870
+
1871
+	/**
1872
+	 * This is called by child static "new_instance" method and we'll check to see if there is an existing db entry for
1873
+	 * the primary key (if present in incoming values). If there is a key in the incoming array that matches the
1874
+	 * primary key for the model AND it is not null, then we check the db. If there's a an object we return it.  If not
1875
+	 * we return false.
1876
+	 *
1877
+	 * @param  array  $props_n_values   incoming array of properties and their values
1878
+	 * @param  string $classname        the classname of the child class
1879
+	 * @param null    $timezone
1880
+	 * @param array   $date_formats     incoming date_formats in an array where the first value is the
1881
+	 *                                  date_format and the second value is the time format
1882
+	 * @return mixed (EE_Base_Class|bool)
1883
+	 * @throws \EE_Error
1884
+	 */
1885
+	protected static function _check_for_object($props_n_values, $classname, $timezone = null, $date_formats = array())
1886
+	{
1887
+		$existing = null;
1888
+		$model = self::_get_model($classname, $timezone);
1889
+		if ($model->has_primary_key_field()) {
1890
+			$primary_id_ref = self::_get_primary_key_name($classname);
1891
+			if (array_key_exists($primary_id_ref, $props_n_values)
1892
+				&& ! empty($props_n_values[$primary_id_ref])
1893
+			) {
1894
+				$existing = $model->get_one_by_ID(
1895
+					$props_n_values[$primary_id_ref]
1896
+				);
1897
+			}
1898
+		} elseif ($model->has_all_combined_primary_key_fields($props_n_values)) {
1899
+			//no primary key on this model, but there's still a matching item in the DB
1900
+			$existing = self::_get_model($classname, $timezone)->get_one_by_ID(
1901
+				self::_get_model($classname, $timezone)->get_index_primary_key_string($props_n_values)
1902
+			);
1903
+		}
1904
+		if ($existing) {
1905
+			//set date formats if present before setting values
1906
+			if ( ! empty($date_formats) && is_array($date_formats)) {
1907
+				$existing->set_date_format($date_formats[0]);
1908
+				$existing->set_time_format($date_formats[1]);
1909
+			} else {
1910
+				//set default formats for date and time
1911
+				$existing->set_date_format(get_option('date_format'));
1912
+				$existing->set_time_format(get_option('time_format'));
1913
+			}
1914
+			foreach ($props_n_values as $property => $field_value) {
1915
+				$existing->set($property, $field_value);
1916
+			}
1917
+			return $existing;
1918
+		} else {
1919
+			return false;
1920
+		}
1921
+	}
1922
+
1923
+
1924
+
1925
+	/**
1926
+	 * Gets the EEM_*_Model for this class
1927
+	 *
1928
+	 * @access public now, as this is more convenient
1929
+	 * @param      $classname
1930
+	 * @param null $timezone
1931
+	 * @throws EE_Error
1932
+	 * @return EEM_Base
1933
+	 */
1934
+	protected static function _get_model($classname, $timezone = null)
1935
+	{
1936
+		//find model for this class
1937
+		if ( ! $classname) {
1938
+			throw new EE_Error(
1939
+				sprintf(
1940
+					__(
1941
+						"What were you thinking calling _get_model(%s)?? You need to specify the class name",
1942
+						"event_espresso"
1943
+					),
1944
+					$classname
1945
+				)
1946
+			);
1947
+		}
1948
+		$modelName = self::_get_model_classname($classname);
1949
+		return self::_get_model_instance_with_name($modelName, $timezone);
1950
+	}
1951
+
1952
+
1953
+
1954
+	/**
1955
+	 * Gets the model instance (eg instance of EEM_Attendee) given its classname (eg EE_Attendee)
1956
+	 *
1957
+	 * @param string $model_classname
1958
+	 * @param null   $timezone
1959
+	 * @return EEM_Base
1960
+	 */
1961
+	protected static function _get_model_instance_with_name($model_classname, $timezone = null)
1962
+	{
1963
+		$model_classname = str_replace('EEM_', '', $model_classname);
1964
+		$model = EE_Registry::instance()->load_model($model_classname);
1965
+		$model->set_timezone($timezone);
1966
+		return $model;
1967
+	}
1968
+
1969
+
1970
+
1971
+	/**
1972
+	 * If a model name is provided (eg Registration), gets the model classname for that model.
1973
+	 * Also works if a model class's classname is provided (eg EE_Registration).
1974
+	 *
1975
+	 * @param null $model_name
1976
+	 * @return string like EEM_Attendee
1977
+	 */
1978
+	private static function _get_model_classname($model_name = null)
1979
+	{
1980
+		if (strpos($model_name, "EE_") === 0) {
1981
+			$model_classname = str_replace("EE_", "EEM_", $model_name);
1982
+		} else {
1983
+			$model_classname = "EEM_" . $model_name;
1984
+		}
1985
+		return $model_classname;
1986
+	}
1987
+
1988
+
1989
+
1990
+	/**
1991
+	 * returns the name of the primary key attribute
1992
+	 *
1993
+	 * @param null $classname
1994
+	 * @throws EE_Error
1995
+	 * @return string
1996
+	 */
1997
+	protected static function _get_primary_key_name($classname = null)
1998
+	{
1999
+		if ( ! $classname) {
2000
+			throw new EE_Error(
2001
+				sprintf(
2002
+					__("What were you thinking calling _get_primary_key_name(%s)", "event_espresso"),
2003
+					$classname
2004
+				)
2005
+			);
2006
+		}
2007
+		return self::_get_model($classname)->get_primary_key_field()->get_name();
2008
+	}
2009
+
2010
+
2011
+
2012
+	/**
2013
+	 * Gets the value of the primary key.
2014
+	 * If the object hasn't yet been saved, it should be whatever the model field's default was
2015
+	 * (eg, if this were the EE_Event class, look at the primary key field on EEM_Event and see what its default value
2016
+	 * is. Usually defaults for integer primary keys are 0; string primary keys are usually NULL).
2017
+	 *
2018
+	 * @return mixed, if the primary key is of type INT it'll be an int. Otherwise it could be a string
2019
+	 * @throws \EE_Error
2020
+	 */
2021
+	public function ID()
2022
+	{
2023
+		$model = $this->get_model();
2024
+		//now that we know the name of the variable, use a variable variable to get its value and return its
2025
+		if ($model->has_primary_key_field()) {
2026
+			return $this->_fields[$model->primary_key_name()];
2027
+		} else {
2028
+			return $model->get_index_primary_key_string($this->_fields);
2029
+		}
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Adds a relationship to the specified EE_Base_Class object, given the relationship's name. Eg, if the current
2036
+	 * model is related to a group of events, the $relationName should be 'Event', and should be a key in the EE
2037
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just caches the related thing
2038
+	 *
2039
+	 * @param mixed  $otherObjectModelObjectOrID       EE_Base_Class or the ID of the other object
2040
+	 * @param string $relationName                     eg 'Events','Question',etc.
2041
+	 *                                                 an attendee to a group, you also want to specify which role they
2042
+	 *                                                 will have in that group. So you would use this parameter to
2043
+	 *                                                 specify array('role-column-name'=>'role-id')
2044
+	 * @param array  $extra_join_model_fields_n_values You can optionally include an array of key=>value pairs that
2045
+	 *                                                 allow you to further constrict the relation to being added.
2046
+	 *                                                 However, keep in mind that the columns (keys) given must match a
2047
+	 *                                                 column on the JOIN table and currently only the HABTM models
2048
+	 *                                                 accept these additional conditions.  Also remember that if an
2049
+	 *                                                 exact match isn't found for these extra cols/val pairs, then a
2050
+	 *                                                 NEW row is created in the join table.
2051
+	 * @param null   $cache_id
2052
+	 * @throws EE_Error
2053
+	 * @return EE_Base_Class the object the relation was added to
2054
+	 */
2055
+	public function _add_relation_to(
2056
+		$otherObjectModelObjectOrID,
2057
+		$relationName,
2058
+		$extra_join_model_fields_n_values = array(),
2059
+		$cache_id = null
2060
+	) {
2061
+		$model = $this->get_model();
2062
+		//if this thing exists in the DB, save the relation to the DB
2063
+		if ($this->ID()) {
2064
+			$otherObject = $model
2065
+								->add_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2066
+									$extra_join_model_fields_n_values);
2067
+			//clear cache so future get_many_related and get_first_related() return new results.
2068
+			$this->clear_cache($relationName, $otherObject, true);
2069
+			if ($otherObject instanceof EE_Base_Class) {
2070
+				$otherObject->clear_cache($model->get_this_model_name(), $this);
2071
+			}
2072
+		} else {
2073
+			//this thing doesn't exist in the DB,  so just cache it
2074
+			if ( ! $otherObjectModelObjectOrID instanceof EE_Base_Class) {
2075
+				throw new EE_Error(sprintf(
2076
+					__('Before a model object is saved to the database, calls to _add_relation_to must be passed an actual object, not just an ID. You provided %s as the model object to a %s',
2077
+						'event_espresso'),
2078
+					$otherObjectModelObjectOrID,
2079
+					get_class($this)
2080
+				));
2081
+			} else {
2082
+				$otherObject = $otherObjectModelObjectOrID;
2083
+			}
2084
+			$this->cache($relationName, $otherObjectModelObjectOrID, $cache_id);
2085
+		}
2086
+		if ($otherObject instanceof EE_Base_Class) {
2087
+			//fix the reciprocal relation too
2088
+			if ($otherObject->ID()) {
2089
+				//its saved so assumed relations exist in the DB, so we can just
2090
+				//clear the cache so future queries use the updated info in the DB
2091
+				$otherObject->clear_cache($model->get_this_model_name(), null, true);
2092
+			} else {
2093
+				//it's not saved, so it caches relations like this
2094
+				$otherObject->cache($model->get_this_model_name(), $this);
2095
+			}
2096
+		}
2097
+		return $otherObject;
2098
+	}
2099
+
2100
+
2101
+
2102
+	/**
2103
+	 * Removes a relationship to the specified EE_Base_Class object, given the relationships' name. Eg, if the current
2104
+	 * model is related to a group of events, the $relationName should be 'Events', and should be a key in the EE
2105
+	 * Model's $_model_relations array. If this model object doesn't exist in the DB, just removes the related thing
2106
+	 * from the cache
2107
+	 *
2108
+	 * @param mixed  $otherObjectModelObjectOrID
2109
+	 *                EE_Base_Class or the ID of the other object, OR an array key into the cache if this isn't saved
2110
+	 *                to the DB yet
2111
+	 * @param string $relationName
2112
+	 * @param array  $where_query
2113
+	 *                You can optionally include an array of key=>value pairs that allow you to further constrict the
2114
+	 *                relation to being added. However, keep in mind that the columns (keys) given must match a column
2115
+	 *                on the JOIN table and currently only the HABTM models accept these additional conditions. Also
2116
+	 *                remember that if an exact match isn't found for these extra cols/val pairs, then a NEW row is
2117
+	 *                created in the join table.
2118
+	 * @return EE_Base_Class the relation was removed from
2119
+	 * @throws \EE_Error
2120
+	 */
2121
+	public function _remove_relation_to($otherObjectModelObjectOrID, $relationName, $where_query = array())
2122
+	{
2123
+		if ($this->ID()) {
2124
+			//if this exists in the DB, save the relation change to the DB too
2125
+			$otherObject = $this->get_model()
2126
+								->remove_relationship_to($this, $otherObjectModelObjectOrID, $relationName,
2127
+									$where_query);
2128
+			$this->clear_cache($relationName, $otherObject);
2129
+		} else {
2130
+			//this doesn't exist in the DB, just remove it from the cache
2131
+			$otherObject = $this->clear_cache($relationName, $otherObjectModelObjectOrID);
2132
+		}
2133
+		if ($otherObject instanceof EE_Base_Class) {
2134
+			$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2135
+		}
2136
+		return $otherObject;
2137
+	}
2138
+
2139
+
2140
+
2141
+	/**
2142
+	 * Removes ALL the related things for the $relationName.
2143
+	 *
2144
+	 * @param string $relationName
2145
+	 * @param array  $where_query_params like EEM_Base::get_all's $query_params[0] (where conditions)
2146
+	 * @return EE_Base_Class
2147
+	 * @throws \EE_Error
2148
+	 */
2149
+	public function _remove_relations($relationName, $where_query_params = array())
2150
+	{
2151
+		if ($this->ID()) {
2152
+			//if this exists in the DB, save the relation change to the DB too
2153
+			$otherObjects = $this->get_model()->remove_relations($this, $relationName, $where_query_params);
2154
+			$this->clear_cache($relationName, null, true);
2155
+		} else {
2156
+			//this doesn't exist in the DB, just remove it from the cache
2157
+			$otherObjects = $this->clear_cache($relationName, null, true);
2158
+		}
2159
+		if (is_array($otherObjects)) {
2160
+			foreach ($otherObjects as $otherObject) {
2161
+				$otherObject->clear_cache($this->get_model()->get_this_model_name(), $this);
2162
+			}
2163
+		}
2164
+		return $otherObjects;
2165
+	}
2166
+
2167
+
2168
+
2169
+	/**
2170
+	 * Gets all the related model objects of the specified type. Eg, if the current class if
2171
+	 * EE_Event, you could call $this->get_many_related('Registration') to get an array of all the
2172
+	 * EE_Registration objects which related to this event. Note: by default, we remove the "default query params"
2173
+	 * because we want to get even deleted items etc.
2174
+	 *
2175
+	 * @param string $relationName key in the model's _model_relations array
2176
+	 * @param array  $query_params like EEM_Base::get_all
2177
+	 * @return EE_Base_Class[] Results not necessarily indexed by IDs, because some results might not have primary keys
2178
+	 * @throws \EE_Error
2179
+	 *                             or might not be saved yet. Consider using EEM_Base::get_IDs() on these results if
2180
+	 *                             you want IDs
2181
+	 */
2182
+	public function get_many_related($relationName, $query_params = array())
2183
+	{
2184
+		if ($this->ID()) {
2185
+			//this exists in the DB, so get the related things from either the cache or the DB
2186
+			//if there are query parameters, forget about caching the related model objects.
2187
+			if ($query_params) {
2188
+				$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2189
+			} else {
2190
+				//did we already cache the result of this query?
2191
+				$cached_results = $this->get_all_from_cache($relationName);
2192
+				if ( ! $cached_results) {
2193
+					$related_model_objects = $this->get_model()->get_all_related($this, $relationName, $query_params);
2194
+					//if no query parameters were passed, then we got all the related model objects
2195
+					//for that relation. We can cache them then.
2196
+					foreach ($related_model_objects as $related_model_object) {
2197
+						$this->cache($relationName, $related_model_object);
2198
+					}
2199
+				} else {
2200
+					$related_model_objects = $cached_results;
2201
+				}
2202
+			}
2203
+		} else {
2204
+			//this doesn't exist in the DB, so just get the related things from the cache
2205
+			$related_model_objects = $this->get_all_from_cache($relationName);
2206
+		}
2207
+		return $related_model_objects;
2208
+	}
2209
+
2210
+
2211
+
2212
+	/**
2213
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2214
+	 * unless otherwise specified in the $query_params
2215
+	 *
2216
+	 * @param string $relation_name  model_name like 'Event', or 'Registration'
2217
+	 * @param array  $query_params   like EEM_Base::get_all's
2218
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2219
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2220
+	 *                               that by the setting $distinct to TRUE;
2221
+	 * @return int
2222
+	 */
2223
+	public function count_related($relation_name, $query_params = array(), $field_to_count = null, $distinct = false)
2224
+	{
2225
+		return $this->get_model()->count_related($this, $relation_name, $query_params, $field_to_count, $distinct);
2226
+	}
2227
+
2228
+
2229
+
2230
+	/**
2231
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2232
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2233
+	 *
2234
+	 * @param string $relation_name model_name like 'Event', or 'Registration'
2235
+	 * @param array  $query_params  like EEM_Base::get_all's
2236
+	 * @param string $field_to_sum  name of field to count by.
2237
+	 *                              By default, uses primary key (which doesn't make much sense, so you should probably
2238
+	 *                              change it)
2239
+	 * @return int
2240
+	 */
2241
+	public function sum_related($relation_name, $query_params = array(), $field_to_sum = null)
2242
+	{
2243
+		return $this->get_model()->sum_related($this, $relation_name, $query_params, $field_to_sum);
2244
+	}
2245
+
2246
+
2247
+
2248
+	/**
2249
+	 * Gets the first (ie, one) related model object of the specified type.
2250
+	 *
2251
+	 * @param string $relationName key in the model's _model_relations array
2252
+	 * @param array  $query_params like EEM_Base::get_all
2253
+	 * @return EE_Base_Class (not an array, a single object)
2254
+	 * @throws \EE_Error
2255
+	 */
2256
+	public function get_first_related($relationName, $query_params = array())
2257
+	{
2258
+		$model = $this->get_model();
2259
+		if ($this->ID()) {//this exists in the DB, get from the cache OR the DB
2260
+			//if they've provided some query parameters, don't bother trying to cache the result
2261
+			//also make sure we're not caching the result of get_first_related
2262
+			//on a relation which should have an array of objects (because the cache might have an array of objects)
2263
+			if ($query_params
2264
+				|| ! $model->related_settings_for($relationName)
2265
+					 instanceof
2266
+					 EE_Belongs_To_Relation
2267
+			) {
2268
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2269
+			} else {
2270
+				//first, check if we've already cached the result of this query
2271
+				$cached_result = $this->get_one_from_cache($relationName);
2272
+				if ( ! $cached_result) {
2273
+					$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2274
+					$this->cache($relationName, $related_model_object);
2275
+				} else {
2276
+					$related_model_object = $cached_result;
2277
+				}
2278
+			}
2279
+		} else {
2280
+			$related_model_object = null;
2281
+			//this doesn't exist in the Db, but maybe the relation is of type belongs to, and so the related thing might
2282
+			if ($model->related_settings_for($relationName) instanceof EE_Belongs_To_Relation) {
2283
+				$related_model_object = $model->get_first_related($this, $relationName, $query_params);
2284
+			}
2285
+			//this doesn't exist in the DB and apparently the thing it belongs to doesn't either, just get what's cached on this object
2286
+			if ( ! $related_model_object) {
2287
+				$related_model_object = $this->get_one_from_cache($relationName);
2288
+			}
2289
+		}
2290
+		return $related_model_object;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Does a delete on all related objects of type $relationName and removes
2297
+	 * the current model object's relation to them. If they can't be deleted (because
2298
+	 * of blocking related model objects) does nothing. If the related model objects are
2299
+	 * soft-deletable, they will be soft-deleted regardless of related blocking model objects.
2300
+	 * If this model object doesn't exist yet in the DB, just removes its related things
2301
+	 *
2302
+	 * @param string $relationName
2303
+	 * @param array  $query_params like EEM_Base::get_all's
2304
+	 * @return int how many deleted
2305
+	 * @throws \EE_Error
2306
+	 */
2307
+	public function delete_related($relationName, $query_params = array())
2308
+	{
2309
+		if ($this->ID()) {
2310
+			$count = $this->get_model()->delete_related($this, $relationName, $query_params);
2311
+		} else {
2312
+			$count = count($this->get_all_from_cache($relationName));
2313
+			$this->clear_cache($relationName, null, true);
2314
+		}
2315
+		return $count;
2316
+	}
2317
+
2318
+
2319
+
2320
+	/**
2321
+	 * Does a hard delete (ie, removes the DB row) on all related objects of type $relationName and removes
2322
+	 * the current model object's relation to them. If they can't be deleted (because
2323
+	 * of blocking related model objects) just does a soft delete on it instead, if possible.
2324
+	 * If the related thing isn't a soft-deletable model object, this function is identical
2325
+	 * to delete_related(). If this model object doesn't exist in the DB, just remove its related things
2326
+	 *
2327
+	 * @param string $relationName
2328
+	 * @param array  $query_params like EEM_Base::get_all's
2329
+	 * @return int how many deleted (including those soft deleted)
2330
+	 * @throws \EE_Error
2331
+	 */
2332
+	public function delete_related_permanently($relationName, $query_params = array())
2333
+	{
2334
+		if ($this->ID()) {
2335
+			$count = $this->get_model()->delete_related_permanently($this, $relationName, $query_params);
2336
+		} else {
2337
+			$count = count($this->get_all_from_cache($relationName));
2338
+		}
2339
+		$this->clear_cache($relationName, null, true);
2340
+		return $count;
2341
+	}
2342
+
2343
+
2344
+
2345
+	/**
2346
+	 * is_set
2347
+	 * Just a simple utility function children can use for checking if property exists
2348
+	 *
2349
+	 * @access  public
2350
+	 * @param  string $field_name property to check
2351
+	 * @return bool                              TRUE if existing,FALSE if not.
2352
+	 */
2353
+	public function is_set($field_name)
2354
+	{
2355
+		return isset($this->_fields[$field_name]);
2356
+	}
2357
+
2358
+
2359
+
2360
+	/**
2361
+	 * Just a simple utility function children can use for checking if property (or properties) exists and throwing an
2362
+	 * EE_Error exception if they don't
2363
+	 *
2364
+	 * @param  mixed (string|array) $properties properties to check
2365
+	 * @throws EE_Error
2366
+	 * @return bool                              TRUE if existing, throw EE_Error if not.
2367
+	 */
2368
+	protected function _property_exists($properties)
2369
+	{
2370
+		foreach ((array)$properties as $property_name) {
2371
+			//first make sure this property exists
2372
+			if ( ! $this->_fields[$property_name]) {
2373
+				throw new EE_Error(
2374
+					sprintf(
2375
+						__(
2376
+							'Trying to retrieve a non-existent property (%s).  Double check the spelling please',
2377
+							'event_espresso'
2378
+						),
2379
+						$property_name
2380
+					)
2381
+				);
2382
+			}
2383
+		}
2384
+		return true;
2385
+	}
2386
+
2387
+
2388
+
2389
+	/**
2390
+	 * This simply returns an array of model fields for this object
2391
+	 *
2392
+	 * @return array
2393
+	 * @throws \EE_Error
2394
+	 */
2395
+	public function model_field_array()
2396
+	{
2397
+		$fields = $this->get_model()->field_settings(false);
2398
+		$properties = array();
2399
+		//remove prepended underscore
2400
+		foreach ($fields as $field_name => $settings) {
2401
+			$properties[$field_name] = $this->get($field_name);
2402
+		}
2403
+		return $properties;
2404
+	}
2405
+
2406
+
2407
+
2408
+	/**
2409
+	 * Very handy general function to allow for plugins to extend any child of EE_Base_Class.
2410
+	 * If a method is called on a child of EE_Base_Class that doesn't exist, this function is called
2411
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
2412
+	 * requiring a plugin to extend the EE_Base_Class (which works fine is there's only 1 plugin, but when will that
2413
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
2414
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
2415
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
2416
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
2417
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
2418
+	 * my_callback($previousReturnValue,EE_Base_Class $object,$argsArray){
2419
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
2420
+	 *        return $previousReturnValue.$returnString;
2421
+	 * }
2422
+	 * require('EE_Answer.class.php');
2423
+	 * $answer= EE_Answer::new_instance(array('REG_ID' => 2,'QST_ID' => 3,'ANS_value' => The answer is 42'));
2424
+	 * echo $answer->my_callback('monkeys',100);
2425
+	 * //will output "you called my_callback! and passed args:monkeys,100"
2426
+	 *
2427
+	 * @param string $methodName name of method which was called on a child of EE_Base_Class, but which
2428
+	 * @param array  $args       array of original arguments passed to the function
2429
+	 * @throws EE_Error
2430
+	 * @return mixed whatever the plugin which calls add_filter decides
2431
+	 */
2432
+	public function __call($methodName, $args)
2433
+	{
2434
+		$className = get_class($this);
2435
+		$tagName = "FHEE__{$className}__{$methodName}";
2436
+		if ( ! has_filter($tagName)) {
2437
+			throw new EE_Error(
2438
+				sprintf(
2439
+					__(
2440
+						"Method %s on class %s does not exist! You can create one with the following code in functions.php or in a plugin: add_filter('%s','my_callback',10,3);function my_callback(\$previousReturnValue,EE_Base_Class \$object, \$argsArray){/*function body*/return \$whatever;}",
2441
+						"event_espresso"
2442
+					),
2443
+					$methodName,
2444
+					$className,
2445
+					$tagName
2446
+				)
2447
+			);
2448
+		}
2449
+		return apply_filters($tagName, null, $this, $args);
2450
+	}
2451
+
2452
+
2453
+
2454
+	/**
2455
+	 * Similar to insert_post_meta, adds a record in the Extra_Meta model's table with the given key and value.
2456
+	 * A $previous_value can be specified in case there are many meta rows with the same key
2457
+	 *
2458
+	 * @param string $meta_key
2459
+	 * @param mixed  $meta_value
2460
+	 * @param mixed  $previous_value
2461
+	 * @return bool|int # of records updated (or BOOLEAN if we actually ended up inserting the extra meta row)
2462
+	 * @throws \EE_Error
2463
+	 * NOTE: if the values haven't changed, returns 0
2464
+	 */
2465
+	public function update_extra_meta($meta_key, $meta_value, $previous_value = null)
2466
+	{
2467
+		$query_params = array(
2468
+			array(
2469
+				'EXM_key'  => $meta_key,
2470
+				'OBJ_ID'   => $this->ID(),
2471
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2472
+			),
2473
+		);
2474
+		if ($previous_value !== null) {
2475
+			$query_params[0]['EXM_value'] = $meta_value;
2476
+		}
2477
+		$existing_rows_like_that = EEM_Extra_Meta::instance()->get_all($query_params);
2478
+		if ( ! $existing_rows_like_that) {
2479
+			return $this->add_extra_meta($meta_key, $meta_value);
2480
+		}
2481
+		foreach ($existing_rows_like_that as $existing_row) {
2482
+			$existing_row->save(array('EXM_value' => $meta_value));
2483
+		}
2484
+		return count($existing_rows_like_that);
2485
+	}
2486
+
2487
+
2488
+
2489
+	/**
2490
+	 * Adds a new extra meta record. If $unique is set to TRUE, we'll first double-check
2491
+	 * no other extra meta for this model object have the same key. Returns TRUE if the
2492
+	 * extra meta row was entered, false if not
2493
+	 *
2494
+	 * @param string  $meta_key
2495
+	 * @param mixed   $meta_value
2496
+	 * @param boolean $unique
2497
+	 * @return boolean
2498
+	 * @throws \EE_Error
2499
+	 */
2500
+	public function add_extra_meta($meta_key, $meta_value, $unique = false)
2501
+	{
2502
+		if ($unique) {
2503
+			$existing_extra_meta = EEM_Extra_Meta::instance()->get_one(
2504
+				array(
2505
+					array(
2506
+						'EXM_key'  => $meta_key,
2507
+						'OBJ_ID'   => $this->ID(),
2508
+						'EXM_type' => $this->get_model()->get_this_model_name(),
2509
+					),
2510
+				)
2511
+			);
2512
+			if ($existing_extra_meta) {
2513
+				return false;
2514
+			}
2515
+		}
2516
+		$new_extra_meta = EE_Extra_Meta::new_instance(
2517
+			array(
2518
+				'EXM_key'   => $meta_key,
2519
+				'EXM_value' => $meta_value,
2520
+				'OBJ_ID'    => $this->ID(),
2521
+				'EXM_type'  => $this->get_model()->get_this_model_name(),
2522
+			)
2523
+		);
2524
+		$new_extra_meta->save();
2525
+		return true;
2526
+	}
2527
+
2528
+
2529
+
2530
+	/**
2531
+	 * Deletes all the extra meta rows for this record as specified by key. If $meta_value
2532
+	 * is specified, only deletes extra meta records with that value.
2533
+	 *
2534
+	 * @param string $meta_key
2535
+	 * @param mixed  $meta_value
2536
+	 * @return int number of extra meta rows deleted
2537
+	 * @throws \EE_Error
2538
+	 */
2539
+	public function delete_extra_meta($meta_key, $meta_value = null)
2540
+	{
2541
+		$query_params = array(
2542
+			array(
2543
+				'EXM_key'  => $meta_key,
2544
+				'OBJ_ID'   => $this->ID(),
2545
+				'EXM_type' => $this->get_model()->get_this_model_name(),
2546
+			),
2547
+		);
2548
+		if ($meta_value !== null) {
2549
+			$query_params[0]['EXM_value'] = $meta_value;
2550
+		}
2551
+		return EEM_Extra_Meta::instance()->delete($query_params);
2552
+	}
2553
+
2554
+
2555
+
2556
+	/**
2557
+	 * Gets the extra meta with the given meta key. If you specify "single" we just return 1, otherwise
2558
+	 * an array of everything found. Requires that this model actually have a relation of type EE_Has_Many_Any_Relation.
2559
+	 * You can specify $default is case you haven't found the extra meta
2560
+	 *
2561
+	 * @param string  $meta_key
2562
+	 * @param boolean $single
2563
+	 * @param mixed   $default if we don't find anything, what should we return?
2564
+	 * @return mixed single value if $single; array if ! $single
2565
+	 * @throws \EE_Error
2566
+	 */
2567
+	public function get_extra_meta($meta_key, $single = false, $default = null)
2568
+	{
2569
+		if ($single) {
2570
+			$result = $this->get_first_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2571
+			if ($result instanceof EE_Extra_Meta) {
2572
+				return $result->value();
2573
+			}
2574
+		} else {
2575
+			$results = $this->get_many_related('Extra_Meta', array(array('EXM_key' => $meta_key)));
2576
+			if ($results) {
2577
+				$values = array();
2578
+				foreach ($results as $result) {
2579
+					if ($result instanceof EE_Extra_Meta) {
2580
+						$values[$result->ID()] = $result->value();
2581
+					}
2582
+				}
2583
+				return $values;
2584
+			}
2585
+		}
2586
+		//if nothing discovered yet return default.
2587
+		return apply_filters(
2588
+			'FHEE__EE_Base_Class__get_extra_meta__default_value',
2589
+			$default,
2590
+			$meta_key,
2591
+			$single,
2592
+			$this
2593
+			);
2594
+	}
2595
+
2596
+
2597
+
2598
+	/**
2599
+	 * Returns a simple array of all the extra meta associated with this model object.
2600
+	 * If $one_of_each_key is true (Default), it will be an array of simple key-value pairs, keys being the
2601
+	 * extra meta's key, and teh value being its value. However, if there are duplicate extra meta rows with
2602
+	 * the same key, only one will be used. (eg array('foo'=>'bar','monkey'=>123))
2603
+	 * If $one_of_each_key is false, it will return an array with the top-level keys being
2604
+	 * the extra meta keys, but their values are also arrays, which have the extra-meta's ID as their sub-key, and
2605
+	 * finally the extra meta's value as each sub-value. (eg
2606
+	 * array('foo'=>array(1=>'bar',2=>'bill'),'monkey'=>array(3=>123)))
2607
+	 *
2608
+	 * @param boolean $one_of_each_key
2609
+	 * @return array
2610
+	 * @throws \EE_Error
2611
+	 */
2612
+	public function all_extra_meta_array($one_of_each_key = true)
2613
+	{
2614
+		$return_array = array();
2615
+		if ($one_of_each_key) {
2616
+			$extra_meta_objs = $this->get_many_related('Extra_Meta', array('group_by' => 'EXM_key'));
2617
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2618
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2619
+					$return_array[$extra_meta_obj->key()] = $extra_meta_obj->value();
2620
+				}
2621
+			}
2622
+		} else {
2623
+			$extra_meta_objs = $this->get_many_related('Extra_Meta');
2624
+			foreach ($extra_meta_objs as $extra_meta_obj) {
2625
+				if ($extra_meta_obj instanceof EE_Extra_Meta) {
2626
+					if ( ! isset($return_array[$extra_meta_obj->key()])) {
2627
+						$return_array[$extra_meta_obj->key()] = array();
2628
+					}
2629
+					$return_array[$extra_meta_obj->key()][$extra_meta_obj->ID()] = $extra_meta_obj->value();
2630
+				}
2631
+			}
2632
+		}
2633
+		return $return_array;
2634
+	}
2635
+
2636
+
2637
+
2638
+	/**
2639
+	 * Gets a pretty nice displayable nice for this model object. Often overridden
2640
+	 *
2641
+	 * @return string
2642
+	 * @throws \EE_Error
2643
+	 */
2644
+	public function name()
2645
+	{
2646
+		//find a field that's not a text field
2647
+		$field_we_can_use = $this->get_model()->get_a_field_of_type('EE_Text_Field_Base');
2648
+		if ($field_we_can_use) {
2649
+			return $this->get($field_we_can_use->get_name());
2650
+		} else {
2651
+			$first_few_properties = $this->model_field_array();
2652
+			$first_few_properties = array_slice($first_few_properties, 0, 3);
2653
+			$name_parts = array();
2654
+			foreach ($first_few_properties as $name => $value) {
2655
+				$name_parts[] = "$name:$value";
2656
+			}
2657
+			return implode(",", $name_parts);
2658
+		}
2659
+	}
2660
+
2661
+
2662
+
2663
+	/**
2664
+	 * in_entity_map
2665
+	 * Checks if this model object has been proven to already be in the entity map
2666
+	 *
2667
+	 * @return boolean
2668
+	 * @throws \EE_Error
2669
+	 */
2670
+	public function in_entity_map()
2671
+	{
2672
+		if ($this->ID() && $this->get_model()->get_from_entity_map($this->ID()) === $this) {
2673
+			//well, if we looked, did we find it in the entity map?
2674
+			return true;
2675
+		} else {
2676
+			return false;
2677
+		}
2678
+	}
2679
+
2680
+
2681
+
2682
+	/**
2683
+	 * refresh_from_db
2684
+	 * Makes sure the fields and values on this model object are in-sync with what's in the database.
2685
+	 *
2686
+	 * @throws EE_Error if this model object isn't in the entity mapper (because then you should
2687
+	 * just use what's in the entity mapper and refresh it) and WP_DEBUG is TRUE
2688
+	 */
2689
+	public function refresh_from_db()
2690
+	{
2691
+		if ($this->ID() && $this->in_entity_map()) {
2692
+			$this->get_model()->refresh_entity_map_from_db($this->ID());
2693
+		} else {
2694
+			//if it doesn't have ID, you shouldn't be asking to refresh it from teh database (because its not in the database)
2695
+			//if it has an ID but it's not in the map, and you're asking me to refresh it
2696
+			//that's kinda dangerous. You should just use what's in the entity map, or add this to the entity map if there's
2697
+			//absolutely nothing in it for this ID
2698
+			if (WP_DEBUG) {
2699
+				throw new EE_Error(
2700
+					sprintf(
2701
+						__('Trying to refresh a model object with ID "%1$s" that\'s not in the entity map? First off: you should put it in the entity map by calling %2$s. Second off, if you want what\'s in the database right now, you should just call %3$s yourself and discard this model object.',
2702
+							'event_espresso'),
2703
+						$this->ID(),
2704
+						get_class($this->get_model()) . '::instance()->add_to_entity_map()',
2705
+						get_class($this->get_model()) . '::instance()->refresh_entity_map()'
2706
+					)
2707
+				);
2708
+			}
2709
+		}
2710
+	}
2711
+
2712
+
2713
+
2714
+	/**
2715
+	 * Because some other plugins, like Advanced Cron Manager, expect all objects to have this method
2716
+	 * (probably a bad assumption they have made, oh well)
2717
+	 *
2718
+	 * @return string
2719
+	 */
2720
+	public function __toString()
2721
+	{
2722
+		try {
2723
+			return sprintf('%s (%s)', $this->name(), $this->ID());
2724
+		} catch (Exception $e) {
2725
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
2726
+			return '';
2727
+		}
2728
+	}
2729
+
2730
+
2731
+
2732
+	/**
2733
+	 * Clear related model objects if they're already in the DB, because otherwise when we
2734
+	 * UN-serialize this model object we'll need to be careful to add them to the entity map.
2735
+	 * This means if we have made changes to those related model objects, and want to unserialize
2736
+	 * the this model object on a subsequent request, changes to those related model objects will be lost.
2737
+	 * Instead, those related model objects should be directly serialized and stored.
2738
+	 * Eg, the following won't work:
2739
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2740
+	 * $att = $reg->attendee();
2741
+	 * $att->set( 'ATT_fname', 'Dirk' );
2742
+	 * update_option( 'my_option', serialize( $reg ) );
2743
+	 * //END REQUEST
2744
+	 * //START NEXT REQUEST
2745
+	 * $reg = get_option( 'my_option' );
2746
+	 * $reg->attendee()->save();
2747
+	 * And would need to be replace with:
2748
+	 * $reg = EEM_Registration::instance()->get_one_by_ID( 123 );
2749
+	 * $att = $reg->attendee();
2750
+	 * $att->set( 'ATT_fname', 'Dirk' );
2751
+	 * update_option( 'my_option', serialize( $reg ) );
2752
+	 * //END REQUEST
2753
+	 * //START NEXT REQUEST
2754
+	 * $att = get_option( 'my_option' );
2755
+	 * $att->save();
2756
+	 *
2757
+	 * @return array
2758
+	 * @throws \EE_Error
2759
+	 */
2760
+	public function __sleep()
2761
+	{
2762
+		$model = $this->get_model();
2763
+		foreach ($model->relation_settings() as $relation_name => $relation_obj) {
2764
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
2765
+				$classname = 'EE_' . $model->get_this_model_name();
2766
+				if (
2767
+					$this->get_one_from_cache($relation_name) instanceof $classname
2768
+					&& $this->get_one_from_cache($relation_name)->ID()
2769
+				) {
2770
+					$this->clear_cache($relation_name, $this->get_one_from_cache($relation_name)->ID());
2771
+				}
2772
+			}
2773
+		}
2774
+		$this->_props_n_values_provided_in_constructor = array();
2775
+		$properties_to_serialize = get_object_vars($this);
2776
+		//don't serialize the model. It's big and that risks recursion
2777
+		unset($properties_to_serialize['_model']);
2778
+		return array_keys($properties_to_serialize);
2779
+	}
2780
+
2781
+
2782
+
2783
+	/**
2784
+	 * restore _props_n_values_provided_in_constructor
2785
+	 * PLZ NOTE: this will reset the array to whatever fields values were present prior to serialization,
2786
+	 * and therefore should NOT be used to determine if state change has occurred since initial construction.
2787
+	 * At best, you would only be able to detect if state change has occurred during THIS request.
2788
+	 */
2789
+	public function __wakeup()
2790
+	{
2791
+		$this->_props_n_values_provided_in_constructor = $this->_fields;
2792
+	}
2793 2793
 
2794 2794
 
2795 2795
 
Please login to merge, or discard this patch.
core/db_classes/EE_Question_Group.class.php 1 patch
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1
-<?php if ( !defined( 'EVENT_ESPRESSO_VERSION' ) ) {
2
-	exit( 'No direct script access allowed' );
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /**
5 5
  * Event Espresso
@@ -32,9 +32,9 @@  discard block
 block discarded – undo
32 32
 	 * @param array $props_n_values
33 33
 	 * @return EE_Question_Group|mixed
34 34
 	 */
35
-	public static function new_instance( $props_n_values = array() ) {
36
-		$has_object = parent::_check_for_object( $props_n_values, __CLASS__ );
37
-		return $has_object ? $has_object : new self( $props_n_values );
35
+	public static function new_instance($props_n_values = array()) {
36
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
37
+		return $has_object ? $has_object : new self($props_n_values);
38 38
 	}
39 39
 
40 40
 
@@ -43,8 +43,8 @@  discard block
 block discarded – undo
43 43
 	 * @param array $props_n_values
44 44
 	 * @return EE_Question_Group
45 45
 	 */
46
-	public static function new_instance_from_db( $props_n_values = array() ) {
47
-		return new self( $props_n_values, TRUE );
46
+	public static function new_instance_from_db($props_n_values = array()) {
47
+		return new self($props_n_values, TRUE);
48 48
 	}
49 49
 
50 50
 
@@ -55,8 +55,8 @@  discard block
 block discarded – undo
55 55
 	 * @param bool $pretty
56 56
 	 * @return string
57 57
 	 */
58
-	public function name( $pretty = FALSE ) {
59
-		return $pretty ? $this->get_pretty( 'QSG_name' ) : $this->get( 'QSG_name' );
58
+	public function name($pretty = FALSE) {
59
+		return $pretty ? $this->get_pretty('QSG_name') : $this->get('QSG_name');
60 60
 	}
61 61
 
62 62
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 	 * @return string
69 69
 	 */
70 70
 	public function identifier() {
71
-		return $this->get( 'QSG_identifier' );
71
+		return $this->get('QSG_identifier');
72 72
 	}
73 73
 
74 74
 
@@ -79,8 +79,8 @@  discard block
 block discarded – undo
79 79
 	 * @param bool $pretty
80 80
 	 * @return string
81 81
 	 */
82
-	public function desc( $pretty = FALSE ) {
83
-		return $pretty ? $this->get_pretty( 'QSG_desc' ) : $this->get( 'QSG_desc' );
82
+	public function desc($pretty = FALSE) {
83
+		return $pretty ? $this->get_pretty('QSG_desc') : $this->get('QSG_desc');
84 84
 	}
85 85
 
86 86
 
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 	 * @return int
93 93
 	 */
94 94
 	public function order() {
95
-		return $this->get( 'QSG_order' );
95
+		return $this->get('QSG_order');
96 96
 	}
97 97
 
98 98
 
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 * @return boolean
104 104
 	 */
105 105
 	public function show_group_name() {
106
-		return $this->get( 'QSG_show_group_name' );
106
+		return $this->get('QSG_show_group_name');
107 107
 	}
108 108
 
109 109
 
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 	 * @return boolean
116 116
 	 */
117 117
 	public function show_group_desc() {
118
-		return $this->get( 'QSG_show_group_desc' );
118
+		return $this->get('QSG_show_group_desc');
119 119
 	}
120 120
 
121 121
 
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 	 * @return int
129 129
 	 */
130 130
 	public function system_group() {
131
-		return $this->get( 'QSG_system' );
131
+		return $this->get('QSG_system');
132 132
 	}
133 133
 
134 134
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	 * @return boolean
154 154
 	 */
155 155
 	public function deleted() {
156
-		return $this->get( 'QST_deleted' );
156
+		return $this->get('QST_deleted');
157 157
 	}
158 158
 
159 159
 
@@ -164,8 +164,8 @@  discard block
 block discarded – undo
164 164
 	 */
165 165
 	public function questions_in_and_not_in_group() {
166 166
 		$questions_in_group = $this->questions();
167
-		$exclude_question_ids = ! empty( $questions_in_group ) ? array_keys( $questions_in_group ) : array();
168
-		$questions_not_in_group = $this->questions_not_in_group( $exclude_question_ids );
167
+		$exclude_question_ids = ! empty($questions_in_group) ? array_keys($questions_in_group) : array();
168
+		$questions_not_in_group = $this->questions_not_in_group($exclude_question_ids);
169 169
 		return $questions_in_group + $questions_not_in_group;
170 170
 	}
171 171
 
@@ -176,9 +176,9 @@  discard block
 block discarded – undo
176 176
 	 * @param array $query_params
177 177
 	 * @return EE_Question[]
178 178
 	 */
179
-	public function questions( $query_params = array() ) {
180
-		$query_params = ! empty( $query_params ) ? $query_params : array( 'order_by' => array( 'Question_Group_Question.QGQ_order' => 'ASC' ) );
181
-		return $this->ID() ? $this->get_many_related( 'Question', $query_params ) : array();
179
+	public function questions($query_params = array()) {
180
+		$query_params = ! empty($query_params) ? $query_params : array('order_by' => array('Question_Group_Question.QGQ_order' => 'ASC'));
181
+		return $this->ID() ? $this->get_many_related('Question', $query_params) : array();
182 182
 	}
183 183
 
184 184
 
@@ -188,14 +188,14 @@  discard block
 block discarded – undo
188 188
 	 * @param  mixed $question_IDS_in_group if empty array then all questions returned.  if FALSE then we first get questions in this group and exclude them from questions get all. IF empty array then we just return all questions.
189 189
 	 * @return EE_Question[]
190 190
 	 */
191
-	public function questions_not_in_group( $question_IDS_in_group = FALSE ) {
192
-		if ( $question_IDS_in_group === FALSE ) {
191
+	public function questions_not_in_group($question_IDS_in_group = FALSE) {
192
+		if ($question_IDS_in_group === FALSE) {
193 193
 			$questions = $this->questions();
194
-			$question_IDS_in_group = ! empty( $questions ) ? array_keys( $questions ) : array();
194
+			$question_IDS_in_group = ! empty($questions) ? array_keys($questions) : array();
195 195
 		}
196
-		$_where = ! empty( $question_IDS_in_group ) ? array( 'QST_ID' => array( 'not_in', $question_IDS_in_group ) ) : array();
196
+		$_where = ! empty($question_IDS_in_group) ? array('QST_ID' => array('not_in', $question_IDS_in_group)) : array();
197 197
 
198
-		return EEM_Question::instance()->get_all( array( $_where, 'order_by' => array( 'QST_ID' => 'ASC' ) ) );
198
+		return EEM_Question::instance()->get_all(array($_where, 'order_by' => array('QST_ID' => 'ASC')));
199 199
 	}
200 200
 
201 201
 
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 	 * @return EE_Event[]
206 206
 	 */
207 207
 	public function events() {
208
-		return $this->get_many_related( 'Event' );
208
+		return $this->get_many_related('Event');
209 209
 	}
210 210
 
211 211
 
@@ -215,8 +215,8 @@  discard block
 block discarded – undo
215 215
 	 * @param EE_Question || int $question object or ID
216 216
 	 * @return boolean if successful
217 217
 	 */
218
-	public function add_question( $questionObjectOrID ) {
219
-		return $this->_add_relation_to( $questionObjectOrID, 'Question' );
218
+	public function add_question($questionObjectOrID) {
219
+		return $this->_add_relation_to($questionObjectOrID, 'Question');
220 220
 	}
221 221
 
222 222
 
@@ -226,8 +226,8 @@  discard block
 block discarded – undo
226 226
 	 * @param EE_Question || int $question object or ID
227 227
 	 * @return boolean of success
228 228
 	 */
229
-	public function remove_question( $questionObjectOrID ) {
230
-		return $this->_remove_relation_to( $questionObjectOrID, 'Question' );
229
+	public function remove_question($questionObjectOrID) {
230
+		return $this->_remove_relation_to($questionObjectOrID, 'Question');
231 231
 	}
232 232
 
233 233
 
@@ -237,9 +237,9 @@  discard block
 block discarded – undo
237 237
 	 * @param $qst_order
238 238
 	 * @return int
239 239
 	 */
240
-	public function update_question_order( $questionObjectOrID, $qst_order ) {
241
-		$qst_ID = $questionObjectOrID instanceof EE_Question ? $questionObjectOrID->ID() : (int)$questionObjectOrID;
242
-		return EEM_Question_Group_Question::instance()->update( array( 'QGQ_order' => $qst_order ), array( array( 'QST_ID' => $qst_ID, 'QSG_ID' => $this->ID() ) ) );
240
+	public function update_question_order($questionObjectOrID, $qst_order) {
241
+		$qst_ID = $questionObjectOrID instanceof EE_Question ? $questionObjectOrID->ID() : (int) $questionObjectOrID;
242
+		return EEM_Question_Group_Question::instance()->update(array('QGQ_order' => $qst_order), array(array('QST_ID' => $qst_ID, 'QSG_ID' => $this->ID())));
243 243
 	}
244 244
 
245 245
 
@@ -250,9 +250,9 @@  discard block
 block discarded – undo
250 250
 	 */
251 251
 	public function has_questions_with_answers() {
252 252
 		$has_answers = FALSE;
253
-		$questions = $this->get_many_related( 'Question' );
254
-		foreach ( $questions as $question ) {
255
-			if ( $question->count_related( 'Answer' ) > 0 )
253
+		$questions = $this->get_many_related('Question');
254
+		foreach ($questions as $question) {
255
+			if ($question->count_related('Answer') > 0)
256 256
 				$has_answers = TRUE;
257 257
 		}
258 258
 		return $has_answers;
@@ -268,7 +268,7 @@  discard block
 block discarded – undo
268 268
 	 */
269 269
 	public function set_order_to_latest() {
270 270
 		$latest_order = $this->get_model()->get_latest_question_group_order();
271
-		$latest_order ++;
272
-		$this->set( 'QSG_order', $latest_order );
271
+		$latest_order++;
272
+		$this->set('QSG_order', $latest_order);
273 273
 	}
274 274
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Event.class.php 1 patch
Indentation   +1335 added lines, -1335 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\exceptions\UnexpectedEntityException;
5 5
 
6 6
 if (!defined('EVENT_ESPRESSO_VERSION')) {
7
-    exit('No direct script access allowed');
7
+	exit('No direct script access allowed');
8 8
 }
9 9
 
10 10
 
@@ -18,1339 +18,1339 @@  discard block
 block discarded – undo
18 18
 class EE_Event extends EE_CPT_Base implements EEI_Line_Item_Object, EEI_Admin_Links, EEI_Has_Icon, EEI_Event
19 19
 {
20 20
 
21
-    /**
22
-     * cached value for the the logical active status for the event
23
-     *
24
-     * @see get_active_status()
25
-     * @var string
26
-     */
27
-    protected $_active_status = '';
28
-
29
-    /**
30
-     * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
-     *
32
-     * @var EE_Datetime
33
-     */
34
-    protected $_Primary_Datetime;
35
-
36
-    /**
37
-     * @var EventSpacesCalculator $available_spaces_calculator
38
-     */
39
-    protected $available_spaces_calculator;
40
-
41
-
42
-    /**
43
-     * @param array $props_n_values incoming values
44
-     * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
-     *                                        used.)
46
-     * @param array $date_formats incoming date_formats in an array where the first value is the
47
-     *                                        date_format and the second value is the time format
48
-     * @return EE_Event
49
-     * @throws EE_Error
50
-     */
51
-    public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
-    {
53
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
-        return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
-    }
56
-
57
-
58
-    /**
59
-     * @param array $props_n_values incoming values from the database
60
-     * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
-     *                                the website will be used.
62
-     * @return EE_Event
63
-     * @throws EE_Error
64
-     */
65
-    public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
-    {
67
-        return new self($props_n_values, true, $timezone);
68
-    }
69
-
70
-
71
-
72
-    /**
73
-     * @return EventSpacesCalculator
74
-     * @throws \EE_Error
75
-     */
76
-    public function getAvailableSpacesCalculator()
77
-    {
78
-        if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
-            $this->available_spaces_calculator = new EventSpacesCalculator($this);
80
-        }
81
-        return $this->available_spaces_calculator;
82
-    }
83
-
84
-
85
-
86
-    /**
87
-     * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
-     *
89
-     * @param string $field_name
90
-     * @param mixed $field_value
91
-     * @param bool $use_default
92
-     * @throws EE_Error
93
-     */
94
-    public function set($field_name, $field_value, $use_default = false)
95
-    {
96
-        switch ($field_name) {
97
-            case 'status' :
98
-                $this->set_status($field_value, $use_default);
99
-                break;
100
-            default :
101
-                parent::set($field_name, $field_value, $use_default);
102
-        }
103
-    }
104
-
105
-
106
-    /**
107
-     *    set_status
108
-     * Checks if event status is being changed to SOLD OUT
109
-     * and updates event meta data with previous event status
110
-     * so that we can revert things if/when the event is no longer sold out
111
-     *
112
-     * @access public
113
-     * @param string $new_status
114
-     * @param bool $use_default
115
-     * @return void
116
-     * @throws EE_Error
117
-     */
118
-    public function set_status($new_status = null, $use_default = false)
119
-    {
120
-        // if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
-        if (empty($new_status) && !$use_default) {
122
-            return;
123
-        }
124
-        // get current Event status
125
-        $old_status = $this->status();
126
-        // if status has changed
127
-        if ($old_status !== $new_status) {
128
-            // TO sold_out
129
-            if ($new_status === EEM_Event::sold_out) {
130
-                // save the previous event status so that we can revert if the event is no longer sold out
131
-                $this->add_post_meta('_previous_event_status', $old_status);
132
-                do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
-                // OR FROM  sold_out
134
-            } else if ($old_status === EEM_Event::sold_out) {
135
-                $this->delete_post_meta('_previous_event_status');
136
-                do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
-            }
138
-            //clear out the active status so that it gets reset the next time it is requested
139
-            $this->_active_status = null;
140
-            // update status
141
-            parent::set('status', $new_status, $use_default);
142
-            do_action('AHEE__EE_Event__set_status__after_update', $this);
143
-            return;
144
-        }
145
-        // even though the old value matches the new value, it's still good to
146
-        // allow the parent set method to have a say
147
-        parent::set('status', $new_status, $use_default);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets all the datetimes for this event
153
-     *
154
-     * @param array $query_params like EEM_Base::get_all
155
-     * @return EE_Base_Class[]|EE_Datetime[]
156
-     * @throws EE_Error
157
-     */
158
-    public function datetimes($query_params = array())
159
-    {
160
-        return $this->get_many_related('Datetime', $query_params);
161
-    }
162
-
163
-
164
-    /**
165
-     * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
166
-     *
167
-     * @return EE_Base_Class[]|EE_Datetime[]
168
-     * @throws EE_Error
169
-     */
170
-    public function datetimes_in_chronological_order()
171
-    {
172
-        return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
173
-    }
174
-
175
-
176
-    /**
177
-     * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
178
-     * @darren, we should probably UNSET timezone on the EEM_Datetime model
179
-     * after running our query, so that this timezone isn't set for EVERY query
180
-     * on EEM_Datetime for the rest of the request, no?
181
-     *
182
-     * @param boolean $show_expired whether or not to include expired events
183
-     * @param boolean $show_deleted whether or not to include deleted events
184
-     * @param null $limit
185
-     * @return EE_Datetime[]
186
-     * @throws EE_Error
187
-     */
188
-    public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
189
-    {
190
-        return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
191
-            $this->ID(),
192
-            $show_expired,
193
-            $show_deleted,
194
-            $limit
195
-        );
196
-    }
197
-
198
-
199
-    /**
200
-     * Returns one related datetime. Mostly only used by some legacy code.
201
-     *
202
-     * @return EE_Base_Class|EE_Datetime
203
-     * @throws EE_Error
204
-     */
205
-    public function first_datetime()
206
-    {
207
-        return $this->get_first_related('Datetime');
208
-    }
209
-
210
-
211
-    /**
212
-     * Returns the 'primary' datetime for the event
213
-     *
214
-     * @param bool $try_to_exclude_expired
215
-     * @param bool $try_to_exclude_deleted
216
-     * @return EE_Datetime
217
-     * @throws EE_Error
218
-     */
219
-    public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
220
-    {
221
-        if (!empty ($this->_Primary_Datetime)) {
222
-            return $this->_Primary_Datetime;
223
-        }
224
-        $this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
225
-            $this->ID(),
226
-            $try_to_exclude_expired,
227
-            $try_to_exclude_deleted
228
-        );
229
-        return $this->_Primary_Datetime;
230
-    }
231
-
232
-
233
-    /**
234
-     * Gets all the tickets available for purchase of this event
235
-     *
236
-     * @param array $query_params like EEM_Base::get_all
237
-     * @return EE_Base_Class[]|EE_Ticket[]
238
-     * @throws EE_Error
239
-     */
240
-    public function tickets($query_params = array())
241
-    {
242
-        //first get all datetimes
243
-        $datetimes = $this->datetimes_ordered();
244
-        if (!$datetimes) {
245
-            return array();
246
-        }
247
-        $datetime_ids = array();
248
-        foreach ($datetimes as $datetime) {
249
-            $datetime_ids[] = $datetime->ID();
250
-        }
251
-        $where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
252
-        //if incoming $query_params has where conditions let's merge but not override existing.
253
-        if (is_array($query_params) && isset($query_params[0])) {
254
-            $where_params = array_merge($query_params[0], $where_params);
255
-            unset($query_params[0]);
256
-        }
257
-        //now add $where_params to $query_params
258
-        $query_params[0] = $where_params;
259
-        return EEM_Ticket::instance()->get_all($query_params);
260
-    }
261
-
262
-
263
-    /**
264
-     * get all unexpired untrashed tickets
265
-     *
266
-     * @return EE_Ticket[]
267
-     * @throws EE_Error
268
-     */
269
-    public function active_tickets()
270
-    {
271
-        return $this->tickets(array(
272
-            array(
273
-                'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
274
-                'TKT_deleted' => false,
275
-            ),
276
-        ));
277
-    }
278
-
279
-
280
-    /**
281
-     * @return bool
282
-     * @throws EE_Error
283
-     */
284
-    public function additional_limit()
285
-    {
286
-        return $this->get('EVT_additional_limit');
287
-    }
288
-
289
-
290
-    /**
291
-     * @return bool
292
-     * @throws EE_Error
293
-     */
294
-    public function allow_overflow()
295
-    {
296
-        return $this->get('EVT_allow_overflow');
297
-    }
298
-
299
-
300
-    /**
301
-     * @return bool
302
-     * @throws EE_Error
303
-     */
304
-    public function created()
305
-    {
306
-        return $this->get('EVT_created');
307
-    }
308
-
309
-
310
-    /**
311
-     * @return bool
312
-     * @throws EE_Error
313
-     */
314
-    public function description()
315
-    {
316
-        return $this->get('EVT_desc');
317
-    }
318
-
319
-
320
-    /**
321
-     * Runs do_shortcode and wpautop on the description
322
-     *
323
-     * @return string of html
324
-     * @throws EE_Error
325
-     */
326
-    public function description_filtered()
327
-    {
328
-        return $this->get_pretty('EVT_desc');
329
-    }
330
-
331
-
332
-    /**
333
-     * @return bool
334
-     * @throws EE_Error
335
-     */
336
-    public function display_description()
337
-    {
338
-        return $this->get('EVT_display_desc');
339
-    }
340
-
341
-
342
-    /**
343
-     * @return bool
344
-     * @throws EE_Error
345
-     */
346
-    public function display_ticket_selector()
347
-    {
348
-        return (bool)$this->get('EVT_display_ticket_selector');
349
-    }
350
-
351
-
352
-    /**
353
-     * @return bool
354
-     * @throws EE_Error
355
-     */
356
-    public function external_url()
357
-    {
358
-        return $this->get('EVT_external_URL');
359
-    }
360
-
361
-
362
-    /**
363
-     * @return bool
364
-     * @throws EE_Error
365
-     */
366
-    public function member_only()
367
-    {
368
-        return $this->get('EVT_member_only');
369
-    }
370
-
371
-
372
-    /**
373
-     * @return bool
374
-     * @throws EE_Error
375
-     */
376
-    public function phone()
377
-    {
378
-        return $this->get('EVT_phone');
379
-    }
380
-
381
-
382
-    /**
383
-     * @return bool
384
-     * @throws EE_Error
385
-     */
386
-    public function modified()
387
-    {
388
-        return $this->get('EVT_modified');
389
-    }
390
-
391
-
392
-    /**
393
-     * @return bool
394
-     * @throws EE_Error
395
-     */
396
-    public function name()
397
-    {
398
-        return $this->get('EVT_name');
399
-    }
400
-
401
-
402
-    /**
403
-     * @return bool
404
-     * @throws EE_Error
405
-     */
406
-    public function order()
407
-    {
408
-        return $this->get('EVT_order');
409
-    }
410
-
411
-
412
-    /**
413
-     * @return bool|string
414
-     * @throws EE_Error
415
-     */
416
-    public function default_registration_status()
417
-    {
418
-        $event_default_registration_status = $this->get('EVT_default_registration_status');
419
-        return !empty($event_default_registration_status)
420
-            ? $event_default_registration_status
421
-            : EE_Registry::instance()->CFG->registration->default_STS_ID;
422
-    }
423
-
424
-
425
-    /**
426
-     * @param int $num_words
427
-     * @param null $more
428
-     * @param bool $not_full_desc
429
-     * @return bool|string
430
-     * @throws EE_Error
431
-     */
432
-    public function short_description($num_words = 55, $more = null, $not_full_desc = false)
433
-    {
434
-        $short_desc = $this->get('EVT_short_desc');
435
-        if (!empty($short_desc) || $not_full_desc) {
436
-            return $short_desc;
437
-        }
438
-        $full_desc = $this->get('EVT_desc');
439
-        return wp_trim_words($full_desc, $num_words, $more);
440
-    }
441
-
442
-
443
-    /**
444
-     * @return bool
445
-     * @throws EE_Error
446
-     */
447
-    public function slug()
448
-    {
449
-        return $this->get('EVT_slug');
450
-    }
451
-
452
-
453
-    /**
454
-     * @return bool
455
-     * @throws EE_Error
456
-     */
457
-    public function timezone_string()
458
-    {
459
-        return $this->get('EVT_timezone_string');
460
-    }
461
-
462
-
463
-    /**
464
-     * @return bool
465
-     * @throws EE_Error
466
-     */
467
-    public function visible_on()
468
-    {
469
-        return $this->get('EVT_visible_on');
470
-    }
471
-
472
-
473
-    /**
474
-     * @return int
475
-     * @throws EE_Error
476
-     */
477
-    public function wp_user()
478
-    {
479
-        return $this->get('EVT_wp_user');
480
-    }
481
-
482
-
483
-    /**
484
-     * @return bool
485
-     * @throws EE_Error
486
-     */
487
-    public function donations()
488
-    {
489
-        return $this->get('EVT_donations');
490
-    }
491
-
492
-
493
-    /**
494
-     * @param $limit
495
-     * @throws EE_Error
496
-     */
497
-    public function set_additional_limit($limit)
498
-    {
499
-        $this->set('EVT_additional_limit', $limit);
500
-    }
501
-
502
-
503
-    /**
504
-     * @param $created
505
-     * @throws EE_Error
506
-     */
507
-    public function set_created($created)
508
-    {
509
-        $this->set('EVT_created', $created);
510
-    }
511
-
512
-
513
-    /**
514
-     * @param $desc
515
-     * @throws EE_Error
516
-     */
517
-    public function set_description($desc)
518
-    {
519
-        $this->set('EVT_desc', $desc);
520
-    }
521
-
522
-
523
-    /**
524
-     * @param $display_desc
525
-     * @throws EE_Error
526
-     */
527
-    public function set_display_description($display_desc)
528
-    {
529
-        $this->set('EVT_display_desc', $display_desc);
530
-    }
531
-
532
-
533
-    /**
534
-     * @param $display_ticket_selector
535
-     * @throws EE_Error
536
-     */
537
-    public function set_display_ticket_selector($display_ticket_selector)
538
-    {
539
-        $this->set('EVT_display_ticket_selector', $display_ticket_selector);
540
-    }
541
-
542
-
543
-    /**
544
-     * @param $external_url
545
-     * @throws EE_Error
546
-     */
547
-    public function set_external_url($external_url)
548
-    {
549
-        $this->set('EVT_external_URL', $external_url);
550
-    }
551
-
552
-
553
-    /**
554
-     * @param $member_only
555
-     * @throws EE_Error
556
-     */
557
-    public function set_member_only($member_only)
558
-    {
559
-        $this->set('EVT_member_only', $member_only);
560
-    }
561
-
562
-
563
-    /**
564
-     * @param $event_phone
565
-     * @throws EE_Error
566
-     */
567
-    public function set_event_phone($event_phone)
568
-    {
569
-        $this->set('EVT_phone', $event_phone);
570
-    }
571
-
572
-
573
-    /**
574
-     * @param $modified
575
-     * @throws EE_Error
576
-     */
577
-    public function set_modified($modified)
578
-    {
579
-        $this->set('EVT_modified', $modified);
580
-    }
581
-
582
-
583
-    /**
584
-     * @param $name
585
-     * @throws EE_Error
586
-     */
587
-    public function set_name($name)
588
-    {
589
-        $this->set('EVT_name', $name);
590
-    }
591
-
592
-
593
-    /**
594
-     * @param $order
595
-     * @throws EE_Error
596
-     */
597
-    public function set_order($order)
598
-    {
599
-        $this->set('EVT_order', $order);
600
-    }
601
-
602
-
603
-    /**
604
-     * @param $short_desc
605
-     * @throws EE_Error
606
-     */
607
-    public function set_short_description($short_desc)
608
-    {
609
-        $this->set('EVT_short_desc', $short_desc);
610
-    }
611
-
612
-
613
-    /**
614
-     * @param $slug
615
-     * @throws EE_Error
616
-     */
617
-    public function set_slug($slug)
618
-    {
619
-        $this->set('EVT_slug', $slug);
620
-    }
621
-
622
-
623
-    /**
624
-     * @param $timezone_string
625
-     * @throws EE_Error
626
-     */
627
-    public function set_timezone_string($timezone_string)
628
-    {
629
-        $this->set('EVT_timezone_string', $timezone_string);
630
-    }
631
-
632
-
633
-    /**
634
-     * @param $visible_on
635
-     * @throws EE_Error
636
-     */
637
-    public function set_visible_on($visible_on)
638
-    {
639
-        $this->set('EVT_visible_on', $visible_on);
640
-    }
641
-
642
-
643
-    /**
644
-     * @param $wp_user
645
-     * @throws EE_Error
646
-     */
647
-    public function set_wp_user($wp_user)
648
-    {
649
-        $this->set('EVT_wp_user', $wp_user);
650
-    }
651
-
652
-
653
-    /**
654
-     * @param $default_registration_status
655
-     * @throws EE_Error
656
-     */
657
-    public function set_default_registration_status($default_registration_status)
658
-    {
659
-        $this->set('EVT_default_registration_status', $default_registration_status);
660
-    }
661
-
662
-
663
-    /**
664
-     * @param $donations
665
-     * @throws EE_Error
666
-     */
667
-    public function set_donations($donations)
668
-    {
669
-        $this->set('EVT_donations', $donations);
670
-    }
671
-
672
-
673
-    /**
674
-     * Adds a venue to this event
675
-     *
676
-     * @param EE_Venue /int $venue_id_or_obj
677
-     * @return EE_Base_Class|EE_Venue
678
-     * @throws EE_Error
679
-     */
680
-    public function add_venue($venue_id_or_obj)
681
-    {
682
-        return $this->_add_relation_to($venue_id_or_obj, 'Venue');
683
-    }
684
-
685
-
686
-    /**
687
-     * Removes a venue from the event
688
-     *
689
-     * @param EE_Venue /int $venue_id_or_obj
690
-     * @return EE_Base_Class|EE_Venue
691
-     * @throws EE_Error
692
-     */
693
-    public function remove_venue($venue_id_or_obj)
694
-    {
695
-        return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
696
-    }
697
-
698
-
699
-    /**
700
-     * Gets all the venues related ot the event. May provide additional $query_params if desired
701
-     *
702
-     * @param array $query_params like EEM_Base::get_all's $query_params
703
-     * @return EE_Base_Class[]|EE_Venue[]
704
-     * @throws EE_Error
705
-     */
706
-    public function venues($query_params = array())
707
-    {
708
-        return $this->get_many_related('Venue', $query_params);
709
-    }
710
-
711
-
712
-    /**
713
-     * check if event id is present and if event is published
714
-     *
715
-     * @access public
716
-     * @return boolean true yes, false no
717
-     * @throws EE_Error
718
-     */
719
-    private function _has_ID_and_is_published()
720
-    {
721
-        // first check if event id is present and not NULL,
722
-        // then check if this event is published (or any of the equivalent "published" statuses)
723
-        return
724
-            $this->ID() && $this->ID() !== null
725
-            && (
726
-                $this->status() === 'publish'
727
-                || $this->status() === EEM_Event::sold_out
728
-                || $this->status() === EEM_Event::postponed
729
-                || $this->status() === EEM_Event::cancelled
730
-            );
731
-    }
732
-
733
-
734
-    /**
735
-     * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
736
-     *
737
-     * @access public
738
-     * @return boolean true yes, false no
739
-     * @throws EE_Error
740
-     */
741
-    public function is_upcoming()
742
-    {
743
-        // check if event id is present and if this event is published
744
-        if ($this->is_inactive()) {
745
-            return false;
746
-        }
747
-        // set initial value
748
-        $upcoming = false;
749
-        //next let's get all datetimes and loop through them
750
-        $datetimes = $this->datetimes_in_chronological_order();
751
-        foreach ($datetimes as $datetime) {
752
-            if ($datetime instanceof EE_Datetime) {
753
-                //if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
754
-                if ($datetime->is_expired()) {
755
-                    continue;
756
-                }
757
-                //if this dtt is active then we return false.
758
-                if ($datetime->is_active()) {
759
-                    return false;
760
-                }
761
-                //otherwise let's check upcoming status
762
-                $upcoming = $datetime->is_upcoming();
763
-            }
764
-        }
765
-        return $upcoming;
766
-    }
767
-
768
-
769
-    /**
770
-     * @return bool
771
-     * @throws EE_Error
772
-     */
773
-    public function is_active()
774
-    {
775
-        // check if event id is present and if this event is published
776
-        if ($this->is_inactive()) {
777
-            return false;
778
-        }
779
-        // set initial value
780
-        $active = false;
781
-        //next let's get all datetimes and loop through them
782
-        $datetimes = $this->datetimes_in_chronological_order();
783
-        foreach ($datetimes as $datetime) {
784
-            if ($datetime instanceof EE_Datetime) {
785
-                //if this dtt is expired then we continue cause one of the other datetimes might be active.
786
-                if ($datetime->is_expired()) {
787
-                    continue;
788
-                }
789
-                //if this dtt is upcoming then we return false.
790
-                if ($datetime->is_upcoming()) {
791
-                    return false;
792
-                }
793
-                //otherwise let's check active status
794
-                $active = $datetime->is_active();
795
-            }
796
-        }
797
-        return $active;
798
-    }
799
-
800
-
801
-    /**
802
-     * @return bool
803
-     * @throws EE_Error
804
-     */
805
-    public function is_expired()
806
-    {
807
-        // check if event id is present and if this event is published
808
-        if ($this->is_inactive()) {
809
-            return false;
810
-        }
811
-        // set initial value
812
-        $expired = false;
813
-        //first let's get all datetimes and loop through them
814
-        $datetimes = $this->datetimes_in_chronological_order();
815
-        foreach ($datetimes as $datetime) {
816
-            if ($datetime instanceof EE_Datetime) {
817
-                //if this dtt is upcoming or active then we return false.
818
-                if ($datetime->is_upcoming() || $datetime->is_active()) {
819
-                    return false;
820
-                }
821
-                //otherwise let's check active status
822
-                $expired = $datetime->is_expired();
823
-            }
824
-        }
825
-        return $expired;
826
-    }
827
-
828
-
829
-    /**
830
-     * @return bool
831
-     * @throws EE_Error
832
-     */
833
-    public function is_inactive()
834
-    {
835
-        // check if event id is present and if this event is published
836
-        if ($this->_has_ID_and_is_published()) {
837
-            return false;
838
-        }
839
-        return true;
840
-    }
841
-
842
-
843
-    /**
844
-     * calculate spaces remaining based on "saleable" tickets
845
-     *
846
-     * @param array $tickets
847
-     * @param bool $filtered
848
-     * @return int|float
849
-     * @throws EE_Error
850
-     * @throws DomainException
851
-     * @throws UnexpectedEntityException
852
-     */
853
-    public function spaces_remaining($tickets = array(), $filtered = true)
854
-    {
855
-        $this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
856
-        $spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
857
-        return $filtered
858
-            ? apply_filters(
859
-                'FHEE_EE_Event__spaces_remaining',
860
-                $spaces_remaining,
861
-                $this,
862
-                $tickets
863
-            )
864
-            : $spaces_remaining;
865
-    }
866
-
867
-
868
-    /**
869
-     *    perform_sold_out_status_check
870
-     *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
871
-     *    if NOT, then the event status will get toggled to 'sold_out'
872
-     *
873
-     * @return bool    return the ACTUAL sold out state.
874
-     * @throws EE_Error
875
-     * @throws DomainException
876
-     * @throws UnexpectedEntityException
877
-     */
878
-    public function perform_sold_out_status_check()
879
-    {
880
-        // get all unexpired untrashed tickets
881
-        $tickets = $this->tickets(
882
-            array(
883
-                array('TKT_deleted' => false),
884
-                'order_by' => array('TKT_qty' => 'ASC'),
885
-            )
886
-        );
887
-        $all_expired = true;
888
-        foreach ($tickets as $ticket) {
889
-            if(!$ticket->is_expired()){
890
-                $all_expired = false;
891
-                break;
892
-            }
893
-        }
894
-        // if all the tickets are just expired, then don't update the event status to sold out
895
-        if ($all_expired) {
896
-            return true;
897
-        }
898
-        $spaces_remaining = $this->spaces_remaining($tickets);
899
-        if ($spaces_remaining < 1) {
900
-            $this->set_status(EEM_Event::sold_out);
901
-            $this->save();
902
-            $sold_out = true;
903
-        } else {
904
-            $sold_out = false;
905
-            // was event previously marked as sold out ?
906
-            if ($this->status() === EEM_Event::sold_out) {
907
-                // revert status to previous value, if it was set
908
-                $previous_event_status = $this->get_post_meta('_previous_event_status', true);
909
-                if ($previous_event_status) {
910
-                    $this->set_status($previous_event_status);
911
-                    $this->save();
912
-                }
913
-            }
914
-        }
915
-        do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
916
-        return $sold_out;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * This returns the total remaining spaces for sale on this event.
923
-     *
924
-     * @uses EE_Event::total_available_spaces()
925
-     * @return float|int
926
-     * @throws EE_Error
927
-     * @throws DomainException
928
-     * @throws UnexpectedEntityException
929
-     */
930
-    public function spaces_remaining_for_sale()
931
-    {
932
-        return $this->total_available_spaces(true);
933
-    }
934
-
935
-
936
-
937
-    /**
938
-     * This returns the total spaces available for an event
939
-     * while considering all the qtys on the tickets and the reg limits
940
-     * on the datetimes attached to this event.
941
-     *
942
-     * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
943
-     *                              If this is false, then we return the most tickets that could ever be sold
944
-     *                              for this event with the datetime and tickets setup on the event under optimal
945
-     *                              selling conditions.  Otherwise we return a live calculation of spaces available
946
-     *                              based on tickets sold.  Depending on setup and stage of sales, this
947
-     *                              may appear to equal remaining tickets.  However, the more tickets are
948
-     *                              sold out, the more accurate the "live" total is.
949
-     * @return float|int
950
-     * @throws EE_Error
951
-     * @throws DomainException
952
-     * @throws UnexpectedEntityException
953
-     */
954
-    public function total_available_spaces($consider_sold = false)
955
-    {
956
-        $spaces_available = $consider_sold
957
-            ? $this->getAvailableSpacesCalculator()->spacesRemaining()
958
-            : $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
959
-        return apply_filters(
960
-            'FHEE_EE_Event__total_available_spaces__spaces_available',
961
-            $spaces_available,
962
-            $this,
963
-            $this->getAvailableSpacesCalculator()->getDatetimes(),
964
-            $this->getAvailableSpacesCalculator()->getActiveTickets()
965
-        );
966
-    }
967
-
968
-
969
-    /**
970
-     * Checks if the event is set to sold out
971
-     *
972
-     * @param  bool $actual whether or not to perform calculations to not only figure the
973
-     *                      actual status but also to flip the status if necessary to sold
974
-     *                      out If false, we just check the existing status of the event
975
-     * @return boolean
976
-     * @throws EE_Error
977
-     */
978
-    public function is_sold_out($actual = false)
979
-    {
980
-        if (!$actual) {
981
-            return $this->status() === EEM_Event::sold_out;
982
-        }
983
-        return $this->perform_sold_out_status_check();
984
-    }
985
-
986
-
987
-    /**
988
-     * Checks if the event is marked as postponed
989
-     *
990
-     * @return boolean
991
-     */
992
-    public function is_postponed()
993
-    {
994
-        return $this->status() === EEM_Event::postponed;
995
-    }
996
-
997
-
998
-    /**
999
-     * Checks if the event is marked as cancelled
1000
-     *
1001
-     * @return boolean
1002
-     */
1003
-    public function is_cancelled()
1004
-    {
1005
-        return $this->status() === EEM_Event::cancelled;
1006
-    }
1007
-
1008
-
1009
-    /**
1010
-     * Get the logical active status in a hierarchical order for all the datetimes.  Note
1011
-     * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1012
-     * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1013
-     * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1014
-     * the event is considered expired.
1015
-     * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1016
-     * set on the EVENT when it is not published and thus is done
1017
-     *
1018
-     * @param bool $reset
1019
-     * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1020
-     * @throws EE_Error
1021
-     */
1022
-    public function get_active_status($reset = false)
1023
-    {
1024
-        // if the active status has already been set, then just use that value (unless we are resetting it)
1025
-        if (!empty($this->_active_status) && !$reset) {
1026
-            return $this->_active_status;
1027
-        }
1028
-        //first check if event id is present on this object
1029
-        if (!$this->ID()) {
1030
-            return false;
1031
-        }
1032
-        $where_params_for_event = array(array('EVT_ID' => $this->ID()));
1033
-        //if event is published:
1034
-        if ($this->status() === 'publish') {
1035
-            //active?
1036
-            if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1037
-                $this->_active_status = EE_Datetime::active;
1038
-            } else {
1039
-                //upcoming?
1040
-                if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1041
-                    $this->_active_status = EE_Datetime::upcoming;
1042
-                } else {
1043
-                    //expired?
1044
-                    if (
1045
-                        EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1046
-                    ) {
1047
-                        $this->_active_status = EE_Datetime::expired;
1048
-                    } else {
1049
-                        //it would be odd if things make it this far because it basically means there are no datetime's
1050
-                        //attached to the event.  So in this case it will just be considered inactive.
1051
-                        $this->_active_status = EE_Datetime::inactive;
1052
-                    }
1053
-                }
1054
-            }
1055
-        } else {
1056
-            //the event is not published, so let's just set it's active status according to its' post status
1057
-            switch ($this->status()) {
1058
-                case EEM_Event::sold_out :
1059
-                    $this->_active_status = EE_Datetime::sold_out;
1060
-                    break;
1061
-                case EEM_Event::cancelled :
1062
-                    $this->_active_status = EE_Datetime::cancelled;
1063
-                    break;
1064
-                case EEM_Event::postponed :
1065
-                    $this->_active_status = EE_Datetime::postponed;
1066
-                    break;
1067
-                default :
1068
-                    $this->_active_status = EE_Datetime::inactive;
1069
-            }
1070
-        }
1071
-        return $this->_active_status;
1072
-    }
1073
-
1074
-
1075
-    /**
1076
-     *    pretty_active_status
1077
-     *
1078
-     * @access public
1079
-     * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1080
-     * @return mixed void|string
1081
-     * @throws EE_Error
1082
-     */
1083
-    public function pretty_active_status($echo = true)
1084
-    {
1085
-        $active_status = $this->get_active_status();
1086
-        $status = '<span class="ee-status event-active-status-'
1087
-            . $active_status
1088
-            . '">'
1089
-            . EEH_Template::pretty_status($active_status, false, 'sentence')
1090
-            . '</span>';
1091
-        if ($echo) {
1092
-            echo $status;
1093
-            return '';
1094
-        }
1095
-        return $status;
1096
-    }
1097
-
1098
-
1099
-    /**
1100
-     * @return bool|int
1101
-     * @throws EE_Error
1102
-     */
1103
-    public function get_number_of_tickets_sold()
1104
-    {
1105
-        $tkt_sold = 0;
1106
-        if (!$this->ID()) {
1107
-            return 0;
1108
-        }
1109
-        $datetimes = $this->datetimes();
1110
-        foreach ($datetimes as $datetime) {
1111
-            if ($datetime instanceof EE_Datetime) {
1112
-                $tkt_sold += $datetime->sold();
1113
-            }
1114
-        }
1115
-        return $tkt_sold;
1116
-    }
1117
-
1118
-
1119
-    /**
1120
-     * This just returns a count of all the registrations for this event
1121
-     *
1122
-     * @access  public
1123
-     * @return int
1124
-     * @throws EE_Error
1125
-     */
1126
-    public function get_count_of_all_registrations()
1127
-    {
1128
-        return EEM_Event::instance()->count_related($this, 'Registration');
1129
-    }
1130
-
1131
-
1132
-    /**
1133
-     * This returns the ticket with the earliest start time that is
1134
-     * available for this event (across all datetimes attached to the event)
1135
-     *
1136
-     * @return EE_Base_Class|EE_Ticket|null
1137
-     * @throws EE_Error
1138
-     */
1139
-    public function get_ticket_with_earliest_start_time()
1140
-    {
1141
-        $where['Datetime.EVT_ID'] = $this->ID();
1142
-        $query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1143
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1144
-    }
1145
-
1146
-
1147
-    /**
1148
-     * This returns the ticket with the latest end time that is available
1149
-     * for this event (across all datetimes attached to the event)
1150
-     *
1151
-     * @return EE_Base_Class|EE_Ticket|null
1152
-     * @throws EE_Error
1153
-     */
1154
-    public function get_ticket_with_latest_end_time()
1155
-    {
1156
-        $where['Datetime.EVT_ID'] = $this->ID();
1157
-        $query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1158
-        return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1159
-    }
1160
-
1161
-
1162
-    /**
1163
-     * This returns whether there are any tickets on sale for this event.
1164
-     *
1165
-     * @return bool true = YES tickets on sale.
1166
-     * @throws EE_Error
1167
-     */
1168
-    public function tickets_on_sale()
1169
-    {
1170
-        $earliest_ticket = $this->get_ticket_with_earliest_start_time();
1171
-        $latest_ticket = $this->get_ticket_with_latest_end_time();
1172
-        if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1173
-            return false;
1174
-        }
1175
-        //check on sale for these two tickets.
1176
-        if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1177
-            return true;
1178
-        }
1179
-        return false;
1180
-    }
1181
-
1182
-
1183
-    /**
1184
-     * Gets the URL for viewing this event on the front-end. Overrides parent
1185
-     * to check for an external URL first
1186
-     *
1187
-     * @return string
1188
-     * @throws EE_Error
1189
-     */
1190
-    public function get_permalink()
1191
-    {
1192
-        if ($this->external_url()) {
1193
-            return $this->external_url();
1194
-        }
1195
-        return parent::get_permalink();
1196
-    }
1197
-
1198
-
1199
-    /**
1200
-     * Gets the first term for 'espresso_event_categories' we can find
1201
-     *
1202
-     * @param array $query_params like EEM_Base::get_all
1203
-     * @return EE_Base_Class|EE_Term|null
1204
-     * @throws EE_Error
1205
-     */
1206
-    public function first_event_category($query_params = array())
1207
-    {
1208
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1209
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1210
-        return EEM_Term::instance()->get_one($query_params);
1211
-    }
1212
-
1213
-
1214
-    /**
1215
-     * Gets all terms for 'espresso_event_categories' we can find
1216
-     *
1217
-     * @param array $query_params
1218
-     * @return EE_Base_Class[]|EE_Term[]
1219
-     * @throws EE_Error
1220
-     */
1221
-    public function get_all_event_categories($query_params = array())
1222
-    {
1223
-        $query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1224
-        $query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1225
-        return EEM_Term::instance()->get_all($query_params);
1226
-    }
1227
-
1228
-
1229
-    /**
1230
-     * Adds a question group to this event
1231
-     *
1232
-     * @param EE_Question_Group|int $question_group_id_or_obj
1233
-     * @param bool                  $for_primary if true, the question group will be added for the primary
1234
-     *                                           registrant, if false will be added for others. default: false
1235
-     * @return EE_Base_Class|EE_Question_Group
1236
-     * @throws EE_Error
1237
-     */
1238
-    public function add_question_group($question_group_id_or_obj, $for_primary = false)
1239
-    {
1240
-        $extra = $for_primary
1241
-            ? array('EQG_primary' => 1)
1242
-            : array();
1243
-        return $this->_add_relation_to($question_group_id_or_obj, 'Question_Group', $extra);
1244
-    }
1245
-
1246
-
1247
-    /**
1248
-     * Removes a question group from the event
1249
-     *
1250
-     * @param EE_Question_Group|int $question_group_id_or_obj
1251
-     * @param bool                  $for_primary if true, the question group will be removed from the primary
1252
-     *                                           registrant, if false will be removed from others. default: false
1253
-     * @return EE_Base_Class|EE_Question_Group
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function remove_question_group($question_group_id_or_obj, $for_primary = false)
1257
-    {
1258
-        $where = $for_primary
1259
-            ? array('EQG_primary' => 1)
1260
-            : array();
1261
-        return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group', $where);
1262
-    }
1263
-
1264
-
1265
-    /**
1266
-     * Gets all the question groups, ordering them by QSG_order ascending
1267
-     *
1268
-     * @param array $query_params @see EEM_Base::get_all
1269
-     * @return EE_Base_Class[]|EE_Question_Group[]
1270
-     * @throws EE_Error
1271
-     */
1272
-    public function question_groups($query_params = array())
1273
-    {
1274
-        $query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1275
-        return $this->get_many_related('Question_Group', $query_params);
1276
-    }
1277
-
1278
-
1279
-    /**
1280
-     * Implementation for EEI_Has_Icon interface method.
1281
-     *
1282
-     * @see EEI_Visual_Representation for comments
1283
-     * @return string
1284
-     */
1285
-    public function get_icon()
1286
-    {
1287
-        return '<span class="dashicons dashicons-flag"></span>';
1288
-    }
1289
-
1290
-
1291
-    /**
1292
-     * Implementation for EEI_Admin_Links interface method.
1293
-     *
1294
-     * @see EEI_Admin_Links for comments
1295
-     * @return string
1296
-     * @throws EE_Error
1297
-     */
1298
-    public function get_admin_details_link()
1299
-    {
1300
-        return $this->get_admin_edit_link();
1301
-    }
1302
-
1303
-
1304
-    /**
1305
-     * Implementation for EEI_Admin_Links interface method.
1306
-     *
1307
-     * @see EEI_Admin_Links for comments
1308
-     * @return string
1309
-     * @throws EE_Error
1310
-     */
1311
-    public function get_admin_edit_link()
1312
-    {
1313
-        return EEH_URL::add_query_args_and_nonce(array(
1314
-            'page' => 'espresso_events',
1315
-            'action' => 'edit',
1316
-            'post' => $this->ID(),
1317
-        ),
1318
-            admin_url('admin.php')
1319
-        );
1320
-    }
1321
-
1322
-
1323
-    /**
1324
-     * Implementation for EEI_Admin_Links interface method.
1325
-     *
1326
-     * @see EEI_Admin_Links for comments
1327
-     * @return string
1328
-     */
1329
-    public function get_admin_settings_link()
1330
-    {
1331
-        return EEH_URL::add_query_args_and_nonce(array(
1332
-            'page' => 'espresso_events',
1333
-            'action' => 'default_event_settings',
1334
-        ),
1335
-            admin_url('admin.php')
1336
-        );
1337
-    }
1338
-
1339
-
1340
-    /**
1341
-     * Implementation for EEI_Admin_Links interface method.
1342
-     *
1343
-     * @see EEI_Admin_Links for comments
1344
-     * @return string
1345
-     */
1346
-    public function get_admin_overview_link()
1347
-    {
1348
-        return EEH_URL::add_query_args_and_nonce(array(
1349
-            'page' => 'espresso_events',
1350
-            'action' => 'default',
1351
-        ),
1352
-            admin_url('admin.php')
1353
-        );
1354
-    }
21
+	/**
22
+	 * cached value for the the logical active status for the event
23
+	 *
24
+	 * @see get_active_status()
25
+	 * @var string
26
+	 */
27
+	protected $_active_status = '';
28
+
29
+	/**
30
+	 * This is just used for caching the Primary Datetime for the Event on initial retrieval
31
+	 *
32
+	 * @var EE_Datetime
33
+	 */
34
+	protected $_Primary_Datetime;
35
+
36
+	/**
37
+	 * @var EventSpacesCalculator $available_spaces_calculator
38
+	 */
39
+	protected $available_spaces_calculator;
40
+
41
+
42
+	/**
43
+	 * @param array $props_n_values incoming values
44
+	 * @param string $timezone incoming timezone (if not set the timezone set for the website will be
45
+	 *                                        used.)
46
+	 * @param array $date_formats incoming date_formats in an array where the first value is the
47
+	 *                                        date_format and the second value is the time format
48
+	 * @return EE_Event
49
+	 * @throws EE_Error
50
+	 */
51
+	public static function new_instance($props_n_values = array(), $timezone = null, $date_formats = array())
52
+	{
53
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__, $timezone, $date_formats);
54
+		return $has_object ? $has_object : new self($props_n_values, false, $timezone, $date_formats);
55
+	}
56
+
57
+
58
+	/**
59
+	 * @param array $props_n_values incoming values from the database
60
+	 * @param string $timezone incoming timezone as set by the model.  If not set the timezone for
61
+	 *                                the website will be used.
62
+	 * @return EE_Event
63
+	 * @throws EE_Error
64
+	 */
65
+	public static function new_instance_from_db($props_n_values = array(), $timezone = null)
66
+	{
67
+		return new self($props_n_values, true, $timezone);
68
+	}
69
+
70
+
71
+
72
+	/**
73
+	 * @return EventSpacesCalculator
74
+	 * @throws \EE_Error
75
+	 */
76
+	public function getAvailableSpacesCalculator()
77
+	{
78
+		if(! $this->available_spaces_calculator instanceof EventSpacesCalculator){
79
+			$this->available_spaces_calculator = new EventSpacesCalculator($this);
80
+		}
81
+		return $this->available_spaces_calculator;
82
+	}
83
+
84
+
85
+
86
+	/**
87
+	 * Overrides parent set() method so that all calls to set( 'status', $status ) can be routed to internal methods
88
+	 *
89
+	 * @param string $field_name
90
+	 * @param mixed $field_value
91
+	 * @param bool $use_default
92
+	 * @throws EE_Error
93
+	 */
94
+	public function set($field_name, $field_value, $use_default = false)
95
+	{
96
+		switch ($field_name) {
97
+			case 'status' :
98
+				$this->set_status($field_value, $use_default);
99
+				break;
100
+			default :
101
+				parent::set($field_name, $field_value, $use_default);
102
+		}
103
+	}
104
+
105
+
106
+	/**
107
+	 *    set_status
108
+	 * Checks if event status is being changed to SOLD OUT
109
+	 * and updates event meta data with previous event status
110
+	 * so that we can revert things if/when the event is no longer sold out
111
+	 *
112
+	 * @access public
113
+	 * @param string $new_status
114
+	 * @param bool $use_default
115
+	 * @return void
116
+	 * @throws EE_Error
117
+	 */
118
+	public function set_status($new_status = null, $use_default = false)
119
+	{
120
+		// if nothing is set, and we aren't explicitly wanting to reset the status, then just leave
121
+		if (empty($new_status) && !$use_default) {
122
+			return;
123
+		}
124
+		// get current Event status
125
+		$old_status = $this->status();
126
+		// if status has changed
127
+		if ($old_status !== $new_status) {
128
+			// TO sold_out
129
+			if ($new_status === EEM_Event::sold_out) {
130
+				// save the previous event status so that we can revert if the event is no longer sold out
131
+				$this->add_post_meta('_previous_event_status', $old_status);
132
+				do_action('AHEE__EE_Event__set_status__to_sold_out', $this, $old_status, $new_status);
133
+				// OR FROM  sold_out
134
+			} else if ($old_status === EEM_Event::sold_out) {
135
+				$this->delete_post_meta('_previous_event_status');
136
+				do_action('AHEE__EE_Event__set_status__from_sold_out', $this, $old_status, $new_status);
137
+			}
138
+			//clear out the active status so that it gets reset the next time it is requested
139
+			$this->_active_status = null;
140
+			// update status
141
+			parent::set('status', $new_status, $use_default);
142
+			do_action('AHEE__EE_Event__set_status__after_update', $this);
143
+			return;
144
+		}
145
+		// even though the old value matches the new value, it's still good to
146
+		// allow the parent set method to have a say
147
+		parent::set('status', $new_status, $use_default);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets all the datetimes for this event
153
+	 *
154
+	 * @param array $query_params like EEM_Base::get_all
155
+	 * @return EE_Base_Class[]|EE_Datetime[]
156
+	 * @throws EE_Error
157
+	 */
158
+	public function datetimes($query_params = array())
159
+	{
160
+		return $this->get_many_related('Datetime', $query_params);
161
+	}
162
+
163
+
164
+	/**
165
+	 * Gets all the datetimes for this event, ordered by DTT_EVT_start in ascending order
166
+	 *
167
+	 * @return EE_Base_Class[]|EE_Datetime[]
168
+	 * @throws EE_Error
169
+	 */
170
+	public function datetimes_in_chronological_order()
171
+	{
172
+		return $this->get_many_related('Datetime', array('order_by' => array('DTT_EVT_start' => 'ASC')));
173
+	}
174
+
175
+
176
+	/**
177
+	 * Gets all the datetimes for this event, ordered by the DTT_order on the datetime.
178
+	 * @darren, we should probably UNSET timezone on the EEM_Datetime model
179
+	 * after running our query, so that this timezone isn't set for EVERY query
180
+	 * on EEM_Datetime for the rest of the request, no?
181
+	 *
182
+	 * @param boolean $show_expired whether or not to include expired events
183
+	 * @param boolean $show_deleted whether or not to include deleted events
184
+	 * @param null $limit
185
+	 * @return EE_Datetime[]
186
+	 * @throws EE_Error
187
+	 */
188
+	public function datetimes_ordered($show_expired = true, $show_deleted = false, $limit = null)
189
+	{
190
+		return EEM_Datetime::instance($this->_timezone)->get_datetimes_for_event_ordered_by_DTT_order(
191
+			$this->ID(),
192
+			$show_expired,
193
+			$show_deleted,
194
+			$limit
195
+		);
196
+	}
197
+
198
+
199
+	/**
200
+	 * Returns one related datetime. Mostly only used by some legacy code.
201
+	 *
202
+	 * @return EE_Base_Class|EE_Datetime
203
+	 * @throws EE_Error
204
+	 */
205
+	public function first_datetime()
206
+	{
207
+		return $this->get_first_related('Datetime');
208
+	}
209
+
210
+
211
+	/**
212
+	 * Returns the 'primary' datetime for the event
213
+	 *
214
+	 * @param bool $try_to_exclude_expired
215
+	 * @param bool $try_to_exclude_deleted
216
+	 * @return EE_Datetime
217
+	 * @throws EE_Error
218
+	 */
219
+	public function primary_datetime($try_to_exclude_expired = true, $try_to_exclude_deleted = true)
220
+	{
221
+		if (!empty ($this->_Primary_Datetime)) {
222
+			return $this->_Primary_Datetime;
223
+		}
224
+		$this->_Primary_Datetime = EEM_Datetime::instance($this->_timezone)->get_primary_datetime_for_event(
225
+			$this->ID(),
226
+			$try_to_exclude_expired,
227
+			$try_to_exclude_deleted
228
+		);
229
+		return $this->_Primary_Datetime;
230
+	}
231
+
232
+
233
+	/**
234
+	 * Gets all the tickets available for purchase of this event
235
+	 *
236
+	 * @param array $query_params like EEM_Base::get_all
237
+	 * @return EE_Base_Class[]|EE_Ticket[]
238
+	 * @throws EE_Error
239
+	 */
240
+	public function tickets($query_params = array())
241
+	{
242
+		//first get all datetimes
243
+		$datetimes = $this->datetimes_ordered();
244
+		if (!$datetimes) {
245
+			return array();
246
+		}
247
+		$datetime_ids = array();
248
+		foreach ($datetimes as $datetime) {
249
+			$datetime_ids[] = $datetime->ID();
250
+		}
251
+		$where_params = array('Datetime.DTT_ID' => array('IN', $datetime_ids));
252
+		//if incoming $query_params has where conditions let's merge but not override existing.
253
+		if (is_array($query_params) && isset($query_params[0])) {
254
+			$where_params = array_merge($query_params[0], $where_params);
255
+			unset($query_params[0]);
256
+		}
257
+		//now add $where_params to $query_params
258
+		$query_params[0] = $where_params;
259
+		return EEM_Ticket::instance()->get_all($query_params);
260
+	}
261
+
262
+
263
+	/**
264
+	 * get all unexpired untrashed tickets
265
+	 *
266
+	 * @return EE_Ticket[]
267
+	 * @throws EE_Error
268
+	 */
269
+	public function active_tickets()
270
+	{
271
+		return $this->tickets(array(
272
+			array(
273
+				'TKT_end_date' => array('>=', EEM_Ticket::instance()->current_time_for_query('TKT_end_date')),
274
+				'TKT_deleted' => false,
275
+			),
276
+		));
277
+	}
278
+
279
+
280
+	/**
281
+	 * @return bool
282
+	 * @throws EE_Error
283
+	 */
284
+	public function additional_limit()
285
+	{
286
+		return $this->get('EVT_additional_limit');
287
+	}
288
+
289
+
290
+	/**
291
+	 * @return bool
292
+	 * @throws EE_Error
293
+	 */
294
+	public function allow_overflow()
295
+	{
296
+		return $this->get('EVT_allow_overflow');
297
+	}
298
+
299
+
300
+	/**
301
+	 * @return bool
302
+	 * @throws EE_Error
303
+	 */
304
+	public function created()
305
+	{
306
+		return $this->get('EVT_created');
307
+	}
308
+
309
+
310
+	/**
311
+	 * @return bool
312
+	 * @throws EE_Error
313
+	 */
314
+	public function description()
315
+	{
316
+		return $this->get('EVT_desc');
317
+	}
318
+
319
+
320
+	/**
321
+	 * Runs do_shortcode and wpautop on the description
322
+	 *
323
+	 * @return string of html
324
+	 * @throws EE_Error
325
+	 */
326
+	public function description_filtered()
327
+	{
328
+		return $this->get_pretty('EVT_desc');
329
+	}
330
+
331
+
332
+	/**
333
+	 * @return bool
334
+	 * @throws EE_Error
335
+	 */
336
+	public function display_description()
337
+	{
338
+		return $this->get('EVT_display_desc');
339
+	}
340
+
341
+
342
+	/**
343
+	 * @return bool
344
+	 * @throws EE_Error
345
+	 */
346
+	public function display_ticket_selector()
347
+	{
348
+		return (bool)$this->get('EVT_display_ticket_selector');
349
+	}
350
+
351
+
352
+	/**
353
+	 * @return bool
354
+	 * @throws EE_Error
355
+	 */
356
+	public function external_url()
357
+	{
358
+		return $this->get('EVT_external_URL');
359
+	}
360
+
361
+
362
+	/**
363
+	 * @return bool
364
+	 * @throws EE_Error
365
+	 */
366
+	public function member_only()
367
+	{
368
+		return $this->get('EVT_member_only');
369
+	}
370
+
371
+
372
+	/**
373
+	 * @return bool
374
+	 * @throws EE_Error
375
+	 */
376
+	public function phone()
377
+	{
378
+		return $this->get('EVT_phone');
379
+	}
380
+
381
+
382
+	/**
383
+	 * @return bool
384
+	 * @throws EE_Error
385
+	 */
386
+	public function modified()
387
+	{
388
+		return $this->get('EVT_modified');
389
+	}
390
+
391
+
392
+	/**
393
+	 * @return bool
394
+	 * @throws EE_Error
395
+	 */
396
+	public function name()
397
+	{
398
+		return $this->get('EVT_name');
399
+	}
400
+
401
+
402
+	/**
403
+	 * @return bool
404
+	 * @throws EE_Error
405
+	 */
406
+	public function order()
407
+	{
408
+		return $this->get('EVT_order');
409
+	}
410
+
411
+
412
+	/**
413
+	 * @return bool|string
414
+	 * @throws EE_Error
415
+	 */
416
+	public function default_registration_status()
417
+	{
418
+		$event_default_registration_status = $this->get('EVT_default_registration_status');
419
+		return !empty($event_default_registration_status)
420
+			? $event_default_registration_status
421
+			: EE_Registry::instance()->CFG->registration->default_STS_ID;
422
+	}
423
+
424
+
425
+	/**
426
+	 * @param int $num_words
427
+	 * @param null $more
428
+	 * @param bool $not_full_desc
429
+	 * @return bool|string
430
+	 * @throws EE_Error
431
+	 */
432
+	public function short_description($num_words = 55, $more = null, $not_full_desc = false)
433
+	{
434
+		$short_desc = $this->get('EVT_short_desc');
435
+		if (!empty($short_desc) || $not_full_desc) {
436
+			return $short_desc;
437
+		}
438
+		$full_desc = $this->get('EVT_desc');
439
+		return wp_trim_words($full_desc, $num_words, $more);
440
+	}
441
+
442
+
443
+	/**
444
+	 * @return bool
445
+	 * @throws EE_Error
446
+	 */
447
+	public function slug()
448
+	{
449
+		return $this->get('EVT_slug');
450
+	}
451
+
452
+
453
+	/**
454
+	 * @return bool
455
+	 * @throws EE_Error
456
+	 */
457
+	public function timezone_string()
458
+	{
459
+		return $this->get('EVT_timezone_string');
460
+	}
461
+
462
+
463
+	/**
464
+	 * @return bool
465
+	 * @throws EE_Error
466
+	 */
467
+	public function visible_on()
468
+	{
469
+		return $this->get('EVT_visible_on');
470
+	}
471
+
472
+
473
+	/**
474
+	 * @return int
475
+	 * @throws EE_Error
476
+	 */
477
+	public function wp_user()
478
+	{
479
+		return $this->get('EVT_wp_user');
480
+	}
481
+
482
+
483
+	/**
484
+	 * @return bool
485
+	 * @throws EE_Error
486
+	 */
487
+	public function donations()
488
+	{
489
+		return $this->get('EVT_donations');
490
+	}
491
+
492
+
493
+	/**
494
+	 * @param $limit
495
+	 * @throws EE_Error
496
+	 */
497
+	public function set_additional_limit($limit)
498
+	{
499
+		$this->set('EVT_additional_limit', $limit);
500
+	}
501
+
502
+
503
+	/**
504
+	 * @param $created
505
+	 * @throws EE_Error
506
+	 */
507
+	public function set_created($created)
508
+	{
509
+		$this->set('EVT_created', $created);
510
+	}
511
+
512
+
513
+	/**
514
+	 * @param $desc
515
+	 * @throws EE_Error
516
+	 */
517
+	public function set_description($desc)
518
+	{
519
+		$this->set('EVT_desc', $desc);
520
+	}
521
+
522
+
523
+	/**
524
+	 * @param $display_desc
525
+	 * @throws EE_Error
526
+	 */
527
+	public function set_display_description($display_desc)
528
+	{
529
+		$this->set('EVT_display_desc', $display_desc);
530
+	}
531
+
532
+
533
+	/**
534
+	 * @param $display_ticket_selector
535
+	 * @throws EE_Error
536
+	 */
537
+	public function set_display_ticket_selector($display_ticket_selector)
538
+	{
539
+		$this->set('EVT_display_ticket_selector', $display_ticket_selector);
540
+	}
541
+
542
+
543
+	/**
544
+	 * @param $external_url
545
+	 * @throws EE_Error
546
+	 */
547
+	public function set_external_url($external_url)
548
+	{
549
+		$this->set('EVT_external_URL', $external_url);
550
+	}
551
+
552
+
553
+	/**
554
+	 * @param $member_only
555
+	 * @throws EE_Error
556
+	 */
557
+	public function set_member_only($member_only)
558
+	{
559
+		$this->set('EVT_member_only', $member_only);
560
+	}
561
+
562
+
563
+	/**
564
+	 * @param $event_phone
565
+	 * @throws EE_Error
566
+	 */
567
+	public function set_event_phone($event_phone)
568
+	{
569
+		$this->set('EVT_phone', $event_phone);
570
+	}
571
+
572
+
573
+	/**
574
+	 * @param $modified
575
+	 * @throws EE_Error
576
+	 */
577
+	public function set_modified($modified)
578
+	{
579
+		$this->set('EVT_modified', $modified);
580
+	}
581
+
582
+
583
+	/**
584
+	 * @param $name
585
+	 * @throws EE_Error
586
+	 */
587
+	public function set_name($name)
588
+	{
589
+		$this->set('EVT_name', $name);
590
+	}
591
+
592
+
593
+	/**
594
+	 * @param $order
595
+	 * @throws EE_Error
596
+	 */
597
+	public function set_order($order)
598
+	{
599
+		$this->set('EVT_order', $order);
600
+	}
601
+
602
+
603
+	/**
604
+	 * @param $short_desc
605
+	 * @throws EE_Error
606
+	 */
607
+	public function set_short_description($short_desc)
608
+	{
609
+		$this->set('EVT_short_desc', $short_desc);
610
+	}
611
+
612
+
613
+	/**
614
+	 * @param $slug
615
+	 * @throws EE_Error
616
+	 */
617
+	public function set_slug($slug)
618
+	{
619
+		$this->set('EVT_slug', $slug);
620
+	}
621
+
622
+
623
+	/**
624
+	 * @param $timezone_string
625
+	 * @throws EE_Error
626
+	 */
627
+	public function set_timezone_string($timezone_string)
628
+	{
629
+		$this->set('EVT_timezone_string', $timezone_string);
630
+	}
631
+
632
+
633
+	/**
634
+	 * @param $visible_on
635
+	 * @throws EE_Error
636
+	 */
637
+	public function set_visible_on($visible_on)
638
+	{
639
+		$this->set('EVT_visible_on', $visible_on);
640
+	}
641
+
642
+
643
+	/**
644
+	 * @param $wp_user
645
+	 * @throws EE_Error
646
+	 */
647
+	public function set_wp_user($wp_user)
648
+	{
649
+		$this->set('EVT_wp_user', $wp_user);
650
+	}
651
+
652
+
653
+	/**
654
+	 * @param $default_registration_status
655
+	 * @throws EE_Error
656
+	 */
657
+	public function set_default_registration_status($default_registration_status)
658
+	{
659
+		$this->set('EVT_default_registration_status', $default_registration_status);
660
+	}
661
+
662
+
663
+	/**
664
+	 * @param $donations
665
+	 * @throws EE_Error
666
+	 */
667
+	public function set_donations($donations)
668
+	{
669
+		$this->set('EVT_donations', $donations);
670
+	}
671
+
672
+
673
+	/**
674
+	 * Adds a venue to this event
675
+	 *
676
+	 * @param EE_Venue /int $venue_id_or_obj
677
+	 * @return EE_Base_Class|EE_Venue
678
+	 * @throws EE_Error
679
+	 */
680
+	public function add_venue($venue_id_or_obj)
681
+	{
682
+		return $this->_add_relation_to($venue_id_or_obj, 'Venue');
683
+	}
684
+
685
+
686
+	/**
687
+	 * Removes a venue from the event
688
+	 *
689
+	 * @param EE_Venue /int $venue_id_or_obj
690
+	 * @return EE_Base_Class|EE_Venue
691
+	 * @throws EE_Error
692
+	 */
693
+	public function remove_venue($venue_id_or_obj)
694
+	{
695
+		return $this->_remove_relation_to($venue_id_or_obj, 'Venue');
696
+	}
697
+
698
+
699
+	/**
700
+	 * Gets all the venues related ot the event. May provide additional $query_params if desired
701
+	 *
702
+	 * @param array $query_params like EEM_Base::get_all's $query_params
703
+	 * @return EE_Base_Class[]|EE_Venue[]
704
+	 * @throws EE_Error
705
+	 */
706
+	public function venues($query_params = array())
707
+	{
708
+		return $this->get_many_related('Venue', $query_params);
709
+	}
710
+
711
+
712
+	/**
713
+	 * check if event id is present and if event is published
714
+	 *
715
+	 * @access public
716
+	 * @return boolean true yes, false no
717
+	 * @throws EE_Error
718
+	 */
719
+	private function _has_ID_and_is_published()
720
+	{
721
+		// first check if event id is present and not NULL,
722
+		// then check if this event is published (or any of the equivalent "published" statuses)
723
+		return
724
+			$this->ID() && $this->ID() !== null
725
+			&& (
726
+				$this->status() === 'publish'
727
+				|| $this->status() === EEM_Event::sold_out
728
+				|| $this->status() === EEM_Event::postponed
729
+				|| $this->status() === EEM_Event::cancelled
730
+			);
731
+	}
732
+
733
+
734
+	/**
735
+	 * This simply compares the internal dates with NOW and determines if the event is upcoming or not.
736
+	 *
737
+	 * @access public
738
+	 * @return boolean true yes, false no
739
+	 * @throws EE_Error
740
+	 */
741
+	public function is_upcoming()
742
+	{
743
+		// check if event id is present and if this event is published
744
+		if ($this->is_inactive()) {
745
+			return false;
746
+		}
747
+		// set initial value
748
+		$upcoming = false;
749
+		//next let's get all datetimes and loop through them
750
+		$datetimes = $this->datetimes_in_chronological_order();
751
+		foreach ($datetimes as $datetime) {
752
+			if ($datetime instanceof EE_Datetime) {
753
+				//if this dtt is expired then we continue cause one of the other datetimes might be upcoming.
754
+				if ($datetime->is_expired()) {
755
+					continue;
756
+				}
757
+				//if this dtt is active then we return false.
758
+				if ($datetime->is_active()) {
759
+					return false;
760
+				}
761
+				//otherwise let's check upcoming status
762
+				$upcoming = $datetime->is_upcoming();
763
+			}
764
+		}
765
+		return $upcoming;
766
+	}
767
+
768
+
769
+	/**
770
+	 * @return bool
771
+	 * @throws EE_Error
772
+	 */
773
+	public function is_active()
774
+	{
775
+		// check if event id is present and if this event is published
776
+		if ($this->is_inactive()) {
777
+			return false;
778
+		}
779
+		// set initial value
780
+		$active = false;
781
+		//next let's get all datetimes and loop through them
782
+		$datetimes = $this->datetimes_in_chronological_order();
783
+		foreach ($datetimes as $datetime) {
784
+			if ($datetime instanceof EE_Datetime) {
785
+				//if this dtt is expired then we continue cause one of the other datetimes might be active.
786
+				if ($datetime->is_expired()) {
787
+					continue;
788
+				}
789
+				//if this dtt is upcoming then we return false.
790
+				if ($datetime->is_upcoming()) {
791
+					return false;
792
+				}
793
+				//otherwise let's check active status
794
+				$active = $datetime->is_active();
795
+			}
796
+		}
797
+		return $active;
798
+	}
799
+
800
+
801
+	/**
802
+	 * @return bool
803
+	 * @throws EE_Error
804
+	 */
805
+	public function is_expired()
806
+	{
807
+		// check if event id is present and if this event is published
808
+		if ($this->is_inactive()) {
809
+			return false;
810
+		}
811
+		// set initial value
812
+		$expired = false;
813
+		//first let's get all datetimes and loop through them
814
+		$datetimes = $this->datetimes_in_chronological_order();
815
+		foreach ($datetimes as $datetime) {
816
+			if ($datetime instanceof EE_Datetime) {
817
+				//if this dtt is upcoming or active then we return false.
818
+				if ($datetime->is_upcoming() || $datetime->is_active()) {
819
+					return false;
820
+				}
821
+				//otherwise let's check active status
822
+				$expired = $datetime->is_expired();
823
+			}
824
+		}
825
+		return $expired;
826
+	}
827
+
828
+
829
+	/**
830
+	 * @return bool
831
+	 * @throws EE_Error
832
+	 */
833
+	public function is_inactive()
834
+	{
835
+		// check if event id is present and if this event is published
836
+		if ($this->_has_ID_and_is_published()) {
837
+			return false;
838
+		}
839
+		return true;
840
+	}
841
+
842
+
843
+	/**
844
+	 * calculate spaces remaining based on "saleable" tickets
845
+	 *
846
+	 * @param array $tickets
847
+	 * @param bool $filtered
848
+	 * @return int|float
849
+	 * @throws EE_Error
850
+	 * @throws DomainException
851
+	 * @throws UnexpectedEntityException
852
+	 */
853
+	public function spaces_remaining($tickets = array(), $filtered = true)
854
+	{
855
+		$this->getAvailableSpacesCalculator()->setActiveTickets($tickets);
856
+		$spaces_remaining = $this->getAvailableSpacesCalculator()->spacesRemaining();
857
+		return $filtered
858
+			? apply_filters(
859
+				'FHEE_EE_Event__spaces_remaining',
860
+				$spaces_remaining,
861
+				$this,
862
+				$tickets
863
+			)
864
+			: $spaces_remaining;
865
+	}
866
+
867
+
868
+	/**
869
+	 *    perform_sold_out_status_check
870
+	 *    checks all of this events's datetime  reg_limit - sold values to determine if ANY datetimes have spaces available...
871
+	 *    if NOT, then the event status will get toggled to 'sold_out'
872
+	 *
873
+	 * @return bool    return the ACTUAL sold out state.
874
+	 * @throws EE_Error
875
+	 * @throws DomainException
876
+	 * @throws UnexpectedEntityException
877
+	 */
878
+	public function perform_sold_out_status_check()
879
+	{
880
+		// get all unexpired untrashed tickets
881
+		$tickets = $this->tickets(
882
+			array(
883
+				array('TKT_deleted' => false),
884
+				'order_by' => array('TKT_qty' => 'ASC'),
885
+			)
886
+		);
887
+		$all_expired = true;
888
+		foreach ($tickets as $ticket) {
889
+			if(!$ticket->is_expired()){
890
+				$all_expired = false;
891
+				break;
892
+			}
893
+		}
894
+		// if all the tickets are just expired, then don't update the event status to sold out
895
+		if ($all_expired) {
896
+			return true;
897
+		}
898
+		$spaces_remaining = $this->spaces_remaining($tickets);
899
+		if ($spaces_remaining < 1) {
900
+			$this->set_status(EEM_Event::sold_out);
901
+			$this->save();
902
+			$sold_out = true;
903
+		} else {
904
+			$sold_out = false;
905
+			// was event previously marked as sold out ?
906
+			if ($this->status() === EEM_Event::sold_out) {
907
+				// revert status to previous value, if it was set
908
+				$previous_event_status = $this->get_post_meta('_previous_event_status', true);
909
+				if ($previous_event_status) {
910
+					$this->set_status($previous_event_status);
911
+					$this->save();
912
+				}
913
+			}
914
+		}
915
+		do_action('AHEE__EE_Event__perform_sold_out_status_check__end', $this, $sold_out, $spaces_remaining, $tickets);
916
+		return $sold_out;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * This returns the total remaining spaces for sale on this event.
923
+	 *
924
+	 * @uses EE_Event::total_available_spaces()
925
+	 * @return float|int
926
+	 * @throws EE_Error
927
+	 * @throws DomainException
928
+	 * @throws UnexpectedEntityException
929
+	 */
930
+	public function spaces_remaining_for_sale()
931
+	{
932
+		return $this->total_available_spaces(true);
933
+	}
934
+
935
+
936
+
937
+	/**
938
+	 * This returns the total spaces available for an event
939
+	 * while considering all the qtys on the tickets and the reg limits
940
+	 * on the datetimes attached to this event.
941
+	 *
942
+	 * @param   bool $consider_sold Whether to consider any tickets that have already sold in our calculation.
943
+	 *                              If this is false, then we return the most tickets that could ever be sold
944
+	 *                              for this event with the datetime and tickets setup on the event under optimal
945
+	 *                              selling conditions.  Otherwise we return a live calculation of spaces available
946
+	 *                              based on tickets sold.  Depending on setup and stage of sales, this
947
+	 *                              may appear to equal remaining tickets.  However, the more tickets are
948
+	 *                              sold out, the more accurate the "live" total is.
949
+	 * @return float|int
950
+	 * @throws EE_Error
951
+	 * @throws DomainException
952
+	 * @throws UnexpectedEntityException
953
+	 */
954
+	public function total_available_spaces($consider_sold = false)
955
+	{
956
+		$spaces_available = $consider_sold
957
+			? $this->getAvailableSpacesCalculator()->spacesRemaining()
958
+			: $this->getAvailableSpacesCalculator()->totalSpacesAvailable();
959
+		return apply_filters(
960
+			'FHEE_EE_Event__total_available_spaces__spaces_available',
961
+			$spaces_available,
962
+			$this,
963
+			$this->getAvailableSpacesCalculator()->getDatetimes(),
964
+			$this->getAvailableSpacesCalculator()->getActiveTickets()
965
+		);
966
+	}
967
+
968
+
969
+	/**
970
+	 * Checks if the event is set to sold out
971
+	 *
972
+	 * @param  bool $actual whether or not to perform calculations to not only figure the
973
+	 *                      actual status but also to flip the status if necessary to sold
974
+	 *                      out If false, we just check the existing status of the event
975
+	 * @return boolean
976
+	 * @throws EE_Error
977
+	 */
978
+	public function is_sold_out($actual = false)
979
+	{
980
+		if (!$actual) {
981
+			return $this->status() === EEM_Event::sold_out;
982
+		}
983
+		return $this->perform_sold_out_status_check();
984
+	}
985
+
986
+
987
+	/**
988
+	 * Checks if the event is marked as postponed
989
+	 *
990
+	 * @return boolean
991
+	 */
992
+	public function is_postponed()
993
+	{
994
+		return $this->status() === EEM_Event::postponed;
995
+	}
996
+
997
+
998
+	/**
999
+	 * Checks if the event is marked as cancelled
1000
+	 *
1001
+	 * @return boolean
1002
+	 */
1003
+	public function is_cancelled()
1004
+	{
1005
+		return $this->status() === EEM_Event::cancelled;
1006
+	}
1007
+
1008
+
1009
+	/**
1010
+	 * Get the logical active status in a hierarchical order for all the datetimes.  Note
1011
+	 * Basically, we order the datetimes by EVT_start_date.  Then first test on whether the event is published.  If its
1012
+	 * NOT published then we test for whether its expired or not.  IF it IS published then we test first on whether an
1013
+	 * event has any active dates.  If no active dates then we check for any upcoming dates.  If no upcoming dates then
1014
+	 * the event is considered expired.
1015
+	 * NOTE: this method does NOT calculate whether the datetimes are sold out when event is published.  Sold Out is a status
1016
+	 * set on the EVENT when it is not published and thus is done
1017
+	 *
1018
+	 * @param bool $reset
1019
+	 * @return bool | string - based on EE_Datetime active constants or FALSE if error.
1020
+	 * @throws EE_Error
1021
+	 */
1022
+	public function get_active_status($reset = false)
1023
+	{
1024
+		// if the active status has already been set, then just use that value (unless we are resetting it)
1025
+		if (!empty($this->_active_status) && !$reset) {
1026
+			return $this->_active_status;
1027
+		}
1028
+		//first check if event id is present on this object
1029
+		if (!$this->ID()) {
1030
+			return false;
1031
+		}
1032
+		$where_params_for_event = array(array('EVT_ID' => $this->ID()));
1033
+		//if event is published:
1034
+		if ($this->status() === 'publish') {
1035
+			//active?
1036
+			if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::active, $where_params_for_event) > 0) {
1037
+				$this->_active_status = EE_Datetime::active;
1038
+			} else {
1039
+				//upcoming?
1040
+				if (EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::upcoming, $where_params_for_event) > 0) {
1041
+					$this->_active_status = EE_Datetime::upcoming;
1042
+				} else {
1043
+					//expired?
1044
+					if (
1045
+						EEM_Datetime::instance()->get_datetime_count_for_status(EE_Datetime::expired, $where_params_for_event) > 0
1046
+					) {
1047
+						$this->_active_status = EE_Datetime::expired;
1048
+					} else {
1049
+						//it would be odd if things make it this far because it basically means there are no datetime's
1050
+						//attached to the event.  So in this case it will just be considered inactive.
1051
+						$this->_active_status = EE_Datetime::inactive;
1052
+					}
1053
+				}
1054
+			}
1055
+		} else {
1056
+			//the event is not published, so let's just set it's active status according to its' post status
1057
+			switch ($this->status()) {
1058
+				case EEM_Event::sold_out :
1059
+					$this->_active_status = EE_Datetime::sold_out;
1060
+					break;
1061
+				case EEM_Event::cancelled :
1062
+					$this->_active_status = EE_Datetime::cancelled;
1063
+					break;
1064
+				case EEM_Event::postponed :
1065
+					$this->_active_status = EE_Datetime::postponed;
1066
+					break;
1067
+				default :
1068
+					$this->_active_status = EE_Datetime::inactive;
1069
+			}
1070
+		}
1071
+		return $this->_active_status;
1072
+	}
1073
+
1074
+
1075
+	/**
1076
+	 *    pretty_active_status
1077
+	 *
1078
+	 * @access public
1079
+	 * @param boolean $echo whether to return (FALSE), or echo out the result (TRUE)
1080
+	 * @return mixed void|string
1081
+	 * @throws EE_Error
1082
+	 */
1083
+	public function pretty_active_status($echo = true)
1084
+	{
1085
+		$active_status = $this->get_active_status();
1086
+		$status = '<span class="ee-status event-active-status-'
1087
+			. $active_status
1088
+			. '">'
1089
+			. EEH_Template::pretty_status($active_status, false, 'sentence')
1090
+			. '</span>';
1091
+		if ($echo) {
1092
+			echo $status;
1093
+			return '';
1094
+		}
1095
+		return $status;
1096
+	}
1097
+
1098
+
1099
+	/**
1100
+	 * @return bool|int
1101
+	 * @throws EE_Error
1102
+	 */
1103
+	public function get_number_of_tickets_sold()
1104
+	{
1105
+		$tkt_sold = 0;
1106
+		if (!$this->ID()) {
1107
+			return 0;
1108
+		}
1109
+		$datetimes = $this->datetimes();
1110
+		foreach ($datetimes as $datetime) {
1111
+			if ($datetime instanceof EE_Datetime) {
1112
+				$tkt_sold += $datetime->sold();
1113
+			}
1114
+		}
1115
+		return $tkt_sold;
1116
+	}
1117
+
1118
+
1119
+	/**
1120
+	 * This just returns a count of all the registrations for this event
1121
+	 *
1122
+	 * @access  public
1123
+	 * @return int
1124
+	 * @throws EE_Error
1125
+	 */
1126
+	public function get_count_of_all_registrations()
1127
+	{
1128
+		return EEM_Event::instance()->count_related($this, 'Registration');
1129
+	}
1130
+
1131
+
1132
+	/**
1133
+	 * This returns the ticket with the earliest start time that is
1134
+	 * available for this event (across all datetimes attached to the event)
1135
+	 *
1136
+	 * @return EE_Base_Class|EE_Ticket|null
1137
+	 * @throws EE_Error
1138
+	 */
1139
+	public function get_ticket_with_earliest_start_time()
1140
+	{
1141
+		$where['Datetime.EVT_ID'] = $this->ID();
1142
+		$query_params = array($where, 'order_by' => array('TKT_start_date' => 'ASC'));
1143
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1144
+	}
1145
+
1146
+
1147
+	/**
1148
+	 * This returns the ticket with the latest end time that is available
1149
+	 * for this event (across all datetimes attached to the event)
1150
+	 *
1151
+	 * @return EE_Base_Class|EE_Ticket|null
1152
+	 * @throws EE_Error
1153
+	 */
1154
+	public function get_ticket_with_latest_end_time()
1155
+	{
1156
+		$where['Datetime.EVT_ID'] = $this->ID();
1157
+		$query_params = array($where, 'order_by' => array('TKT_end_date' => 'DESC'));
1158
+		return EE_Registry::instance()->load_model('Ticket')->get_one($query_params);
1159
+	}
1160
+
1161
+
1162
+	/**
1163
+	 * This returns whether there are any tickets on sale for this event.
1164
+	 *
1165
+	 * @return bool true = YES tickets on sale.
1166
+	 * @throws EE_Error
1167
+	 */
1168
+	public function tickets_on_sale()
1169
+	{
1170
+		$earliest_ticket = $this->get_ticket_with_earliest_start_time();
1171
+		$latest_ticket = $this->get_ticket_with_latest_end_time();
1172
+		if (!$latest_ticket instanceof EE_Ticket && !$earliest_ticket instanceof EE_Ticket) {
1173
+			return false;
1174
+		}
1175
+		//check on sale for these two tickets.
1176
+		if ($latest_ticket->is_on_sale() || $earliest_ticket->is_on_sale()) {
1177
+			return true;
1178
+		}
1179
+		return false;
1180
+	}
1181
+
1182
+
1183
+	/**
1184
+	 * Gets the URL for viewing this event on the front-end. Overrides parent
1185
+	 * to check for an external URL first
1186
+	 *
1187
+	 * @return string
1188
+	 * @throws EE_Error
1189
+	 */
1190
+	public function get_permalink()
1191
+	{
1192
+		if ($this->external_url()) {
1193
+			return $this->external_url();
1194
+		}
1195
+		return parent::get_permalink();
1196
+	}
1197
+
1198
+
1199
+	/**
1200
+	 * Gets the first term for 'espresso_event_categories' we can find
1201
+	 *
1202
+	 * @param array $query_params like EEM_Base::get_all
1203
+	 * @return EE_Base_Class|EE_Term|null
1204
+	 * @throws EE_Error
1205
+	 */
1206
+	public function first_event_category($query_params = array())
1207
+	{
1208
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1209
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1210
+		return EEM_Term::instance()->get_one($query_params);
1211
+	}
1212
+
1213
+
1214
+	/**
1215
+	 * Gets all terms for 'espresso_event_categories' we can find
1216
+	 *
1217
+	 * @param array $query_params
1218
+	 * @return EE_Base_Class[]|EE_Term[]
1219
+	 * @throws EE_Error
1220
+	 */
1221
+	public function get_all_event_categories($query_params = array())
1222
+	{
1223
+		$query_params[0]['Term_Taxonomy.taxonomy'] = 'espresso_event_categories';
1224
+		$query_params[0]['Term_Taxonomy.Event.EVT_ID'] = $this->ID();
1225
+		return EEM_Term::instance()->get_all($query_params);
1226
+	}
1227
+
1228
+
1229
+	/**
1230
+	 * Adds a question group to this event
1231
+	 *
1232
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1233
+	 * @param bool                  $for_primary if true, the question group will be added for the primary
1234
+	 *                                           registrant, if false will be added for others. default: false
1235
+	 * @return EE_Base_Class|EE_Question_Group
1236
+	 * @throws EE_Error
1237
+	 */
1238
+	public function add_question_group($question_group_id_or_obj, $for_primary = false)
1239
+	{
1240
+		$extra = $for_primary
1241
+			? array('EQG_primary' => 1)
1242
+			: array();
1243
+		return $this->_add_relation_to($question_group_id_or_obj, 'Question_Group', $extra);
1244
+	}
1245
+
1246
+
1247
+	/**
1248
+	 * Removes a question group from the event
1249
+	 *
1250
+	 * @param EE_Question_Group|int $question_group_id_or_obj
1251
+	 * @param bool                  $for_primary if true, the question group will be removed from the primary
1252
+	 *                                           registrant, if false will be removed from others. default: false
1253
+	 * @return EE_Base_Class|EE_Question_Group
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function remove_question_group($question_group_id_or_obj, $for_primary = false)
1257
+	{
1258
+		$where = $for_primary
1259
+			? array('EQG_primary' => 1)
1260
+			: array();
1261
+		return $this->_remove_relation_to($question_group_id_or_obj, 'Question_Group', $where);
1262
+	}
1263
+
1264
+
1265
+	/**
1266
+	 * Gets all the question groups, ordering them by QSG_order ascending
1267
+	 *
1268
+	 * @param array $query_params @see EEM_Base::get_all
1269
+	 * @return EE_Base_Class[]|EE_Question_Group[]
1270
+	 * @throws EE_Error
1271
+	 */
1272
+	public function question_groups($query_params = array())
1273
+	{
1274
+		$query_params = !empty($query_params) ? $query_params : array('order_by' => array('QSG_order' => 'ASC'));
1275
+		return $this->get_many_related('Question_Group', $query_params);
1276
+	}
1277
+
1278
+
1279
+	/**
1280
+	 * Implementation for EEI_Has_Icon interface method.
1281
+	 *
1282
+	 * @see EEI_Visual_Representation for comments
1283
+	 * @return string
1284
+	 */
1285
+	public function get_icon()
1286
+	{
1287
+		return '<span class="dashicons dashicons-flag"></span>';
1288
+	}
1289
+
1290
+
1291
+	/**
1292
+	 * Implementation for EEI_Admin_Links interface method.
1293
+	 *
1294
+	 * @see EEI_Admin_Links for comments
1295
+	 * @return string
1296
+	 * @throws EE_Error
1297
+	 */
1298
+	public function get_admin_details_link()
1299
+	{
1300
+		return $this->get_admin_edit_link();
1301
+	}
1302
+
1303
+
1304
+	/**
1305
+	 * Implementation for EEI_Admin_Links interface method.
1306
+	 *
1307
+	 * @see EEI_Admin_Links for comments
1308
+	 * @return string
1309
+	 * @throws EE_Error
1310
+	 */
1311
+	public function get_admin_edit_link()
1312
+	{
1313
+		return EEH_URL::add_query_args_and_nonce(array(
1314
+			'page' => 'espresso_events',
1315
+			'action' => 'edit',
1316
+			'post' => $this->ID(),
1317
+		),
1318
+			admin_url('admin.php')
1319
+		);
1320
+	}
1321
+
1322
+
1323
+	/**
1324
+	 * Implementation for EEI_Admin_Links interface method.
1325
+	 *
1326
+	 * @see EEI_Admin_Links for comments
1327
+	 * @return string
1328
+	 */
1329
+	public function get_admin_settings_link()
1330
+	{
1331
+		return EEH_URL::add_query_args_and_nonce(array(
1332
+			'page' => 'espresso_events',
1333
+			'action' => 'default_event_settings',
1334
+		),
1335
+			admin_url('admin.php')
1336
+		);
1337
+	}
1338
+
1339
+
1340
+	/**
1341
+	 * Implementation for EEI_Admin_Links interface method.
1342
+	 *
1343
+	 * @see EEI_Admin_Links for comments
1344
+	 * @return string
1345
+	 */
1346
+	public function get_admin_overview_link()
1347
+	{
1348
+		return EEH_URL::add_query_args_and_nonce(array(
1349
+			'page' => 'espresso_events',
1350
+			'action' => 'default',
1351
+		),
1352
+			admin_url('admin.php')
1353
+		);
1354
+	}
1355 1355
 
1356 1356
 }
Please login to merge, or discard this patch.
core/domain/entities/notifications/PersistentAdminNotice.php 2 patches
Indentation   +327 added lines, -327 removed lines patch added patch discarded remove patch
@@ -28,336 +28,336 @@
 block discarded – undo
28 28
 class PersistentAdminNotice implements RequiresCapCheckInterface
29 29
 {
30 30
 
31
-    /**
32
-     * @var string $name
33
-     */
34
-    protected $name = '';
35
-
36
-    /**
37
-     * @var string $message
38
-     */
39
-    protected $message = '';
40
-
41
-    /**
42
-     * @var boolean $force_update
43
-     */
44
-    protected $force_update = false;
45
-
46
-    /**
47
-     * @var string $capability
48
-     */
49
-    protected $capability = 'manage_options';
50
-
51
-    /**
52
-     * @var string $cap_context
53
-     */
54
-    protected $cap_context = 'view persistent admin notice';
55
-
56
-    /**
57
-     * @var boolean $dismissed
58
-     */
59
-    protected $dismissed = false;
60
-
61
-    /**
62
-     * @var CapCheckInterface $cap_check
63
-     */
64
-    protected $cap_check;
65
-
66
-    /**
67
-     * if true, then this notice will be deleted from the database
68
-     *
69
-     * @var boolean $purge
70
-     */
71
-    protected $purge = false;
72
-
73
-    /**
74
-     * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
-     * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
-     *
77
-     * @var boolean $registered
78
-     */
79
-    private $registered = false;
80
-
81
-
82
-
83
-    /**
84
-     * PersistentAdminNotice constructor
85
-     *
86
-     * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
-     * @param string $message      [required] the message to be stored persistently until dismissed
88
-     * @param bool   $force_update enforce the reappearance of a persistent message
89
-     * @param string $capability   user capability required to view this notice
90
-     * @param string $cap_context  description for why the cap check is being performed
91
-     * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
-     * @throws InvalidDataTypeException
93
-     */
94
-    public function __construct(
95
-        $name,
96
-        $message,
97
-        $force_update = false,
98
-        $capability = 'manage_options',
99
-        $cap_context = 'view persistent admin notice',
100
-        $dismissed = false
101
-    ) {
102
-        $this->setName($name);
103
-        $this->setMessage($message);
104
-        $this->setForceUpdate($force_update);
105
-        $this->setCapability($capability);
106
-        $this->setCapContext($cap_context);
107
-        $this->setDismissed($dismissed);
108
-        add_action(
109
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
-            array($this, 'registerPersistentAdminNotice')
111
-        );
112
-        add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
-    }
114
-
115
-
116
-
117
-    /**
118
-     * @return string
119
-     */
120
-    public function getName()
121
-    {
122
-        return $this->name;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * @param string $name
129
-     * @throws InvalidDataTypeException
130
-     */
131
-    private function setName($name)
132
-    {
133
-        if (! is_string($name)) {
134
-            throw new InvalidDataTypeException('$name', $name, 'string');
135
-        }
136
-        $this->name = sanitize_key($name);
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @return string
143
-     */
144
-    public function getMessage()
145
-    {
146
-        return $this->message;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $message
153
-     * @throws InvalidDataTypeException
154
-     */
155
-    private function setMessage($message)
156
-    {
157
-        if (! is_string($message)) {
158
-            throw new InvalidDataTypeException('$message', $message, 'string');
159
-        }
160
-        global $allowedtags;
161
-        $allowedtags['br'] = array();
162
-        $this->message     = wp_kses($message, $allowedtags);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * @return bool
169
-     */
170
-    public function getForceUpdate()
171
-    {
172
-        return $this->force_update;
173
-    }
174
-
175
-
176
-
177
-    /**
178
-     * @param bool $force_update
179
-     */
180
-    private function setForceUpdate($force_update)
181
-    {
182
-        $this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * @return string
189
-     */
190
-    public function getCapability()
191
-    {
192
-        return $this->capability;
193
-    }
194
-
195
-
196
-
197
-    /**
198
-     * @param string $capability
199
-     * @throws InvalidDataTypeException
200
-     */
201
-    private function setCapability($capability)
202
-    {
203
-        if (! is_string($capability)) {
204
-            throw new InvalidDataTypeException('$capability', $capability, 'string');
205
-        }
206
-        $this->capability = ! empty($capability) ? $capability : 'manage_options';
207
-    }
31
+	/**
32
+	 * @var string $name
33
+	 */
34
+	protected $name = '';
35
+
36
+	/**
37
+	 * @var string $message
38
+	 */
39
+	protected $message = '';
40
+
41
+	/**
42
+	 * @var boolean $force_update
43
+	 */
44
+	protected $force_update = false;
45
+
46
+	/**
47
+	 * @var string $capability
48
+	 */
49
+	protected $capability = 'manage_options';
50
+
51
+	/**
52
+	 * @var string $cap_context
53
+	 */
54
+	protected $cap_context = 'view persistent admin notice';
55
+
56
+	/**
57
+	 * @var boolean $dismissed
58
+	 */
59
+	protected $dismissed = false;
60
+
61
+	/**
62
+	 * @var CapCheckInterface $cap_check
63
+	 */
64
+	protected $cap_check;
65
+
66
+	/**
67
+	 * if true, then this notice will be deleted from the database
68
+	 *
69
+	 * @var boolean $purge
70
+	 */
71
+	protected $purge = false;
72
+
73
+	/**
74
+	 * gets set to true if notice is successfully registered with the PersistentAdminNoticeManager
75
+	 * if false, and WP_DEBUG is on, then an exception will be thrown in the admin footer
76
+	 *
77
+	 * @var boolean $registered
78
+	 */
79
+	private $registered = false;
80
+
81
+
82
+
83
+	/**
84
+	 * PersistentAdminNotice constructor
85
+	 *
86
+	 * @param string $name         [required] the name, or key of the Persistent Admin Notice to be stored
87
+	 * @param string $message      [required] the message to be stored persistently until dismissed
88
+	 * @param bool   $force_update enforce the reappearance of a persistent message
89
+	 * @param string $capability   user capability required to view this notice
90
+	 * @param string $cap_context  description for why the cap check is being performed
91
+	 * @param bool   $dismissed    whether or not the user has already dismissed/viewed this notice
92
+	 * @throws InvalidDataTypeException
93
+	 */
94
+	public function __construct(
95
+		$name,
96
+		$message,
97
+		$force_update = false,
98
+		$capability = 'manage_options',
99
+		$cap_context = 'view persistent admin notice',
100
+		$dismissed = false
101
+	) {
102
+		$this->setName($name);
103
+		$this->setMessage($message);
104
+		$this->setForceUpdate($force_update);
105
+		$this->setCapability($capability);
106
+		$this->setCapContext($cap_context);
107
+		$this->setDismissed($dismissed);
108
+		add_action(
109
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
110
+			array($this, 'registerPersistentAdminNotice')
111
+		);
112
+		add_action('shutdown', array($this, 'confirmRegistered'), 999);
113
+	}
114
+
115
+
116
+
117
+	/**
118
+	 * @return string
119
+	 */
120
+	public function getName()
121
+	{
122
+		return $this->name;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * @param string $name
129
+	 * @throws InvalidDataTypeException
130
+	 */
131
+	private function setName($name)
132
+	{
133
+		if (! is_string($name)) {
134
+			throw new InvalidDataTypeException('$name', $name, 'string');
135
+		}
136
+		$this->name = sanitize_key($name);
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @return string
143
+	 */
144
+	public function getMessage()
145
+	{
146
+		return $this->message;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $message
153
+	 * @throws InvalidDataTypeException
154
+	 */
155
+	private function setMessage($message)
156
+	{
157
+		if (! is_string($message)) {
158
+			throw new InvalidDataTypeException('$message', $message, 'string');
159
+		}
160
+		global $allowedtags;
161
+		$allowedtags['br'] = array();
162
+		$this->message     = wp_kses($message, $allowedtags);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * @return bool
169
+	 */
170
+	public function getForceUpdate()
171
+	{
172
+		return $this->force_update;
173
+	}
174
+
175
+
176
+
177
+	/**
178
+	 * @param bool $force_update
179
+	 */
180
+	private function setForceUpdate($force_update)
181
+	{
182
+		$this->force_update = filter_var($force_update, FILTER_VALIDATE_BOOLEAN);
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * @return string
189
+	 */
190
+	public function getCapability()
191
+	{
192
+		return $this->capability;
193
+	}
194
+
195
+
196
+
197
+	/**
198
+	 * @param string $capability
199
+	 * @throws InvalidDataTypeException
200
+	 */
201
+	private function setCapability($capability)
202
+	{
203
+		if (! is_string($capability)) {
204
+			throw new InvalidDataTypeException('$capability', $capability, 'string');
205
+		}
206
+		$this->capability = ! empty($capability) ? $capability : 'manage_options';
207
+	}
208 208
 
209 209
 
210 210
 
211
-    /**
212
-     * @return string
213
-     */
214
-    public function getCapContext()
215
-    {
216
-        return $this->cap_context;
217
-    }
218
-
219
-
220
-
221
-    /**
222
-     * @param string $cap_context
223
-     * @throws InvalidDataTypeException
224
-     */
225
-    private function setCapContext($cap_context)
226
-    {
227
-        if (! is_string($cap_context)) {
228
-            throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
-        }
230
-        $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * @return bool
237
-     */
238
-    public function getDismissed()
239
-    {
240
-        return $this->dismissed;
241
-    }
242
-
243
-
244
-
245
-    /**
246
-     * @param bool $dismissed
247
-     */
248
-    public function setDismissed($dismissed)
249
-    {
250
-        $this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
-    }
252
-
253
-
254
-
255
-    /**
256
-     * @return CapCheckInterface
257
-     * @throws InvalidDataTypeException
258
-     */
259
-    public function getCapCheck()
260
-    {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
262
-            $this->setCapCheck(
263
-                new CapCheck(
264
-                    $this->capability,
265
-                    $this->cap_context
266
-                )
267
-            );
268
-        }
269
-        return $this->cap_check;
270
-    }
271
-
272
-
273
-
274
-    /**
275
-     * @param CapCheckInterface $cap_check
276
-     */
277
-    private function setCapCheck(CapCheckInterface $cap_check)
278
-    {
279
-        $this->cap_check = $cap_check;
280
-    }
281
-
282
-
283
-
284
-    /**
285
-     * @return bool
286
-     */
287
-    public function getPurge()
288
-    {
289
-        return $this->purge;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * @param bool $purge
296
-     */
297
-    public function setPurge($purge)
298
-    {
299
-        $this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
-    }
301
-
302
-
303
-
304
-    /**
305
-     * given a valid PersistentAdminNotice Collection,
306
-     * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
-     * if an existing notice is found that has already been dismissed,
308
-     * but we are overriding with a forced update, then we will toggle its dismissed state,
309
-     * so that the notice is displayed again
310
-     *
311
-     * @param Collection $persistent_admin_notice_collection
312
-     * @throws InvalidEntityException
313
-     * @throws InvalidDataTypeException
314
-     */
315
-    public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
316
-    {
317
-        if ($this->registered) {
318
-            return;
319
-        }
320
-        // first check if this notice has already been added to the collection
321
-        if ($persistent_admin_notice_collection->has($this->name)) {
322
-            /** @var PersistentAdminNotice $existing */
323
-            $existing = $persistent_admin_notice_collection->get($this->name);
324
-            // we don't need to add it again (we can't actually)
325
-            // but if it has already been dismissed, and we are overriding with a forced update
326
-            if ($existing->getDismissed() && $this->getForceUpdate()) {
327
-                // then toggle the notice's dismissed state to true
328
-                // so that it gets displayed again
329
-                $existing->setDismissed(false);
330
-                // and make sure the message is set
331
-                $existing->setMessage($this->message);
332
-            }
333
-        } else {
334
-            $persistent_admin_notice_collection->add($this, $this->name);
335
-        }
336
-        $this->registered = true;
337
-    }
338
-
339
-
340
-
341
-    /**
342
-     * @throws Exception
343
-     */
344
-    public function confirmRegistered()
345
-    {
346
-        if (! apply_filters('PersistentAdminNoticeManager__registerAndSaveNotices__complete', false)) {
347
-            PersistentAdminNoticeManager::loadRegisterAndSaveNotices();
348
-        }
349
-        if (! $this->registered && WP_DEBUG) {
350
-            throw new DomainException(
351
-                sprintf(
352
-                    esc_html__(
353
-                        'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
354
-                        'event_espresso'
355
-                    ),
356
-                    $this->name
357
-                )
358
-            );
359
-        }
360
-    }
211
+	/**
212
+	 * @return string
213
+	 */
214
+	public function getCapContext()
215
+	{
216
+		return $this->cap_context;
217
+	}
218
+
219
+
220
+
221
+	/**
222
+	 * @param string $cap_context
223
+	 * @throws InvalidDataTypeException
224
+	 */
225
+	private function setCapContext($cap_context)
226
+	{
227
+		if (! is_string($cap_context)) {
228
+			throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229
+		}
230
+		$this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * @return bool
237
+	 */
238
+	public function getDismissed()
239
+	{
240
+		return $this->dismissed;
241
+	}
242
+
243
+
244
+
245
+	/**
246
+	 * @param bool $dismissed
247
+	 */
248
+	public function setDismissed($dismissed)
249
+	{
250
+		$this->dismissed = filter_var($dismissed, FILTER_VALIDATE_BOOLEAN);
251
+	}
252
+
253
+
254
+
255
+	/**
256
+	 * @return CapCheckInterface
257
+	 * @throws InvalidDataTypeException
258
+	 */
259
+	public function getCapCheck()
260
+	{
261
+		if (! $this->cap_check instanceof CapCheckInterface) {
262
+			$this->setCapCheck(
263
+				new CapCheck(
264
+					$this->capability,
265
+					$this->cap_context
266
+				)
267
+			);
268
+		}
269
+		return $this->cap_check;
270
+	}
271
+
272
+
273
+
274
+	/**
275
+	 * @param CapCheckInterface $cap_check
276
+	 */
277
+	private function setCapCheck(CapCheckInterface $cap_check)
278
+	{
279
+		$this->cap_check = $cap_check;
280
+	}
281
+
282
+
283
+
284
+	/**
285
+	 * @return bool
286
+	 */
287
+	public function getPurge()
288
+	{
289
+		return $this->purge;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * @param bool $purge
296
+	 */
297
+	public function setPurge($purge)
298
+	{
299
+		$this->purge = filter_var($purge, FILTER_VALIDATE_BOOLEAN);
300
+	}
301
+
302
+
303
+
304
+	/**
305
+	 * given a valid PersistentAdminNotice Collection,
306
+	 * this notice will be added if it is not already found in the collection (using its name as the identifier)
307
+	 * if an existing notice is found that has already been dismissed,
308
+	 * but we are overriding with a forced update, then we will toggle its dismissed state,
309
+	 * so that the notice is displayed again
310
+	 *
311
+	 * @param Collection $persistent_admin_notice_collection
312
+	 * @throws InvalidEntityException
313
+	 * @throws InvalidDataTypeException
314
+	 */
315
+	public function registerPersistentAdminNotice(Collection $persistent_admin_notice_collection)
316
+	{
317
+		if ($this->registered) {
318
+			return;
319
+		}
320
+		// first check if this notice has already been added to the collection
321
+		if ($persistent_admin_notice_collection->has($this->name)) {
322
+			/** @var PersistentAdminNotice $existing */
323
+			$existing = $persistent_admin_notice_collection->get($this->name);
324
+			// we don't need to add it again (we can't actually)
325
+			// but if it has already been dismissed, and we are overriding with a forced update
326
+			if ($existing->getDismissed() && $this->getForceUpdate()) {
327
+				// then toggle the notice's dismissed state to true
328
+				// so that it gets displayed again
329
+				$existing->setDismissed(false);
330
+				// and make sure the message is set
331
+				$existing->setMessage($this->message);
332
+			}
333
+		} else {
334
+			$persistent_admin_notice_collection->add($this, $this->name);
335
+		}
336
+		$this->registered = true;
337
+	}
338
+
339
+
340
+
341
+	/**
342
+	 * @throws Exception
343
+	 */
344
+	public function confirmRegistered()
345
+	{
346
+		if (! apply_filters('PersistentAdminNoticeManager__registerAndSaveNotices__complete', false)) {
347
+			PersistentAdminNoticeManager::loadRegisterAndSaveNotices();
348
+		}
349
+		if (! $this->registered && WP_DEBUG) {
350
+			throw new DomainException(
351
+				sprintf(
352
+					esc_html__(
353
+						'The "%1$s" PersistentAdminNotice was not successfully registered. Please ensure that it is being created prior to either the "admin_notices" or "network_admin_notices" hooks being triggered.',
354
+						'event_espresso'
355
+					),
356
+					$this->name
357
+				)
358
+			);
359
+		}
360
+	}
361 361
 
362 362
 
363 363
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
      */
131 131
     private function setName($name)
132 132
     {
133
-        if (! is_string($name)) {
133
+        if ( ! is_string($name)) {
134 134
             throw new InvalidDataTypeException('$name', $name, 'string');
135 135
         }
136 136
         $this->name = sanitize_key($name);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
      */
155 155
     private function setMessage($message)
156 156
     {
157
-        if (! is_string($message)) {
157
+        if ( ! is_string($message)) {
158 158
             throw new InvalidDataTypeException('$message', $message, 'string');
159 159
         }
160 160
         global $allowedtags;
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
      */
201 201
     private function setCapability($capability)
202 202
     {
203
-        if (! is_string($capability)) {
203
+        if ( ! is_string($capability)) {
204 204
             throw new InvalidDataTypeException('$capability', $capability, 'string');
205 205
         }
206 206
         $this->capability = ! empty($capability) ? $capability : 'manage_options';
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
      */
225 225
     private function setCapContext($cap_context)
226 226
     {
227
-        if (! is_string($cap_context)) {
227
+        if ( ! is_string($cap_context)) {
228 228
             throw new InvalidDataTypeException('$cap_context', $cap_context, 'string');
229 229
         }
230 230
         $this->cap_context = ! empty($cap_context) ? $cap_context : 'view persistent admin notice';
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
      */
259 259
     public function getCapCheck()
260 260
     {
261
-        if (! $this->cap_check instanceof CapCheckInterface) {
261
+        if ( ! $this->cap_check instanceof CapCheckInterface) {
262 262
             $this->setCapCheck(
263 263
                 new CapCheck(
264 264
                     $this->capability,
@@ -343,10 +343,10 @@  discard block
 block discarded – undo
343 343
      */
344 344
     public function confirmRegistered()
345 345
     {
346
-        if (! apply_filters('PersistentAdminNoticeManager__registerAndSaveNotices__complete', false)) {
346
+        if ( ! apply_filters('PersistentAdminNoticeManager__registerAndSaveNotices__complete', false)) {
347 347
             PersistentAdminNoticeManager::loadRegisterAndSaveNotices();
348 348
         }
349
-        if (! $this->registered && WP_DEBUG) {
349
+        if ( ! $this->registered && WP_DEBUG) {
350 350
             throw new DomainException(
351 351
                 sprintf(
352 352
                     esc_html__(
Please login to merge, or discard this patch.
core/services/notifications/PersistentAdminNoticeManager.php 2 patches
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -32,390 +32,390 @@
 block discarded – undo
32 32
 class PersistentAdminNoticeManager
33 33
 {
34 34
 
35
-    const WP_OPTION_KEY = 'ee_pers_admin_notices';
36
-
37
-    /**
38
-     * @var Collection|PersistentAdminNotice[] $notice_collection
39
-     */
40
-    private $notice_collection;
41
-
42
-    /**
43
-     * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
44
-     * persistent admin notice was displayed, and ultimately dismissed from.
45
-     *
46
-     * @var string $return_url
47
-     */
48
-    private $return_url;
49
-
50
-    /**
51
-     * @var CapabilitiesChecker $capabilities_checker
52
-     */
53
-    private $capabilities_checker;
54
-
55
-    /**
56
-     * @var EE_Request $request
57
-     */
58
-    private $request;
59
-
60
-
61
-
62
-    /**
63
-     * PersistentAdminNoticeManager constructor
64
-     *
65
-     * @param string              $return_url  where to  redirect to after dismissing notices
66
-     * @param CapabilitiesChecker $capabilities_checker
67
-     * @param EE_Request          $request
68
-     * @throws InvalidDataTypeException
69
-     */
70
-    public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
71
-    {
72
-        $this->setReturnUrl($return_url);
73
-        $this->capabilities_checker = $capabilities_checker;
74
-        $this->request              = $request;
75
-        // setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
76
-        // and we want to retrieve and generate any nag notices at the last possible moment
77
-        add_action('admin_notices', array($this, 'displayNotices'), 9);
78
-        add_action('network_admin_notices', array($this, 'displayNotices'), 9);
79
-        add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
80
-        add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
81
-    }
82
-
83
-
84
-
85
-    /**
86
-     * @param string $return_url
87
-     * @throws InvalidDataTypeException
88
-     */
89
-    public function setReturnUrl($return_url)
90
-    {
91
-        if (! is_string($return_url)) {
92
-            throw new InvalidDataTypeException('$return_url', $return_url, 'string');
93
-        }
94
-        $this->return_url = $return_url;
95
-    }
96
-
97
-
98
-
99
-    /**
100
-     * @return Collection
101
-     * @throws InvalidEntityException
102
-     * @throws InvalidInterfaceException
103
-     * @throws InvalidDataTypeException
104
-     * @throws DomainException
105
-     */
106
-    protected function getPersistentAdminNoticeCollection()
107
-    {
108
-        if (! $this->notice_collection instanceof Collection) {
109
-            $this->notice_collection = new Collection(
110
-                'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
111
-            );
112
-            $this->retrieveStoredNotices();
113
-            $this->registerNotices();
114
-        }
115
-        return $this->notice_collection;
116
-    }
117
-
118
-
119
-
120
-    /**
121
-     * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
122
-     *
123
-     * @return void
124
-     * @throws InvalidEntityException
125
-     * @throws DomainException
126
-     * @throws InvalidDataTypeException
127
-     */
128
-    protected function retrieveStoredNotices()
129
-    {
130
-        $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
131
-        // \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
132
-        if (! empty($persistent_admin_notices)) {
133
-            foreach ($persistent_admin_notices as $name => $details) {
134
-                if (is_array($details)) {
135
-                    if (
136
-                        ! isset(
137
-                            $details['message'],
138
-                            $details['capability'],
139
-                            $details['cap_context'],
140
-                            $details['dismissed']
141
-                        )
142
-                    ) {
143
-                        throw new DomainException(
144
-                            sprintf(
145
-                                esc_html__(
146
-                                    'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
147
-                                    'event_espresso'
148
-                                ),
149
-                                $name
150
-                            )
151
-                        );
152
-                    }
153
-                    // new format for nag notices
154
-                    $this->notice_collection->add(
155
-                        new PersistentAdminNotice(
156
-                            $name,
157
-                            $details['message'],
158
-                            false,
159
-                            $details['capability'],
160
-                            $details['cap_context'],
161
-                            $details['dismissed']
162
-                        ),
163
-                        $name
164
-                    );
165
-                } else {
166
-                    try {
167
-                        // old nag notices, that we want to convert to the new format
168
-                        $this->notice_collection->add(
169
-                            new PersistentAdminNotice(
170
-                                $name,
171
-                                (string)$details,
172
-                                false,
173
-                                '',
174
-                                '',
175
-                                empty($details)
176
-                            ),
177
-                            $name
178
-                        );
179
-                    } catch (Exception $e) {
180
-                        EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
181
-                    }
182
-                }
183
-                // each notice will self register when the action hook in registerNotices is triggered
184
-            }
185
-        }
186
-    }
187
-
188
-
189
-
190
-    /**
191
-     * exposes the Persistent Admin Notice Collection via an action
192
-     * so that PersistentAdminNotice objects can be added and/or removed
193
-     * without compromising the actual collection like a filter would
194
-     */
195
-    protected function registerNotices()
196
-    {
197
-        do_action(
198
-            'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
199
-            $this->notice_collection
200
-        );
201
-    }
202
-
203
-
204
-
205
-    /**
206
-     * @throws DomainException
207
-     * @throws InvalidClassException
208
-     * @throws InvalidDataTypeException
209
-     * @throws InvalidInterfaceException
210
-     * @throws InvalidEntityException
211
-     */
212
-    public function displayNotices()
213
-    {
214
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
215
-        if ($this->notice_collection->hasObjects()) {
216
-            $enqueue_assets = false;
217
-            // and display notices
218
-            foreach ($this->notice_collection as $persistent_admin_notice) {
219
-                /** @var PersistentAdminNotice $persistent_admin_notice */
220
-                // don't display notices that have already been dismissed
221
-                if ($persistent_admin_notice->getDismissed()) {
222
-                    continue;
223
-                }
224
-                try {
225
-                    $this->capabilities_checker->processCapCheck(
226
-                        $persistent_admin_notice->getCapCheck()
227
-                    );
228
-                } catch (InsufficientPermissionsException $e) {
229
-                    // user does not have required cap, so skip to next notice
230
-                    // and just eat the exception - nom nom nom nom
231
-                    continue;
232
-                }
233
-                if ($persistent_admin_notice->getMessage() === '') {
234
-                    continue;
235
-                }
236
-                $this->displayPersistentAdminNotice($persistent_admin_notice);
237
-                $enqueue_assets = true;
238
-            }
239
-            if ($enqueue_assets) {
240
-                $this->enqueueAssets();
241
-            }
242
-        }
243
-    }
244
-
245
-
246
-
247
-    /**
248
-     * does what it's named
249
-     *
250
-     * @return void
251
-     */
252
-    public function enqueueAssets()
253
-    {
254
-        wp_register_script(
255
-            'espresso_core',
256
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
257
-            array('jquery'),
258
-            EVENT_ESPRESSO_VERSION,
259
-            true
260
-        );
261
-        wp_register_script(
262
-            'ee_error_js',
263
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
264
-            array('espresso_core'),
265
-            EVENT_ESPRESSO_VERSION,
266
-            true
267
-        );
268
-        wp_localize_script(
269
-            'ee_error_js',
270
-            'ee_dismiss',
271
-            array(
272
-                'return_url'    => urlencode($this->return_url),
273
-                'ajax_url'      => WP_AJAX_URL,
274
-                'unknown_error' => esc_html__(
275
-                    'An unknown error has occurred on the server while attempting to dismiss this notice.',
276
-                    'event_espresso'
277
-                ),
278
-            )
279
-        );
280
-        wp_enqueue_script('ee_error_js');
281
-    }
282
-
283
-
284
-
285
-    /**
286
-     * displayPersistentAdminNoticeHtml
287
-     *
288
-     * @param  PersistentAdminNotice $persistent_admin_notice
289
-     */
290
-    protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
291
-    {
292
-        // used in template
293
-        $persistent_admin_notice_name    = $persistent_admin_notice->getName();
294
-        $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
295
-        require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * dismissNotice
302
-     *
303
-     * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
304
-     * @param bool   $purge    if true, then delete it from the db
305
-     * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
306
-     * @return void
307
-     * @throws InvalidEntityException
308
-     * @throws InvalidInterfaceException
309
-     * @throws InvalidDataTypeException
310
-     * @throws DomainException
311
-     */
312
-    public function dismissNotice($pan_name = '', $purge = false, $return = false)
313
-    {
314
-        $pan_name                = $this->request->get('ee_nag_notice', $pan_name);
315
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
316
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
317
-            /** @var PersistentAdminNotice $persistent_admin_notice */
318
-            $persistent_admin_notice = $this->notice_collection->get($pan_name);
319
-            $persistent_admin_notice->setDismissed(true);
320
-            $persistent_admin_notice->setPurge($purge);
321
-            $this->saveNotices();
322
-        }
323
-        if ($return) {
324
-            return;
325
-        }
326
-        if ($this->request->ajax) {
327
-            // grab any notices and concatenate into string
328
-            echo wp_json_encode(
329
-                array(
330
-                    'errors' => implode('<br />', EE_Error::get_notices(false)),
331
-                )
332
-            );
333
-            exit();
334
-        }
335
-        // save errors to a transient to be displayed on next request (after redirect)
336
-        EE_Error::get_notices(false, true);
337
-        wp_safe_redirect(
338
-            urldecode(
339
-                $this->request->get('return_url', '')
340
-            )
341
-        );
342
-    }
343
-
344
-
345
-
346
-    /**
347
-     * saveNotices
348
-     *
349
-     * @throws DomainException
350
-     * @throws InvalidDataTypeException
351
-     * @throws InvalidInterfaceException
352
-     * @throws InvalidEntityException
353
-     */
354
-    public function saveNotices()
355
-    {
356
-        $this->notice_collection = $this->getPersistentAdminNoticeCollection();
357
-        if ($this->notice_collection->hasObjects()) {
358
-            $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
359
-            //maybe initialize persistent_admin_notices
360
-            if (empty($persistent_admin_notices)) {
361
-                add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
362
-            }
363
-            foreach ($this->notice_collection as $persistent_admin_notice) {
364
-                // are we deleting this notice ?
365
-                if ($persistent_admin_notice->getPurge()) {
366
-                    unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
367
-                } else {
368
-                    /** @var PersistentAdminNotice $persistent_admin_notice */
369
-                    $persistent_admin_notices[$persistent_admin_notice->getName()] = array(
370
-                        'message'     => $persistent_admin_notice->getMessage(),
371
-                        'capability'  => $persistent_admin_notice->getCapability(),
372
-                        'cap_context' => $persistent_admin_notice->getCapContext(),
373
-                        'dismissed'   => $persistent_admin_notice->getDismissed(),
374
-                    );
375
-                }
376
-            }
377
-            update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
378
-        }
379
-    }
380
-
381
-
382
-
383
-    /**
384
-     * @throws DomainException
385
-     * @throws InvalidDataTypeException
386
-     * @throws InvalidEntityException
387
-     * @throws InvalidInterfaceException
388
-     */
389
-    public function registerAndSaveNotices()
390
-    {
391
-        $this->getPersistentAdminNoticeCollection();
392
-        $this->registerNotices();
393
-        $this->saveNotices();
394
-        add_filter(
395
-            'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
396
-            '__return_true'
397
-        );
398
-    }
399
-
400
-
401
-    /**
402
-     * @throws DomainException
403
-     * @throws InvalidDataTypeException
404
-     * @throws InvalidEntityException
405
-     * @throws InvalidInterfaceException
406
-     * @throws InvalidArgumentException
407
-     */
408
-    public static function loadRegisterAndSaveNotices()
409
-    {
410
-        /** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
411
-        $persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
412
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
413
-        );
414
-        // if shutdown has already run, then call registerAndSaveNotices() manually
415
-        if(did_action('shutdown')){
416
-            $persistent_admin_notice_manager->registerAndSaveNotices();
417
-        }
418
-    }
35
+	const WP_OPTION_KEY = 'ee_pers_admin_notices';
36
+
37
+	/**
38
+	 * @var Collection|PersistentAdminNotice[] $notice_collection
39
+	 */
40
+	private $notice_collection;
41
+
42
+	/**
43
+	 * if AJAX is not enabled, then the return URL will be used for redirecting back to the admin page where the
44
+	 * persistent admin notice was displayed, and ultimately dismissed from.
45
+	 *
46
+	 * @var string $return_url
47
+	 */
48
+	private $return_url;
49
+
50
+	/**
51
+	 * @var CapabilitiesChecker $capabilities_checker
52
+	 */
53
+	private $capabilities_checker;
54
+
55
+	/**
56
+	 * @var EE_Request $request
57
+	 */
58
+	private $request;
59
+
60
+
61
+
62
+	/**
63
+	 * PersistentAdminNoticeManager constructor
64
+	 *
65
+	 * @param string              $return_url  where to  redirect to after dismissing notices
66
+	 * @param CapabilitiesChecker $capabilities_checker
67
+	 * @param EE_Request          $request
68
+	 * @throws InvalidDataTypeException
69
+	 */
70
+	public function __construct($return_url = '', CapabilitiesChecker $capabilities_checker, EE_Request $request)
71
+	{
72
+		$this->setReturnUrl($return_url);
73
+		$this->capabilities_checker = $capabilities_checker;
74
+		$this->request              = $request;
75
+		// setup up notices at priority 9 because `EE_Admin::display_admin_notices()` runs at priority 10,
76
+		// and we want to retrieve and generate any nag notices at the last possible moment
77
+		add_action('admin_notices', array($this, 'displayNotices'), 9);
78
+		add_action('network_admin_notices', array($this, 'displayNotices'), 9);
79
+		add_action('wp_ajax_dismiss_ee_nag_notice', array($this, 'dismissNotice'));
80
+		add_action('shutdown', array($this, 'registerAndSaveNotices'), 998);
81
+	}
82
+
83
+
84
+
85
+	/**
86
+	 * @param string $return_url
87
+	 * @throws InvalidDataTypeException
88
+	 */
89
+	public function setReturnUrl($return_url)
90
+	{
91
+		if (! is_string($return_url)) {
92
+			throw new InvalidDataTypeException('$return_url', $return_url, 'string');
93
+		}
94
+		$this->return_url = $return_url;
95
+	}
96
+
97
+
98
+
99
+	/**
100
+	 * @return Collection
101
+	 * @throws InvalidEntityException
102
+	 * @throws InvalidInterfaceException
103
+	 * @throws InvalidDataTypeException
104
+	 * @throws DomainException
105
+	 */
106
+	protected function getPersistentAdminNoticeCollection()
107
+	{
108
+		if (! $this->notice_collection instanceof Collection) {
109
+			$this->notice_collection = new Collection(
110
+				'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
111
+			);
112
+			$this->retrieveStoredNotices();
113
+			$this->registerNotices();
114
+		}
115
+		return $this->notice_collection;
116
+	}
117
+
118
+
119
+
120
+	/**
121
+	 * generates PersistentAdminNotice objects for all non-dismissed notices saved to the db
122
+	 *
123
+	 * @return void
124
+	 * @throws InvalidEntityException
125
+	 * @throws DomainException
126
+	 * @throws InvalidDataTypeException
127
+	 */
128
+	protected function retrieveStoredNotices()
129
+	{
130
+		$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
131
+		// \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
132
+		if (! empty($persistent_admin_notices)) {
133
+			foreach ($persistent_admin_notices as $name => $details) {
134
+				if (is_array($details)) {
135
+					if (
136
+						! isset(
137
+							$details['message'],
138
+							$details['capability'],
139
+							$details['cap_context'],
140
+							$details['dismissed']
141
+						)
142
+					) {
143
+						throw new DomainException(
144
+							sprintf(
145
+								esc_html__(
146
+									'The "%1$s" PersistentAdminNotice could not be retrieved from the database.',
147
+									'event_espresso'
148
+								),
149
+								$name
150
+							)
151
+						);
152
+					}
153
+					// new format for nag notices
154
+					$this->notice_collection->add(
155
+						new PersistentAdminNotice(
156
+							$name,
157
+							$details['message'],
158
+							false,
159
+							$details['capability'],
160
+							$details['cap_context'],
161
+							$details['dismissed']
162
+						),
163
+						$name
164
+					);
165
+				} else {
166
+					try {
167
+						// old nag notices, that we want to convert to the new format
168
+						$this->notice_collection->add(
169
+							new PersistentAdminNotice(
170
+								$name,
171
+								(string)$details,
172
+								false,
173
+								'',
174
+								'',
175
+								empty($details)
176
+							),
177
+							$name
178
+						);
179
+					} catch (Exception $e) {
180
+						EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
181
+					}
182
+				}
183
+				// each notice will self register when the action hook in registerNotices is triggered
184
+			}
185
+		}
186
+	}
187
+
188
+
189
+
190
+	/**
191
+	 * exposes the Persistent Admin Notice Collection via an action
192
+	 * so that PersistentAdminNotice objects can be added and/or removed
193
+	 * without compromising the actual collection like a filter would
194
+	 */
195
+	protected function registerNotices()
196
+	{
197
+		do_action(
198
+			'AHEE__EventEspresso_core_services_notifications_PersistentAdminNoticeManager__registerNotices',
199
+			$this->notice_collection
200
+		);
201
+	}
202
+
203
+
204
+
205
+	/**
206
+	 * @throws DomainException
207
+	 * @throws InvalidClassException
208
+	 * @throws InvalidDataTypeException
209
+	 * @throws InvalidInterfaceException
210
+	 * @throws InvalidEntityException
211
+	 */
212
+	public function displayNotices()
213
+	{
214
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
215
+		if ($this->notice_collection->hasObjects()) {
216
+			$enqueue_assets = false;
217
+			// and display notices
218
+			foreach ($this->notice_collection as $persistent_admin_notice) {
219
+				/** @var PersistentAdminNotice $persistent_admin_notice */
220
+				// don't display notices that have already been dismissed
221
+				if ($persistent_admin_notice->getDismissed()) {
222
+					continue;
223
+				}
224
+				try {
225
+					$this->capabilities_checker->processCapCheck(
226
+						$persistent_admin_notice->getCapCheck()
227
+					);
228
+				} catch (InsufficientPermissionsException $e) {
229
+					// user does not have required cap, so skip to next notice
230
+					// and just eat the exception - nom nom nom nom
231
+					continue;
232
+				}
233
+				if ($persistent_admin_notice->getMessage() === '') {
234
+					continue;
235
+				}
236
+				$this->displayPersistentAdminNotice($persistent_admin_notice);
237
+				$enqueue_assets = true;
238
+			}
239
+			if ($enqueue_assets) {
240
+				$this->enqueueAssets();
241
+			}
242
+		}
243
+	}
244
+
245
+
246
+
247
+	/**
248
+	 * does what it's named
249
+	 *
250
+	 * @return void
251
+	 */
252
+	public function enqueueAssets()
253
+	{
254
+		wp_register_script(
255
+			'espresso_core',
256
+			EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
257
+			array('jquery'),
258
+			EVENT_ESPRESSO_VERSION,
259
+			true
260
+		);
261
+		wp_register_script(
262
+			'ee_error_js',
263
+			EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
264
+			array('espresso_core'),
265
+			EVENT_ESPRESSO_VERSION,
266
+			true
267
+		);
268
+		wp_localize_script(
269
+			'ee_error_js',
270
+			'ee_dismiss',
271
+			array(
272
+				'return_url'    => urlencode($this->return_url),
273
+				'ajax_url'      => WP_AJAX_URL,
274
+				'unknown_error' => esc_html__(
275
+					'An unknown error has occurred on the server while attempting to dismiss this notice.',
276
+					'event_espresso'
277
+				),
278
+			)
279
+		);
280
+		wp_enqueue_script('ee_error_js');
281
+	}
282
+
283
+
284
+
285
+	/**
286
+	 * displayPersistentAdminNoticeHtml
287
+	 *
288
+	 * @param  PersistentAdminNotice $persistent_admin_notice
289
+	 */
290
+	protected function displayPersistentAdminNotice(PersistentAdminNotice $persistent_admin_notice)
291
+	{
292
+		// used in template
293
+		$persistent_admin_notice_name    = $persistent_admin_notice->getName();
294
+		$persistent_admin_notice_message = $persistent_admin_notice->getMessage();
295
+		require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * dismissNotice
302
+	 *
303
+	 * @param string $pan_name the name, or key of the Persistent Admin Notice to be dismissed
304
+	 * @param bool   $purge    if true, then delete it from the db
305
+	 * @param bool   $return   forget all of this AJAX or redirect nonsense, and just return
306
+	 * @return void
307
+	 * @throws InvalidEntityException
308
+	 * @throws InvalidInterfaceException
309
+	 * @throws InvalidDataTypeException
310
+	 * @throws DomainException
311
+	 */
312
+	public function dismissNotice($pan_name = '', $purge = false, $return = false)
313
+	{
314
+		$pan_name                = $this->request->get('ee_nag_notice', $pan_name);
315
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
316
+		if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
317
+			/** @var PersistentAdminNotice $persistent_admin_notice */
318
+			$persistent_admin_notice = $this->notice_collection->get($pan_name);
319
+			$persistent_admin_notice->setDismissed(true);
320
+			$persistent_admin_notice->setPurge($purge);
321
+			$this->saveNotices();
322
+		}
323
+		if ($return) {
324
+			return;
325
+		}
326
+		if ($this->request->ajax) {
327
+			// grab any notices and concatenate into string
328
+			echo wp_json_encode(
329
+				array(
330
+					'errors' => implode('<br />', EE_Error::get_notices(false)),
331
+				)
332
+			);
333
+			exit();
334
+		}
335
+		// save errors to a transient to be displayed on next request (after redirect)
336
+		EE_Error::get_notices(false, true);
337
+		wp_safe_redirect(
338
+			urldecode(
339
+				$this->request->get('return_url', '')
340
+			)
341
+		);
342
+	}
343
+
344
+
345
+
346
+	/**
347
+	 * saveNotices
348
+	 *
349
+	 * @throws DomainException
350
+	 * @throws InvalidDataTypeException
351
+	 * @throws InvalidInterfaceException
352
+	 * @throws InvalidEntityException
353
+	 */
354
+	public function saveNotices()
355
+	{
356
+		$this->notice_collection = $this->getPersistentAdminNoticeCollection();
357
+		if ($this->notice_collection->hasObjects()) {
358
+			$persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
359
+			//maybe initialize persistent_admin_notices
360
+			if (empty($persistent_admin_notices)) {
361
+				add_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array(), '', 'no');
362
+			}
363
+			foreach ($this->notice_collection as $persistent_admin_notice) {
364
+				// are we deleting this notice ?
365
+				if ($persistent_admin_notice->getPurge()) {
366
+					unset($persistent_admin_notices[$persistent_admin_notice->getName()]);
367
+				} else {
368
+					/** @var PersistentAdminNotice $persistent_admin_notice */
369
+					$persistent_admin_notices[$persistent_admin_notice->getName()] = array(
370
+						'message'     => $persistent_admin_notice->getMessage(),
371
+						'capability'  => $persistent_admin_notice->getCapability(),
372
+						'cap_context' => $persistent_admin_notice->getCapContext(),
373
+						'dismissed'   => $persistent_admin_notice->getDismissed(),
374
+					);
375
+				}
376
+			}
377
+			update_option(PersistentAdminNoticeManager::WP_OPTION_KEY, $persistent_admin_notices);
378
+		}
379
+	}
380
+
381
+
382
+
383
+	/**
384
+	 * @throws DomainException
385
+	 * @throws InvalidDataTypeException
386
+	 * @throws InvalidEntityException
387
+	 * @throws InvalidInterfaceException
388
+	 */
389
+	public function registerAndSaveNotices()
390
+	{
391
+		$this->getPersistentAdminNoticeCollection();
392
+		$this->registerNotices();
393
+		$this->saveNotices();
394
+		add_filter(
395
+			'PersistentAdminNoticeManager__registerAndSaveNotices__complete',
396
+			'__return_true'
397
+		);
398
+	}
399
+
400
+
401
+	/**
402
+	 * @throws DomainException
403
+	 * @throws InvalidDataTypeException
404
+	 * @throws InvalidEntityException
405
+	 * @throws InvalidInterfaceException
406
+	 * @throws InvalidArgumentException
407
+	 */
408
+	public static function loadRegisterAndSaveNotices()
409
+	{
410
+		/** @var PersistentAdminNoticeManager $persistent_admin_notice_manager */
411
+		$persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
412
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
413
+		);
414
+		// if shutdown has already run, then call registerAndSaveNotices() manually
415
+		if(did_action('shutdown')){
416
+			$persistent_admin_notice_manager->registerAndSaveNotices();
417
+		}
418
+	}
419 419
 
420 420
 
421 421
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
      */
89 89
     public function setReturnUrl($return_url)
90 90
     {
91
-        if (! is_string($return_url)) {
91
+        if ( ! is_string($return_url)) {
92 92
             throw new InvalidDataTypeException('$return_url', $return_url, 'string');
93 93
         }
94 94
         $this->return_url = $return_url;
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
      */
106 106
     protected function getPersistentAdminNoticeCollection()
107 107
     {
108
-        if (! $this->notice_collection instanceof Collection) {
108
+        if ( ! $this->notice_collection instanceof Collection) {
109 109
             $this->notice_collection = new Collection(
110 110
                 'EventEspresso\core\domain\entities\notifications\PersistentAdminNotice'
111 111
             );
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
     {
130 130
         $persistent_admin_notices = get_option(PersistentAdminNoticeManager::WP_OPTION_KEY, array());
131 131
         // \EEH_Debug_Tools::printr($persistent_admin_notices, '$persistent_admin_notices', __FILE__, __LINE__);
132
-        if (! empty($persistent_admin_notices)) {
132
+        if ( ! empty($persistent_admin_notices)) {
133 133
             foreach ($persistent_admin_notices as $name => $details) {
134 134
                 if (is_array($details)) {
135 135
                     if (
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
                         $this->notice_collection->add(
169 169
                             new PersistentAdminNotice(
170 170
                                 $name,
171
-                                (string)$details,
171
+                                (string) $details,
172 172
                                 false,
173 173
                                 '',
174 174
                                 '',
@@ -253,14 +253,14 @@  discard block
 block discarded – undo
253 253
     {
254 254
         wp_register_script(
255 255
             'espresso_core',
256
-            EE_GLOBAL_ASSETS_URL . 'scripts/espresso_core.js',
256
+            EE_GLOBAL_ASSETS_URL.'scripts/espresso_core.js',
257 257
             array('jquery'),
258 258
             EVENT_ESPRESSO_VERSION,
259 259
             true
260 260
         );
261 261
         wp_register_script(
262 262
             'ee_error_js',
263
-            EE_GLOBAL_ASSETS_URL . 'scripts/EE_Error.js',
263
+            EE_GLOBAL_ASSETS_URL.'scripts/EE_Error.js',
264 264
             array('espresso_core'),
265 265
             EVENT_ESPRESSO_VERSION,
266 266
             true
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
         // used in template
293 293
         $persistent_admin_notice_name    = $persistent_admin_notice->getName();
294 294
         $persistent_admin_notice_message = $persistent_admin_notice->getMessage();
295
-        require EE_TEMPLATES . DS . 'notifications' . DS . 'persistent_admin_notice.template.php';
295
+        require EE_TEMPLATES.DS.'notifications'.DS.'persistent_admin_notice.template.php';
296 296
     }
297 297
 
298 298
 
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
     {
314 314
         $pan_name                = $this->request->get('ee_nag_notice', $pan_name);
315 315
         $this->notice_collection = $this->getPersistentAdminNoticeCollection();
316
-        if (! empty($pan_name) && $this->notice_collection->has($pan_name)) {
316
+        if ( ! empty($pan_name) && $this->notice_collection->has($pan_name)) {
317 317
             /** @var PersistentAdminNotice $persistent_admin_notice */
318 318
             $persistent_admin_notice = $this->notice_collection->get($pan_name);
319 319
             $persistent_admin_notice->setDismissed(true);
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
             'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
413 413
         );
414 414
         // if shutdown has already run, then call registerAndSaveNotices() manually
415
-        if(did_action('shutdown')){
415
+        if (did_action('shutdown')) {
416 416
             $persistent_admin_notice_manager->registerAndSaveNotices();
417 417
         }
418 418
     }
Please login to merge, or discard this patch.
core/admin/EE_Admin.core.php 1 patch
Indentation   +899 added lines, -899 removed lines patch added patch discarded remove patch
@@ -22,457 +22,457 @@  discard block
 block discarded – undo
22 22
 final class EE_Admin implements InterminableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var EE_Admin $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
32
-     */
33
-    private $persistent_admin_notice_manager;
34
-
35
-    /**
36
-     * @singleton method used to instantiate class object
37
-     * @return EE_Admin
38
-     * @throws EE_Error
39
-     */
40
-    public static function instance()
41
-    {
42
-        // check if class object is instantiated
43
-        if (! self::$_instance instanceof EE_Admin) {
44
-            self::$_instance = new self();
45
-        }
46
-        return self::$_instance;
47
-    }
48
-
49
-
50
-    /**
51
-     * @return EE_Admin
52
-     * @throws EE_Error
53
-     */
54
-    public static function reset()
55
-    {
56
-        self::$_instance = null;
57
-        return self::instance();
58
-    }
59
-
60
-
61
-    /**
62
-     * class constructor
63
-     *
64
-     * @throws EE_Error
65
-     * @throws InvalidDataTypeException
66
-     * @throws InvalidInterfaceException
67
-     * @throws InvalidArgumentException
68
-     */
69
-    protected function __construct()
70
-    {
71
-        // define global EE_Admin constants
72
-        $this->_define_all_constants();
73
-        // set autoloaders for our admin page classes based on included path information
74
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
75
-        // admin hooks
76
-        add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
77
-        // load EE_Request_Handler early
78
-        add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'get_request'));
79
-        add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
80
-        add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
81
-        add_action('wp_loaded', array($this, 'wp_loaded'), 100);
82
-        add_action('admin_init', array($this, 'admin_init'), 100);
83
-        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
84
-        add_action('admin_notices', array($this, 'display_admin_notices'), 10);
85
-        add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
86
-        add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
87
-        add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
88
-        //reset Environment config (we only do this on admin page loads);
89
-        EE_Registry::instance()->CFG->environment->recheck_values();
90
-        do_action('AHEE__EE_Admin__loaded');
91
-    }
92
-
93
-
94
-
95
-    /**
96
-     * _define_all_constants
97
-     * define constants that are set globally for all admin pages
98
-     *
99
-     * @return void
100
-     */
101
-    private function _define_all_constants()
102
-    {
103
-        if (! defined('EE_ADMIN_URL')) {
104
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
105
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
106
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates' . DS);
107
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
108
-            define('WP_AJAX_URL', admin_url('admin-ajax.php'));
109
-        }
110
-    }
111
-
112
-
113
-    /**
114
-     * filter_plugin_actions - adds links to the Plugins page listing
115
-     *
116
-     * @param    array  $links
117
-     * @param    string $plugin
118
-     * @return    array
119
-     */
120
-    public function filter_plugin_actions($links, $plugin)
121
-    {
122
-        // set $main_file in stone
123
-        static $main_file;
124
-        // if $main_file is not set yet
125
-        if (! $main_file) {
126
-            $main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
127
-        }
128
-        if ($plugin === $main_file) {
129
-            // compare current plugin to this one
130
-            if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
131
-                $maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
132
-                                    . ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
133
-                                    . esc_html__('Maintenance Mode Active', 'event_espresso')
134
-                                    . '</a>';
135
-                array_unshift($links, $maintenance_link);
136
-            } else {
137
-                $org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
138
-                                     . esc_html__('Settings', 'event_espresso')
139
-                                     . '</a>';
140
-                $events_link       = '<a href="admin.php?page=espresso_events">'
141
-                                     . esc_html__('Events', 'event_espresso')
142
-                                     . '</a>';
143
-                // add before other links
144
-                array_unshift($links, $org_settings_link, $events_link);
145
-            }
146
-        }
147
-        return $links;
148
-    }
149
-
150
-
151
-    /**
152
-     * _get_request
153
-     *
154
-     * @return void
155
-     * @throws EE_Error
156
-     * @throws InvalidArgumentException
157
-     * @throws InvalidDataTypeException
158
-     * @throws InvalidInterfaceException
159
-     * @throws ReflectionException
160
-     */
161
-    public function get_request()
162
-    {
163
-        EE_Registry::instance()->load_core('Request_Handler');
164
-        EE_Registry::instance()->load_core('CPT_Strategy');
165
-    }
166
-
167
-
168
-
169
-    /**
170
-     * hide_admin_pages_except_maintenance_mode
171
-     *
172
-     * @param array $admin_page_folder_names
173
-     * @return array
174
-     */
175
-    public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
176
-    {
177
-        return array(
178
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance' . DS,
179
-            'about'       => EE_ADMIN_PAGES . 'about' . DS,
180
-            'support'     => EE_ADMIN_PAGES . 'support' . DS,
181
-        );
182
-    }
183
-
184
-
185
-
186
-    /**
187
-     * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
188
-     * EE_Front_Controller's init phases have run
189
-     *
190
-     * @return void
191
-     * @throws EE_Error
192
-     * @throws InvalidArgumentException
193
-     * @throws InvalidDataTypeException
194
-     * @throws InvalidInterfaceException
195
-     * @throws ReflectionException
196
-     * @throws ServiceNotFoundException
197
-     */
198
-    public function init()
199
-    {
200
-        //only enable most of the EE_Admin IF we're not in full maintenance mode
201
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
202
-            //ok so we want to enable the entire admin
203
-            $this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
204
-                'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
205
-            );
206
-            $this->persistent_admin_notice_manager->setReturnUrl(
207
-                EE_Admin_Page::add_query_args_and_nonce(
208
-                    array(
209
-                        'page'   => EE_Registry::instance()->REQ->get('page', ''),
210
-                        'action' => EE_Registry::instance()->REQ->get('action', ''),
211
-                    ),
212
-                    EE_ADMIN_URL
213
-                )
214
-            );
215
-            $this->maybeSetDatetimeWarningNotice();
216
-            //at a glance dashboard widget
217
-            add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
218
-            //filter for get_edit_post_link used on comments for custom post types
219
-            add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
220
-        }
221
-        // run the admin page factory but ONLY if we are doing an ee admin ajax request
222
-        if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
223
-            try {
224
-                //this loads the controller for the admin pages which will setup routing etc
225
-                EE_Registry::instance()->load_core('Admin_Page_Loader');
226
-            } catch (EE_Error $e) {
227
-                $e->get_error();
228
-            }
229
-        }
230
-        add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
231
-        //make sure our CPTs and custom taxonomy metaboxes get shown for first time users
232
-        add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
233
-        add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
234
-        //exclude EE critical pages from all nav menus and wp_list_pages
235
-        add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
236
-    }
237
-
238
-
239
-    /**
240
-     *    get_persistent_admin_notices
241
-     *
242
-     * @access    public
243
-     * @return void
244
-     * @throws EE_Error
245
-     * @throws InvalidArgumentException
246
-     * @throws InvalidDataTypeException
247
-     * @throws InvalidInterfaceException
248
-     */
249
-    public function maybeSetDatetimeWarningNotice()
250
-    {
251
-        //add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
252
-        //@todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
253
-        //with this.  But after enough time (indeterminate at this point) we can just remove this notice.
254
-        //this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
255
-        if (apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
256
-            && ! get_option('timezone_string')
257
-            && EEM_Event::instance()->count() > 0
258
-        ) {
259
-            new PersistentAdminNotice(
260
-                'datetime_fix_notice',
261
-                sprintf(
262
-                    esc_html__(
263
-                        '%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
264
-                        'event_espresso'
265
-                    ),
266
-                    '<strong>',
267
-                    '</strong>',
268
-                    '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
269
-                    '</a>',
270
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
271
-                        array(
272
-                            'page' => 'espresso_maintenance_settings',
273
-                            'action' => 'datetime_tools'
274
-                        ),
275
-                        admin_url('admin.php')
276
-                    ) . '">'
277
-                ),
278
-                false,
279
-                'manage_options',
280
-                'datetime_fix_persistent_notice'
281
-            );
282
-        }
283
-    }
284
-
285
-
286
-
287
-    /**
288
-     * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
289
-     * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
290
-     * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
291
-     * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
292
-     * normal property on the post_type object.  It's found ONLY in this particular context.
293
-     *
294
-     * @param WP_Post $post_type WP post type object
295
-     * @return WP_Post
296
-     * @throws InvalidArgumentException
297
-     * @throws InvalidDataTypeException
298
-     * @throws InvalidInterfaceException
299
-     */
300
-    public function remove_pages_from_nav_menu($post_type)
301
-    {
302
-        //if this isn't the "pages" post type let's get out
303
-        if ($post_type->name !== 'page') {
304
-            return $post_type;
305
-        }
306
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
307
-        $post_type->_default_query = array(
308
-            'post__not_in' => $critical_pages,
309
-        );
310
-        return $post_type;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
317
-     * metaboxes get shown as well
318
-     *
319
-     * @return void
320
-     */
321
-    public function enable_hidden_ee_nav_menu_metaboxes()
322
-    {
323
-        global $wp_meta_boxes, $pagenow;
324
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
325
-            return;
326
-        }
327
-        $user = wp_get_current_user();
328
-        //has this been done yet?
329
-        if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
330
-            return;
331
-        }
332
-
333
-        $hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
334
-        $initial_meta_boxes = apply_filters(
335
-            'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
336
-            array(
337
-                'nav-menu-theme-locations',
338
-                'add-page',
339
-                'add-custom-links',
340
-                'add-category',
341
-                'add-espresso_events',
342
-                'add-espresso_venues',
343
-                'add-espresso_event_categories',
344
-                'add-espresso_venue_categories',
345
-                'add-post-type-post',
346
-                'add-post-type-page',
347
-            )
348
-        );
349
-
350
-        if (is_array($hidden_meta_boxes)) {
351
-            foreach ($hidden_meta_boxes as $key => $meta_box_id) {
352
-                if (in_array($meta_box_id, $initial_meta_boxes, true)) {
353
-                    unset($hidden_meta_boxes[$key]);
354
-                }
355
-            }
356
-        }
357
-        update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
358
-        update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
359
-    }
360
-
361
-
362
-
363
-    /**
364
-     * This method simply registers custom nav menu boxes for "nav_menus.php route"
365
-     * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
366
-     *
367
-     * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
368
-     *         addons etc.
369
-     * @return void
370
-     */
371
-    public function register_custom_nav_menu_boxes()
372
-    {
373
-        add_meta_box(
374
-            'add-extra-nav-menu-pages',
375
-            esc_html__('Event Espresso Pages', 'event_espresso'),
376
-            array($this, 'ee_cpt_archive_pages'),
377
-            'nav-menus',
378
-            'side',
379
-            'core'
380
-        );
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * Use this to edit the post link for our cpts so that the edit link points to the correct page.
387
-     *
388
-     * @since   4.3.0
389
-     * @param string $link the original link generated by wp
390
-     * @param int    $id   post id
391
-     * @return string  the (maybe) modified link
392
-     */
393
-    public function modify_edit_post_link($link, $id)
394
-    {
395
-        if (! $post = get_post($id)) {
396
-            return $link;
397
-        }
398
-        if ($post->post_type === 'espresso_attendees') {
399
-            $query_args = array(
400
-                'action' => 'edit_attendee',
401
-                'post'   => $id,
402
-            );
403
-            return EEH_URL::add_query_args_and_nonce(
404
-                $query_args,
405
-                admin_url('admin.php?page=espresso_registrations')
406
-            );
407
-        }
408
-        return $link;
409
-    }
410
-
411
-
412
-
413
-    public function ee_cpt_archive_pages()
414
-    {
415
-        global $nav_menu_selected_id;
416
-        $db_fields   = false;
417
-        $walker      = new Walker_Nav_Menu_Checklist($db_fields);
418
-        $current_tab = 'event-archives';
419
-        $removed_args = array(
420
-            'action',
421
-            'customlink-tab',
422
-            'edit-menu-item',
423
-            'menu-item',
424
-            'page-tab',
425
-            '_wpnonce',
426
-        );
427
-        ?>
25
+	/**
26
+	 * @var EE_Admin $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
32
+	 */
33
+	private $persistent_admin_notice_manager;
34
+
35
+	/**
36
+	 * @singleton method used to instantiate class object
37
+	 * @return EE_Admin
38
+	 * @throws EE_Error
39
+	 */
40
+	public static function instance()
41
+	{
42
+		// check if class object is instantiated
43
+		if (! self::$_instance instanceof EE_Admin) {
44
+			self::$_instance = new self();
45
+		}
46
+		return self::$_instance;
47
+	}
48
+
49
+
50
+	/**
51
+	 * @return EE_Admin
52
+	 * @throws EE_Error
53
+	 */
54
+	public static function reset()
55
+	{
56
+		self::$_instance = null;
57
+		return self::instance();
58
+	}
59
+
60
+
61
+	/**
62
+	 * class constructor
63
+	 *
64
+	 * @throws EE_Error
65
+	 * @throws InvalidDataTypeException
66
+	 * @throws InvalidInterfaceException
67
+	 * @throws InvalidArgumentException
68
+	 */
69
+	protected function __construct()
70
+	{
71
+		// define global EE_Admin constants
72
+		$this->_define_all_constants();
73
+		// set autoloaders for our admin page classes based on included path information
74
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
75
+		// admin hooks
76
+		add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
77
+		// load EE_Request_Handler early
78
+		add_action('AHEE__EE_System__core_loaded_and_ready', array($this, 'get_request'));
79
+		add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
80
+		add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
81
+		add_action('wp_loaded', array($this, 'wp_loaded'), 100);
82
+		add_action('admin_init', array($this, 'admin_init'), 100);
83
+		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
84
+		add_action('admin_notices', array($this, 'display_admin_notices'), 10);
85
+		add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
86
+		add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
87
+		add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
88
+		//reset Environment config (we only do this on admin page loads);
89
+		EE_Registry::instance()->CFG->environment->recheck_values();
90
+		do_action('AHEE__EE_Admin__loaded');
91
+	}
92
+
93
+
94
+
95
+	/**
96
+	 * _define_all_constants
97
+	 * define constants that are set globally for all admin pages
98
+	 *
99
+	 * @return void
100
+	 */
101
+	private function _define_all_constants()
102
+	{
103
+		if (! defined('EE_ADMIN_URL')) {
104
+			define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
105
+			define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
106
+			define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates' . DS);
107
+			define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
108
+			define('WP_AJAX_URL', admin_url('admin-ajax.php'));
109
+		}
110
+	}
111
+
112
+
113
+	/**
114
+	 * filter_plugin_actions - adds links to the Plugins page listing
115
+	 *
116
+	 * @param    array  $links
117
+	 * @param    string $plugin
118
+	 * @return    array
119
+	 */
120
+	public function filter_plugin_actions($links, $plugin)
121
+	{
122
+		// set $main_file in stone
123
+		static $main_file;
124
+		// if $main_file is not set yet
125
+		if (! $main_file) {
126
+			$main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
127
+		}
128
+		if ($plugin === $main_file) {
129
+			// compare current plugin to this one
130
+			if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
131
+				$maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
132
+									. ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
133
+									. esc_html__('Maintenance Mode Active', 'event_espresso')
134
+									. '</a>';
135
+				array_unshift($links, $maintenance_link);
136
+			} else {
137
+				$org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
138
+									 . esc_html__('Settings', 'event_espresso')
139
+									 . '</a>';
140
+				$events_link       = '<a href="admin.php?page=espresso_events">'
141
+									 . esc_html__('Events', 'event_espresso')
142
+									 . '</a>';
143
+				// add before other links
144
+				array_unshift($links, $org_settings_link, $events_link);
145
+			}
146
+		}
147
+		return $links;
148
+	}
149
+
150
+
151
+	/**
152
+	 * _get_request
153
+	 *
154
+	 * @return void
155
+	 * @throws EE_Error
156
+	 * @throws InvalidArgumentException
157
+	 * @throws InvalidDataTypeException
158
+	 * @throws InvalidInterfaceException
159
+	 * @throws ReflectionException
160
+	 */
161
+	public function get_request()
162
+	{
163
+		EE_Registry::instance()->load_core('Request_Handler');
164
+		EE_Registry::instance()->load_core('CPT_Strategy');
165
+	}
166
+
167
+
168
+
169
+	/**
170
+	 * hide_admin_pages_except_maintenance_mode
171
+	 *
172
+	 * @param array $admin_page_folder_names
173
+	 * @return array
174
+	 */
175
+	public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
176
+	{
177
+		return array(
178
+			'maintenance' => EE_ADMIN_PAGES . 'maintenance' . DS,
179
+			'about'       => EE_ADMIN_PAGES . 'about' . DS,
180
+			'support'     => EE_ADMIN_PAGES . 'support' . DS,
181
+		);
182
+	}
183
+
184
+
185
+
186
+	/**
187
+	 * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
188
+	 * EE_Front_Controller's init phases have run
189
+	 *
190
+	 * @return void
191
+	 * @throws EE_Error
192
+	 * @throws InvalidArgumentException
193
+	 * @throws InvalidDataTypeException
194
+	 * @throws InvalidInterfaceException
195
+	 * @throws ReflectionException
196
+	 * @throws ServiceNotFoundException
197
+	 */
198
+	public function init()
199
+	{
200
+		//only enable most of the EE_Admin IF we're not in full maintenance mode
201
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
202
+			//ok so we want to enable the entire admin
203
+			$this->persistent_admin_notice_manager = LoaderFactory::getLoader()->getShared(
204
+				'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
205
+			);
206
+			$this->persistent_admin_notice_manager->setReturnUrl(
207
+				EE_Admin_Page::add_query_args_and_nonce(
208
+					array(
209
+						'page'   => EE_Registry::instance()->REQ->get('page', ''),
210
+						'action' => EE_Registry::instance()->REQ->get('action', ''),
211
+					),
212
+					EE_ADMIN_URL
213
+				)
214
+			);
215
+			$this->maybeSetDatetimeWarningNotice();
216
+			//at a glance dashboard widget
217
+			add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
218
+			//filter for get_edit_post_link used on comments for custom post types
219
+			add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
220
+		}
221
+		// run the admin page factory but ONLY if we are doing an ee admin ajax request
222
+		if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
223
+			try {
224
+				//this loads the controller for the admin pages which will setup routing etc
225
+				EE_Registry::instance()->load_core('Admin_Page_Loader');
226
+			} catch (EE_Error $e) {
227
+				$e->get_error();
228
+			}
229
+		}
230
+		add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
231
+		//make sure our CPTs and custom taxonomy metaboxes get shown for first time users
232
+		add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
233
+		add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
234
+		//exclude EE critical pages from all nav menus and wp_list_pages
235
+		add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
236
+	}
237
+
238
+
239
+	/**
240
+	 *    get_persistent_admin_notices
241
+	 *
242
+	 * @access    public
243
+	 * @return void
244
+	 * @throws EE_Error
245
+	 * @throws InvalidArgumentException
246
+	 * @throws InvalidDataTypeException
247
+	 * @throws InvalidInterfaceException
248
+	 */
249
+	public function maybeSetDatetimeWarningNotice()
250
+	{
251
+		//add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
252
+		//@todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
253
+		//with this.  But after enough time (indeterminate at this point) we can just remove this notice.
254
+		//this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
255
+		if (apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
256
+			&& ! get_option('timezone_string')
257
+			&& EEM_Event::instance()->count() > 0
258
+		) {
259
+			new PersistentAdminNotice(
260
+				'datetime_fix_notice',
261
+				sprintf(
262
+					esc_html__(
263
+						'%1$sImportant announcement related to your install of Event Espresso%2$s: There are some changes made to your site that could affect how dates display for your events and other related items with dates and times.  Read more about it %3$shere%4$s. If your dates and times are displaying incorrectly (incorrect offset), you can fix it using the tool on %5$sthis page%4$s.',
264
+						'event_espresso'
265
+					),
266
+					'<strong>',
267
+					'</strong>',
268
+					'<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
269
+					'</a>',
270
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
271
+						array(
272
+							'page' => 'espresso_maintenance_settings',
273
+							'action' => 'datetime_tools'
274
+						),
275
+						admin_url('admin.php')
276
+					) . '">'
277
+				),
278
+				false,
279
+				'manage_options',
280
+				'datetime_fix_persistent_notice'
281
+			);
282
+		}
283
+	}
284
+
285
+
286
+
287
+	/**
288
+	 * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
289
+	 * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
290
+	 * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
291
+	 * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
292
+	 * normal property on the post_type object.  It's found ONLY in this particular context.
293
+	 *
294
+	 * @param WP_Post $post_type WP post type object
295
+	 * @return WP_Post
296
+	 * @throws InvalidArgumentException
297
+	 * @throws InvalidDataTypeException
298
+	 * @throws InvalidInterfaceException
299
+	 */
300
+	public function remove_pages_from_nav_menu($post_type)
301
+	{
302
+		//if this isn't the "pages" post type let's get out
303
+		if ($post_type->name !== 'page') {
304
+			return $post_type;
305
+		}
306
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
307
+		$post_type->_default_query = array(
308
+			'post__not_in' => $critical_pages,
309
+		);
310
+		return $post_type;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
317
+	 * metaboxes get shown as well
318
+	 *
319
+	 * @return void
320
+	 */
321
+	public function enable_hidden_ee_nav_menu_metaboxes()
322
+	{
323
+		global $wp_meta_boxes, $pagenow;
324
+		if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
325
+			return;
326
+		}
327
+		$user = wp_get_current_user();
328
+		//has this been done yet?
329
+		if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
330
+			return;
331
+		}
332
+
333
+		$hidden_meta_boxes  = get_user_option('metaboxhidden_nav-menus', $user->ID);
334
+		$initial_meta_boxes = apply_filters(
335
+			'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
336
+			array(
337
+				'nav-menu-theme-locations',
338
+				'add-page',
339
+				'add-custom-links',
340
+				'add-category',
341
+				'add-espresso_events',
342
+				'add-espresso_venues',
343
+				'add-espresso_event_categories',
344
+				'add-espresso_venue_categories',
345
+				'add-post-type-post',
346
+				'add-post-type-page',
347
+			)
348
+		);
349
+
350
+		if (is_array($hidden_meta_boxes)) {
351
+			foreach ($hidden_meta_boxes as $key => $meta_box_id) {
352
+				if (in_array($meta_box_id, $initial_meta_boxes, true)) {
353
+					unset($hidden_meta_boxes[$key]);
354
+				}
355
+			}
356
+		}
357
+		update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
358
+		update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
359
+	}
360
+
361
+
362
+
363
+	/**
364
+	 * This method simply registers custom nav menu boxes for "nav_menus.php route"
365
+	 * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
366
+	 *
367
+	 * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
368
+	 *         addons etc.
369
+	 * @return void
370
+	 */
371
+	public function register_custom_nav_menu_boxes()
372
+	{
373
+		add_meta_box(
374
+			'add-extra-nav-menu-pages',
375
+			esc_html__('Event Espresso Pages', 'event_espresso'),
376
+			array($this, 'ee_cpt_archive_pages'),
377
+			'nav-menus',
378
+			'side',
379
+			'core'
380
+		);
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * Use this to edit the post link for our cpts so that the edit link points to the correct page.
387
+	 *
388
+	 * @since   4.3.0
389
+	 * @param string $link the original link generated by wp
390
+	 * @param int    $id   post id
391
+	 * @return string  the (maybe) modified link
392
+	 */
393
+	public function modify_edit_post_link($link, $id)
394
+	{
395
+		if (! $post = get_post($id)) {
396
+			return $link;
397
+		}
398
+		if ($post->post_type === 'espresso_attendees') {
399
+			$query_args = array(
400
+				'action' => 'edit_attendee',
401
+				'post'   => $id,
402
+			);
403
+			return EEH_URL::add_query_args_and_nonce(
404
+				$query_args,
405
+				admin_url('admin.php?page=espresso_registrations')
406
+			);
407
+		}
408
+		return $link;
409
+	}
410
+
411
+
412
+
413
+	public function ee_cpt_archive_pages()
414
+	{
415
+		global $nav_menu_selected_id;
416
+		$db_fields   = false;
417
+		$walker      = new Walker_Nav_Menu_Checklist($db_fields);
418
+		$current_tab = 'event-archives';
419
+		$removed_args = array(
420
+			'action',
421
+			'customlink-tab',
422
+			'edit-menu-item',
423
+			'menu-item',
424
+			'page-tab',
425
+			'_wpnonce',
426
+		);
427
+		?>
428 428
         <div id="posttype-extra-nav-menu-pages" class="posttypediv">
429 429
             <ul id="posttype-extra-nav-menu-pages-tabs" class="posttype-tabs add-menu-item-tabs">
430 430
                 <li <?php echo('event-archives' === $current_tab ? ' class="tabs"' : ''); ?>>
431 431
                     <a class="nav-tab-link" data-type="tabs-panel-posttype-extra-nav-menu-pages-event-archives"
432 432
                        href="<?php if ($nav_menu_selected_id) {
433
-                            echo esc_url(
434
-                                add_query_arg(
435
-                                    'extra-nav-menu-pages-tab',
436
-                                    'event-archives',
437
-                                    remove_query_arg($removed_args)
438
-                                )
439
-                            );
440
-                       } ?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
433
+							echo esc_url(
434
+								add_query_arg(
435
+									'extra-nav-menu-pages-tab',
436
+									'event-archives',
437
+									remove_query_arg($removed_args)
438
+								)
439
+							);
440
+					   } ?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
441 441
                         <?php _e('Event Archive Pages', 'event_espresso'); ?>
442 442
                     </a>
443 443
                 </li>
444 444
             </ul><!-- .posttype-tabs -->
445 445
 
446 446
             <div id="tabs-panel-posttype-extra-nav-menu-pages-event-archives" class="tabs-panel <?php
447
-                echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
448
-                ?>">
447
+				echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
448
+				?>">
449 449
                     <ul id="extra-nav-menu-pageschecklist-event-archives" class="categorychecklist form-no-clear">
450 450
                         <?php
451
-                        $pages          = $this->_get_extra_nav_menu_pages_items();
452
-                        $args['walker'] = $walker;
453
-                        echo walk_nav_menu_tree(
454
-                            array_map(
455
-                                array($this, '_setup_extra_nav_menu_pages_items'),
456
-                                $pages
457
-                            ),
458
-                            0,
459
-                            (object) $args
460
-                        );
461
-                        ?>
451
+						$pages          = $this->_get_extra_nav_menu_pages_items();
452
+						$args['walker'] = $walker;
453
+						echo walk_nav_menu_tree(
454
+							array_map(
455
+								array($this, '_setup_extra_nav_menu_pages_items'),
456
+								$pages
457
+							),
458
+							0,
459
+							(object) $args
460
+						);
461
+						?>
462 462
                     </ul>
463 463
                 </div><!-- /.tabs-panel -->
464 464
 
465 465
                 <p class="button-controls">
466 466
                 <span class="list-controls">
467 467
                     <a href="<?php
468
-                    echo esc_url(add_query_arg(
469
-                        array(
470
-                            'extra-nav-menu-pages-tab' => 'event-archives',
471
-                            'selectall'                => 1,
472
-                        ),
473
-                        remove_query_arg($removed_args)
474
-                    ));
475
-                    ?>#posttype-extra-nav-menu-pages>" class="select-all"><?php _e('Select All'); ?></a>
468
+					echo esc_url(add_query_arg(
469
+						array(
470
+							'extra-nav-menu-pages-tab' => 'event-archives',
471
+							'selectall'                => 1,
472
+						),
473
+						remove_query_arg($removed_args)
474
+					));
475
+					?>#posttype-extra-nav-menu-pages>" class="select-all"><?php _e('Select All'); ?></a>
476 476
                 </span>
477 477
                 <span class="add-to-menu">
478 478
                     <input type="submit"<?php wp_nav_menu_disabled_check($nav_menu_selected_id); ?>
@@ -485,471 +485,471 @@  discard block
 block discarded – undo
485 485
 
486 486
         </div><!-- /.posttypediv -->
487 487
         <?php
488
-    }
489
-
490
-
491
-    /**
492
-     * Returns an array of event archive nav items.
493
-     *
494
-     * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
495
-     *        method we use for getting the extra nav menu items
496
-     * @return array
497
-     */
498
-    private function _get_extra_nav_menu_pages_items()
499
-    {
500
-        $menuitems[] = array(
501
-            'title'       => esc_html__('Event List', 'event_espresso'),
502
-            'url'         => get_post_type_archive_link('espresso_events'),
503
-            'description' => esc_html__('Archive page for all events.', 'event_espresso'),
504
-        );
505
-        return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
506
-    }
507
-
508
-
509
-    /**
510
-     * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
511
-     * the properties and converts it to the menu item object.
512
-     *
513
-     * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
514
-     * @param $menu_item_values
515
-     * @return stdClass
516
-     */
517
-    private function _setup_extra_nav_menu_pages_items($menu_item_values)
518
-    {
519
-        $menu_item = new stdClass();
520
-        $keys      = array(
521
-            'ID'               => 0,
522
-            'db_id'            => 0,
523
-            'menu_item_parent' => 0,
524
-            'object_id'        => -1,
525
-            'post_parent'      => 0,
526
-            'type'             => 'custom',
527
-            'object'           => '',
528
-            'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
529
-            'title'            => '',
530
-            'url'              => '',
531
-            'target'           => '',
532
-            'attr_title'       => '',
533
-            'description'      => '',
534
-            'classes'          => array(),
535
-            'xfn'              => '',
536
-        );
537
-
538
-        foreach ($keys as $key => $value) {
539
-            $menu_item->{$key} = isset($menu_item_values[$key]) ? $menu_item_values[$key] : $value;
540
-        }
541
-        return $menu_item;
542
-    }
543
-
544
-
545
-    /**
546
-     * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
547
-     * EE_Admin_Page route is called.
548
-     *
549
-     * @return void
550
-     */
551
-    public function route_admin_request()
552
-    {
553
-    }
554
-
555
-
556
-    /**
557
-     * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
558
-     *
559
-     * @return void
560
-     */
561
-    public function wp_loaded()
562
-    {
563
-    }
564
-
565
-
566
-    /**
567
-     * admin_init
568
-     *
569
-     * @return void
570
-     * @throws EE_Error
571
-     * @throws InvalidArgumentException
572
-     * @throws InvalidDataTypeException
573
-     * @throws InvalidInterfaceException
574
-     * @throws ReflectionException
575
-     */
576
-    public function admin_init()
577
-    {
578
-
579
-        /**
580
-         * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
581
-         * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
582
-         * - check if doing post processing.
583
-         * - check if doing post processing of one of EE CPTs
584
-         * - instantiate the corresponding EE CPT model for the post_type being processed.
585
-         */
586
-        if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
587
-            EE_Registry::instance()->load_core('Register_CPTs');
588
-            EE_Register_CPTs::instantiate_cpt_models($_POST['post_type']);
589
-        }
590
-
591
-
592
-        /**
593
-         * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
594
-         * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
595
-         * Pages" tab in the EE General Settings Admin page.
596
-         * This is for user-proofing.
597
-         */
598
-        add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
599
-    }
600
-
601
-
602
-    /**
603
-     * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
604
-     *
605
-     * @param string $output Current output.
606
-     * @return string
607
-     * @throws InvalidArgumentException
608
-     * @throws InvalidDataTypeException
609
-     * @throws InvalidInterfaceException
610
-     */
611
-    public function modify_dropdown_pages($output)
612
-    {
613
-        //get critical pages
614
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
615
-
616
-        //split current output by line break for easier parsing.
617
-        $split_output = explode("\n", $output);
618
-
619
-        //loop through to remove any critical pages from the array.
620
-        foreach ($critical_pages as $page_id) {
621
-            $needle = 'value="' . $page_id . '"';
622
-            foreach ($split_output as $key => $haystack) {
623
-                if (strpos($haystack, $needle) !== false) {
624
-                    unset($split_output[$key]);
625
-                }
626
-            }
627
-        }
628
-        //replace output with the new contents
629
-        return implode("\n", $split_output);
630
-    }
631
-
632
-
633
-    /**
634
-     * enqueue all admin scripts that need loaded for admin pages
635
-     *
636
-     * @return void
637
-     */
638
-    public function enqueue_admin_scripts()
639
-    {
640
-        // this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
641
-        // Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
642
-        // calls.
643
-        wp_enqueue_script(
644
-            'ee-inject-wp',
645
-            EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
646
-            array('jquery'),
647
-            EVENT_ESPRESSO_VERSION,
648
-            true
649
-        );
650
-        // register cookie script for future dependencies
651
-        wp_register_script(
652
-            'jquery-cookie',
653
-            EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
654
-            array('jquery'),
655
-            '2.1',
656
-            true
657
-        );
658
-        //joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
659
-        // via: add_filter('FHEE_load_joyride', '__return_true' );
660
-        if (apply_filters('FHEE_load_joyride', false)) {
661
-            //joyride style
662
-            wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
663
-            wp_register_style(
664
-                'ee-joyride-css',
665
-                EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
666
-                array('joyride-css'),
667
-                EVENT_ESPRESSO_VERSION
668
-            );
669
-            wp_register_script(
670
-                'joyride-modernizr',
671
-                EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
672
-                array(),
673
-                '2.1',
674
-                true
675
-            );
676
-            //joyride JS
677
-            wp_register_script(
678
-                'jquery-joyride',
679
-                EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
680
-                array('jquery-cookie', 'joyride-modernizr'),
681
-                '2.1',
682
-                true
683
-            );
684
-            // wanna go for a joyride?
685
-            wp_enqueue_style('ee-joyride-css');
686
-            wp_enqueue_script('jquery-joyride');
687
-        }
688
-    }
689
-
690
-
691
-    /**
692
-     * display_admin_notices
693
-     *
694
-     * @return void
695
-     */
696
-    public function display_admin_notices()
697
-    {
698
-        echo EE_Error::get_notices();
699
-    }
700
-
701
-
702
-
703
-    /**
704
-     * @param array $elements
705
-     * @return array
706
-     * @throws EE_Error
707
-     * @throws InvalidArgumentException
708
-     * @throws InvalidDataTypeException
709
-     * @throws InvalidInterfaceException
710
-     */
711
-    public function dashboard_glance_items($elements)
712
-    {
713
-        $elements                        = is_array($elements) ? $elements : array($elements);
714
-        $events                          = EEM_Event::instance()->count();
715
-        $items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
716
-            array('page' => 'espresso_events'),
717
-            admin_url('admin.php')
718
-        );
719
-        $items['events']['text']         = sprintf(_n('%s Event', '%s Events', $events), number_format_i18n($events));
720
-        $items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
721
-        $registrations                   = EEM_Registration::instance()->count(
722
-            array(
723
-                array(
724
-                    'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
725
-                ),
726
-            )
727
-        );
728
-        $items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
729
-            array('page' => 'espresso_registrations'),
730
-            admin_url('admin.php')
731
-        );
732
-        $items['registrations']['text']  = sprintf(
733
-            _n('%s Registration', '%s Registrations', $registrations),
734
-            number_format_i18n($registrations)
735
-        );
736
-        $items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
737
-
738
-        $items = (array)apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
739
-
740
-        foreach ($items as $type => $item_properties) {
741
-            $elements[] = sprintf(
742
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
743
-                $item_properties['url'],
744
-                $item_properties['title'],
745
-                $item_properties['text']
746
-            );
747
-        }
748
-        return $elements;
749
-    }
750
-
751
-
752
-    /**
753
-     * check_for_invalid_datetime_formats
754
-     * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
755
-     * their selected format can be parsed by PHP
756
-     *
757
-     * @param    $value
758
-     * @param    $option
759
-     * @throws EE_Error
760
-     * @return    string
761
-     */
762
-    public function check_for_invalid_datetime_formats($value, $option)
763
-    {
764
-        // check for date_format or time_format
765
-        switch ($option) {
766
-            case 'date_format':
767
-                $date_time_format = $value . ' ' . get_option('time_format');
768
-                break;
769
-            case 'time_format':
770
-                $date_time_format = get_option('date_format') . ' ' . $value;
771
-                break;
772
-            default:
773
-                $date_time_format = false;
774
-        }
775
-        // do we have a date_time format to check ?
776
-        if ($date_time_format) {
777
-            $error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
778
-
779
-            if (is_array($error_msg)) {
780
-                $msg = '<p>'
781
-                       . sprintf(
782
-                           esc_html__(
783
-                               'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
784
-                               'event_espresso'
785
-                           ),
786
-                           date($date_time_format),
787
-                           $date_time_format
788
-                       )
789
-                       . '</p><p><ul>';
790
-
791
-
792
-                foreach ($error_msg as $error) {
793
-                    $msg .= '<li>' . $error . '</li>';
794
-                }
795
-
796
-                $msg .= '</ul></p><p>'
797
-                        . sprintf(
798
-                            esc_html__(
799
-                                '%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
800
-                                'event_espresso'
801
-                            ),
802
-                            '<span style="color:#D54E21;">',
803
-                            '</span>'
804
-                        )
805
-                        . '</p>';
806
-
807
-                // trigger WP settings error
808
-                add_settings_error(
809
-                    'date_format',
810
-                    'date_format',
811
-                    $msg
812
-                );
813
-
814
-                // set format to something valid
815
-                switch ($option) {
816
-                    case 'date_format':
817
-                        $value = 'F j, Y';
818
-                        break;
819
-                    case 'time_format':
820
-                        $value = 'g:i a';
821
-                        break;
822
-                }
823
-            }
824
-        }
825
-        return $value;
826
-    }
827
-
828
-
829
-    /**
830
-     * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
831
-     *
832
-     * @param $content
833
-     * @return    string
834
-     */
835
-    public function its_eSpresso($content)
836
-    {
837
-        return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
838
-    }
839
-
840
-
841
-    /**
842
-     * espresso_admin_footer
843
-     *
844
-     * @return    string
845
-     */
846
-    public function espresso_admin_footer()
847
-    {
848
-        return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
849
-    }
850
-
851
-
852
-    /**
853
-     * static method for registering ee admin page.
854
-     * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
855
-     *
856
-     * @since      4.3.0
857
-     * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
858
-     * @see        EE_Register_Admin_Page::register()
859
-     * @param       $page_basename
860
-     * @param       $page_path
861
-     * @param array $config
862
-     * @return void
863
-     * @throws EE_Error
864
-     */
865
-    public static function register_ee_admin_page($page_basename, $page_path, $config = array())
866
-    {
867
-        EE_Error::doing_it_wrong(
868
-            __METHOD__,
869
-            sprintf(
870
-                esc_html__(
871
-                    'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
872
-                    'event_espresso'
873
-                ),
874
-                $page_basename
875
-            ),
876
-            '4.3'
877
-        );
878
-        if (class_exists('EE_Register_Admin_Page')) {
879
-            $config['page_path'] = $page_path;
880
-        }
881
-        EE_Register_Admin_Page::register($page_basename, $config);
882
-    }
883
-
884
-
885
-    /**
886
-     * @deprecated 4.8.41
887
-     * @param  int      $post_ID
888
-     * @param  \WP_Post $post
889
-     * @return void
890
-     */
891
-    public static function parse_post_content_on_save($post_ID, $post)
892
-    {
893
-        EE_Error::doing_it_wrong(
894
-            __METHOD__,
895
-            esc_html__('Usage is deprecated', 'event_espresso'),
896
-            '4.8.41'
897
-        );
898
-    }
899
-
900
-
901
-    /**
902
-     * @deprecated 4.8.41
903
-     * @param  $option
904
-     * @param  $old_value
905
-     * @param  $value
906
-     * @return void
907
-     */
908
-    public function reset_page_for_posts_on_change($option, $old_value, $value)
909
-    {
910
-        EE_Error::doing_it_wrong(
911
-            __METHOD__,
912
-            esc_html__('Usage is deprecated', 'event_espresso'),
913
-            '4.8.41'
914
-        );
915
-    }
916
-
917
-
918
-
919
-    /**
920
-     * @deprecated 4.9.27
921
-     * @return void
922
-     */
923
-    public function get_persistent_admin_notices()
924
-    {
925
-        EE_Error::doing_it_wrong(
926
-            __METHOD__,
927
-            sprintf(
928
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
929
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
930
-            ),
931
-            '4.9.27'
932
-        );
933
-    }
934
-
935
-
936
-
937
-    /**
938
-     * @deprecated 4.9.27
939
-     * @throws InvalidInterfaceException
940
-     * @throws InvalidDataTypeException
941
-     * @throws DomainException
942
-     */
943
-    public function dismiss_ee_nag_notice_callback()
944
-    {
945
-        EE_Error::doing_it_wrong(
946
-            __METHOD__,
947
-            sprintf(
948
-                __('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
949
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
950
-            ),
951
-            '4.9.27'
952
-        );
953
-        $this->persistent_admin_notice_manager->dismissNotice();
954
-    }
488
+	}
489
+
490
+
491
+	/**
492
+	 * Returns an array of event archive nav items.
493
+	 *
494
+	 * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
495
+	 *        method we use for getting the extra nav menu items
496
+	 * @return array
497
+	 */
498
+	private function _get_extra_nav_menu_pages_items()
499
+	{
500
+		$menuitems[] = array(
501
+			'title'       => esc_html__('Event List', 'event_espresso'),
502
+			'url'         => get_post_type_archive_link('espresso_events'),
503
+			'description' => esc_html__('Archive page for all events.', 'event_espresso'),
504
+		);
505
+		return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
506
+	}
507
+
508
+
509
+	/**
510
+	 * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
511
+	 * the properties and converts it to the menu item object.
512
+	 *
513
+	 * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
514
+	 * @param $menu_item_values
515
+	 * @return stdClass
516
+	 */
517
+	private function _setup_extra_nav_menu_pages_items($menu_item_values)
518
+	{
519
+		$menu_item = new stdClass();
520
+		$keys      = array(
521
+			'ID'               => 0,
522
+			'db_id'            => 0,
523
+			'menu_item_parent' => 0,
524
+			'object_id'        => -1,
525
+			'post_parent'      => 0,
526
+			'type'             => 'custom',
527
+			'object'           => '',
528
+			'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
529
+			'title'            => '',
530
+			'url'              => '',
531
+			'target'           => '',
532
+			'attr_title'       => '',
533
+			'description'      => '',
534
+			'classes'          => array(),
535
+			'xfn'              => '',
536
+		);
537
+
538
+		foreach ($keys as $key => $value) {
539
+			$menu_item->{$key} = isset($menu_item_values[$key]) ? $menu_item_values[$key] : $value;
540
+		}
541
+		return $menu_item;
542
+	}
543
+
544
+
545
+	/**
546
+	 * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
547
+	 * EE_Admin_Page route is called.
548
+	 *
549
+	 * @return void
550
+	 */
551
+	public function route_admin_request()
552
+	{
553
+	}
554
+
555
+
556
+	/**
557
+	 * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
558
+	 *
559
+	 * @return void
560
+	 */
561
+	public function wp_loaded()
562
+	{
563
+	}
564
+
565
+
566
+	/**
567
+	 * admin_init
568
+	 *
569
+	 * @return void
570
+	 * @throws EE_Error
571
+	 * @throws InvalidArgumentException
572
+	 * @throws InvalidDataTypeException
573
+	 * @throws InvalidInterfaceException
574
+	 * @throws ReflectionException
575
+	 */
576
+	public function admin_init()
577
+	{
578
+
579
+		/**
580
+		 * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
581
+		 * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
582
+		 * - check if doing post processing.
583
+		 * - check if doing post processing of one of EE CPTs
584
+		 * - instantiate the corresponding EE CPT model for the post_type being processed.
585
+		 */
586
+		if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
587
+			EE_Registry::instance()->load_core('Register_CPTs');
588
+			EE_Register_CPTs::instantiate_cpt_models($_POST['post_type']);
589
+		}
590
+
591
+
592
+		/**
593
+		 * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
594
+		 * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
595
+		 * Pages" tab in the EE General Settings Admin page.
596
+		 * This is for user-proofing.
597
+		 */
598
+		add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
599
+	}
600
+
601
+
602
+	/**
603
+	 * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
604
+	 *
605
+	 * @param string $output Current output.
606
+	 * @return string
607
+	 * @throws InvalidArgumentException
608
+	 * @throws InvalidDataTypeException
609
+	 * @throws InvalidInterfaceException
610
+	 */
611
+	public function modify_dropdown_pages($output)
612
+	{
613
+		//get critical pages
614
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
615
+
616
+		//split current output by line break for easier parsing.
617
+		$split_output = explode("\n", $output);
618
+
619
+		//loop through to remove any critical pages from the array.
620
+		foreach ($critical_pages as $page_id) {
621
+			$needle = 'value="' . $page_id . '"';
622
+			foreach ($split_output as $key => $haystack) {
623
+				if (strpos($haystack, $needle) !== false) {
624
+					unset($split_output[$key]);
625
+				}
626
+			}
627
+		}
628
+		//replace output with the new contents
629
+		return implode("\n", $split_output);
630
+	}
631
+
632
+
633
+	/**
634
+	 * enqueue all admin scripts that need loaded for admin pages
635
+	 *
636
+	 * @return void
637
+	 */
638
+	public function enqueue_admin_scripts()
639
+	{
640
+		// this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
641
+		// Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
642
+		// calls.
643
+		wp_enqueue_script(
644
+			'ee-inject-wp',
645
+			EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
646
+			array('jquery'),
647
+			EVENT_ESPRESSO_VERSION,
648
+			true
649
+		);
650
+		// register cookie script for future dependencies
651
+		wp_register_script(
652
+			'jquery-cookie',
653
+			EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
654
+			array('jquery'),
655
+			'2.1',
656
+			true
657
+		);
658
+		//joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
659
+		// via: add_filter('FHEE_load_joyride', '__return_true' );
660
+		if (apply_filters('FHEE_load_joyride', false)) {
661
+			//joyride style
662
+			wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
663
+			wp_register_style(
664
+				'ee-joyride-css',
665
+				EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
666
+				array('joyride-css'),
667
+				EVENT_ESPRESSO_VERSION
668
+			);
669
+			wp_register_script(
670
+				'joyride-modernizr',
671
+				EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
672
+				array(),
673
+				'2.1',
674
+				true
675
+			);
676
+			//joyride JS
677
+			wp_register_script(
678
+				'jquery-joyride',
679
+				EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
680
+				array('jquery-cookie', 'joyride-modernizr'),
681
+				'2.1',
682
+				true
683
+			);
684
+			// wanna go for a joyride?
685
+			wp_enqueue_style('ee-joyride-css');
686
+			wp_enqueue_script('jquery-joyride');
687
+		}
688
+	}
689
+
690
+
691
+	/**
692
+	 * display_admin_notices
693
+	 *
694
+	 * @return void
695
+	 */
696
+	public function display_admin_notices()
697
+	{
698
+		echo EE_Error::get_notices();
699
+	}
700
+
701
+
702
+
703
+	/**
704
+	 * @param array $elements
705
+	 * @return array
706
+	 * @throws EE_Error
707
+	 * @throws InvalidArgumentException
708
+	 * @throws InvalidDataTypeException
709
+	 * @throws InvalidInterfaceException
710
+	 */
711
+	public function dashboard_glance_items($elements)
712
+	{
713
+		$elements                        = is_array($elements) ? $elements : array($elements);
714
+		$events                          = EEM_Event::instance()->count();
715
+		$items['events']['url']          = EE_Admin_Page::add_query_args_and_nonce(
716
+			array('page' => 'espresso_events'),
717
+			admin_url('admin.php')
718
+		);
719
+		$items['events']['text']         = sprintf(_n('%s Event', '%s Events', $events), number_format_i18n($events));
720
+		$items['events']['title']        = esc_html__('Click to view all Events', 'event_espresso');
721
+		$registrations                   = EEM_Registration::instance()->count(
722
+			array(
723
+				array(
724
+					'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
725
+				),
726
+			)
727
+		);
728
+		$items['registrations']['url']   = EE_Admin_Page::add_query_args_and_nonce(
729
+			array('page' => 'espresso_registrations'),
730
+			admin_url('admin.php')
731
+		);
732
+		$items['registrations']['text']  = sprintf(
733
+			_n('%s Registration', '%s Registrations', $registrations),
734
+			number_format_i18n($registrations)
735
+		);
736
+		$items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
737
+
738
+		$items = (array)apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
739
+
740
+		foreach ($items as $type => $item_properties) {
741
+			$elements[] = sprintf(
742
+				'<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
743
+				$item_properties['url'],
744
+				$item_properties['title'],
745
+				$item_properties['text']
746
+			);
747
+		}
748
+		return $elements;
749
+	}
750
+
751
+
752
+	/**
753
+	 * check_for_invalid_datetime_formats
754
+	 * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
755
+	 * their selected format can be parsed by PHP
756
+	 *
757
+	 * @param    $value
758
+	 * @param    $option
759
+	 * @throws EE_Error
760
+	 * @return    string
761
+	 */
762
+	public function check_for_invalid_datetime_formats($value, $option)
763
+	{
764
+		// check for date_format or time_format
765
+		switch ($option) {
766
+			case 'date_format':
767
+				$date_time_format = $value . ' ' . get_option('time_format');
768
+				break;
769
+			case 'time_format':
770
+				$date_time_format = get_option('date_format') . ' ' . $value;
771
+				break;
772
+			default:
773
+				$date_time_format = false;
774
+		}
775
+		// do we have a date_time format to check ?
776
+		if ($date_time_format) {
777
+			$error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
778
+
779
+			if (is_array($error_msg)) {
780
+				$msg = '<p>'
781
+					   . sprintf(
782
+						   esc_html__(
783
+							   'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
784
+							   'event_espresso'
785
+						   ),
786
+						   date($date_time_format),
787
+						   $date_time_format
788
+					   )
789
+					   . '</p><p><ul>';
790
+
791
+
792
+				foreach ($error_msg as $error) {
793
+					$msg .= '<li>' . $error . '</li>';
794
+				}
795
+
796
+				$msg .= '</ul></p><p>'
797
+						. sprintf(
798
+							esc_html__(
799
+								'%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
800
+								'event_espresso'
801
+							),
802
+							'<span style="color:#D54E21;">',
803
+							'</span>'
804
+						)
805
+						. '</p>';
806
+
807
+				// trigger WP settings error
808
+				add_settings_error(
809
+					'date_format',
810
+					'date_format',
811
+					$msg
812
+				);
813
+
814
+				// set format to something valid
815
+				switch ($option) {
816
+					case 'date_format':
817
+						$value = 'F j, Y';
818
+						break;
819
+					case 'time_format':
820
+						$value = 'g:i a';
821
+						break;
822
+				}
823
+			}
824
+		}
825
+		return $value;
826
+	}
827
+
828
+
829
+	/**
830
+	 * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
831
+	 *
832
+	 * @param $content
833
+	 * @return    string
834
+	 */
835
+	public function its_eSpresso($content)
836
+	{
837
+		return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
838
+	}
839
+
840
+
841
+	/**
842
+	 * espresso_admin_footer
843
+	 *
844
+	 * @return    string
845
+	 */
846
+	public function espresso_admin_footer()
847
+	{
848
+		return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
849
+	}
850
+
851
+
852
+	/**
853
+	 * static method for registering ee admin page.
854
+	 * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
855
+	 *
856
+	 * @since      4.3.0
857
+	 * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
858
+	 * @see        EE_Register_Admin_Page::register()
859
+	 * @param       $page_basename
860
+	 * @param       $page_path
861
+	 * @param array $config
862
+	 * @return void
863
+	 * @throws EE_Error
864
+	 */
865
+	public static function register_ee_admin_page($page_basename, $page_path, $config = array())
866
+	{
867
+		EE_Error::doing_it_wrong(
868
+			__METHOD__,
869
+			sprintf(
870
+				esc_html__(
871
+					'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
872
+					'event_espresso'
873
+				),
874
+				$page_basename
875
+			),
876
+			'4.3'
877
+		);
878
+		if (class_exists('EE_Register_Admin_Page')) {
879
+			$config['page_path'] = $page_path;
880
+		}
881
+		EE_Register_Admin_Page::register($page_basename, $config);
882
+	}
883
+
884
+
885
+	/**
886
+	 * @deprecated 4.8.41
887
+	 * @param  int      $post_ID
888
+	 * @param  \WP_Post $post
889
+	 * @return void
890
+	 */
891
+	public static function parse_post_content_on_save($post_ID, $post)
892
+	{
893
+		EE_Error::doing_it_wrong(
894
+			__METHOD__,
895
+			esc_html__('Usage is deprecated', 'event_espresso'),
896
+			'4.8.41'
897
+		);
898
+	}
899
+
900
+
901
+	/**
902
+	 * @deprecated 4.8.41
903
+	 * @param  $option
904
+	 * @param  $old_value
905
+	 * @param  $value
906
+	 * @return void
907
+	 */
908
+	public function reset_page_for_posts_on_change($option, $old_value, $value)
909
+	{
910
+		EE_Error::doing_it_wrong(
911
+			__METHOD__,
912
+			esc_html__('Usage is deprecated', 'event_espresso'),
913
+			'4.8.41'
914
+		);
915
+	}
916
+
917
+
918
+
919
+	/**
920
+	 * @deprecated 4.9.27
921
+	 * @return void
922
+	 */
923
+	public function get_persistent_admin_notices()
924
+	{
925
+		EE_Error::doing_it_wrong(
926
+			__METHOD__,
927
+			sprintf(
928
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
929
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
930
+			),
931
+			'4.9.27'
932
+		);
933
+	}
934
+
935
+
936
+
937
+	/**
938
+	 * @deprecated 4.9.27
939
+	 * @throws InvalidInterfaceException
940
+	 * @throws InvalidDataTypeException
941
+	 * @throws DomainException
942
+	 */
943
+	public function dismiss_ee_nag_notice_callback()
944
+	{
945
+		EE_Error::doing_it_wrong(
946
+			__METHOD__,
947
+			sprintf(
948
+				__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
949
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
950
+			),
951
+			'4.9.27'
952
+		);
953
+		$this->persistent_admin_notice_manager->dismissNotice();
954
+	}
955 955
 }
Please login to merge, or discard this patch.
core/EE_Load_Espresso_Core.core.php 2 patches
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -28,223 +28,223 @@
 block discarded – undo
28 28
 class EE_Load_Espresso_Core implements EEI_Request_Decorator, EEI_Request_Stack_Core_App
29 29
 {
30 30
 
31
-    /**
32
-     * @var EE_Request $request
33
-     */
34
-    protected $request;
35
-
36
-    /**
37
-     * @var EE_Response $response
38
-     */
39
-    protected $response;
40
-
41
-    /**
42
-     * @var EE_Dependency_Map $dependency_map
43
-     */
44
-    protected $dependency_map;
45
-
46
-    /**
47
-     * @var EE_Registry $registry
48
-     */
49
-    protected $registry;
50
-
51
-
52
-    /**
53
-     * EE_Load_Espresso_Core constructor
54
-     *
55
-     * @throws EE_Error
56
-     */
31
+	/**
32
+	 * @var EE_Request $request
33
+	 */
34
+	protected $request;
35
+
36
+	/**
37
+	 * @var EE_Response $response
38
+	 */
39
+	protected $response;
40
+
41
+	/**
42
+	 * @var EE_Dependency_Map $dependency_map
43
+	 */
44
+	protected $dependency_map;
45
+
46
+	/**
47
+	 * @var EE_Registry $registry
48
+	 */
49
+	protected $registry;
50
+
51
+
52
+	/**
53
+	 * EE_Load_Espresso_Core constructor
54
+	 *
55
+	 * @throws EE_Error
56
+	 */
57 57
 	public function __construct() {
58
-        // deprecated functions
59
-        espresso_load_required('EE_Base', EE_CORE . 'EE_Base.core.php');
60
-        espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
61
-    }
62
-
63
-
64
-    /**
65
-     * handle
66
-     * sets hooks for running rest of system
67
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
68
-     * starting EE Addons from any other point may lead to problems
69
-     *
70
-     * @param EE_Request  $request
71
-     * @param EE_Response $response
72
-     * @return EE_Response
73
-     * @throws \EventEspresso\core\exceptions\InvalidFilePathException
74
-     * @throws \EventEspresso\core\exceptions\InvalidClassException
75
-     * @throws EE_Error
76
-     * @throws InvalidDataTypeException
77
-     * @throws InvalidInterfaceException
78
-     * @throws InvalidArgumentException
79
-     * @throws DomainException
80
-     */
81
-    public function handle_request(EE_Request $request, EE_Response $response)
82
-    {
83
-        $this->request = $request;
84
-        $this->response = $response;
85
-        // info about how to load classes required by other classes
86
-        $this->dependency_map = $this->_load_dependency_map();
87
-        // central repository for classes
88
-        $this->registry = $this->_load_registry();
89
-        do_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading');
90
-        $loader = LoaderFactory::getLoader($this->registry);
91
-        $this->dependency_map->setLoader($loader);
92
-        // instantiate core Domain class
93
-        DomainFactory::getShared(
94
-            new FullyQualifiedName(
95
-                'EventEspresso\core\domain\Domain'
96
-            ),
97
-            array(
98
-                new FilePath(EVENT_ESPRESSO_MAIN_FILE),
99
-                Version::fromString(espresso_version())
100
-            )
101
-        );
102
-        // build DI container
103
-        // $OpenCoffeeShop = new EventEspresso\core\services\container\OpenCoffeeShop();
104
-        // $OpenCoffeeShop->addRecipes();
105
-        // $CoffeeShop = $OpenCoffeeShop->CoffeeShop();
106
-        // workarounds for PHP < 5.3
107
-        $this->_load_class_tools();
108
-        // deprecated functions
109
-        espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
110
-        $loader->getShared(
111
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
112
-        );
113
-        // WP cron jobs
114
-        $loader->getShared('EE_Cron_Tasks');
115
-        $loader->getShared('EE_Request_Handler');
116
-        $loader->getShared('EE_System');
117
-        return $this->response;
118
-    }
119
-
120
-
121
-
122
-    /**
123
-     * @return EE_Request
124
-     */
125
-    public function request()
126
-    {
127
-        return $this->request;
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     * @return EE_Response
134
-     */
135
-    public function response()
136
-    {
137
-        return $this->response;
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @return EE_Dependency_Map
144
-     * @throws EE_Error
145
-     */
146
-    public function dependency_map()
147
-    {
148
-        if (! $this->dependency_map instanceof EE_Dependency_Map) {
149
-            throw new EE_Error(
150
-                sprintf(
151
-                    __('Invalid EE_Dependency_Map: "%1$s"', 'event_espresso'),
152
-                    print_r($this->dependency_map, true)
153
-                )
154
-            );
155
-        }
156
-        return $this->dependency_map;
157
-    }
158
-
159
-
160
-
161
-    /**
162
-     * @return EE_Registry
163
-     * @throws EE_Error
164
-     */
165
-    public function registry()
166
-    {
167
-        if (! $this->registry instanceof EE_Registry) {
168
-            throw new EE_Error(
169
-                sprintf(
170
-                    __('Invalid EE_Registry: "%1$s"', 'event_espresso'),
171
-                    print_r($this->registry, true)
172
-                )
173
-            );
174
-        }
175
-        return $this->registry;
176
-    }
177
-
178
-
179
-
180
-    /**
181
-     * @return EE_Dependency_Map
182
-     */
183
-    private function _load_dependency_map()
184
-    {
185
-        if (! is_readable(EE_CORE . 'EE_Dependency_Map.core.php')) {
186
-            EE_Error::add_error(
187
-                __('The EE_Dependency_Map core class could not be loaded.', 'event_espresso'),
188
-                __FILE__, __FUNCTION__, __LINE__
189
-            );
190
-            wp_die(EE_Error::get_notices());
191
-        }
192
-        require_once EE_CORE . 'EE_Dependency_Map.core.php';
193
-        return EE_Dependency_Map::instance($this->request, $this->response);
194
-    }
195
-
196
-
197
-
198
-    /**
199
-     * @return EE_Registry
200
-     * @throws \InvalidArgumentException
201
-     * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
202
-     * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
203
-     */
204
-    private function _load_registry()
205
-    {
206
-        if (! is_readable(EE_CORE . 'EE_Registry.core.php')) {
207
-            EE_Error::add_error(
208
-                __('The EE_Registry core class could not be loaded.', 'event_espresso'),
209
-                __FILE__, __FUNCTION__, __LINE__
210
-            );
211
-            wp_die(EE_Error::get_notices());
212
-        }
213
-        require_once EE_CORE . 'EE_Registry.core.php';
214
-        return EE_Registry::instance($this->dependency_map);
215
-    }
216
-
217
-
218
-
219
-    /**
220
-     * @return void
221
-     */
222
-    private function _load_class_tools()
223
-    {
224
-        if (! is_readable(EE_HELPERS . 'EEH_Class_Tools.helper.php')) {
225
-            EE_Error::add_error(
226
-                __('The EEH_Class_Tools helper could not be loaded.', 'event_espresso'),
227
-                __FILE__, __FUNCTION__, __LINE__
228
-            );
229
-        }
230
-        require_once EE_HELPERS . 'EEH_Class_Tools.helper.php';
231
-    }
232
-
233
-
234
-
235
-    /**
236
-     * called after the request stack has been fully processed
237
-     * if any of the middleware apps has requested the plugin be deactivated, then we do that now
238
-     *
239
-     * @param EE_Request  $request
240
-     * @param EE_Response $response
241
-     */
242
-    public function handle_response(EE_Request $request, EE_Response $response)
243
-    {
244
-        if ($response->plugin_deactivated()) {
245
-            espresso_deactivate_plugin(EE_PLUGIN_BASENAME);
246
-        }
247
-    }
58
+		// deprecated functions
59
+		espresso_load_required('EE_Base', EE_CORE . 'EE_Base.core.php');
60
+		espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
61
+	}
62
+
63
+
64
+	/**
65
+	 * handle
66
+	 * sets hooks for running rest of system
67
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
68
+	 * starting EE Addons from any other point may lead to problems
69
+	 *
70
+	 * @param EE_Request  $request
71
+	 * @param EE_Response $response
72
+	 * @return EE_Response
73
+	 * @throws \EventEspresso\core\exceptions\InvalidFilePathException
74
+	 * @throws \EventEspresso\core\exceptions\InvalidClassException
75
+	 * @throws EE_Error
76
+	 * @throws InvalidDataTypeException
77
+	 * @throws InvalidInterfaceException
78
+	 * @throws InvalidArgumentException
79
+	 * @throws DomainException
80
+	 */
81
+	public function handle_request(EE_Request $request, EE_Response $response)
82
+	{
83
+		$this->request = $request;
84
+		$this->response = $response;
85
+		// info about how to load classes required by other classes
86
+		$this->dependency_map = $this->_load_dependency_map();
87
+		// central repository for classes
88
+		$this->registry = $this->_load_registry();
89
+		do_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading');
90
+		$loader = LoaderFactory::getLoader($this->registry);
91
+		$this->dependency_map->setLoader($loader);
92
+		// instantiate core Domain class
93
+		DomainFactory::getShared(
94
+			new FullyQualifiedName(
95
+				'EventEspresso\core\domain\Domain'
96
+			),
97
+			array(
98
+				new FilePath(EVENT_ESPRESSO_MAIN_FILE),
99
+				Version::fromString(espresso_version())
100
+			)
101
+		);
102
+		// build DI container
103
+		// $OpenCoffeeShop = new EventEspresso\core\services\container\OpenCoffeeShop();
104
+		// $OpenCoffeeShop->addRecipes();
105
+		// $CoffeeShop = $OpenCoffeeShop->CoffeeShop();
106
+		// workarounds for PHP < 5.3
107
+		$this->_load_class_tools();
108
+		// deprecated functions
109
+		espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
110
+		$loader->getShared(
111
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
112
+		);
113
+		// WP cron jobs
114
+		$loader->getShared('EE_Cron_Tasks');
115
+		$loader->getShared('EE_Request_Handler');
116
+		$loader->getShared('EE_System');
117
+		return $this->response;
118
+	}
119
+
120
+
121
+
122
+	/**
123
+	 * @return EE_Request
124
+	 */
125
+	public function request()
126
+	{
127
+		return $this->request;
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 * @return EE_Response
134
+	 */
135
+	public function response()
136
+	{
137
+		return $this->response;
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @return EE_Dependency_Map
144
+	 * @throws EE_Error
145
+	 */
146
+	public function dependency_map()
147
+	{
148
+		if (! $this->dependency_map instanceof EE_Dependency_Map) {
149
+			throw new EE_Error(
150
+				sprintf(
151
+					__('Invalid EE_Dependency_Map: "%1$s"', 'event_espresso'),
152
+					print_r($this->dependency_map, true)
153
+				)
154
+			);
155
+		}
156
+		return $this->dependency_map;
157
+	}
158
+
159
+
160
+
161
+	/**
162
+	 * @return EE_Registry
163
+	 * @throws EE_Error
164
+	 */
165
+	public function registry()
166
+	{
167
+		if (! $this->registry instanceof EE_Registry) {
168
+			throw new EE_Error(
169
+				sprintf(
170
+					__('Invalid EE_Registry: "%1$s"', 'event_espresso'),
171
+					print_r($this->registry, true)
172
+				)
173
+			);
174
+		}
175
+		return $this->registry;
176
+	}
177
+
178
+
179
+
180
+	/**
181
+	 * @return EE_Dependency_Map
182
+	 */
183
+	private function _load_dependency_map()
184
+	{
185
+		if (! is_readable(EE_CORE . 'EE_Dependency_Map.core.php')) {
186
+			EE_Error::add_error(
187
+				__('The EE_Dependency_Map core class could not be loaded.', 'event_espresso'),
188
+				__FILE__, __FUNCTION__, __LINE__
189
+			);
190
+			wp_die(EE_Error::get_notices());
191
+		}
192
+		require_once EE_CORE . 'EE_Dependency_Map.core.php';
193
+		return EE_Dependency_Map::instance($this->request, $this->response);
194
+	}
195
+
196
+
197
+
198
+	/**
199
+	 * @return EE_Registry
200
+	 * @throws \InvalidArgumentException
201
+	 * @throws \EventEspresso\core\exceptions\InvalidInterfaceException
202
+	 * @throws \EventEspresso\core\exceptions\InvalidDataTypeException
203
+	 */
204
+	private function _load_registry()
205
+	{
206
+		if (! is_readable(EE_CORE . 'EE_Registry.core.php')) {
207
+			EE_Error::add_error(
208
+				__('The EE_Registry core class could not be loaded.', 'event_espresso'),
209
+				__FILE__, __FUNCTION__, __LINE__
210
+			);
211
+			wp_die(EE_Error::get_notices());
212
+		}
213
+		require_once EE_CORE . 'EE_Registry.core.php';
214
+		return EE_Registry::instance($this->dependency_map);
215
+	}
216
+
217
+
218
+
219
+	/**
220
+	 * @return void
221
+	 */
222
+	private function _load_class_tools()
223
+	{
224
+		if (! is_readable(EE_HELPERS . 'EEH_Class_Tools.helper.php')) {
225
+			EE_Error::add_error(
226
+				__('The EEH_Class_Tools helper could not be loaded.', 'event_espresso'),
227
+				__FILE__, __FUNCTION__, __LINE__
228
+			);
229
+		}
230
+		require_once EE_HELPERS . 'EEH_Class_Tools.helper.php';
231
+	}
232
+
233
+
234
+
235
+	/**
236
+	 * called after the request stack has been fully processed
237
+	 * if any of the middleware apps has requested the plugin be deactivated, then we do that now
238
+	 *
239
+	 * @param EE_Request  $request
240
+	 * @param EE_Response $response
241
+	 */
242
+	public function handle_response(EE_Request $request, EE_Response $response)
243
+	{
244
+		if ($response->plugin_deactivated()) {
245
+			espresso_deactivate_plugin(EE_PLUGIN_BASENAME);
246
+		}
247
+	}
248 248
 
249 249
 
250 250
 
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -56,8 +56,8 @@  discard block
 block discarded – undo
56 56
      */
57 57
 	public function __construct() {
58 58
         // deprecated functions
59
-        espresso_load_required('EE_Base', EE_CORE . 'EE_Base.core.php');
60
-        espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
59
+        espresso_load_required('EE_Base', EE_CORE.'EE_Base.core.php');
60
+        espresso_load_required('EE_Deprecated', EE_CORE.'EE_Deprecated.core.php');
61 61
     }
62 62
 
63 63
 
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
         // workarounds for PHP < 5.3
107 107
         $this->_load_class_tools();
108 108
         // deprecated functions
109
-        espresso_load_required('EE_Deprecated', EE_CORE . 'EE_Deprecated.core.php');
109
+        espresso_load_required('EE_Deprecated', EE_CORE.'EE_Deprecated.core.php');
110 110
         $loader->getShared(
111 111
             'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
112 112
         );
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
      */
146 146
     public function dependency_map()
147 147
     {
148
-        if (! $this->dependency_map instanceof EE_Dependency_Map) {
148
+        if ( ! $this->dependency_map instanceof EE_Dependency_Map) {
149 149
             throw new EE_Error(
150 150
                 sprintf(
151 151
                     __('Invalid EE_Dependency_Map: "%1$s"', 'event_espresso'),
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
      */
165 165
     public function registry()
166 166
     {
167
-        if (! $this->registry instanceof EE_Registry) {
167
+        if ( ! $this->registry instanceof EE_Registry) {
168 168
             throw new EE_Error(
169 169
                 sprintf(
170 170
                     __('Invalid EE_Registry: "%1$s"', 'event_espresso'),
@@ -182,14 +182,14 @@  discard block
 block discarded – undo
182 182
      */
183 183
     private function _load_dependency_map()
184 184
     {
185
-        if (! is_readable(EE_CORE . 'EE_Dependency_Map.core.php')) {
185
+        if ( ! is_readable(EE_CORE.'EE_Dependency_Map.core.php')) {
186 186
             EE_Error::add_error(
187 187
                 __('The EE_Dependency_Map core class could not be loaded.', 'event_espresso'),
188 188
                 __FILE__, __FUNCTION__, __LINE__
189 189
             );
190 190
             wp_die(EE_Error::get_notices());
191 191
         }
192
-        require_once EE_CORE . 'EE_Dependency_Map.core.php';
192
+        require_once EE_CORE.'EE_Dependency_Map.core.php';
193 193
         return EE_Dependency_Map::instance($this->request, $this->response);
194 194
     }
195 195
 
@@ -203,14 +203,14 @@  discard block
 block discarded – undo
203 203
      */
204 204
     private function _load_registry()
205 205
     {
206
-        if (! is_readable(EE_CORE . 'EE_Registry.core.php')) {
206
+        if ( ! is_readable(EE_CORE.'EE_Registry.core.php')) {
207 207
             EE_Error::add_error(
208 208
                 __('The EE_Registry core class could not be loaded.', 'event_espresso'),
209 209
                 __FILE__, __FUNCTION__, __LINE__
210 210
             );
211 211
             wp_die(EE_Error::get_notices());
212 212
         }
213
-        require_once EE_CORE . 'EE_Registry.core.php';
213
+        require_once EE_CORE.'EE_Registry.core.php';
214 214
         return EE_Registry::instance($this->dependency_map);
215 215
     }
216 216
 
@@ -221,13 +221,13 @@  discard block
 block discarded – undo
221 221
      */
222 222
     private function _load_class_tools()
223 223
     {
224
-        if (! is_readable(EE_HELPERS . 'EEH_Class_Tools.helper.php')) {
224
+        if ( ! is_readable(EE_HELPERS.'EEH_Class_Tools.helper.php')) {
225 225
             EE_Error::add_error(
226 226
                 __('The EEH_Class_Tools helper could not be loaded.', 'event_espresso'),
227 227
                 __FILE__, __FUNCTION__, __LINE__
228 228
             );
229 229
         }
230
-        require_once EE_HELPERS . 'EEH_Class_Tools.helper.php';
230
+        require_once EE_HELPERS.'EEH_Class_Tools.helper.php';
231 231
     }
232 232
 
233 233
 
Please login to merge, or discard this patch.