Completed
Branch decaf-fixes/replace-request-ha... (dd0ac0)
by
unknown
04:45 queued 03:02
created
core/db_models/EEM_Base.model.php 1 patch
Indentation   +6455 added lines, -6455 removed lines patch added patch discarded remove patch
@@ -36,6461 +36,6461 @@
 block discarded – undo
36 36
 abstract class EEM_Base extends EE_Base implements ResettableInterface
37 37
 {
38 38
 
39
-    /**
40
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
-     * They almost always WILL NOT, but it's not necessarily a requirement.
43
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
-     *
45
-     * @var boolean
46
-     */
47
-    private $_values_already_prepared_by_model_object = 0;
48
-
49
-    /**
50
-     * when $_values_already_prepared_by_model_object equals this, we assume
51
-     * the data is just like form input that needs to have the model fields'
52
-     * prepare_for_set and prepare_for_use_in_db called on it
53
-     */
54
-    const not_prepared_by_model_object = 0;
55
-
56
-    /**
57
-     * when $_values_already_prepared_by_model_object equals this, we
58
-     * assume this value is coming from a model object and doesn't need to have
59
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
60
-     */
61
-    const prepared_by_model_object = 1;
62
-
63
-    /**
64
-     * when $_values_already_prepared_by_model_object equals this, we assume
65
-     * the values are already to be used in the database (ie no processing is done
66
-     * on them by the model's fields)
67
-     */
68
-    const prepared_for_use_in_db = 2;
69
-
70
-
71
-    protected $singular_item = 'Item';
72
-
73
-    protected $plural_item   = 'Items';
74
-
75
-    /**
76
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
-     */
78
-    protected $_tables;
79
-
80
-    /**
81
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
-     *
85
-     * @var \EE_Model_Field_Base[][] $_fields
86
-     */
87
-    protected $_fields;
88
-
89
-    /**
90
-     * array of different kinds of relations
91
-     *
92
-     * @var \EE_Model_Relation_Base[] $_model_relations
93
-     */
94
-    protected $_model_relations;
95
-
96
-    /**
97
-     * @var \EE_Index[] $_indexes
98
-     */
99
-    protected $_indexes = array();
100
-
101
-    /**
102
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
103
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
-     * by setting the same columns as used in these queries in the query yourself.
105
-     *
106
-     * @var EE_Default_Where_Conditions
107
-     */
108
-    protected $_default_where_conditions_strategy;
109
-
110
-    /**
111
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
-     * This is particularly useful when you want something between 'none' and 'default'
113
-     *
114
-     * @var EE_Default_Where_Conditions
115
-     */
116
-    protected $_minimum_where_conditions_strategy;
117
-
118
-    /**
119
-     * String describing how to find the "owner" of this model's objects.
120
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
-     * But when there isn't, this indicates which related model, or transiently-related model,
122
-     * has the foreign key to the wp_users table.
123
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
-     * related to events, and events have a foreign key to wp_users.
125
-     * On EEM_Transaction, this would be 'Transaction.Event'
126
-     *
127
-     * @var string
128
-     */
129
-    protected $_model_chain_to_wp_user = '';
130
-
131
-    /**
132
-     * String describing how to find the model with a password controlling access to this model. This property has the
133
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
-     * This value is the path of models to follow to arrive at the model with the password field.
135
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
-     * model with a password that should affect reading this on the front-end.
137
-     * Eg this is an empty string for the Event model because it has a password.
138
-     * This is null for the Registration model, because its event's password has no bearing on whether
139
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
-     * should hide tickets for datetimes for events that have a password set.
142
-     * @var string |null
143
-     */
144
-    protected $model_chain_to_password = null;
145
-
146
-    /**
147
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
-     * don't need it (particularly CPT models)
149
-     *
150
-     * @var bool
151
-     */
152
-    protected $_ignore_where_strategy = false;
153
-
154
-    /**
155
-     * String used in caps relating to this model. Eg, if the caps relating to this
156
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
-     *
158
-     * @var string. If null it hasn't been initialized yet. If false then we
159
-     * have indicated capabilities don't apply to this
160
-     */
161
-    protected $_caps_slug = null;
162
-
163
-    /**
164
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
-     * and next-level keys are capability names, and each's value is a
166
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
-     * they specify which context to use (ie, frontend, backend, edit or delete)
168
-     * and then each capability in the corresponding sub-array that they're missing
169
-     * adds the where conditions onto the query.
170
-     *
171
-     * @var array
172
-     */
173
-    protected $_cap_restrictions = array(
174
-        self::caps_read       => array(),
175
-        self::caps_read_admin => array(),
176
-        self::caps_edit       => array(),
177
-        self::caps_delete     => array(),
178
-    );
179
-
180
-    /**
181
-     * Array defining which cap restriction generators to use to create default
182
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
183
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
-     * automatically set this to false (not just null).
186
-     *
187
-     * @var EE_Restriction_Generator_Base[]
188
-     */
189
-    protected $_cap_restriction_generators = array();
190
-
191
-    /**
192
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
-     */
194
-    const caps_read       = 'read';
195
-
196
-    const caps_read_admin = 'read_admin';
197
-
198
-    const caps_edit       = 'edit';
199
-
200
-    const caps_delete     = 'delete';
201
-
202
-    /**
203
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
-     * maps to 'read' because when looking for relevant permissions we're going to use
206
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
207
-     *
208
-     * @var array
209
-     */
210
-    protected $_cap_contexts_to_cap_action_map = array(
211
-        self::caps_read       => 'read',
212
-        self::caps_read_admin => 'read',
213
-        self::caps_edit       => 'edit',
214
-        self::caps_delete     => 'delete',
215
-    );
216
-
217
-    /**
218
-     * Timezone
219
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
-     * EE_Datetime_Field data type will have access to it.
223
-     *
224
-     * @var string
225
-     */
226
-    protected $_timezone;
227
-
228
-
229
-    /**
230
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
-     * multisite.
232
-     *
233
-     * @var int
234
-     */
235
-    protected static $_model_query_blog_id;
236
-
237
-    /**
238
-     * A copy of _fields, except the array keys are the model names pointed to by
239
-     * the field
240
-     *
241
-     * @var EE_Model_Field_Base[]
242
-     */
243
-    private $_cache_foreign_key_to_fields = array();
244
-
245
-    /**
246
-     * Cached list of all the fields on the model, indexed by their name
247
-     *
248
-     * @var EE_Model_Field_Base[]
249
-     */
250
-    private $_cached_fields = null;
251
-
252
-    /**
253
-     * Cached list of all the fields on the model, except those that are
254
-     * marked as only pertinent to the database
255
-     *
256
-     * @var EE_Model_Field_Base[]
257
-     */
258
-    private $_cached_fields_non_db_only = null;
259
-
260
-    /**
261
-     * A cached reference to the primary key for quick lookup
262
-     *
263
-     * @var EE_Model_Field_Base
264
-     */
265
-    private $_primary_key_field = null;
266
-
267
-    /**
268
-     * Flag indicating whether this model has a primary key or not
269
-     *
270
-     * @var boolean
271
-     */
272
-    protected $_has_primary_key_field = null;
273
-
274
-    /**
275
-     * array in the format:  [ FK alias => full PK ]
276
-     * where keys are local column name aliases for foreign keys
277
-     * and values are the fully qualified column name for the primary key they represent
278
-     *  ex:
279
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
-     *
281
-     * @var array $foreign_key_aliases
282
-     */
283
-    protected $foreign_key_aliases = [];
284
-
285
-    /**
286
-     * Whether or not this model is based off a table in WP core only (CPTs should set
287
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
-     * This should be true for models that deal with data that should exist independent of EE.
289
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
291
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
293
-     * @var boolean
294
-     */
295
-    protected $_wp_core_model = false;
296
-
297
-    /**
298
-     * @var bool stores whether this model has a password field or not.
299
-     * null until initialized by hasPasswordField()
300
-     */
301
-    protected $has_password_field;
302
-
303
-    /**
304
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
-     */
306
-    protected $password_field;
307
-
308
-    /**
309
-     *    List of valid operators that can be used for querying.
310
-     * The keys are all operators we'll accept, the values are the real SQL
311
-     * operators used
312
-     *
313
-     * @var array
314
-     */
315
-    protected $_valid_operators = array(
316
-        '='           => '=',
317
-        '<='          => '<=',
318
-        '<'           => '<',
319
-        '>='          => '>=',
320
-        '>'           => '>',
321
-        '!='          => '!=',
322
-        'LIKE'        => 'LIKE',
323
-        'like'        => 'LIKE',
324
-        'NOT_LIKE'    => 'NOT LIKE',
325
-        'not_like'    => 'NOT LIKE',
326
-        'NOT LIKE'    => 'NOT LIKE',
327
-        'not like'    => 'NOT LIKE',
328
-        'IN'          => 'IN',
329
-        'in'          => 'IN',
330
-        'NOT_IN'      => 'NOT IN',
331
-        'not_in'      => 'NOT IN',
332
-        'NOT IN'      => 'NOT IN',
333
-        'not in'      => 'NOT IN',
334
-        'between'     => 'BETWEEN',
335
-        'BETWEEN'     => 'BETWEEN',
336
-        'IS_NOT_NULL' => 'IS NOT NULL',
337
-        'is_not_null' => 'IS NOT NULL',
338
-        'IS NOT NULL' => 'IS NOT NULL',
339
-        'is not null' => 'IS NOT NULL',
340
-        'IS_NULL'     => 'IS NULL',
341
-        'is_null'     => 'IS NULL',
342
-        'IS NULL'     => 'IS NULL',
343
-        'is null'     => 'IS NULL',
344
-        'REGEXP'      => 'REGEXP',
345
-        'regexp'      => 'REGEXP',
346
-        'NOT_REGEXP'  => 'NOT REGEXP',
347
-        'not_regexp'  => 'NOT REGEXP',
348
-        'NOT REGEXP'  => 'NOT REGEXP',
349
-        'not regexp'  => 'NOT REGEXP',
350
-    );
351
-
352
-    /**
353
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
-     *
355
-     * @var array
356
-     */
357
-    protected $_in_style_operators = array('IN', 'NOT IN');
358
-
359
-    /**
360
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
-     * '12-31-2012'"
362
-     *
363
-     * @var array
364
-     */
365
-    protected $_between_style_operators = array('BETWEEN');
366
-
367
-    /**
368
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
-     * @var array
370
-     */
371
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
-    /**
373
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
-     * on a join table.
375
-     *
376
-     * @var array
377
-     */
378
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
-
380
-    /**
381
-     * Allowed values for $query_params['order'] for ordering in queries
382
-     *
383
-     * @var array
384
-     */
385
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
-
387
-    /**
388
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
390
-     *
391
-     * @var array
392
-     */
393
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
-
395
-    /**
396
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
398
-     *
399
-     * @var array
400
-     */
401
-    private $_allowed_query_params = array(
402
-        0,
403
-        'limit',
404
-        'order_by',
405
-        'group_by',
406
-        'having',
407
-        'force_join',
408
-        'order',
409
-        'on_join_limit',
410
-        'default_where_conditions',
411
-        'caps',
412
-        'extra_selects',
413
-        'exclude_protected',
414
-    );
415
-
416
-    /**
417
-     * All the data types that can be used in $wpdb->prepare statements.
418
-     *
419
-     * @var array
420
-     */
421
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
-
423
-    /**
424
-     * @var EE_Registry $EE
425
-     */
426
-    protected $EE = null;
427
-
428
-
429
-    /**
430
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
-     *
432
-     * @var int
433
-     */
434
-    protected $_show_next_x_db_queries = 0;
435
-
436
-    /**
437
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
-     * WHERE, GROUP_BY, etc.
440
-     *
441
-     * @var CustomSelects
442
-     */
443
-    protected $_custom_selections = array();
444
-
445
-    /**
446
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
-     * caches every model object we've fetched from the DB on this request
448
-     *
449
-     * @var array
450
-     */
451
-    protected $_entity_map;
452
-
453
-    /**
454
-     * @var LoaderInterface $loader
455
-     */
456
-    protected static $loader;
457
-
458
-
459
-    /**
460
-     * constant used to show EEM_Base has not yet verified the db on this http request
461
-     */
462
-    const db_verified_none = 0;
463
-
464
-    /**
465
-     * constant used to show EEM_Base has verified the EE core db on this http request,
466
-     * but not the addons' dbs
467
-     */
468
-    const db_verified_core = 1;
469
-
470
-    /**
471
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
-     * the EE core db too)
473
-     */
474
-    const db_verified_addons = 2;
475
-
476
-    /**
477
-     * indicates whether an EEM_Base child has already re-verified the DB
478
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
479
-     * looking like EEM_Base::db_verified_*
480
-     *
481
-     * @var int - 0 = none, 1 = core, 2 = addons
482
-     */
483
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
484
-
485
-    /**
486
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
-     *        registrations for non-trashed tickets for non-trashed datetimes)
489
-     */
490
-    const default_where_conditions_all = 'all';
491
-
492
-    /**
493
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
-     *        models which share tables with other models, this can return data for the wrong model.
498
-     */
499
-    const default_where_conditions_this_only = 'this_model_only';
500
-
501
-    /**
502
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
-     */
506
-    const default_where_conditions_others_only = 'other_models_only';
507
-
508
-    /**
509
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
512
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
-     *        (regardless of whether those events and venues are trashed)
514
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
-     *        events.
516
-     */
517
-    const default_where_conditions_minimum_all = 'minimum';
518
-
519
-    /**
520
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
-     *        not)
524
-     */
525
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
-
527
-    /**
528
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
-     *        it's possible it will return table entries for other models. You should use
531
-     *        EEM_Base::default_where_conditions_minimum_all instead.
532
-     */
533
-    const default_where_conditions_none = 'none';
534
-
535
-
536
-
537
-    /**
538
-     * About all child constructors:
539
-     * they should define the _tables, _fields and _model_relations arrays.
540
-     * Should ALWAYS be called after child constructor.
541
-     * In order to make the child constructors to be as simple as possible, this parent constructor
542
-     * finalizes constructing all the object's attributes.
543
-     * Generally, rather than requiring a child to code
544
-     * $this->_tables = array(
545
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
-     *        ...);
547
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
-     * each EE_Table has a function to set the table's alias after the constructor, using
549
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
-     * do something similar.
551
-     *
552
-     * @param null $timezone
553
-     * @throws EE_Error
554
-     */
555
-    protected function __construct($timezone = null)
556
-    {
557
-        // check that the model has not been loaded too soon
558
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
-            throw new EE_Error(
560
-                sprintf(
561
-                    __(
562
-                        '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.',
563
-                        'event_espresso'
564
-                    ),
565
-                    get_class($this)
566
-                )
567
-            );
568
-        }
569
-        /**
570
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
-         */
572
-        if (empty(EEM_Base::$_model_query_blog_id)) {
573
-            EEM_Base::set_model_query_blog_id();
574
-        }
575
-        /**
576
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
-         * just use EE_Register_Model_Extension
578
-         *
579
-         * @var EE_Table_Base[] $_tables
580
-         */
581
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
-        foreach ($this->_tables as $table_alias => $table_obj) {
583
-            /** @var $table_obj EE_Table_Base */
584
-            $table_obj->_construct_finalize_with_alias($table_alias);
585
-            if ($table_obj instanceof EE_Secondary_Table) {
586
-                /** @var $table_obj EE_Secondary_Table */
587
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
-            }
589
-        }
590
-        /**
591
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
-         * EE_Register_Model_Extension
593
-         *
594
-         * @param EE_Model_Field_Base[] $_fields
595
-         */
596
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
-        $this->_invalidate_field_caches();
598
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
599
-            if (! array_key_exists($table_alias, $this->_tables)) {
600
-                throw new EE_Error(sprintf(__(
601
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
-                    'event_espresso'
603
-                ), $table_alias, implode(",", $this->_fields)));
604
-            }
605
-            foreach ($fields_for_table as $field_name => $field_obj) {
606
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
-                // primary key field base has a slightly different _construct_finalize
608
-                /** @var $field_obj EE_Model_Field_Base */
609
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
-            }
611
-        }
612
-        // everything is related to Extra_Meta
613
-        if (get_class($this) !== 'EEM_Extra_Meta') {
614
-            // make extra meta related to everything, but don't block deleting things just
615
-            // because they have related extra meta info. For now just orphan those extra meta
616
-            // in the future we should automatically delete them
617
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
-        }
619
-        // and change logs
620
-        if (get_class($this) !== 'EEM_Change_Log') {
621
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
-        }
623
-        /**
624
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
-         * EE_Register_Model_Extension
626
-         *
627
-         * @param EE_Model_Relation_Base[] $_model_relations
628
-         */
629
-        $this->_model_relations = (array) apply_filters(
630
-            'FHEE__' . get_class($this) . '__construct__model_relations',
631
-            $this->_model_relations
632
-        );
633
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
634
-            /** @var $relation_obj EE_Model_Relation_Base */
635
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
-        }
637
-        foreach ($this->_indexes as $index_name => $index_obj) {
638
-            /** @var $index_obj EE_Index */
639
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
-        }
641
-        $this->set_timezone($timezone);
642
-        // finalize default where condition strategy, or set default
643
-        if (! $this->_default_where_conditions_strategy) {
644
-            // nothing was set during child constructor, so set default
645
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
-        }
647
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
648
-        if (! $this->_minimum_where_conditions_strategy) {
649
-            // nothing was set during child constructor, so set default
650
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
-        }
652
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
654
-        // to indicate to NOT set it, set it to the logical default
655
-        if ($this->_caps_slug === null) {
656
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
-        }
658
-        // initialize the standard cap restriction generators if none were specified by the child constructor
659
-        if ($this->_cap_restriction_generators !== false) {
660
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
-                        new EE_Restriction_Generator_Protected(),
665
-                        $cap_context,
666
-                        $this
667
-                    );
668
-                }
669
-            }
670
-        }
671
-        // if there are cap restriction generators, use them to make the default cap restrictions
672
-        if ($this->_cap_restriction_generators !== false) {
673
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
-                if (! $generator_object) {
675
-                    continue;
676
-                }
677
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
-                    throw new EE_Error(
679
-                        sprintf(
680
-                            __(
681
-                                '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.',
682
-                                'event_espresso'
683
-                            ),
684
-                            $context,
685
-                            $this->get_this_model_name()
686
-                        )
687
-                    );
688
-                }
689
-                $action = $this->cap_action_for_context($context);
690
-                if (! $generator_object->construction_finalized()) {
691
-                    $generator_object->_construct_finalize($this, $action);
692
-                }
693
-            }
694
-        }
695
-        do_action('AHEE__' . get_class($this) . '__construct__end');
696
-    }
697
-
698
-
699
-
700
-    /**
701
-     * Used to set the $_model_query_blog_id static property.
702
-     *
703
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
-     *                      value for get_current_blog_id() will be used.
705
-     */
706
-    public static function set_model_query_blog_id($blog_id = 0)
707
-    {
708
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
-    }
710
-
711
-
712
-
713
-    /**
714
-     * Returns whatever is set as the internal $model_query_blog_id.
715
-     *
716
-     * @return int
717
-     */
718
-    public static function get_model_query_blog_id()
719
-    {
720
-        return EEM_Base::$_model_query_blog_id;
721
-    }
722
-
723
-
724
-
725
-    /**
726
-     * This function is a singleton method used to instantiate the Espresso_model object
727
-     *
728
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
-     *                                (and any incoming timezone data that gets saved).
730
-     *                                Note this just sends the timezone info to the date time model field objects.
731
-     *                                Default is NULL
732
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
-     * @return static (as in the concrete child class)
734
-     * @throws EE_Error
735
-     * @throws InvalidArgumentException
736
-     * @throws InvalidDataTypeException
737
-     * @throws InvalidInterfaceException
738
-     */
739
-    public static function instance($timezone = null)
740
-    {
741
-        // check if instance of Espresso_model already exists
742
-        if (! static::$_instance instanceof static) {
743
-            // instantiate Espresso_model
744
-            static::$_instance = new static(
745
-                $timezone,
746
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
-            );
748
-        }
749
-        // we might have a timezone set, let set_timezone decide what to do with it
750
-        static::$_instance->set_timezone($timezone);
751
-        // Espresso_model object
752
-        return static::$_instance;
753
-    }
754
-
755
-
756
-
757
-    /**
758
-     * resets the model and returns it
759
-     *
760
-     * @param null | string $timezone
761
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
-     * all its properties reset; if it wasn't instantiated, returns null)
763
-     * @throws EE_Error
764
-     * @throws ReflectionException
765
-     * @throws InvalidArgumentException
766
-     * @throws InvalidDataTypeException
767
-     * @throws InvalidInterfaceException
768
-     */
769
-    public static function reset($timezone = null)
770
-    {
771
-        if (static::$_instance instanceof EEM_Base) {
772
-            // let's try to NOT swap out the current instance for a new one
773
-            // because if someone has a reference to it, we can't remove their reference
774
-            // so it's best to keep using the same reference, but change the original object
775
-            // reset all its properties to their original values as defined in the class
776
-            $r = new ReflectionClass(get_class(static::$_instance));
777
-            $static_properties = $r->getStaticProperties();
778
-            foreach ($r->getDefaultProperties() as $property => $value) {
779
-                // don't set instance to null like it was originally,
780
-                // but it's static anyways, and we're ignoring static properties (for now at least)
781
-                if (! isset($static_properties[ $property ])) {
782
-                    static::$_instance->{$property} = $value;
783
-                }
784
-            }
785
-            // and then directly call its constructor again, like we would if we were creating a new one
786
-            static::$_instance->__construct(
787
-                $timezone,
788
-                EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
-            );
790
-            return self::instance();
791
-        }
792
-        return null;
793
-    }
794
-
795
-
796
-
797
-    /**
798
-     * @return LoaderInterface
799
-     * @throws InvalidArgumentException
800
-     * @throws InvalidDataTypeException
801
-     * @throws InvalidInterfaceException
802
-     */
803
-    private static function getLoader()
804
-    {
805
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
806
-            EEM_Base::$loader = LoaderFactory::getLoader();
807
-        }
808
-        return EEM_Base::$loader;
809
-    }
810
-
811
-
812
-
813
-    /**
814
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
-     *
816
-     * @param  boolean $translated return localized strings or JUST the array.
817
-     * @return array
818
-     * @throws EE_Error
819
-     * @throws InvalidArgumentException
820
-     * @throws InvalidDataTypeException
821
-     * @throws InvalidInterfaceException
822
-     */
823
-    public function status_array($translated = false)
824
-    {
825
-        if (! array_key_exists('Status', $this->_model_relations)) {
826
-            return array();
827
-        }
828
-        $model_name = $this->get_this_model_name();
829
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
-        $status_array = array();
832
-        foreach ($stati as $status) {
833
-            $status_array[ $status->ID() ] = $status->get('STS_code');
834
-        }
835
-        return $translated
836
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
-            : $status_array;
838
-    }
839
-
840
-
841
-
842
-    /**
843
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
-     *
845
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
-     *                             or if you have the development copy of EE you can view this at the path:
847
-     *                             /docs/G--Model-System/model-query-params.md
848
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
-     *                                        array( array(
853
-     *                                        'OR'=>array(
854
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
-     *                                        )
857
-     *                                        ),
858
-     *                                        'limit'=>10,
859
-     *                                        'group_by'=>'TXN_ID'
860
-     *                                        ));
861
-     *                                        get all the answers to the question titled "shirt size" for event with id
862
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
-     *                                        'Question.QST_display_text'=>'shirt size',
864
-     *                                        'Registration.Event.EVT_ID'=>12
865
-     *                                        ),
866
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
867
-     *                                        ));
868
-     * @throws EE_Error
869
-     */
870
-    public function get_all($query_params = array())
871
-    {
872
-        if (isset($query_params['limit'])
873
-            && ! isset($query_params['group_by'])
874
-        ) {
875
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
-        }
877
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
-    }
879
-
880
-
881
-
882
-    /**
883
-     * Modifies the query parameters so we only get back model objects
884
-     * that "belong" to the current user
885
-     *
886
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
-     */
889
-    public function alter_query_params_to_only_include_mine($query_params = array())
890
-    {
891
-        $wp_user_field_name = $this->wp_user_field_name();
892
-        if ($wp_user_field_name) {
893
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
-        }
895
-        return $query_params;
896
-    }
897
-
898
-
899
-
900
-    /**
901
-     * Returns the name of the field's name that points to the WP_User table
902
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
-     * foreign key to the WP_User table)
904
-     *
905
-     * @return string|boolean string on success, boolean false when there is no
906
-     * foreign key to the WP_User table
907
-     */
908
-    public function wp_user_field_name()
909
-    {
910
-        try {
911
-            if (! empty($this->_model_chain_to_wp_user)) {
912
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
-                $last_model_name = end($models_to_follow_to_wp_users);
914
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
-            } else {
917
-                $model_with_fk_to_wp_users = $this;
918
-                $model_chain_to_wp_user = '';
919
-            }
920
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
922
-        } catch (EE_Error $e) {
923
-            return false;
924
-        }
925
-    }
926
-
927
-
928
-
929
-    /**
930
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
931
-     * (or transiently-related model) has a foreign key to the wp_users table;
932
-     * useful for finding if model objects of this type are 'owned' by the current user.
933
-     * This is an empty string when the foreign key is on this model and when it isn't,
934
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
935
-     * (or transiently-related model)
936
-     *
937
-     * @return string
938
-     */
939
-    public function model_chain_to_wp_user()
940
-    {
941
-        return $this->_model_chain_to_wp_user;
942
-    }
943
-
944
-
945
-
946
-    /**
947
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
-     * like how registrations don't have a foreign key to wp_users, but the
949
-     * events they are for are), or is unrelated to wp users.
950
-     * generally available
951
-     *
952
-     * @return boolean
953
-     */
954
-    public function is_owned()
955
-    {
956
-        if ($this->model_chain_to_wp_user()) {
957
-            return true;
958
-        }
959
-        try {
960
-            $this->get_foreign_key_to('WP_User');
961
-            return true;
962
-        } catch (EE_Error $e) {
963
-            return false;
964
-        }
965
-    }
966
-
967
-
968
-    /**
969
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
-     * the model)
972
-     *
973
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
-     *                                  fields on the model, and the models we joined to in the query. However, you can
977
-     *                                  override this and set the select to "*", or a specific column name, like
978
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
-     *                                  the aliases used to refer to this selection, and values are to be
981
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
-     * @throws EE_Error
985
-     * @throws InvalidArgumentException
986
-     */
987
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
-    {
989
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
-        ;
991
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
992
-        $select_expressions = $columns_to_select === null
993
-            ? $this->_construct_default_select_sql($model_query_info)
994
-            : '';
995
-        if ($this->_custom_selections instanceof CustomSelects) {
996
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
-            $select_expressions .= $select_expressions
998
-                ? ', ' . $custom_expressions
999
-                : $custom_expressions;
1000
-        }
1001
-
1002
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
-    }
1005
-
1006
-
1007
-    /**
1008
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
-     * method of including extra select information.
1011
-     *
1012
-     * @param array             $query_params
1013
-     * @param null|array|string $columns_to_select
1014
-     * @return null|CustomSelects
1015
-     * @throws InvalidArgumentException
1016
-     */
1017
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
-    {
1019
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
-            return null;
1021
-        }
1022
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
-        return new CustomSelects($selects);
1025
-    }
1026
-
1027
-
1028
-
1029
-    /**
1030
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1031
-     * but you can use the model query params to more easily
1032
-     * take care of joins, field preparation etc.
1033
-     *
1034
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1038
-     *                                  override this and set the select to "*", or a specific column name, like
1039
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
-     *                                  the aliases used to refer to this selection, and values are to be
1042
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
-     * @throws EE_Error
1046
-     */
1047
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
-    {
1049
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
-    }
1051
-
1052
-
1053
-
1054
-    /**
1055
-     * For creating a custom select statement
1056
-     *
1057
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
-     *                                 SQL, and 1=>is the datatype
1060
-     * @throws EE_Error
1061
-     * @return string
1062
-     */
1063
-    private function _construct_select_from_input($columns_to_select)
1064
-    {
1065
-        if (is_array($columns_to_select)) {
1066
-            $select_sql_array = array();
1067
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
-                    throw new EE_Error(
1070
-                        sprintf(
1071
-                            __(
1072
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
-                                'event_espresso'
1074
-                            ),
1075
-                            $selection_and_datatype,
1076
-                            $alias
1077
-                        )
1078
-                    );
1079
-                }
1080
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
-                    throw new EE_Error(
1082
-                        sprintf(
1083
-                            esc_html__(
1084
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
-                                'event_espresso'
1086
-                            ),
1087
-                            $selection_and_datatype[1],
1088
-                            $selection_and_datatype[0],
1089
-                            $alias,
1090
-                            implode(', ', $this->_valid_wpdb_data_types)
1091
-                        )
1092
-                    );
1093
-                }
1094
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
-            }
1096
-            $columns_to_select_string = implode(', ', $select_sql_array);
1097
-        } else {
1098
-            $columns_to_select_string = $columns_to_select;
1099
-        }
1100
-        return $columns_to_select_string;
1101
-    }
1102
-
1103
-
1104
-
1105
-    /**
1106
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
-     *
1108
-     * @return string
1109
-     * @throws EE_Error
1110
-     */
1111
-    public function primary_key_name()
1112
-    {
1113
-        return $this->get_primary_key_field()->get_name();
1114
-    }
1115
-
1116
-
1117
-    /**
1118
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
-     * If there is no primary key on this model, $id is treated as primary key string
1120
-     *
1121
-     * @param mixed $id int or string, depending on the type of the model's primary key
1122
-     * @return EE_Base_Class
1123
-     * @throws EE_Error
1124
-     */
1125
-    public function get_one_by_ID($id)
1126
-    {
1127
-        if ($this->get_from_entity_map($id)) {
1128
-            return $this->get_from_entity_map($id);
1129
-        }
1130
-        $model_object = $this->get_one(
1131
-            $this->alter_query_params_to_restrict_by_ID(
1132
-                $id,
1133
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
-            )
1135
-        );
1136
-        $className = $this->_get_class_name();
1137
-        if ($model_object instanceof $className) {
1138
-            // make sure valid objects get added to the entity map
1139
-            // so that the next call to this method doesn't trigger another trip to the db
1140
-            $this->add_to_entity_map($model_object);
1141
-        }
1142
-        return $model_object;
1143
-    }
1144
-
1145
-
1146
-
1147
-    /**
1148
-     * Alters query parameters to only get items with this ID are returned.
1149
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
-     * or could just be a simple primary key ID
1151
-     *
1152
-     * @param int   $id
1153
-     * @param array $query_params
1154
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
-     * @throws EE_Error
1156
-     */
1157
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
-    {
1159
-        if (! isset($query_params[0])) {
1160
-            $query_params[0] = array();
1161
-        }
1162
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1163
-        if ($conditions_from_id === null) {
1164
-            $query_params[0][ $this->primary_key_name() ] = $id;
1165
-        } else {
1166
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1167
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
-        }
1169
-        return $query_params;
1170
-    }
1171
-
1172
-
1173
-
1174
-    /**
1175
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
-     * array. If no item is found, null is returned.
1177
-     *
1178
-     * @param array $query_params like EEM_Base's $query_params variable.
1179
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
-     * @throws EE_Error
1181
-     */
1182
-    public function get_one($query_params = array())
1183
-    {
1184
-        if (! is_array($query_params)) {
1185
-            EE_Error::doing_it_wrong(
1186
-                'EEM_Base::get_one',
1187
-                sprintf(
1188
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
-                    gettype($query_params)
1190
-                ),
1191
-                '4.6.0'
1192
-            );
1193
-            $query_params = array();
1194
-        }
1195
-        $query_params['limit'] = 1;
1196
-        $items = $this->get_all($query_params);
1197
-        if (empty($items)) {
1198
-            return null;
1199
-        }
1200
-        return array_shift($items);
1201
-    }
1202
-
1203
-
1204
-
1205
-    /**
1206
-     * Returns the next x number of items in sequence from the given value as
1207
-     * found in the database matching the given query conditions.
1208
-     *
1209
-     * @param mixed $current_field_value    Value used for the reference point.
1210
-     * @param null  $field_to_order_by      What field is used for the
1211
-     *                                      reference point.
1212
-     * @param int   $limit                  How many to return.
1213
-     * @param array $query_params           Extra conditions on the query.
1214
-     * @param null  $columns_to_select      If left null, then an array of
1215
-     *                                      EE_Base_Class objects is returned,
1216
-     *                                      otherwise you can indicate just the
1217
-     *                                      columns you want returned.
1218
-     * @return EE_Base_Class[]|array
1219
-     * @throws EE_Error
1220
-     */
1221
-    public function next_x(
1222
-        $current_field_value,
1223
-        $field_to_order_by = null,
1224
-        $limit = 1,
1225
-        $query_params = array(),
1226
-        $columns_to_select = null
1227
-    ) {
1228
-        return $this->_get_consecutive(
1229
-            $current_field_value,
1230
-            '>',
1231
-            $field_to_order_by,
1232
-            $limit,
1233
-            $query_params,
1234
-            $columns_to_select
1235
-        );
1236
-    }
1237
-
1238
-
1239
-
1240
-    /**
1241
-     * Returns the previous x number of items in sequence from the given value
1242
-     * as found in the database matching the given query conditions.
1243
-     *
1244
-     * @param mixed $current_field_value    Value used for the reference point.
1245
-     * @param null  $field_to_order_by      What field is used for the
1246
-     *                                      reference point.
1247
-     * @param int   $limit                  How many to return.
1248
-     * @param array $query_params           Extra conditions on the query.
1249
-     * @param null  $columns_to_select      If left null, then an array of
1250
-     *                                      EE_Base_Class objects is returned,
1251
-     *                                      otherwise you can indicate just the
1252
-     *                                      columns you want returned.
1253
-     * @return EE_Base_Class[]|array
1254
-     * @throws EE_Error
1255
-     */
1256
-    public function previous_x(
1257
-        $current_field_value,
1258
-        $field_to_order_by = null,
1259
-        $limit = 1,
1260
-        $query_params = array(),
1261
-        $columns_to_select = null
1262
-    ) {
1263
-        return $this->_get_consecutive(
1264
-            $current_field_value,
1265
-            '<',
1266
-            $field_to_order_by,
1267
-            $limit,
1268
-            $query_params,
1269
-            $columns_to_select
1270
-        );
1271
-    }
1272
-
1273
-
1274
-
1275
-    /**
1276
-     * Returns the next item in sequence from the given value as found in the
1277
-     * database matching the given query conditions.
1278
-     *
1279
-     * @param mixed $current_field_value    Value used for the reference point.
1280
-     * @param null  $field_to_order_by      What field is used for the
1281
-     *                                      reference point.
1282
-     * @param array $query_params           Extra conditions on the query.
1283
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
-     *                                      object is returned, otherwise you
1285
-     *                                      can indicate just the columns you
1286
-     *                                      want and a single array indexed by
1287
-     *                                      the columns will be returned.
1288
-     * @return EE_Base_Class|null|array()
1289
-     * @throws EE_Error
1290
-     */
1291
-    public function next(
1292
-        $current_field_value,
1293
-        $field_to_order_by = null,
1294
-        $query_params = array(),
1295
-        $columns_to_select = null
1296
-    ) {
1297
-        $results = $this->_get_consecutive(
1298
-            $current_field_value,
1299
-            '>',
1300
-            $field_to_order_by,
1301
-            1,
1302
-            $query_params,
1303
-            $columns_to_select
1304
-        );
1305
-        return empty($results) ? null : reset($results);
1306
-    }
1307
-
1308
-
1309
-
1310
-    /**
1311
-     * Returns the previous item in sequence from the given value as found in
1312
-     * the database matching the given query conditions.
1313
-     *
1314
-     * @param mixed $current_field_value    Value used for the reference point.
1315
-     * @param null  $field_to_order_by      What field is used for the
1316
-     *                                      reference point.
1317
-     * @param array $query_params           Extra conditions on the query.
1318
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
-     *                                      object is returned, otherwise you
1320
-     *                                      can indicate just the columns you
1321
-     *                                      want and a single array indexed by
1322
-     *                                      the columns will be returned.
1323
-     * @return EE_Base_Class|null|array()
1324
-     * @throws EE_Error
1325
-     */
1326
-    public function previous(
1327
-        $current_field_value,
1328
-        $field_to_order_by = null,
1329
-        $query_params = array(),
1330
-        $columns_to_select = null
1331
-    ) {
1332
-        $results = $this->_get_consecutive(
1333
-            $current_field_value,
1334
-            '<',
1335
-            $field_to_order_by,
1336
-            1,
1337
-            $query_params,
1338
-            $columns_to_select
1339
-        );
1340
-        return empty($results) ? null : reset($results);
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * Returns the a consecutive number of items in sequence from the given
1347
-     * value as found in the database matching the given query conditions.
1348
-     *
1349
-     * @param mixed  $current_field_value   Value used for the reference point.
1350
-     * @param string $operand               What operand is used for the sequence.
1351
-     * @param string $field_to_order_by     What field is used for the reference point.
1352
-     * @param int    $limit                 How many to return.
1353
-     * @param array  $query_params          Extra conditions on the query.
1354
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
-     *                                      otherwise you can indicate just the columns you want returned.
1356
-     * @return EE_Base_Class[]|array
1357
-     * @throws EE_Error
1358
-     */
1359
-    protected function _get_consecutive(
1360
-        $current_field_value,
1361
-        $operand = '>',
1362
-        $field_to_order_by = null,
1363
-        $limit = 1,
1364
-        $query_params = array(),
1365
-        $columns_to_select = null
1366
-    ) {
1367
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
-        if (empty($field_to_order_by)) {
1369
-            if ($this->has_primary_key_field()) {
1370
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1371
-            } else {
1372
-                if (WP_DEBUG) {
1373
-                    throw new EE_Error(__(
1374
-                        '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).',
1375
-                        'event_espresso'
1376
-                    ));
1377
-                }
1378
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1379
-                return array();
1380
-            }
1381
-        }
1382
-        if (! is_array($query_params)) {
1383
-            EE_Error::doing_it_wrong(
1384
-                'EEM_Base::_get_consecutive',
1385
-                sprintf(
1386
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
-                    gettype($query_params)
1388
-                ),
1389
-                '4.6.0'
1390
-            );
1391
-            $query_params = array();
1392
-        }
1393
-        // let's add the where query param for consecutive look up.
1394
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
-        $query_params['limit'] = $limit;
1396
-        // set direction
1397
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
-        $query_params['order_by'] = $operand === '>'
1399
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
-        if (empty($columns_to_select)) {
1403
-            return $this->get_all($query_params);
1404
-        }
1405
-        // getting just the fields
1406
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
-    }
1408
-
1409
-
1410
-
1411
-    /**
1412
-     * This sets the _timezone property after model object has been instantiated.
1413
-     *
1414
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
-     */
1416
-    public function set_timezone($timezone)
1417
-    {
1418
-        if ($timezone !== null) {
1419
-            $this->_timezone = $timezone;
1420
-        }
1421
-        // note we need to loop through relations and set the timezone on those objects as well.
1422
-        foreach ($this->_model_relations as $relation) {
1423
-            $relation->set_timezone($timezone);
1424
-        }
1425
-        // and finally we do the same for any datetime fields
1426
-        foreach ($this->_fields as $field) {
1427
-            if ($field instanceof EE_Datetime_Field) {
1428
-                $field->set_timezone($timezone);
1429
-            }
1430
-        }
1431
-    }
1432
-
1433
-
1434
-
1435
-    /**
1436
-     * This just returns whatever is set for the current timezone.
1437
-     *
1438
-     * @access public
1439
-     * @return string
1440
-     */
1441
-    public function get_timezone()
1442
-    {
1443
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
-        if (empty($this->_timezone)) {
1445
-            foreach ($this->_fields as $field) {
1446
-                if ($field instanceof EE_Datetime_Field) {
1447
-                    $this->set_timezone($field->get_timezone());
1448
-                    break;
1449
-                }
1450
-            }
1451
-        }
1452
-        // if timezone STILL empty then return the default timezone for the site.
1453
-        if (empty($this->_timezone)) {
1454
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
-        }
1456
-        return $this->_timezone;
1457
-    }
1458
-
1459
-
1460
-
1461
-    /**
1462
-     * This returns the date formats set for the given field name and also ensures that
1463
-     * $this->_timezone property is set correctly.
1464
-     *
1465
-     * @since 4.6.x
1466
-     * @param string $field_name The name of the field the formats are being retrieved for.
1467
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
-     * @return array formats in an array with the date format first, and the time format last.
1470
-     */
1471
-    public function get_formats_for($field_name, $pretty = false)
1472
-    {
1473
-        $field_settings = $this->field_settings_for($field_name);
1474
-        // if not a valid EE_Datetime_Field then throw error
1475
-        if (! $field_settings instanceof EE_Datetime_Field) {
1476
-            throw new EE_Error(sprintf(__(
1477
-                '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.',
1478
-                'event_espresso'
1479
-            ), $field_name));
1480
-        }
1481
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
-        // the field.
1483
-        $this->_timezone = $field_settings->get_timezone();
1484
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
-    }
1486
-
1487
-
1488
-
1489
-    /**
1490
-     * This returns the current time in a format setup for a query on this model.
1491
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
-     * it will return:
1493
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
-     *  NOW
1495
-     *  - or a unix timestamp (equivalent to time())
1496
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
-     * @since 4.6.x
1500
-     * @param string $field_name       The field the current time is needed for.
1501
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
-     *                                 formatted string matching the set format for the field in the set timezone will
1503
-     *                                 be returned.
1504
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
-     *                                 exception is triggered.
1508
-     */
1509
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
-    {
1511
-        $formats = $this->get_formats_for($field_name);
1512
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
-        if ($timestamp) {
1514
-            return $DateTime->format('U');
1515
-        }
1516
-        // not returning timestamp, so return formatted string in timezone.
1517
-        switch ($what) {
1518
-            case 'time':
1519
-                return $DateTime->format($formats[1]);
1520
-                break;
1521
-            case 'date':
1522
-                return $DateTime->format($formats[0]);
1523
-                break;
1524
-            default:
1525
-                return $DateTime->format(implode(' ', $formats));
1526
-                break;
1527
-        }
1528
-    }
1529
-
1530
-
1531
-
1532
-    /**
1533
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
-     * for the model are.  Returns a DateTime object.
1535
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
-     * ignored.
1538
-     *
1539
-     * @param string $field_name      The field being setup.
1540
-     * @param string $timestring      The date time string being used.
1541
-     * @param string $incoming_format The format for the time string.
1542
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
-     *                                format is
1545
-     *                                'U', this is ignored.
1546
-     * @return DateTime
1547
-     * @throws EE_Error
1548
-     */
1549
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
-    {
1551
-        // just using this to ensure the timezone is set correctly internally
1552
-        $this->get_formats_for($field_name);
1553
-        // load EEH_DTT_Helper
1554
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
-    }
1559
-
1560
-
1561
-
1562
-    /**
1563
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
-     *
1565
-     * @return EE_Table_Base[]
1566
-     */
1567
-    public function get_tables()
1568
-    {
1569
-        return $this->_tables;
1570
-    }
1571
-
1572
-
1573
-
1574
-    /**
1575
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
-     * model object with EVT_ID = 1
1581
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
-     * are not specified)
1586
-     *
1587
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1592
-     *                                         ID=34, we'd use this method as follows:
1593
-     *                                         EEM_Transaction::instance()->update(
1594
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
-     *                                         array(array('TXN_ID'=>34)));
1596
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
-     *                                         TRUE, it is assumed that you've already called
1603
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
-     *                                         malicious javascript. However, if
1605
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
-     *                                         and every other field, before insertion. We provide this parameter
1608
-     *                                         because model objects perform their prepare_for_set function on all
1609
-     *                                         their values, and so don't need to be called again (and in many cases,
1610
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
-     *                                         prepare_for_set method...)
1612
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
-     *                                         in this model's entity map according to $fields_n_values that match
1614
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1615
-     *                                         by setting this to FALSE, but be aware that model objects being used
1616
-     *                                         could get out-of-sync with the database
1617
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
-     *                                         bad)
1620
-     * @throws EE_Error
1621
-     */
1622
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
-    {
1624
-        if (! is_array($query_params)) {
1625
-            EE_Error::doing_it_wrong(
1626
-                'EEM_Base::update',
1627
-                sprintf(
1628
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
-                    gettype($query_params)
1630
-                ),
1631
-                '4.6.0'
1632
-            );
1633
-            $query_params = array();
1634
-        }
1635
-        /**
1636
-         * Action called before a model update call has been made.
1637
-         *
1638
-         * @param EEM_Base $model
1639
-         * @param array    $fields_n_values the updated fields and their new values
1640
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
-         */
1642
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
-        /**
1644
-         * Filters the fields about to be updated given the query parameters. You can provide the
1645
-         * $query_params to $this->get_all() to find exactly which records will be updated
1646
-         *
1647
-         * @param array    $fields_n_values fields and their new values
1648
-         * @param EEM_Base $model           the model being queried
1649
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
-         */
1651
-        $fields_n_values = (array) apply_filters(
1652
-            'FHEE__EEM_Base__update__fields_n_values',
1653
-            $fields_n_values,
1654
-            $this,
1655
-            $query_params
1656
-        );
1657
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
-        // to do that, for each table, verify that it's PK isn't null.
1659
-        $tables = $this->get_tables();
1660
-        // 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
1661
-        // NOTE: we should make this code more efficient by NOT querying twice
1662
-        // before the real update, but that needs to first go through ALPHA testing
1663
-        // as it's dangerous. says Mike August 8 2014
1664
-        // we want to make sure the default_where strategy is ignored
1665
-        $this->_ignore_where_strategy = true;
1666
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
-        foreach ($wpdb_select_results as $wpdb_result) {
1668
-            // type cast stdClass as array
1669
-            $wpdb_result = (array) $wpdb_result;
1670
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
-            if ($this->has_primary_key_field()) {
1672
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
-            } else {
1674
-                // 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)
1675
-                $main_table_pk_value = null;
1676
-            }
1677
-            // 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
1678
-            // 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
1679
-            if (count($tables) > 1) {
1680
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
-                // in that table, and so we'll want to insert one
1682
-                foreach ($tables as $table_obj) {
1683
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
-                    // if there is no private key for this table on the results, it means there's no entry
1685
-                    // in this table, right? so insert a row in the current table, using any fields available
1686
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1687
-                           && $wpdb_result[ $this_table_pk_column ])
1688
-                    ) {
1689
-                        $success = $this->_insert_into_specific_table(
1690
-                            $table_obj,
1691
-                            $fields_n_values,
1692
-                            $main_table_pk_value
1693
-                        );
1694
-                        // if we died here, report the error
1695
-                        if (! $success) {
1696
-                            return false;
1697
-                        }
1698
-                    }
1699
-                }
1700
-            }
1701
-            //              //and now check that if we have cached any models by that ID on the model, that
1702
-            //              //they also get updated properly
1703
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1704
-            //              if( $model_object ){
1705
-            //                  foreach( $fields_n_values as $field => $value ){
1706
-            //                      $model_object->set($field, $value);
1707
-            // let's make sure default_where strategy is followed now
1708
-            $this->_ignore_where_strategy = false;
1709
-        }
1710
-        // if we want to keep model objects in sync, AND
1711
-        // if this wasn't called from a model object (to update itself)
1712
-        // then we want to make sure we keep all the existing
1713
-        // model objects in sync with the db
1714
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1715
-            if ($this->has_primary_key_field()) {
1716
-                $model_objs_affected_ids = $this->get_col($query_params);
1717
-            } else {
1718
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1719
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1720
-                $model_objs_affected_ids = array();
1721
-                foreach ($models_affected_key_columns as $row) {
1722
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1723
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1724
-                }
1725
-            }
1726
-            if (! $model_objs_affected_ids) {
1727
-                // wait wait wait- if nothing was affected let's stop here
1728
-                return 0;
1729
-            }
1730
-            foreach ($model_objs_affected_ids as $id) {
1731
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1732
-                if ($model_obj_in_entity_map) {
1733
-                    foreach ($fields_n_values as $field => $new_value) {
1734
-                        $model_obj_in_entity_map->set($field, $new_value);
1735
-                    }
1736
-                }
1737
-            }
1738
-            // if there is a primary key on this model, we can now do a slight optimization
1739
-            if ($this->has_primary_key_field()) {
1740
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1741
-                $query_params = array(
1742
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1743
-                    'limit'                    => count($model_objs_affected_ids),
1744
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1745
-                );
1746
-            }
1747
-        }
1748
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1749
-        $SQL = "UPDATE "
1750
-               . $model_query_info->get_full_join_sql()
1751
-               . " SET "
1752
-               . $this->_construct_update_sql($fields_n_values)
1753
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1754
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1755
-        /**
1756
-         * Action called after a model update call has been made.
1757
-         *
1758
-         * @param EEM_Base $model
1759
-         * @param array    $fields_n_values the updated fields and their new values
1760
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1761
-         * @param int      $rows_affected
1762
-         */
1763
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1764
-        return $rows_affected;// how many supposedly got updated
1765
-    }
1766
-
1767
-
1768
-
1769
-    /**
1770
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1771
-     * are teh values of the field specified (or by default the primary key field)
1772
-     * that matched the query params. Note that you should pass the name of the
1773
-     * model FIELD, not the database table's column name.
1774
-     *
1775
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1776
-     * @param string $field_to_select
1777
-     * @return array just like $wpdb->get_col()
1778
-     * @throws EE_Error
1779
-     */
1780
-    public function get_col($query_params = array(), $field_to_select = null)
1781
-    {
1782
-        if ($field_to_select) {
1783
-            $field = $this->field_settings_for($field_to_select);
1784
-        } elseif ($this->has_primary_key_field()) {
1785
-            $field = $this->get_primary_key_field();
1786
-        } else {
1787
-            // no primary key, just grab the first column
1788
-            $field = reset($this->field_settings());
1789
-        }
1790
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1791
-        $select_expressions = $field->get_qualified_column();
1792
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1793
-        return $this->_do_wpdb_query('get_col', array($SQL));
1794
-    }
1795
-
1796
-
1797
-
1798
-    /**
1799
-     * Returns a single column value for a single row from the database
1800
-     *
1801
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1802
-     * @param string $field_to_select @see EEM_Base::get_col()
1803
-     * @return string
1804
-     * @throws EE_Error
1805
-     */
1806
-    public function get_var($query_params = array(), $field_to_select = null)
1807
-    {
1808
-        $query_params['limit'] = 1;
1809
-        $col = $this->get_col($query_params, $field_to_select);
1810
-        if (! empty($col)) {
1811
-            return reset($col);
1812
-        }
1813
-        return null;
1814
-    }
1815
-
1816
-
1817
-
1818
-    /**
1819
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1820
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1821
-     * injection, but currently no further filtering is done
1822
-     *
1823
-     * @global      $wpdb
1824
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1825
-     *                               be updated to in the DB
1826
-     * @return string of SQL
1827
-     * @throws EE_Error
1828
-     */
1829
-    public function _construct_update_sql($fields_n_values)
1830
-    {
1831
-        /** @type WPDB $wpdb */
1832
-        global $wpdb;
1833
-        $cols_n_values = array();
1834
-        foreach ($fields_n_values as $field_name => $value) {
1835
-            $field_obj = $this->field_settings_for($field_name);
1836
-            // if the value is NULL, we want to assign the value to that.
1837
-            // wpdb->prepare doesn't really handle that properly
1838
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1839
-            $value_sql = $prepared_value === null ? 'NULL'
1840
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1841
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1842
-        }
1843
-        return implode(",", $cols_n_values);
1844
-    }
1845
-
1846
-
1847
-
1848
-    /**
1849
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
-     * Performs a HARD delete, meaning the database row should always be removed,
1851
-     * not just have a flag field on it switched
1852
-     * Wrapper for EEM_Base::delete_permanently()
1853
-     *
1854
-     * @param mixed $id
1855
-     * @param boolean $allow_blocking
1856
-     * @return int the number of rows deleted
1857
-     * @throws EE_Error
1858
-     */
1859
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1860
-    {
1861
-        return $this->delete_permanently(
1862
-            array(
1863
-                array($this->get_primary_key_field()->get_name() => $id),
1864
-                'limit' => 1,
1865
-            ),
1866
-            $allow_blocking
1867
-        );
1868
-    }
1869
-
1870
-
1871
-
1872
-    /**
1873
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1874
-     * Wrapper for EEM_Base::delete()
1875
-     *
1876
-     * @param mixed $id
1877
-     * @param boolean $allow_blocking
1878
-     * @return int the number of rows deleted
1879
-     * @throws EE_Error
1880
-     */
1881
-    public function delete_by_ID($id, $allow_blocking = true)
1882
-    {
1883
-        return $this->delete(
1884
-            array(
1885
-                array($this->get_primary_key_field()->get_name() => $id),
1886
-                'limit' => 1,
1887
-            ),
1888
-            $allow_blocking
1889
-        );
1890
-    }
1891
-
1892
-
1893
-
1894
-    /**
1895
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1896
-     * meaning if the model has a field that indicates its been "trashed" or
1897
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1898
-     *
1899
-     * @see EEM_Base::delete_permanently
1900
-     * @param array   $query_params
1901
-     * @param boolean $allow_blocking
1902
-     * @return int how many rows got deleted
1903
-     * @throws EE_Error
1904
-     */
1905
-    public function delete($query_params, $allow_blocking = true)
1906
-    {
1907
-        return $this->delete_permanently($query_params, $allow_blocking);
1908
-    }
1909
-
1910
-
1911
-
1912
-    /**
1913
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1914
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1915
-     * as archived, not actually deleted
1916
-     *
1917
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1918
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1919
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1920
-     *                                deletes regardless of other objects which may depend on it. Its generally
1921
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1922
-     *                                DB
1923
-     * @return int how many rows got deleted
1924
-     * @throws EE_Error
1925
-     */
1926
-    public function delete_permanently($query_params, $allow_blocking = true)
1927
-    {
1928
-        /**
1929
-         * Action called just before performing a real deletion query. You can use the
1930
-         * model and its $query_params to find exactly which items will be deleted
1931
-         *
1932
-         * @param EEM_Base $model
1933
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1934
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1935
-         *                                 to block (prevent) this deletion
1936
-         */
1937
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1938
-        // some MySQL databases may be running safe mode, which may restrict
1939
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1940
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1941
-        // to delete them
1942
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1943
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1944
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1945
-            $columns_and_ids_for_deleting
1946
-        );
1947
-        /**
1948
-         * Allows client code to act on the items being deleted before the query is actually executed.
1949
-         *
1950
-         * @param EEM_Base $this  The model instance being acted on.
1951
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1952
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1953
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1954
-         *                                                  derived from the incoming query parameters.
1955
-         *                                                  @see details on the structure of this array in the phpdocs
1956
-         *                                                  for the `_get_ids_for_delete_method`
1957
-         *
1958
-         */
1959
-        do_action(
1960
-            'AHEE__EEM_Base__delete__before_query',
1961
-            $this,
1962
-            $query_params,
1963
-            $allow_blocking,
1964
-            $columns_and_ids_for_deleting
1965
-        );
1966
-        if ($deletion_where_query_part) {
1967
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1968
-            $table_aliases = array_keys($this->_tables);
1969
-            $SQL = "DELETE "
1970
-                   . implode(", ", $table_aliases)
1971
-                   . " FROM "
1972
-                   . $model_query_info->get_full_join_sql()
1973
-                   . " WHERE "
1974
-                   . $deletion_where_query_part;
1975
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1976
-        } else {
1977
-            $rows_deleted = 0;
1978
-        }
1979
-
1980
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1981
-        // there was no error with the delete query.
1982
-        if ($this->has_primary_key_field()
1983
-            && $rows_deleted !== false
1984
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1985
-        ) {
1986
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1987
-            foreach ($ids_for_removal as $id) {
1988
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1989
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1990
-                }
1991
-            }
1992
-
1993
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1994
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1995
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1996
-            // (although it is possible).
1997
-            // Note this can be skipped by using the provided filter and returning false.
1998
-            if (apply_filters(
1999
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2000
-                ! $this instanceof EEM_Extra_Meta,
2001
-                $this
2002
-            )) {
2003
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2004
-                    0 => array(
2005
-                        'EXM_type' => $this->get_this_model_name(),
2006
-                        'OBJ_ID'   => array(
2007
-                            'IN',
2008
-                            $ids_for_removal
2009
-                        )
2010
-                    )
2011
-                ));
2012
-            }
2013
-        }
2014
-
2015
-        /**
2016
-         * Action called just after performing a real deletion query. Although at this point the
2017
-         * items should have been deleted
2018
-         *
2019
-         * @param EEM_Base $model
2020
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
-         * @param int      $rows_deleted
2022
-         */
2023
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2024
-        return $rows_deleted;// how many supposedly got deleted
2025
-    }
2026
-
2027
-
2028
-
2029
-    /**
2030
-     * Checks all the relations that throw error messages when there are blocking related objects
2031
-     * for related model objects. If there are any related model objects on those relations,
2032
-     * adds an EE_Error, and return true
2033
-     *
2034
-     * @param EE_Base_Class|int $this_model_obj_or_id
2035
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2036
-     *                                                 should be ignored when determining whether there are related
2037
-     *                                                 model objects which block this model object's deletion. Useful
2038
-     *                                                 if you know A is related to B and are considering deleting A,
2039
-     *                                                 but want to see if A has any other objects blocking its deletion
2040
-     *                                                 before removing the relation between A and B
2041
-     * @return boolean
2042
-     * @throws EE_Error
2043
-     */
2044
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2045
-    {
2046
-        // first, if $ignore_this_model_obj was supplied, get its model
2047
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2048
-            $ignored_model = $ignore_this_model_obj->get_model();
2049
-        } else {
2050
-            $ignored_model = null;
2051
-        }
2052
-        // now check all the relations of $this_model_obj_or_id and see if there
2053
-        // are any related model objects blocking it?
2054
-        $is_blocked = false;
2055
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2056
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2057
-                // if $ignore_this_model_obj was supplied, then for the query
2058
-                // on that model needs to be told to ignore $ignore_this_model_obj
2059
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2060
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2061
-                        array(
2062
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2063
-                                '!=',
2064
-                                $ignore_this_model_obj->ID(),
2065
-                            ),
2066
-                        ),
2067
-                    ));
2068
-                } else {
2069
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2070
-                }
2071
-                if ($related_model_objects) {
2072
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2073
-                    $is_blocked = true;
2074
-                }
2075
-            }
2076
-        }
2077
-        return $is_blocked;
2078
-    }
2079
-
2080
-
2081
-    /**
2082
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2083
-     * @param array $row_results_for_deleting
2084
-     * @param bool  $allow_blocking
2085
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2086
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2087
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2088
-     *                 deleted. Example:
2089
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2090
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2091
-     *                 where each element is a group of columns and values that get deleted. Example:
2092
-     *                      array(
2093
-     *                          0 => array(
2094
-     *                              'Term_Relationship.object_id' => 1
2095
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2096
-     *                          ),
2097
-     *                          1 => array(
2098
-     *                              'Term_Relationship.object_id' => 1
2099
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2100
-     *                          )
2101
-     *                      )
2102
-     * @throws EE_Error
2103
-     */
2104
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2105
-    {
2106
-        $ids_to_delete_indexed_by_column = array();
2107
-        if ($this->has_primary_key_field()) {
2108
-            $primary_table = $this->_get_main_table();
2109
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2110
-            $other_tables = $this->_get_other_tables();
2111
-            $ids_to_delete_indexed_by_column = $query = array();
2112
-            foreach ($row_results_for_deleting as $item_to_delete) {
2113
-                // before we mark this item for deletion,
2114
-                // make sure there's no related entities blocking its deletion (if we're checking)
2115
-                if ($allow_blocking
2116
-                    && $this->delete_is_blocked_by_related_models(
2117
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2118
-                    )
2119
-                ) {
2120
-                    continue;
2121
-                }
2122
-                // primary table deletes
2123
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2124
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2125
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2126
-                }
2127
-            }
2128
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2129
-            $fields = $this->get_combined_primary_key_fields();
2130
-            foreach ($row_results_for_deleting as $item_to_delete) {
2131
-                $ids_to_delete_indexed_by_column_for_row = array();
2132
-                foreach ($fields as $cpk_field) {
2133
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2134
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2135
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2136
-                    }
2137
-                }
2138
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2139
-            }
2140
-        } else {
2141
-            // so there's no primary key and no combined key...
2142
-            // sorry, can't help you
2143
-            throw new EE_Error(
2144
-                sprintf(
2145
-                    __(
2146
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2147
-                        "event_espresso"
2148
-                    ),
2149
-                    get_class($this)
2150
-                )
2151
-            );
2152
-        }
2153
-        return $ids_to_delete_indexed_by_column;
2154
-    }
2155
-
2156
-
2157
-    /**
2158
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2159
-     * the corresponding query_part for the query performing the delete.
2160
-     *
2161
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2162
-     * @return string
2163
-     * @throws EE_Error
2164
-     */
2165
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2166
-    {
2167
-        $query_part = '';
2168
-        if (empty($ids_to_delete_indexed_by_column)) {
2169
-            return $query_part;
2170
-        } elseif ($this->has_primary_key_field()) {
2171
-            $query = array();
2172
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2173
-                $query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2174
-            }
2175
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2176
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2177
-            $ways_to_identify_a_row = array();
2178
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2179
-                $values_for_each_combined_primary_key_for_a_row = array();
2180
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2181
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2182
-                }
2183
-                $ways_to_identify_a_row[] = '('
2184
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2185
-                                            . ')';
2186
-            }
2187
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2188
-        }
2189
-        return $query_part;
2190
-    }
2191
-
2192
-
2193
-
2194
-    /**
2195
-     * Gets the model field by the fully qualified name
2196
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2197
-     * @return EE_Model_Field_Base
2198
-     */
2199
-    public function get_field_by_column($qualified_column_name)
2200
-    {
2201
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2202
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2203
-                return $field_obj;
2204
-            }
2205
-        }
2206
-        throw new EE_Error(
2207
-            sprintf(
2208
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2209
-                $this->get_this_model_name(),
2210
-                $qualified_column_name
2211
-            )
2212
-        );
2213
-    }
2214
-
2215
-
2216
-
2217
-    /**
2218
-     * Count all the rows that match criteria the model query params.
2219
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2220
-     * column
2221
-     *
2222
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2223
-     * @param string $field_to_count field on model to count by (not column name)
2224
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2225
-     *                               that by the setting $distinct to TRUE;
2226
-     * @return int
2227
-     * @throws EE_Error
2228
-     */
2229
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2230
-    {
2231
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2232
-        if ($field_to_count) {
2233
-            $field_obj = $this->field_settings_for($field_to_count);
2234
-            $column_to_count = $field_obj->get_qualified_column();
2235
-        } elseif ($this->has_primary_key_field()) {
2236
-            $pk_field_obj = $this->get_primary_key_field();
2237
-            $column_to_count = $pk_field_obj->get_qualified_column();
2238
-        } else {
2239
-            // there's no primary key
2240
-            // if we're counting distinct items, and there's no primary key,
2241
-            // we need to list out the columns for distinction;
2242
-            // otherwise we can just use star
2243
-            if ($distinct) {
2244
-                $columns_to_use = array();
2245
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2246
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2247
-                }
2248
-                $column_to_count = implode(',', $columns_to_use);
2249
-            } else {
2250
-                $column_to_count = '*';
2251
-            }
2252
-        }
2253
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2254
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2255
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2256
-    }
2257
-
2258
-
2259
-
2260
-    /**
2261
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2262
-     *
2263
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2264
-     * @param string $field_to_sum name of field (array key in $_fields array)
2265
-     * @return float
2266
-     * @throws EE_Error
2267
-     */
2268
-    public function sum($query_params, $field_to_sum = null)
2269
-    {
2270
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2271
-        if ($field_to_sum) {
2272
-            $field_obj = $this->field_settings_for($field_to_sum);
2273
-        } else {
2274
-            $field_obj = $this->get_primary_key_field();
2275
-        }
2276
-        $column_to_count = $field_obj->get_qualified_column();
2277
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2278
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2279
-        $data_type = $field_obj->get_wpdb_data_type();
2280
-        if ($data_type === '%d' || $data_type === '%s') {
2281
-            return (float) $return_value;
2282
-        }
2283
-        // must be %f
2284
-        return (float) $return_value;
2285
-    }
2286
-
2287
-
2288
-
2289
-    /**
2290
-     * Just calls the specified method on $wpdb with the given arguments
2291
-     * Consolidates a little extra error handling code
2292
-     *
2293
-     * @param string $wpdb_method
2294
-     * @param array  $arguments_to_provide
2295
-     * @throws EE_Error
2296
-     * @global wpdb  $wpdb
2297
-     * @return mixed
2298
-     */
2299
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2300
-    {
2301
-        // if we're in maintenance mode level 2, DON'T run any queries
2302
-        // because level 2 indicates the database needs updating and
2303
-        // is probably out of sync with the code
2304
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2305
-            throw new EE_Error(sprintf(__(
2306
-                "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.",
2307
-                "event_espresso"
2308
-            )));
2309
-        }
2310
-        /** @type WPDB $wpdb */
2311
-        global $wpdb;
2312
-        if (! method_exists($wpdb, $wpdb_method)) {
2313
-            throw new EE_Error(sprintf(__(
2314
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2315
-                'event_espresso'
2316
-            ), $wpdb_method));
2317
-        }
2318
-        if (WP_DEBUG) {
2319
-            $old_show_errors_value = $wpdb->show_errors;
2320
-            $wpdb->show_errors(false);
2321
-        }
2322
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2323
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2324
-        if (WP_DEBUG) {
2325
-            $wpdb->show_errors($old_show_errors_value);
2326
-            if (! empty($wpdb->last_error)) {
2327
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2328
-            }
2329
-            if ($result === false) {
2330
-                throw new EE_Error(sprintf(__(
2331
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2332
-                    'event_espresso'
2333
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2334
-            }
2335
-        } elseif ($result === false) {
2336
-            EE_Error::add_error(
2337
-                sprintf(
2338
-                    __(
2339
-                        '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"',
2340
-                        'event_espresso'
2341
-                    ),
2342
-                    $wpdb_method,
2343
-                    var_export($arguments_to_provide, true),
2344
-                    $wpdb->last_error
2345
-                ),
2346
-                __FILE__,
2347
-                __FUNCTION__,
2348
-                __LINE__
2349
-            );
2350
-        }
2351
-        return $result;
2352
-    }
2353
-
2354
-
2355
-
2356
-    /**
2357
-     * Attempts to run the indicated WPDB method with the provided arguments,
2358
-     * and if there's an error tries to verify the DB is correct. Uses
2359
-     * the static property EEM_Base::$_db_verification_level to determine whether
2360
-     * we should try to fix the EE core db, the addons, or just give up
2361
-     *
2362
-     * @param string $wpdb_method
2363
-     * @param array  $arguments_to_provide
2364
-     * @return mixed
2365
-     */
2366
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2367
-    {
2368
-        /** @type WPDB $wpdb */
2369
-        global $wpdb;
2370
-        $wpdb->last_error = null;
2371
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2372
-        // was there an error running the query? but we don't care on new activations
2373
-        // (we're going to setup the DB anyway on new activations)
2374
-        if (($result === false || ! empty($wpdb->last_error))
2375
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2376
-        ) {
2377
-            switch (EEM_Base::$_db_verification_level) {
2378
-                case EEM_Base::db_verified_none:
2379
-                    // let's double-check core's DB
2380
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2381
-                    break;
2382
-                case EEM_Base::db_verified_core:
2383
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2384
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2385
-                    break;
2386
-                case EEM_Base::db_verified_addons:
2387
-                    // ummmm... you in trouble
2388
-                    return $result;
2389
-                    break;
2390
-            }
2391
-            if (! empty($error_message)) {
2392
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2393
-                trigger_error($error_message);
2394
-            }
2395
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
-        }
2397
-        return $result;
2398
-    }
2399
-
2400
-
2401
-
2402
-    /**
2403
-     * Verifies the EE core database is up-to-date and records that we've done it on
2404
-     * EEM_Base::$_db_verification_level
2405
-     *
2406
-     * @param string $wpdb_method
2407
-     * @param array  $arguments_to_provide
2408
-     * @return string
2409
-     */
2410
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2411
-    {
2412
-        /** @type WPDB $wpdb */
2413
-        global $wpdb;
2414
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2415
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2416
-        $error_message = sprintf(
2417
-            __(
2418
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2419
-                'event_espresso'
2420
-            ),
2421
-            $wpdb->last_error,
2422
-            $wpdb_method,
2423
-            wp_json_encode($arguments_to_provide)
2424
-        );
2425
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2426
-        return $error_message;
2427
-    }
2428
-
2429
-
2430
-
2431
-    /**
2432
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2433
-     * EEM_Base::$_db_verification_level
2434
-     *
2435
-     * @param $wpdb_method
2436
-     * @param $arguments_to_provide
2437
-     * @return string
2438
-     */
2439
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2440
-    {
2441
-        /** @type WPDB $wpdb */
2442
-        global $wpdb;
2443
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2444
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2445
-        $error_message = sprintf(
2446
-            __(
2447
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2448
-                'event_espresso'
2449
-            ),
2450
-            $wpdb->last_error,
2451
-            $wpdb_method,
2452
-            wp_json_encode($arguments_to_provide)
2453
-        );
2454
-        EE_System::instance()->initialize_addons();
2455
-        return $error_message;
2456
-    }
2457
-
2458
-
2459
-
2460
-    /**
2461
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2462
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2463
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2464
-     * ..."
2465
-     *
2466
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2467
-     * @return string
2468
-     */
2469
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2470
-    {
2471
-        return " FROM " . $model_query_info->get_full_join_sql() .
2472
-               $model_query_info->get_where_sql() .
2473
-               $model_query_info->get_group_by_sql() .
2474
-               $model_query_info->get_having_sql() .
2475
-               $model_query_info->get_order_by_sql() .
2476
-               $model_query_info->get_limit_sql();
2477
-    }
2478
-
2479
-
2480
-
2481
-    /**
2482
-     * Set to easily debug the next X queries ran from this model.
2483
-     *
2484
-     * @param int $count
2485
-     */
2486
-    public function show_next_x_db_queries($count = 1)
2487
-    {
2488
-        $this->_show_next_x_db_queries = $count;
2489
-    }
2490
-
2491
-
2492
-
2493
-    /**
2494
-     * @param $sql_query
2495
-     */
2496
-    public function show_db_query_if_previously_requested($sql_query)
2497
-    {
2498
-        if ($this->_show_next_x_db_queries > 0) {
2499
-            echo $sql_query;
2500
-            $this->_show_next_x_db_queries--;
2501
-        }
2502
-    }
2503
-
2504
-
2505
-
2506
-    /**
2507
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2508
-     * There are the 3 cases:
2509
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2510
-     * $otherModelObject has no ID, it is first saved.
2511
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2512
-     * has no ID, it is first saved.
2513
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2514
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2515
-     * join table
2516
-     *
2517
-     * @param        EE_Base_Class                     /int $thisModelObject
2518
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2519
-     * @param string $relationName                     , key in EEM_Base::_relations
2520
-     *                                                 an attendee to a group, you also want to specify which role they
2521
-     *                                                 will have in that group. So you would use this parameter to
2522
-     *                                                 specify array('role-column-name'=>'role-id')
2523
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2524
-     *                                                 to for relation to methods that allow you to further specify
2525
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2526
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2527
-     *                                                 because these will be inserted in any new rows created as well.
2528
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2529
-     * @throws EE_Error
2530
-     */
2531
-    public function add_relationship_to(
2532
-        $id_or_obj,
2533
-        $other_model_id_or_obj,
2534
-        $relationName,
2535
-        $extra_join_model_fields_n_values = array()
2536
-    ) {
2537
-        $relation_obj = $this->related_settings_for($relationName);
2538
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2539
-    }
2540
-
2541
-
2542
-
2543
-    /**
2544
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2545
-     * There are the 3 cases:
2546
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2547
-     * error
2548
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2549
-     * an error
2550
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2551
-     *
2552
-     * @param        EE_Base_Class /int $id_or_obj
2553
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2554
-     * @param string $relationName key in EEM_Base::_relations
2555
-     * @return boolean of success
2556
-     * @throws EE_Error
2557
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2558
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2559
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2560
-     *                             because these will be inserted in any new rows created as well.
2561
-     */
2562
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2563
-    {
2564
-        $relation_obj = $this->related_settings_for($relationName);
2565
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2566
-    }
2567
-
2568
-
2569
-
2570
-    /**
2571
-     * @param mixed           $id_or_obj
2572
-     * @param string          $relationName
2573
-     * @param array           $where_query_params
2574
-     * @param EE_Base_Class[] objects to which relations were removed
2575
-     * @return \EE_Base_Class[]
2576
-     * @throws EE_Error
2577
-     */
2578
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2579
-    {
2580
-        $relation_obj = $this->related_settings_for($relationName);
2581
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2582
-    }
2583
-
2584
-
2585
-
2586
-    /**
2587
-     * Gets all the related items of the specified $model_name, using $query_params.
2588
-     * Note: by default, we remove the "default query params"
2589
-     * because we want to get even deleted items etc.
2590
-     *
2591
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2592
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2593
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2594
-     * @return EE_Base_Class[]
2595
-     * @throws EE_Error
2596
-     */
2597
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2598
-    {
2599
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2600
-        $relation_settings = $this->related_settings_for($model_name);
2601
-        return $relation_settings->get_all_related($model_obj, $query_params);
2602
-    }
2603
-
2604
-
2605
-
2606
-    /**
2607
-     * Deletes all the model objects across the relation indicated by $model_name
2608
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2609
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2610
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2611
-     *
2612
-     * @param EE_Base_Class|int|string $id_or_obj
2613
-     * @param string                   $model_name
2614
-     * @param array                    $query_params
2615
-     * @return int how many deleted
2616
-     * @throws EE_Error
2617
-     */
2618
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2619
-    {
2620
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2621
-        $relation_settings = $this->related_settings_for($model_name);
2622
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2623
-    }
2624
-
2625
-
2626
-
2627
-    /**
2628
-     * Hard deletes all the model objects across the relation indicated by $model_name
2629
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2630
-     * the model objects can't be hard deleted because of blocking related model objects,
2631
-     * just does a soft-delete on them instead.
2632
-     *
2633
-     * @param EE_Base_Class|int|string $id_or_obj
2634
-     * @param string                   $model_name
2635
-     * @param array                    $query_params
2636
-     * @return int how many deleted
2637
-     * @throws EE_Error
2638
-     */
2639
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2640
-    {
2641
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2642
-        $relation_settings = $this->related_settings_for($model_name);
2643
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2644
-    }
2645
-
2646
-
2647
-
2648
-    /**
2649
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2650
-     * unless otherwise specified in the $query_params
2651
-     *
2652
-     * @param        int             /EE_Base_Class $id_or_obj
2653
-     * @param string $model_name     like 'Event', or 'Registration'
2654
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2655
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2656
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2657
-     *                               that by the setting $distinct to TRUE;
2658
-     * @return int
2659
-     * @throws EE_Error
2660
-     */
2661
-    public function count_related(
2662
-        $id_or_obj,
2663
-        $model_name,
2664
-        $query_params = array(),
2665
-        $field_to_count = null,
2666
-        $distinct = false
2667
-    ) {
2668
-        $related_model = $this->get_related_model_obj($model_name);
2669
-        // we're just going to use the query params on the related model's normal get_all query,
2670
-        // except add a condition to say to match the current mod
2671
-        if (! isset($query_params['default_where_conditions'])) {
2672
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2673
-        }
2674
-        $this_model_name = $this->get_this_model_name();
2675
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2676
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2677
-        return $related_model->count($query_params, $field_to_count, $distinct);
2678
-    }
2679
-
2680
-
2681
-
2682
-    /**
2683
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2684
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2685
-     *
2686
-     * @param        int           /EE_Base_Class $id_or_obj
2687
-     * @param string $model_name   like 'Event', or 'Registration'
2688
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2689
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2690
-     * @return float
2691
-     * @throws EE_Error
2692
-     */
2693
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2694
-    {
2695
-        $related_model = $this->get_related_model_obj($model_name);
2696
-        if (! is_array($query_params)) {
2697
-            EE_Error::doing_it_wrong(
2698
-                'EEM_Base::sum_related',
2699
-                sprintf(
2700
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2701
-                    gettype($query_params)
2702
-                ),
2703
-                '4.6.0'
2704
-            );
2705
-            $query_params = array();
2706
-        }
2707
-        // we're just going to use the query params on the related model's normal get_all query,
2708
-        // except add a condition to say to match the current mod
2709
-        if (! isset($query_params['default_where_conditions'])) {
2710
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2711
-        }
2712
-        $this_model_name = $this->get_this_model_name();
2713
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2714
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2715
-        return $related_model->sum($query_params, $field_to_sum);
2716
-    }
2717
-
2718
-
2719
-
2720
-    /**
2721
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2722
-     * $modelObject
2723
-     *
2724
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2725
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2726
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2727
-     * @return EE_Base_Class
2728
-     * @throws EE_Error
2729
-     */
2730
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2731
-    {
2732
-        $query_params['limit'] = 1;
2733
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2734
-        if ($results) {
2735
-            return array_shift($results);
2736
-        }
2737
-        return null;
2738
-    }
2739
-
2740
-
2741
-
2742
-    /**
2743
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2744
-     *
2745
-     * @return string
2746
-     */
2747
-    public function get_this_model_name()
2748
-    {
2749
-        return str_replace("EEM_", "", get_class($this));
2750
-    }
2751
-
2752
-
2753
-
2754
-    /**
2755
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2756
-     *
2757
-     * @return EE_Any_Foreign_Model_Name_Field
2758
-     * @throws EE_Error
2759
-     */
2760
-    public function get_field_containing_related_model_name()
2761
-    {
2762
-        foreach ($this->field_settings(true) as $field) {
2763
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2764
-                $field_with_model_name = $field;
2765
-            }
2766
-        }
2767
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2768
-            throw new EE_Error(sprintf(
2769
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770
-                $this->get_this_model_name()
2771
-            ));
2772
-        }
2773
-        return $field_with_model_name;
2774
-    }
2775
-
2776
-
2777
-
2778
-    /**
2779
-     * Inserts a new entry into the database, for each table.
2780
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2781
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2782
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2783
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2784
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2785
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2786
-     *
2787
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2788
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2789
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2790
-     *                              of EEM_Base)
2791
-     * @return int|string new primary key on main table that got inserted
2792
-     * @throws EE_Error
2793
-     */
2794
-    public function insert($field_n_values)
2795
-    {
2796
-        /**
2797
-         * Filters the fields and their values before inserting an item using the models
2798
-         *
2799
-         * @param array    $fields_n_values keys are the fields and values are their new values
2800
-         * @param EEM_Base $model           the model used
2801
-         */
2802
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2803
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2804
-            $main_table = $this->_get_main_table();
2805
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2806
-            if ($new_id !== false) {
2807
-                foreach ($this->_get_other_tables() as $other_table) {
2808
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2809
-                }
2810
-            }
2811
-            /**
2812
-             * Done just after attempting to insert a new model object
2813
-             *
2814
-             * @param EEM_Base   $model           used
2815
-             * @param array      $fields_n_values fields and their values
2816
-             * @param int|string the              ID of the newly-inserted model object
2817
-             */
2818
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2819
-            return $new_id;
2820
-        }
2821
-        return false;
2822
-    }
2823
-
2824
-
2825
-
2826
-    /**
2827
-     * Checks that the result would satisfy the unique indexes on this model
2828
-     *
2829
-     * @param array  $field_n_values
2830
-     * @param string $action
2831
-     * @return boolean
2832
-     * @throws EE_Error
2833
-     */
2834
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2835
-    {
2836
-        foreach ($this->unique_indexes() as $index_name => $index) {
2837
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2838
-            if ($this->exists(array($uniqueness_where_params))) {
2839
-                EE_Error::add_error(
2840
-                    sprintf(
2841
-                        __(
2842
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2843
-                            "event_espresso"
2844
-                        ),
2845
-                        $action,
2846
-                        $this->_get_class_name(),
2847
-                        $index_name,
2848
-                        implode(",", $index->field_names()),
2849
-                        http_build_query($uniqueness_where_params)
2850
-                    ),
2851
-                    __FILE__,
2852
-                    __FUNCTION__,
2853
-                    __LINE__
2854
-                );
2855
-                return false;
2856
-            }
2857
-        }
2858
-        return true;
2859
-    }
2860
-
2861
-
2862
-
2863
-    /**
2864
-     * Checks the database for an item that conflicts (ie, if this item were
2865
-     * saved to the DB would break some uniqueness requirement, like a primary key
2866
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2867
-     * can be either an EE_Base_Class or an array of fields n values
2868
-     *
2869
-     * @param EE_Base_Class|array $obj_or_fields_array
2870
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2871
-     *                                                 when looking for conflicts
2872
-     *                                                 (ie, if false, we ignore the model object's primary key
2873
-     *                                                 when finding "conflicts". If true, it's also considered).
2874
-     *                                                 Only works for INT primary key,
2875
-     *                                                 STRING primary keys cannot be ignored
2876
-     * @throws EE_Error
2877
-     * @return EE_Base_Class|array
2878
-     */
2879
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2880
-    {
2881
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2882
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2883
-        } elseif (is_array($obj_or_fields_array)) {
2884
-            $fields_n_values = $obj_or_fields_array;
2885
-        } else {
2886
-            throw new EE_Error(
2887
-                sprintf(
2888
-                    __(
2889
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2890
-                        "event_espresso"
2891
-                    ),
2892
-                    get_class($this),
2893
-                    $obj_or_fields_array
2894
-                )
2895
-            );
2896
-        }
2897
-        $query_params = array();
2898
-        if ($this->has_primary_key_field()
2899
-            && ($include_primary_key
2900
-                || $this->get_primary_key_field()
2901
-                   instanceof
2902
-                   EE_Primary_Key_String_Field)
2903
-            && isset($fields_n_values[ $this->primary_key_name() ])
2904
-        ) {
2905
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2906
-        }
2907
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2908
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2909
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2910
-        }
2911
-        // if there is nothing to base this search on, then we shouldn't find anything
2912
-        if (empty($query_params)) {
2913
-            return array();
2914
-        }
2915
-        return $this->get_one($query_params);
2916
-    }
2917
-
2918
-
2919
-
2920
-    /**
2921
-     * Like count, but is optimized and returns a boolean instead of an int
2922
-     *
2923
-     * @param array $query_params
2924
-     * @return boolean
2925
-     * @throws EE_Error
2926
-     */
2927
-    public function exists($query_params)
2928
-    {
2929
-        $query_params['limit'] = 1;
2930
-        return $this->count($query_params) > 0;
2931
-    }
2932
-
2933
-
2934
-
2935
-    /**
2936
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2937
-     *
2938
-     * @param int|string $id
2939
-     * @return boolean
2940
-     * @throws EE_Error
2941
-     */
2942
-    public function exists_by_ID($id)
2943
-    {
2944
-        return $this->exists(
2945
-            array(
2946
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2947
-                array(
2948
-                    $this->primary_key_name() => $id,
2949
-                ),
2950
-            )
2951
-        );
2952
-    }
2953
-
2954
-
2955
-
2956
-    /**
2957
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2958
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2959
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2960
-     * on the main table)
2961
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2962
-     * cases where we want to call it directly rather than via insert().
2963
-     *
2964
-     * @access   protected
2965
-     * @param EE_Table_Base $table
2966
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2967
-     *                                       float
2968
-     * @param int           $new_id          for now we assume only int keys
2969
-     * @throws EE_Error
2970
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2971
-     * @return int ID of new row inserted, or FALSE on failure
2972
-     */
2973
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2974
-    {
2975
-        global $wpdb;
2976
-        $insertion_col_n_values = array();
2977
-        $format_for_insertion = array();
2978
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2979
-        foreach ($fields_on_table as $field_name => $field_obj) {
2980
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2981
-            if ($field_obj->is_auto_increment()) {
2982
-                continue;
2983
-            }
2984
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2985
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2986
-            if ($prepared_value !== null) {
2987
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2988
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2989
-            }
2990
-        }
2991
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2992
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2993
-            // so add the fk to the main table as a column
2994
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2995
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2996
-        }
2997
-        // insert the new entry
2998
-        $result = $this->_do_wpdb_query(
2999
-            'insert',
3000
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3001
-        );
3002
-        if ($result === false) {
3003
-            return false;
3004
-        }
3005
-        // ok, now what do we return for the ID of the newly-inserted thing?
3006
-        if ($this->has_primary_key_field()) {
3007
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3008
-                return $wpdb->insert_id;
3009
-            }
3010
-            // it's not an auto-increment primary key, so
3011
-            // it must have been supplied
3012
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3013
-        }
3014
-        // we can't return a  primary key because there is none. instead return
3015
-        // a unique string indicating this model
3016
-        return $this->get_index_primary_key_string($fields_n_values);
3017
-    }
3018
-
3019
-
3020
-
3021
-    /**
3022
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3023
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3024
-     * and there is no default, we pass it along. WPDB will take care of it)
3025
-     *
3026
-     * @param EE_Model_Field_Base $field_obj
3027
-     * @param array               $fields_n_values
3028
-     * @return mixed string|int|float depending on what the table column will be expecting
3029
-     * @throws EE_Error
3030
-     */
3031
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3032
-    {
3033
-        // if this field doesn't allow nullable, don't allow it
3034
-        if (! $field_obj->is_nullable()
3035
-            && (
3036
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3037
-                || $fields_n_values[ $field_obj->get_name() ] === null
3038
-            )
3039
-        ) {
3040
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3041
-        }
3042
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3043
-            ? $fields_n_values[ $field_obj->get_name() ]
3044
-            : null;
3045
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3046
-    }
3047
-
3048
-
3049
-
3050
-    /**
3051
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3052
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3053
-     * the field's prepare_for_set() method.
3054
-     *
3055
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3056
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3057
-     *                                   top of file)
3058
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3059
-     *                                   $value is a custom selection
3060
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3061
-     */
3062
-    private function _prepare_value_for_use_in_db($value, $field)
3063
-    {
3064
-        if ($field && $field instanceof EE_Model_Field_Base) {
3065
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3066
-            switch ($this->_values_already_prepared_by_model_object) {
3067
-                /** @noinspection PhpMissingBreakStatementInspection */
3068
-                case self::not_prepared_by_model_object:
3069
-                    $value = $field->prepare_for_set($value);
3070
-                // purposefully left out "return"
3071
-                case self::prepared_by_model_object:
3072
-                    /** @noinspection SuspiciousAssignmentsInspection */
3073
-                    $value = $field->prepare_for_use_in_db($value);
3074
-                case self::prepared_for_use_in_db:
3075
-                    // leave the value alone
3076
-            }
3077
-            return $value;
3078
-            // phpcs:enable
3079
-        }
3080
-        return $value;
3081
-    }
3082
-
3083
-
3084
-
3085
-    /**
3086
-     * Returns the main table on this model
3087
-     *
3088
-     * @return EE_Primary_Table
3089
-     * @throws EE_Error
3090
-     */
3091
-    protected function _get_main_table()
3092
-    {
3093
-        foreach ($this->_tables as $table) {
3094
-            if ($table instanceof EE_Primary_Table) {
3095
-                return $table;
3096
-            }
3097
-        }
3098
-        throw new EE_Error(sprintf(__(
3099
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3100
-            'event_espresso'
3101
-        ), get_class($this)));
3102
-    }
3103
-
3104
-
3105
-
3106
-    /**
3107
-     * table
3108
-     * returns EE_Primary_Table table name
3109
-     *
3110
-     * @return string
3111
-     * @throws EE_Error
3112
-     */
3113
-    public function table()
3114
-    {
3115
-        return $this->_get_main_table()->get_table_name();
3116
-    }
3117
-
3118
-
3119
-
3120
-    /**
3121
-     * table
3122
-     * returns first EE_Secondary_Table table name
3123
-     *
3124
-     * @return string
3125
-     */
3126
-    public function second_table()
3127
-    {
3128
-        // grab second table from tables array
3129
-        $second_table = end($this->_tables);
3130
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3131
-    }
3132
-
3133
-
3134
-
3135
-    /**
3136
-     * get_table_obj_by_alias
3137
-     * returns table name given it's alias
3138
-     *
3139
-     * @param string $table_alias
3140
-     * @return EE_Primary_Table | EE_Secondary_Table
3141
-     */
3142
-    public function get_table_obj_by_alias($table_alias = '')
3143
-    {
3144
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3145
-    }
3146
-
3147
-
3148
-
3149
-    /**
3150
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3151
-     *
3152
-     * @return EE_Secondary_Table[]
3153
-     */
3154
-    protected function _get_other_tables()
3155
-    {
3156
-        $other_tables = array();
3157
-        foreach ($this->_tables as $table_alias => $table) {
3158
-            if ($table instanceof EE_Secondary_Table) {
3159
-                $other_tables[ $table_alias ] = $table;
3160
-            }
3161
-        }
3162
-        return $other_tables;
3163
-    }
3164
-
3165
-
3166
-
3167
-    /**
3168
-     * Finds all the fields that correspond to the given table
3169
-     *
3170
-     * @param string $table_alias , array key in EEM_Base::_tables
3171
-     * @return EE_Model_Field_Base[]
3172
-     */
3173
-    public function _get_fields_for_table($table_alias)
3174
-    {
3175
-        return $this->_fields[ $table_alias ];
3176
-    }
3177
-
3178
-
3179
-
3180
-    /**
3181
-     * Recurses through all the where parameters, and finds all the related models we'll need
3182
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3183
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3184
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3185
-     * related Registration, Transaction, and Payment models.
3186
-     *
3187
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3188
-     * @return EE_Model_Query_Info_Carrier
3189
-     * @throws EE_Error
3190
-     */
3191
-    public function _extract_related_models_from_query($query_params)
3192
-    {
3193
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3194
-        if (array_key_exists(0, $query_params)) {
3195
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3196
-        }
3197
-        if (array_key_exists('group_by', $query_params)) {
3198
-            if (is_array($query_params['group_by'])) {
3199
-                $this->_extract_related_models_from_sub_params_array_values(
3200
-                    $query_params['group_by'],
3201
-                    $query_info_carrier,
3202
-                    'group_by'
3203
-                );
3204
-            } elseif (! empty($query_params['group_by'])) {
3205
-                $this->_extract_related_model_info_from_query_param(
3206
-                    $query_params['group_by'],
3207
-                    $query_info_carrier,
3208
-                    'group_by'
3209
-                );
3210
-            }
3211
-        }
3212
-        if (array_key_exists('having', $query_params)) {
3213
-            $this->_extract_related_models_from_sub_params_array_keys(
3214
-                $query_params[0],
3215
-                $query_info_carrier,
3216
-                'having'
3217
-            );
3218
-        }
3219
-        if (array_key_exists('order_by', $query_params)) {
3220
-            if (is_array($query_params['order_by'])) {
3221
-                $this->_extract_related_models_from_sub_params_array_keys(
3222
-                    $query_params['order_by'],
3223
-                    $query_info_carrier,
3224
-                    'order_by'
3225
-                );
3226
-            } elseif (! empty($query_params['order_by'])) {
3227
-                $this->_extract_related_model_info_from_query_param(
3228
-                    $query_params['order_by'],
3229
-                    $query_info_carrier,
3230
-                    'order_by'
3231
-                );
3232
-            }
3233
-        }
3234
-        if (array_key_exists('force_join', $query_params)) {
3235
-            $this->_extract_related_models_from_sub_params_array_values(
3236
-                $query_params['force_join'],
3237
-                $query_info_carrier,
3238
-                'force_join'
3239
-            );
3240
-        }
3241
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3242
-        return $query_info_carrier;
3243
-    }
3244
-
3245
-
3246
-
3247
-    /**
3248
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3249
-     *
3250
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3251
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3252
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3253
-     * @throws EE_Error
3254
-     * @return \EE_Model_Query_Info_Carrier
3255
-     */
3256
-    private function _extract_related_models_from_sub_params_array_keys(
3257
-        $sub_query_params,
3258
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3259
-        $query_param_type
3260
-    ) {
3261
-        if (! empty($sub_query_params)) {
3262
-            $sub_query_params = (array) $sub_query_params;
3263
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3264
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3265
-                $this->_extract_related_model_info_from_query_param(
3266
-                    $param,
3267
-                    $model_query_info_carrier,
3268
-                    $query_param_type
3269
-                );
3270
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3271
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3272
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3273
-                // of array('Registration.TXN_ID'=>23)
3274
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3275
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3276
-                    if (! is_array($possibly_array_of_params)) {
3277
-                        throw new EE_Error(sprintf(
3278
-                            __(
3279
-                                "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'))",
3280
-                                "event_espresso"
3281
-                            ),
3282
-                            $param,
3283
-                            $possibly_array_of_params
3284
-                        ));
3285
-                    }
3286
-                    $this->_extract_related_models_from_sub_params_array_keys(
3287
-                        $possibly_array_of_params,
3288
-                        $model_query_info_carrier,
3289
-                        $query_param_type
3290
-                    );
3291
-                } elseif ($query_param_type === 0 // ie WHERE
3292
-                          && is_array($possibly_array_of_params)
3293
-                          && isset($possibly_array_of_params[2])
3294
-                          && $possibly_array_of_params[2] == true
3295
-                ) {
3296
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3297
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3298
-                    // from which we should extract query parameters!
3299
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3300
-                        throw new EE_Error(sprintf(__(
3301
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3302
-                            "event_espresso"
3303
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3304
-                    }
3305
-                    $this->_extract_related_model_info_from_query_param(
3306
-                        $possibly_array_of_params[1],
3307
-                        $model_query_info_carrier,
3308
-                        $query_param_type
3309
-                    );
3310
-                }
3311
-            }
3312
-        }
3313
-        return $model_query_info_carrier;
3314
-    }
3315
-
3316
-
3317
-
3318
-    /**
3319
-     * For extracting related models from forced_joins, where the array values contain the info about what
3320
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3321
-     *
3322
-     * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3323
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3325
-     * @throws EE_Error
3326
-     * @return \EE_Model_Query_Info_Carrier
3327
-     */
3328
-    private function _extract_related_models_from_sub_params_array_values(
3329
-        $sub_query_params,
3330
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
-        $query_param_type
3332
-    ) {
3333
-        if (! empty($sub_query_params)) {
3334
-            if (! is_array($sub_query_params)) {
3335
-                throw new EE_Error(sprintf(
3336
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3337
-                    $sub_query_params
3338
-                ));
3339
-            }
3340
-            foreach ($sub_query_params as $param) {
3341
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3342
-                $this->_extract_related_model_info_from_query_param(
3343
-                    $param,
3344
-                    $model_query_info_carrier,
3345
-                    $query_param_type
3346
-                );
3347
-            }
3348
-        }
3349
-        return $model_query_info_carrier;
3350
-    }
3351
-
3352
-
3353
-    /**
3354
-     * Extract all the query parts from  model query params
3355
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3356
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3357
-     * but use them in a different order. Eg, we need to know what models we are querying
3358
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3359
-     * other models before we can finalize the where clause SQL.
3360
-     *
3361
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3362
-     * @throws EE_Error
3363
-     * @return EE_Model_Query_Info_Carrier
3364
-     * @throws ModelConfigurationException
3365
-     */
3366
-    public function _create_model_query_info_carrier($query_params)
3367
-    {
3368
-        if (! is_array($query_params)) {
3369
-            EE_Error::doing_it_wrong(
3370
-                'EEM_Base::_create_model_query_info_carrier',
3371
-                sprintf(
3372
-                    __(
3373
-                        '$query_params should be an array, you passed a variable of type %s',
3374
-                        'event_espresso'
3375
-                    ),
3376
-                    gettype($query_params)
3377
-                ),
3378
-                '4.6.0'
3379
-            );
3380
-            $query_params = array();
3381
-        }
3382
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3383
-        // first check if we should alter the query to account for caps or not
3384
-        // because the caps might require us to do extra joins
3385
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3386
-            $query_params[0] = array_replace_recursive(
3387
-                $query_params[0],
3388
-                $this->caps_where_conditions(
3389
-                    $query_params['caps']
3390
-                )
3391
-            );
3392
-        }
3393
-
3394
-        // check if we should alter the query to remove data related to protected
3395
-        // custom post types
3396
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3397
-            $where_param_key_for_password = $this->modelChainAndPassword();
3398
-            // only include if related to a cpt where no password has been set
3399
-            $query_params[0]['OR*nopassword'] = array(
3400
-                $where_param_key_for_password => '',
3401
-                $where_param_key_for_password . '*' => array('IS_NULL')
3402
-            );
3403
-        }
3404
-        $query_object = $this->_extract_related_models_from_query($query_params);
3405
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3406
-        foreach ($query_params[0] as $key => $value) {
3407
-            if (is_int($key)) {
3408
-                throw new EE_Error(
3409
-                    sprintf(
3410
-                        __(
3411
-                            "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.",
3412
-                            "event_espresso"
3413
-                        ),
3414
-                        $key,
3415
-                        var_export($value, true),
3416
-                        var_export($query_params, true),
3417
-                        get_class($this)
3418
-                    )
3419
-                );
3420
-            }
3421
-        }
3422
-        if (array_key_exists('default_where_conditions', $query_params)
3423
-            && ! empty($query_params['default_where_conditions'])
3424
-        ) {
3425
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3426
-        } else {
3427
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3428
-        }
3429
-        $query_params[0] = array_merge(
3430
-            $this->_get_default_where_conditions_for_models_in_query(
3431
-                $query_object,
3432
-                $use_default_where_conditions,
3433
-                $query_params[0]
3434
-            ),
3435
-            $query_params[0]
3436
-        );
3437
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3438
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3439
-        // So we need to setup a subquery and use that for the main join.
3440
-        // Note for now this only works on the primary table for the model.
3441
-        // So for instance, you could set the limit array like this:
3442
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3443
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3444
-            $query_object->set_main_model_join_sql(
3445
-                $this->_construct_limit_join_select(
3446
-                    $query_params['on_join_limit'][0],
3447
-                    $query_params['on_join_limit'][1]
3448
-                )
3449
-            );
3450
-        }
3451
-        // set limit
3452
-        if (array_key_exists('limit', $query_params)) {
3453
-            if (is_array($query_params['limit'])) {
3454
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3455
-                    $e = sprintf(
3456
-                        __(
3457
-                            "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)",
3458
-                            "event_espresso"
3459
-                        ),
3460
-                        http_build_query($query_params['limit'])
3461
-                    );
3462
-                    throw new EE_Error($e . "|" . $e);
3463
-                }
3464
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3465
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3466
-            } elseif (! empty($query_params['limit'])) {
3467
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3468
-            }
3469
-        }
3470
-        // set order by
3471
-        if (array_key_exists('order_by', $query_params)) {
3472
-            if (is_array($query_params['order_by'])) {
3473
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3474
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3475
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3476
-                if (array_key_exists('order', $query_params)) {
3477
-                    throw new EE_Error(
3478
-                        sprintf(
3479
-                            __(
3480
-                                "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 ",
3481
-                                "event_espresso"
3482
-                            ),
3483
-                            get_class($this),
3484
-                            implode(", ", array_keys($query_params['order_by'])),
3485
-                            implode(", ", $query_params['order_by']),
3486
-                            $query_params['order']
3487
-                        )
3488
-                    );
3489
-                }
3490
-                $this->_extract_related_models_from_sub_params_array_keys(
3491
-                    $query_params['order_by'],
3492
-                    $query_object,
3493
-                    'order_by'
3494
-                );
3495
-                // assume it's an array of fields to order by
3496
-                $order_array = array();
3497
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3498
-                    $order = $this->_extract_order($order);
3499
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3500
-                }
3501
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3502
-            } elseif (! empty($query_params['order_by'])) {
3503
-                $this->_extract_related_model_info_from_query_param(
3504
-                    $query_params['order_by'],
3505
-                    $query_object,
3506
-                    'order',
3507
-                    $query_params['order_by']
3508
-                );
3509
-                $order = isset($query_params['order'])
3510
-                    ? $this->_extract_order($query_params['order'])
3511
-                    : 'DESC';
3512
-                $query_object->set_order_by_sql(
3513
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3514
-                );
3515
-            }
3516
-        }
3517
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3518
-        if (! array_key_exists('order_by', $query_params)
3519
-            && array_key_exists('order', $query_params)
3520
-            && ! empty($query_params['order'])
3521
-        ) {
3522
-            $pk_field = $this->get_primary_key_field();
3523
-            $order = $this->_extract_order($query_params['order']);
3524
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3525
-        }
3526
-        // set group by
3527
-        if (array_key_exists('group_by', $query_params)) {
3528
-            if (is_array($query_params['group_by'])) {
3529
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3530
-                $group_by_array = array();
3531
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3532
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3533
-                }
3534
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3535
-            } elseif (! empty($query_params['group_by'])) {
3536
-                $query_object->set_group_by_sql(
3537
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3538
-                );
3539
-            }
3540
-        }
3541
-        // set having
3542
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3543
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3544
-        }
3545
-        // now, just verify they didn't pass anything wack
3546
-        foreach ($query_params as $query_key => $query_value) {
3547
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3548
-                throw new EE_Error(
3549
-                    sprintf(
3550
-                        __(
3551
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3552
-                            'event_espresso'
3553
-                        ),
3554
-                        $query_key,
3555
-                        get_class($this),
3556
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3557
-                        implode(',', $this->_allowed_query_params)
3558
-                    )
3559
-                );
3560
-            }
3561
-        }
3562
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3563
-        if (empty($main_model_join_sql)) {
3564
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3565
-        }
3566
-        return $query_object;
3567
-    }
3568
-
3569
-
3570
-
3571
-    /**
3572
-     * Gets the where conditions that should be imposed on the query based on the
3573
-     * context (eg reading frontend, backend, edit or delete).
3574
-     *
3575
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3576
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3577
-     * @throws EE_Error
3578
-     */
3579
-    public function caps_where_conditions($context = self::caps_read)
3580
-    {
3581
-        EEM_Base::verify_is_valid_cap_context($context);
3582
-        $cap_where_conditions = array();
3583
-        $cap_restrictions = $this->caps_missing($context);
3584
-        /**
3585
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3586
-         */
3587
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3588
-            $cap_where_conditions = array_replace_recursive(
3589
-                $cap_where_conditions,
3590
-                $restriction_if_no_cap->get_default_where_conditions()
3591
-            );
3592
-        }
3593
-        return apply_filters(
3594
-            'FHEE__EEM_Base__caps_where_conditions__return',
3595
-            $cap_where_conditions,
3596
-            $this,
3597
-            $context,
3598
-            $cap_restrictions
3599
-        );
3600
-    }
3601
-
3602
-
3603
-
3604
-    /**
3605
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3606
-     * otherwise throws an exception
3607
-     *
3608
-     * @param string $should_be_order_string
3609
-     * @return string either ASC, asc, DESC or desc
3610
-     * @throws EE_Error
3611
-     */
3612
-    private function _extract_order($should_be_order_string)
3613
-    {
3614
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3615
-            return $should_be_order_string;
3616
-        }
3617
-        throw new EE_Error(
3618
-            sprintf(
3619
-                __(
3620
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3621
-                    "event_espresso"
3622
-                ),
3623
-                get_class($this),
3624
-                $should_be_order_string
3625
-            )
3626
-        );
3627
-    }
3628
-
3629
-
3630
-
3631
-    /**
3632
-     * Looks at all the models which are included in this query, and asks each
3633
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3634
-     * so they can be merged
3635
-     *
3636
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3637
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3638
-     *                                                                  'none' means NO default where conditions will
3639
-     *                                                                  be used AT ALL during this query.
3640
-     *                                                                  'other_models_only' means default where
3641
-     *                                                                  conditions from other models will be used, but
3642
-     *                                                                  not for this primary model. 'all', the default,
3643
-     *                                                                  means default where conditions will apply as
3644
-     *                                                                  normal
3645
-     * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3646
-     * @throws EE_Error
3647
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3648
-     */
3649
-    private function _get_default_where_conditions_for_models_in_query(
3650
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3651
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3652
-        $where_query_params = array()
3653
-    ) {
3654
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3655
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3656
-            throw new EE_Error(sprintf(
3657
-                __(
3658
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3659
-                    "event_espresso"
3660
-                ),
3661
-                $use_default_where_conditions,
3662
-                implode(", ", $allowed_used_default_where_conditions_values)
3663
-            ));
3664
-        }
3665
-        $universal_query_params = array();
3666
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3667
-            $universal_query_params = $this->_get_default_where_conditions();
3668
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3669
-            $universal_query_params = $this->_get_minimum_where_conditions();
3670
-        }
3671
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3672
-            $related_model = $this->get_related_model_obj($model_name);
3673
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3674
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3675
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3676
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3677
-            } else {
3678
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3679
-                continue;
3680
-            }
3681
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3682
-                $related_model_universal_where_params,
3683
-                $where_query_params,
3684
-                $related_model,
3685
-                $model_relation_path
3686
-            );
3687
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3688
-                $universal_query_params,
3689
-                $overrides
3690
-            );
3691
-        }
3692
-        return $universal_query_params;
3693
-    }
3694
-
3695
-
3696
-
3697
-    /**
3698
-     * Determines whether or not we should use default where conditions for the model in question
3699
-     * (this model, or other related models).
3700
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3701
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3702
-     * We should use default where conditions on related models when they requested to use default where conditions
3703
-     * on all models, or specifically just on other related models
3704
-     * @param      $default_where_conditions_value
3705
-     * @param bool $for_this_model false means this is for OTHER related models
3706
-     * @return bool
3707
-     */
3708
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3709
-    {
3710
-        return (
3711
-                   $for_this_model
3712
-                   && in_array(
3713
-                       $default_where_conditions_value,
3714
-                       array(
3715
-                           EEM_Base::default_where_conditions_all,
3716
-                           EEM_Base::default_where_conditions_this_only,
3717
-                           EEM_Base::default_where_conditions_minimum_others,
3718
-                       ),
3719
-                       true
3720
-                   )
3721
-               )
3722
-               || (
3723
-                   ! $for_this_model
3724
-                   && in_array(
3725
-                       $default_where_conditions_value,
3726
-                       array(
3727
-                           EEM_Base::default_where_conditions_all,
3728
-                           EEM_Base::default_where_conditions_others_only,
3729
-                       ),
3730
-                       true
3731
-                   )
3732
-               );
3733
-    }
3734
-
3735
-    /**
3736
-     * Determines whether or not we should use default minimum conditions for the model in question
3737
-     * (this model, or other related models).
3738
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3739
-     * where conditions.
3740
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3741
-     * on this model or others
3742
-     * @param      $default_where_conditions_value
3743
-     * @param bool $for_this_model false means this is for OTHER related models
3744
-     * @return bool
3745
-     */
3746
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3747
-    {
3748
-        return (
3749
-                   $for_this_model
3750
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3751
-               )
3752
-               || (
3753
-                   ! $for_this_model
3754
-                   && in_array(
3755
-                       $default_where_conditions_value,
3756
-                       array(
3757
-                           EEM_Base::default_where_conditions_minimum_others,
3758
-                           EEM_Base::default_where_conditions_minimum_all,
3759
-                       ),
3760
-                       true
3761
-                   )
3762
-               );
3763
-    }
3764
-
3765
-
3766
-    /**
3767
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3768
-     * then we also add a special where condition which allows for that model's primary key
3769
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3770
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3771
-     *
3772
-     * @param array    $default_where_conditions
3773
-     * @param array    $provided_where_conditions
3774
-     * @param EEM_Base $model
3775
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3776
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3777
-     * @throws EE_Error
3778
-     */
3779
-    private function _override_defaults_or_make_null_friendly(
3780
-        $default_where_conditions,
3781
-        $provided_where_conditions,
3782
-        $model,
3783
-        $model_relation_path
3784
-    ) {
3785
-        $null_friendly_where_conditions = array();
3786
-        $none_overridden = true;
3787
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3788
-        foreach ($default_where_conditions as $key => $val) {
3789
-            if (isset($provided_where_conditions[ $key ])) {
3790
-                $none_overridden = false;
3791
-            } else {
3792
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3793
-            }
3794
-        }
3795
-        if ($none_overridden && $default_where_conditions) {
3796
-            if ($model->has_primary_key_field()) {
3797
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3798
-                                                                                . "."
3799
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3800
-            }/*else{
39
+	/**
40
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
41
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
42
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
43
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
44
+	 *
45
+	 * @var boolean
46
+	 */
47
+	private $_values_already_prepared_by_model_object = 0;
48
+
49
+	/**
50
+	 * when $_values_already_prepared_by_model_object equals this, we assume
51
+	 * the data is just like form input that needs to have the model fields'
52
+	 * prepare_for_set and prepare_for_use_in_db called on it
53
+	 */
54
+	const not_prepared_by_model_object = 0;
55
+
56
+	/**
57
+	 * when $_values_already_prepared_by_model_object equals this, we
58
+	 * assume this value is coming from a model object and doesn't need to have
59
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
60
+	 */
61
+	const prepared_by_model_object = 1;
62
+
63
+	/**
64
+	 * when $_values_already_prepared_by_model_object equals this, we assume
65
+	 * the values are already to be used in the database (ie no processing is done
66
+	 * on them by the model's fields)
67
+	 */
68
+	const prepared_for_use_in_db = 2;
69
+
70
+
71
+	protected $singular_item = 'Item';
72
+
73
+	protected $plural_item   = 'Items';
74
+
75
+	/**
76
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
77
+	 */
78
+	protected $_tables;
79
+
80
+	/**
81
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
82
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
83
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
84
+	 *
85
+	 * @var \EE_Model_Field_Base[][] $_fields
86
+	 */
87
+	protected $_fields;
88
+
89
+	/**
90
+	 * array of different kinds of relations
91
+	 *
92
+	 * @var \EE_Model_Relation_Base[] $_model_relations
93
+	 */
94
+	protected $_model_relations;
95
+
96
+	/**
97
+	 * @var \EE_Index[] $_indexes
98
+	 */
99
+	protected $_indexes = array();
100
+
101
+	/**
102
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
103
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
104
+	 * by setting the same columns as used in these queries in the query yourself.
105
+	 *
106
+	 * @var EE_Default_Where_Conditions
107
+	 */
108
+	protected $_default_where_conditions_strategy;
109
+
110
+	/**
111
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
112
+	 * This is particularly useful when you want something between 'none' and 'default'
113
+	 *
114
+	 * @var EE_Default_Where_Conditions
115
+	 */
116
+	protected $_minimum_where_conditions_strategy;
117
+
118
+	/**
119
+	 * String describing how to find the "owner" of this model's objects.
120
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
121
+	 * But when there isn't, this indicates which related model, or transiently-related model,
122
+	 * has the foreign key to the wp_users table.
123
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
124
+	 * related to events, and events have a foreign key to wp_users.
125
+	 * On EEM_Transaction, this would be 'Transaction.Event'
126
+	 *
127
+	 * @var string
128
+	 */
129
+	protected $_model_chain_to_wp_user = '';
130
+
131
+	/**
132
+	 * String describing how to find the model with a password controlling access to this model. This property has the
133
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
134
+	 * This value is the path of models to follow to arrive at the model with the password field.
135
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
136
+	 * model with a password that should affect reading this on the front-end.
137
+	 * Eg this is an empty string for the Event model because it has a password.
138
+	 * This is null for the Registration model, because its event's password has no bearing on whether
139
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
140
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
141
+	 * should hide tickets for datetimes for events that have a password set.
142
+	 * @var string |null
143
+	 */
144
+	protected $model_chain_to_password = null;
145
+
146
+	/**
147
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
148
+	 * don't need it (particularly CPT models)
149
+	 *
150
+	 * @var bool
151
+	 */
152
+	protected $_ignore_where_strategy = false;
153
+
154
+	/**
155
+	 * String used in caps relating to this model. Eg, if the caps relating to this
156
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
157
+	 *
158
+	 * @var string. If null it hasn't been initialized yet. If false then we
159
+	 * have indicated capabilities don't apply to this
160
+	 */
161
+	protected $_caps_slug = null;
162
+
163
+	/**
164
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
165
+	 * and next-level keys are capability names, and each's value is a
166
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
167
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
168
+	 * and then each capability in the corresponding sub-array that they're missing
169
+	 * adds the where conditions onto the query.
170
+	 *
171
+	 * @var array
172
+	 */
173
+	protected $_cap_restrictions = array(
174
+		self::caps_read       => array(),
175
+		self::caps_read_admin => array(),
176
+		self::caps_edit       => array(),
177
+		self::caps_delete     => array(),
178
+	);
179
+
180
+	/**
181
+	 * Array defining which cap restriction generators to use to create default
182
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
183
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
184
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
185
+	 * automatically set this to false (not just null).
186
+	 *
187
+	 * @var EE_Restriction_Generator_Base[]
188
+	 */
189
+	protected $_cap_restriction_generators = array();
190
+
191
+	/**
192
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
193
+	 */
194
+	const caps_read       = 'read';
195
+
196
+	const caps_read_admin = 'read_admin';
197
+
198
+	const caps_edit       = 'edit';
199
+
200
+	const caps_delete     = 'delete';
201
+
202
+	/**
203
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
204
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
205
+	 * maps to 'read' because when looking for relevant permissions we're going to use
206
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
207
+	 *
208
+	 * @var array
209
+	 */
210
+	protected $_cap_contexts_to_cap_action_map = array(
211
+		self::caps_read       => 'read',
212
+		self::caps_read_admin => 'read',
213
+		self::caps_edit       => 'edit',
214
+		self::caps_delete     => 'delete',
215
+	);
216
+
217
+	/**
218
+	 * Timezone
219
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
220
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
221
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
222
+	 * EE_Datetime_Field data type will have access to it.
223
+	 *
224
+	 * @var string
225
+	 */
226
+	protected $_timezone;
227
+
228
+
229
+	/**
230
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
231
+	 * multisite.
232
+	 *
233
+	 * @var int
234
+	 */
235
+	protected static $_model_query_blog_id;
236
+
237
+	/**
238
+	 * A copy of _fields, except the array keys are the model names pointed to by
239
+	 * the field
240
+	 *
241
+	 * @var EE_Model_Field_Base[]
242
+	 */
243
+	private $_cache_foreign_key_to_fields = array();
244
+
245
+	/**
246
+	 * Cached list of all the fields on the model, indexed by their name
247
+	 *
248
+	 * @var EE_Model_Field_Base[]
249
+	 */
250
+	private $_cached_fields = null;
251
+
252
+	/**
253
+	 * Cached list of all the fields on the model, except those that are
254
+	 * marked as only pertinent to the database
255
+	 *
256
+	 * @var EE_Model_Field_Base[]
257
+	 */
258
+	private $_cached_fields_non_db_only = null;
259
+
260
+	/**
261
+	 * A cached reference to the primary key for quick lookup
262
+	 *
263
+	 * @var EE_Model_Field_Base
264
+	 */
265
+	private $_primary_key_field = null;
266
+
267
+	/**
268
+	 * Flag indicating whether this model has a primary key or not
269
+	 *
270
+	 * @var boolean
271
+	 */
272
+	protected $_has_primary_key_field = null;
273
+
274
+	/**
275
+	 * array in the format:  [ FK alias => full PK ]
276
+	 * where keys are local column name aliases for foreign keys
277
+	 * and values are the fully qualified column name for the primary key they represent
278
+	 *  ex:
279
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
280
+	 *
281
+	 * @var array $foreign_key_aliases
282
+	 */
283
+	protected $foreign_key_aliases = [];
284
+
285
+	/**
286
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
287
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
288
+	 * This should be true for models that deal with data that should exist independent of EE.
289
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
290
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
291
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
292
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
293
+	 * @var boolean
294
+	 */
295
+	protected $_wp_core_model = false;
296
+
297
+	/**
298
+	 * @var bool stores whether this model has a password field or not.
299
+	 * null until initialized by hasPasswordField()
300
+	 */
301
+	protected $has_password_field;
302
+
303
+	/**
304
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
305
+	 */
306
+	protected $password_field;
307
+
308
+	/**
309
+	 *    List of valid operators that can be used for querying.
310
+	 * The keys are all operators we'll accept, the values are the real SQL
311
+	 * operators used
312
+	 *
313
+	 * @var array
314
+	 */
315
+	protected $_valid_operators = array(
316
+		'='           => '=',
317
+		'<='          => '<=',
318
+		'<'           => '<',
319
+		'>='          => '>=',
320
+		'>'           => '>',
321
+		'!='          => '!=',
322
+		'LIKE'        => 'LIKE',
323
+		'like'        => 'LIKE',
324
+		'NOT_LIKE'    => 'NOT LIKE',
325
+		'not_like'    => 'NOT LIKE',
326
+		'NOT LIKE'    => 'NOT LIKE',
327
+		'not like'    => 'NOT LIKE',
328
+		'IN'          => 'IN',
329
+		'in'          => 'IN',
330
+		'NOT_IN'      => 'NOT IN',
331
+		'not_in'      => 'NOT IN',
332
+		'NOT IN'      => 'NOT IN',
333
+		'not in'      => 'NOT IN',
334
+		'between'     => 'BETWEEN',
335
+		'BETWEEN'     => 'BETWEEN',
336
+		'IS_NOT_NULL' => 'IS NOT NULL',
337
+		'is_not_null' => 'IS NOT NULL',
338
+		'IS NOT NULL' => 'IS NOT NULL',
339
+		'is not null' => 'IS NOT NULL',
340
+		'IS_NULL'     => 'IS NULL',
341
+		'is_null'     => 'IS NULL',
342
+		'IS NULL'     => 'IS NULL',
343
+		'is null'     => 'IS NULL',
344
+		'REGEXP'      => 'REGEXP',
345
+		'regexp'      => 'REGEXP',
346
+		'NOT_REGEXP'  => 'NOT REGEXP',
347
+		'not_regexp'  => 'NOT REGEXP',
348
+		'NOT REGEXP'  => 'NOT REGEXP',
349
+		'not regexp'  => 'NOT REGEXP',
350
+	);
351
+
352
+	/**
353
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
354
+	 *
355
+	 * @var array
356
+	 */
357
+	protected $_in_style_operators = array('IN', 'NOT IN');
358
+
359
+	/**
360
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
361
+	 * '12-31-2012'"
362
+	 *
363
+	 * @var array
364
+	 */
365
+	protected $_between_style_operators = array('BETWEEN');
366
+
367
+	/**
368
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
369
+	 * @var array
370
+	 */
371
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
372
+	/**
373
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
374
+	 * on a join table.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
379
+
380
+	/**
381
+	 * Allowed values for $query_params['order'] for ordering in queries
382
+	 *
383
+	 * @var array
384
+	 */
385
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
386
+
387
+	/**
388
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
389
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
390
+	 *
391
+	 * @var array
392
+	 */
393
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
394
+
395
+	/**
396
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
397
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
398
+	 *
399
+	 * @var array
400
+	 */
401
+	private $_allowed_query_params = array(
402
+		0,
403
+		'limit',
404
+		'order_by',
405
+		'group_by',
406
+		'having',
407
+		'force_join',
408
+		'order',
409
+		'on_join_limit',
410
+		'default_where_conditions',
411
+		'caps',
412
+		'extra_selects',
413
+		'exclude_protected',
414
+	);
415
+
416
+	/**
417
+	 * All the data types that can be used in $wpdb->prepare statements.
418
+	 *
419
+	 * @var array
420
+	 */
421
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
422
+
423
+	/**
424
+	 * @var EE_Registry $EE
425
+	 */
426
+	protected $EE = null;
427
+
428
+
429
+	/**
430
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
431
+	 *
432
+	 * @var int
433
+	 */
434
+	protected $_show_next_x_db_queries = 0;
435
+
436
+	/**
437
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
438
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
439
+	 * WHERE, GROUP_BY, etc.
440
+	 *
441
+	 * @var CustomSelects
442
+	 */
443
+	protected $_custom_selections = array();
444
+
445
+	/**
446
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
447
+	 * caches every model object we've fetched from the DB on this request
448
+	 *
449
+	 * @var array
450
+	 */
451
+	protected $_entity_map;
452
+
453
+	/**
454
+	 * @var LoaderInterface $loader
455
+	 */
456
+	protected static $loader;
457
+
458
+
459
+	/**
460
+	 * constant used to show EEM_Base has not yet verified the db on this http request
461
+	 */
462
+	const db_verified_none = 0;
463
+
464
+	/**
465
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
466
+	 * but not the addons' dbs
467
+	 */
468
+	const db_verified_core = 1;
469
+
470
+	/**
471
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
472
+	 * the EE core db too)
473
+	 */
474
+	const db_verified_addons = 2;
475
+
476
+	/**
477
+	 * indicates whether an EEM_Base child has already re-verified the DB
478
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
479
+	 * looking like EEM_Base::db_verified_*
480
+	 *
481
+	 * @var int - 0 = none, 1 = core, 2 = addons
482
+	 */
483
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
484
+
485
+	/**
486
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
487
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
488
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
489
+	 */
490
+	const default_where_conditions_all = 'all';
491
+
492
+	/**
493
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
494
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
495
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
496
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
497
+	 *        models which share tables with other models, this can return data for the wrong model.
498
+	 */
499
+	const default_where_conditions_this_only = 'this_model_only';
500
+
501
+	/**
502
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
503
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
504
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
505
+	 */
506
+	const default_where_conditions_others_only = 'other_models_only';
507
+
508
+	/**
509
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
510
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
511
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
512
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
513
+	 *        (regardless of whether those events and venues are trashed)
514
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
515
+	 *        events.
516
+	 */
517
+	const default_where_conditions_minimum_all = 'minimum';
518
+
519
+	/**
520
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
521
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
522
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
523
+	 *        not)
524
+	 */
525
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
526
+
527
+	/**
528
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
529
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
530
+	 *        it's possible it will return table entries for other models. You should use
531
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
532
+	 */
533
+	const default_where_conditions_none = 'none';
534
+
535
+
536
+
537
+	/**
538
+	 * About all child constructors:
539
+	 * they should define the _tables, _fields and _model_relations arrays.
540
+	 * Should ALWAYS be called after child constructor.
541
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
542
+	 * finalizes constructing all the object's attributes.
543
+	 * Generally, rather than requiring a child to code
544
+	 * $this->_tables = array(
545
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
546
+	 *        ...);
547
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
548
+	 * each EE_Table has a function to set the table's alias after the constructor, using
549
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
550
+	 * do something similar.
551
+	 *
552
+	 * @param null $timezone
553
+	 * @throws EE_Error
554
+	 */
555
+	protected function __construct($timezone = null)
556
+	{
557
+		// check that the model has not been loaded too soon
558
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
559
+			throw new EE_Error(
560
+				sprintf(
561
+					__(
562
+						'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.',
563
+						'event_espresso'
564
+					),
565
+					get_class($this)
566
+				)
567
+			);
568
+		}
569
+		/**
570
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
571
+		 */
572
+		if (empty(EEM_Base::$_model_query_blog_id)) {
573
+			EEM_Base::set_model_query_blog_id();
574
+		}
575
+		/**
576
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
577
+		 * just use EE_Register_Model_Extension
578
+		 *
579
+		 * @var EE_Table_Base[] $_tables
580
+		 */
581
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
582
+		foreach ($this->_tables as $table_alias => $table_obj) {
583
+			/** @var $table_obj EE_Table_Base */
584
+			$table_obj->_construct_finalize_with_alias($table_alias);
585
+			if ($table_obj instanceof EE_Secondary_Table) {
586
+				/** @var $table_obj EE_Secondary_Table */
587
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
588
+			}
589
+		}
590
+		/**
591
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
592
+		 * EE_Register_Model_Extension
593
+		 *
594
+		 * @param EE_Model_Field_Base[] $_fields
595
+		 */
596
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
597
+		$this->_invalidate_field_caches();
598
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
599
+			if (! array_key_exists($table_alias, $this->_tables)) {
600
+				throw new EE_Error(sprintf(__(
601
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
602
+					'event_espresso'
603
+				), $table_alias, implode(",", $this->_fields)));
604
+			}
605
+			foreach ($fields_for_table as $field_name => $field_obj) {
606
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
607
+				// primary key field base has a slightly different _construct_finalize
608
+				/** @var $field_obj EE_Model_Field_Base */
609
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
610
+			}
611
+		}
612
+		// everything is related to Extra_Meta
613
+		if (get_class($this) !== 'EEM_Extra_Meta') {
614
+			// make extra meta related to everything, but don't block deleting things just
615
+			// because they have related extra meta info. For now just orphan those extra meta
616
+			// in the future we should automatically delete them
617
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
618
+		}
619
+		// and change logs
620
+		if (get_class($this) !== 'EEM_Change_Log') {
621
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
622
+		}
623
+		/**
624
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
625
+		 * EE_Register_Model_Extension
626
+		 *
627
+		 * @param EE_Model_Relation_Base[] $_model_relations
628
+		 */
629
+		$this->_model_relations = (array) apply_filters(
630
+			'FHEE__' . get_class($this) . '__construct__model_relations',
631
+			$this->_model_relations
632
+		);
633
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
634
+			/** @var $relation_obj EE_Model_Relation_Base */
635
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
636
+		}
637
+		foreach ($this->_indexes as $index_name => $index_obj) {
638
+			/** @var $index_obj EE_Index */
639
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
640
+		}
641
+		$this->set_timezone($timezone);
642
+		// finalize default where condition strategy, or set default
643
+		if (! $this->_default_where_conditions_strategy) {
644
+			// nothing was set during child constructor, so set default
645
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
646
+		}
647
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
648
+		if (! $this->_minimum_where_conditions_strategy) {
649
+			// nothing was set during child constructor, so set default
650
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
651
+		}
652
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
653
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
654
+		// to indicate to NOT set it, set it to the logical default
655
+		if ($this->_caps_slug === null) {
656
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
657
+		}
658
+		// initialize the standard cap restriction generators if none were specified by the child constructor
659
+		if ($this->_cap_restriction_generators !== false) {
660
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
661
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
662
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
663
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
664
+						new EE_Restriction_Generator_Protected(),
665
+						$cap_context,
666
+						$this
667
+					);
668
+				}
669
+			}
670
+		}
671
+		// if there are cap restriction generators, use them to make the default cap restrictions
672
+		if ($this->_cap_restriction_generators !== false) {
673
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
674
+				if (! $generator_object) {
675
+					continue;
676
+				}
677
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
678
+					throw new EE_Error(
679
+						sprintf(
680
+							__(
681
+								'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.',
682
+								'event_espresso'
683
+							),
684
+							$context,
685
+							$this->get_this_model_name()
686
+						)
687
+					);
688
+				}
689
+				$action = $this->cap_action_for_context($context);
690
+				if (! $generator_object->construction_finalized()) {
691
+					$generator_object->_construct_finalize($this, $action);
692
+				}
693
+			}
694
+		}
695
+		do_action('AHEE__' . get_class($this) . '__construct__end');
696
+	}
697
+
698
+
699
+
700
+	/**
701
+	 * Used to set the $_model_query_blog_id static property.
702
+	 *
703
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
704
+	 *                      value for get_current_blog_id() will be used.
705
+	 */
706
+	public static function set_model_query_blog_id($blog_id = 0)
707
+	{
708
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
709
+	}
710
+
711
+
712
+
713
+	/**
714
+	 * Returns whatever is set as the internal $model_query_blog_id.
715
+	 *
716
+	 * @return int
717
+	 */
718
+	public static function get_model_query_blog_id()
719
+	{
720
+		return EEM_Base::$_model_query_blog_id;
721
+	}
722
+
723
+
724
+
725
+	/**
726
+	 * This function is a singleton method used to instantiate the Espresso_model object
727
+	 *
728
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
729
+	 *                                (and any incoming timezone data that gets saved).
730
+	 *                                Note this just sends the timezone info to the date time model field objects.
731
+	 *                                Default is NULL
732
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
733
+	 * @return static (as in the concrete child class)
734
+	 * @throws EE_Error
735
+	 * @throws InvalidArgumentException
736
+	 * @throws InvalidDataTypeException
737
+	 * @throws InvalidInterfaceException
738
+	 */
739
+	public static function instance($timezone = null)
740
+	{
741
+		// check if instance of Espresso_model already exists
742
+		if (! static::$_instance instanceof static) {
743
+			// instantiate Espresso_model
744
+			static::$_instance = new static(
745
+				$timezone,
746
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
747
+			);
748
+		}
749
+		// we might have a timezone set, let set_timezone decide what to do with it
750
+		static::$_instance->set_timezone($timezone);
751
+		// Espresso_model object
752
+		return static::$_instance;
753
+	}
754
+
755
+
756
+
757
+	/**
758
+	 * resets the model and returns it
759
+	 *
760
+	 * @param null | string $timezone
761
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
762
+	 * all its properties reset; if it wasn't instantiated, returns null)
763
+	 * @throws EE_Error
764
+	 * @throws ReflectionException
765
+	 * @throws InvalidArgumentException
766
+	 * @throws InvalidDataTypeException
767
+	 * @throws InvalidInterfaceException
768
+	 */
769
+	public static function reset($timezone = null)
770
+	{
771
+		if (static::$_instance instanceof EEM_Base) {
772
+			// let's try to NOT swap out the current instance for a new one
773
+			// because if someone has a reference to it, we can't remove their reference
774
+			// so it's best to keep using the same reference, but change the original object
775
+			// reset all its properties to their original values as defined in the class
776
+			$r = new ReflectionClass(get_class(static::$_instance));
777
+			$static_properties = $r->getStaticProperties();
778
+			foreach ($r->getDefaultProperties() as $property => $value) {
779
+				// don't set instance to null like it was originally,
780
+				// but it's static anyways, and we're ignoring static properties (for now at least)
781
+				if (! isset($static_properties[ $property ])) {
782
+					static::$_instance->{$property} = $value;
783
+				}
784
+			}
785
+			// and then directly call its constructor again, like we would if we were creating a new one
786
+			static::$_instance->__construct(
787
+				$timezone,
788
+				EEM_Base::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
789
+			);
790
+			return self::instance();
791
+		}
792
+		return null;
793
+	}
794
+
795
+
796
+
797
+	/**
798
+	 * @return LoaderInterface
799
+	 * @throws InvalidArgumentException
800
+	 * @throws InvalidDataTypeException
801
+	 * @throws InvalidInterfaceException
802
+	 */
803
+	private static function getLoader()
804
+	{
805
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
806
+			EEM_Base::$loader = LoaderFactory::getLoader();
807
+		}
808
+		return EEM_Base::$loader;
809
+	}
810
+
811
+
812
+
813
+	/**
814
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
815
+	 *
816
+	 * @param  boolean $translated return localized strings or JUST the array.
817
+	 * @return array
818
+	 * @throws EE_Error
819
+	 * @throws InvalidArgumentException
820
+	 * @throws InvalidDataTypeException
821
+	 * @throws InvalidInterfaceException
822
+	 */
823
+	public function status_array($translated = false)
824
+	{
825
+		if (! array_key_exists('Status', $this->_model_relations)) {
826
+			return array();
827
+		}
828
+		$model_name = $this->get_this_model_name();
829
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
830
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
831
+		$status_array = array();
832
+		foreach ($stati as $status) {
833
+			$status_array[ $status->ID() ] = $status->get('STS_code');
834
+		}
835
+		return $translated
836
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
837
+			: $status_array;
838
+	}
839
+
840
+
841
+
842
+	/**
843
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
844
+	 *
845
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
846
+	 *                             or if you have the development copy of EE you can view this at the path:
847
+	 *                             /docs/G--Model-System/model-query-params.md
848
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
849
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
850
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
851
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
852
+	 *                                        array( array(
853
+	 *                                        'OR'=>array(
854
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
855
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
856
+	 *                                        )
857
+	 *                                        ),
858
+	 *                                        'limit'=>10,
859
+	 *                                        'group_by'=>'TXN_ID'
860
+	 *                                        ));
861
+	 *                                        get all the answers to the question titled "shirt size" for event with id
862
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
863
+	 *                                        'Question.QST_display_text'=>'shirt size',
864
+	 *                                        'Registration.Event.EVT_ID'=>12
865
+	 *                                        ),
866
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
867
+	 *                                        ));
868
+	 * @throws EE_Error
869
+	 */
870
+	public function get_all($query_params = array())
871
+	{
872
+		if (isset($query_params['limit'])
873
+			&& ! isset($query_params['group_by'])
874
+		) {
875
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
876
+		}
877
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
878
+	}
879
+
880
+
881
+
882
+	/**
883
+	 * Modifies the query parameters so we only get back model objects
884
+	 * that "belong" to the current user
885
+	 *
886
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
888
+	 */
889
+	public function alter_query_params_to_only_include_mine($query_params = array())
890
+	{
891
+		$wp_user_field_name = $this->wp_user_field_name();
892
+		if ($wp_user_field_name) {
893
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
894
+		}
895
+		return $query_params;
896
+	}
897
+
898
+
899
+
900
+	/**
901
+	 * Returns the name of the field's name that points to the WP_User table
902
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
903
+	 * foreign key to the WP_User table)
904
+	 *
905
+	 * @return string|boolean string on success, boolean false when there is no
906
+	 * foreign key to the WP_User table
907
+	 */
908
+	public function wp_user_field_name()
909
+	{
910
+		try {
911
+			if (! empty($this->_model_chain_to_wp_user)) {
912
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
913
+				$last_model_name = end($models_to_follow_to_wp_users);
914
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
915
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
916
+			} else {
917
+				$model_with_fk_to_wp_users = $this;
918
+				$model_chain_to_wp_user = '';
919
+			}
920
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
921
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
922
+		} catch (EE_Error $e) {
923
+			return false;
924
+		}
925
+	}
926
+
927
+
928
+
929
+	/**
930
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
931
+	 * (or transiently-related model) has a foreign key to the wp_users table;
932
+	 * useful for finding if model objects of this type are 'owned' by the current user.
933
+	 * This is an empty string when the foreign key is on this model and when it isn't,
934
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
935
+	 * (or transiently-related model)
936
+	 *
937
+	 * @return string
938
+	 */
939
+	public function model_chain_to_wp_user()
940
+	{
941
+		return $this->_model_chain_to_wp_user;
942
+	}
943
+
944
+
945
+
946
+	/**
947
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
948
+	 * like how registrations don't have a foreign key to wp_users, but the
949
+	 * events they are for are), or is unrelated to wp users.
950
+	 * generally available
951
+	 *
952
+	 * @return boolean
953
+	 */
954
+	public function is_owned()
955
+	{
956
+		if ($this->model_chain_to_wp_user()) {
957
+			return true;
958
+		}
959
+		try {
960
+			$this->get_foreign_key_to('WP_User');
961
+			return true;
962
+		} catch (EE_Error $e) {
963
+			return false;
964
+		}
965
+	}
966
+
967
+
968
+	/**
969
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
970
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
971
+	 * the model)
972
+	 *
973
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
974
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
975
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
976
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
977
+	 *                                  override this and set the select to "*", or a specific column name, like
978
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
979
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
980
+	 *                                  the aliases used to refer to this selection, and values are to be
981
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
982
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
983
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
984
+	 * @throws EE_Error
985
+	 * @throws InvalidArgumentException
986
+	 */
987
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
988
+	{
989
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
990
+		;
991
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
992
+		$select_expressions = $columns_to_select === null
993
+			? $this->_construct_default_select_sql($model_query_info)
994
+			: '';
995
+		if ($this->_custom_selections instanceof CustomSelects) {
996
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
997
+			$select_expressions .= $select_expressions
998
+				? ', ' . $custom_expressions
999
+				: $custom_expressions;
1000
+		}
1001
+
1002
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1003
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1004
+	}
1005
+
1006
+
1007
+	/**
1008
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1009
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1010
+	 * method of including extra select information.
1011
+	 *
1012
+	 * @param array             $query_params
1013
+	 * @param null|array|string $columns_to_select
1014
+	 * @return null|CustomSelects
1015
+	 * @throws InvalidArgumentException
1016
+	 */
1017
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1018
+	{
1019
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1020
+			return null;
1021
+		}
1022
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1023
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1024
+		return new CustomSelects($selects);
1025
+	}
1026
+
1027
+
1028
+
1029
+	/**
1030
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1031
+	 * but you can use the model query params to more easily
1032
+	 * take care of joins, field preparation etc.
1033
+	 *
1034
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1035
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1036
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1037
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1038
+	 *                                  override this and set the select to "*", or a specific column name, like
1039
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1040
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1041
+	 *                                  the aliases used to refer to this selection, and values are to be
1042
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1043
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1044
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1045
+	 * @throws EE_Error
1046
+	 */
1047
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1048
+	{
1049
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1050
+	}
1051
+
1052
+
1053
+
1054
+	/**
1055
+	 * For creating a custom select statement
1056
+	 *
1057
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1058
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1059
+	 *                                 SQL, and 1=>is the datatype
1060
+	 * @throws EE_Error
1061
+	 * @return string
1062
+	 */
1063
+	private function _construct_select_from_input($columns_to_select)
1064
+	{
1065
+		if (is_array($columns_to_select)) {
1066
+			$select_sql_array = array();
1067
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1068
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1069
+					throw new EE_Error(
1070
+						sprintf(
1071
+							__(
1072
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1073
+								'event_espresso'
1074
+							),
1075
+							$selection_and_datatype,
1076
+							$alias
1077
+						)
1078
+					);
1079
+				}
1080
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1081
+					throw new EE_Error(
1082
+						sprintf(
1083
+							esc_html__(
1084
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1085
+								'event_espresso'
1086
+							),
1087
+							$selection_and_datatype[1],
1088
+							$selection_and_datatype[0],
1089
+							$alias,
1090
+							implode(', ', $this->_valid_wpdb_data_types)
1091
+						)
1092
+					);
1093
+				}
1094
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1095
+			}
1096
+			$columns_to_select_string = implode(', ', $select_sql_array);
1097
+		} else {
1098
+			$columns_to_select_string = $columns_to_select;
1099
+		}
1100
+		return $columns_to_select_string;
1101
+	}
1102
+
1103
+
1104
+
1105
+	/**
1106
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1107
+	 *
1108
+	 * @return string
1109
+	 * @throws EE_Error
1110
+	 */
1111
+	public function primary_key_name()
1112
+	{
1113
+		return $this->get_primary_key_field()->get_name();
1114
+	}
1115
+
1116
+
1117
+	/**
1118
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1119
+	 * If there is no primary key on this model, $id is treated as primary key string
1120
+	 *
1121
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1122
+	 * @return EE_Base_Class
1123
+	 * @throws EE_Error
1124
+	 */
1125
+	public function get_one_by_ID($id)
1126
+	{
1127
+		if ($this->get_from_entity_map($id)) {
1128
+			return $this->get_from_entity_map($id);
1129
+		}
1130
+		$model_object = $this->get_one(
1131
+			$this->alter_query_params_to_restrict_by_ID(
1132
+				$id,
1133
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1134
+			)
1135
+		);
1136
+		$className = $this->_get_class_name();
1137
+		if ($model_object instanceof $className) {
1138
+			// make sure valid objects get added to the entity map
1139
+			// so that the next call to this method doesn't trigger another trip to the db
1140
+			$this->add_to_entity_map($model_object);
1141
+		}
1142
+		return $model_object;
1143
+	}
1144
+
1145
+
1146
+
1147
+	/**
1148
+	 * Alters query parameters to only get items with this ID are returned.
1149
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1150
+	 * or could just be a simple primary key ID
1151
+	 *
1152
+	 * @param int   $id
1153
+	 * @param array $query_params
1154
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1155
+	 * @throws EE_Error
1156
+	 */
1157
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1158
+	{
1159
+		if (! isset($query_params[0])) {
1160
+			$query_params[0] = array();
1161
+		}
1162
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1163
+		if ($conditions_from_id === null) {
1164
+			$query_params[0][ $this->primary_key_name() ] = $id;
1165
+		} else {
1166
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1167
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1168
+		}
1169
+		return $query_params;
1170
+	}
1171
+
1172
+
1173
+
1174
+	/**
1175
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1176
+	 * array. If no item is found, null is returned.
1177
+	 *
1178
+	 * @param array $query_params like EEM_Base's $query_params variable.
1179
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1180
+	 * @throws EE_Error
1181
+	 */
1182
+	public function get_one($query_params = array())
1183
+	{
1184
+		if (! is_array($query_params)) {
1185
+			EE_Error::doing_it_wrong(
1186
+				'EEM_Base::get_one',
1187
+				sprintf(
1188
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1189
+					gettype($query_params)
1190
+				),
1191
+				'4.6.0'
1192
+			);
1193
+			$query_params = array();
1194
+		}
1195
+		$query_params['limit'] = 1;
1196
+		$items = $this->get_all($query_params);
1197
+		if (empty($items)) {
1198
+			return null;
1199
+		}
1200
+		return array_shift($items);
1201
+	}
1202
+
1203
+
1204
+
1205
+	/**
1206
+	 * Returns the next x number of items in sequence from the given value as
1207
+	 * found in the database matching the given query conditions.
1208
+	 *
1209
+	 * @param mixed $current_field_value    Value used for the reference point.
1210
+	 * @param null  $field_to_order_by      What field is used for the
1211
+	 *                                      reference point.
1212
+	 * @param int   $limit                  How many to return.
1213
+	 * @param array $query_params           Extra conditions on the query.
1214
+	 * @param null  $columns_to_select      If left null, then an array of
1215
+	 *                                      EE_Base_Class objects is returned,
1216
+	 *                                      otherwise you can indicate just the
1217
+	 *                                      columns you want returned.
1218
+	 * @return EE_Base_Class[]|array
1219
+	 * @throws EE_Error
1220
+	 */
1221
+	public function next_x(
1222
+		$current_field_value,
1223
+		$field_to_order_by = null,
1224
+		$limit = 1,
1225
+		$query_params = array(),
1226
+		$columns_to_select = null
1227
+	) {
1228
+		return $this->_get_consecutive(
1229
+			$current_field_value,
1230
+			'>',
1231
+			$field_to_order_by,
1232
+			$limit,
1233
+			$query_params,
1234
+			$columns_to_select
1235
+		);
1236
+	}
1237
+
1238
+
1239
+
1240
+	/**
1241
+	 * Returns the previous x number of items in sequence from the given value
1242
+	 * as found in the database matching the given query conditions.
1243
+	 *
1244
+	 * @param mixed $current_field_value    Value used for the reference point.
1245
+	 * @param null  $field_to_order_by      What field is used for the
1246
+	 *                                      reference point.
1247
+	 * @param int   $limit                  How many to return.
1248
+	 * @param array $query_params           Extra conditions on the query.
1249
+	 * @param null  $columns_to_select      If left null, then an array of
1250
+	 *                                      EE_Base_Class objects is returned,
1251
+	 *                                      otherwise you can indicate just the
1252
+	 *                                      columns you want returned.
1253
+	 * @return EE_Base_Class[]|array
1254
+	 * @throws EE_Error
1255
+	 */
1256
+	public function previous_x(
1257
+		$current_field_value,
1258
+		$field_to_order_by = null,
1259
+		$limit = 1,
1260
+		$query_params = array(),
1261
+		$columns_to_select = null
1262
+	) {
1263
+		return $this->_get_consecutive(
1264
+			$current_field_value,
1265
+			'<',
1266
+			$field_to_order_by,
1267
+			$limit,
1268
+			$query_params,
1269
+			$columns_to_select
1270
+		);
1271
+	}
1272
+
1273
+
1274
+
1275
+	/**
1276
+	 * Returns the next item in sequence from the given value as found in the
1277
+	 * database matching the given query conditions.
1278
+	 *
1279
+	 * @param mixed $current_field_value    Value used for the reference point.
1280
+	 * @param null  $field_to_order_by      What field is used for the
1281
+	 *                                      reference point.
1282
+	 * @param array $query_params           Extra conditions on the query.
1283
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1284
+	 *                                      object is returned, otherwise you
1285
+	 *                                      can indicate just the columns you
1286
+	 *                                      want and a single array indexed by
1287
+	 *                                      the columns will be returned.
1288
+	 * @return EE_Base_Class|null|array()
1289
+	 * @throws EE_Error
1290
+	 */
1291
+	public function next(
1292
+		$current_field_value,
1293
+		$field_to_order_by = null,
1294
+		$query_params = array(),
1295
+		$columns_to_select = null
1296
+	) {
1297
+		$results = $this->_get_consecutive(
1298
+			$current_field_value,
1299
+			'>',
1300
+			$field_to_order_by,
1301
+			1,
1302
+			$query_params,
1303
+			$columns_to_select
1304
+		);
1305
+		return empty($results) ? null : reset($results);
1306
+	}
1307
+
1308
+
1309
+
1310
+	/**
1311
+	 * Returns the previous item in sequence from the given value as found in
1312
+	 * the database matching the given query conditions.
1313
+	 *
1314
+	 * @param mixed $current_field_value    Value used for the reference point.
1315
+	 * @param null  $field_to_order_by      What field is used for the
1316
+	 *                                      reference point.
1317
+	 * @param array $query_params           Extra conditions on the query.
1318
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1319
+	 *                                      object is returned, otherwise you
1320
+	 *                                      can indicate just the columns you
1321
+	 *                                      want and a single array indexed by
1322
+	 *                                      the columns will be returned.
1323
+	 * @return EE_Base_Class|null|array()
1324
+	 * @throws EE_Error
1325
+	 */
1326
+	public function previous(
1327
+		$current_field_value,
1328
+		$field_to_order_by = null,
1329
+		$query_params = array(),
1330
+		$columns_to_select = null
1331
+	) {
1332
+		$results = $this->_get_consecutive(
1333
+			$current_field_value,
1334
+			'<',
1335
+			$field_to_order_by,
1336
+			1,
1337
+			$query_params,
1338
+			$columns_to_select
1339
+		);
1340
+		return empty($results) ? null : reset($results);
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * Returns the a consecutive number of items in sequence from the given
1347
+	 * value as found in the database matching the given query conditions.
1348
+	 *
1349
+	 * @param mixed  $current_field_value   Value used for the reference point.
1350
+	 * @param string $operand               What operand is used for the sequence.
1351
+	 * @param string $field_to_order_by     What field is used for the reference point.
1352
+	 * @param int    $limit                 How many to return.
1353
+	 * @param array  $query_params          Extra conditions on the query.
1354
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1355
+	 *                                      otherwise you can indicate just the columns you want returned.
1356
+	 * @return EE_Base_Class[]|array
1357
+	 * @throws EE_Error
1358
+	 */
1359
+	protected function _get_consecutive(
1360
+		$current_field_value,
1361
+		$operand = '>',
1362
+		$field_to_order_by = null,
1363
+		$limit = 1,
1364
+		$query_params = array(),
1365
+		$columns_to_select = null
1366
+	) {
1367
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1368
+		if (empty($field_to_order_by)) {
1369
+			if ($this->has_primary_key_field()) {
1370
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1371
+			} else {
1372
+				if (WP_DEBUG) {
1373
+					throw new EE_Error(__(
1374
+						'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).',
1375
+						'event_espresso'
1376
+					));
1377
+				}
1378
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1379
+				return array();
1380
+			}
1381
+		}
1382
+		if (! is_array($query_params)) {
1383
+			EE_Error::doing_it_wrong(
1384
+				'EEM_Base::_get_consecutive',
1385
+				sprintf(
1386
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1387
+					gettype($query_params)
1388
+				),
1389
+				'4.6.0'
1390
+			);
1391
+			$query_params = array();
1392
+		}
1393
+		// let's add the where query param for consecutive look up.
1394
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1395
+		$query_params['limit'] = $limit;
1396
+		// set direction
1397
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1398
+		$query_params['order_by'] = $operand === '>'
1399
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1400
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1401
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1402
+		if (empty($columns_to_select)) {
1403
+			return $this->get_all($query_params);
1404
+		}
1405
+		// getting just the fields
1406
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1407
+	}
1408
+
1409
+
1410
+
1411
+	/**
1412
+	 * This sets the _timezone property after model object has been instantiated.
1413
+	 *
1414
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1415
+	 */
1416
+	public function set_timezone($timezone)
1417
+	{
1418
+		if ($timezone !== null) {
1419
+			$this->_timezone = $timezone;
1420
+		}
1421
+		// note we need to loop through relations and set the timezone on those objects as well.
1422
+		foreach ($this->_model_relations as $relation) {
1423
+			$relation->set_timezone($timezone);
1424
+		}
1425
+		// and finally we do the same for any datetime fields
1426
+		foreach ($this->_fields as $field) {
1427
+			if ($field instanceof EE_Datetime_Field) {
1428
+				$field->set_timezone($timezone);
1429
+			}
1430
+		}
1431
+	}
1432
+
1433
+
1434
+
1435
+	/**
1436
+	 * This just returns whatever is set for the current timezone.
1437
+	 *
1438
+	 * @access public
1439
+	 * @return string
1440
+	 */
1441
+	public function get_timezone()
1442
+	{
1443
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1444
+		if (empty($this->_timezone)) {
1445
+			foreach ($this->_fields as $field) {
1446
+				if ($field instanceof EE_Datetime_Field) {
1447
+					$this->set_timezone($field->get_timezone());
1448
+					break;
1449
+				}
1450
+			}
1451
+		}
1452
+		// if timezone STILL empty then return the default timezone for the site.
1453
+		if (empty($this->_timezone)) {
1454
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1455
+		}
1456
+		return $this->_timezone;
1457
+	}
1458
+
1459
+
1460
+
1461
+	/**
1462
+	 * This returns the date formats set for the given field name and also ensures that
1463
+	 * $this->_timezone property is set correctly.
1464
+	 *
1465
+	 * @since 4.6.x
1466
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1467
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1468
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1469
+	 * @return array formats in an array with the date format first, and the time format last.
1470
+	 */
1471
+	public function get_formats_for($field_name, $pretty = false)
1472
+	{
1473
+		$field_settings = $this->field_settings_for($field_name);
1474
+		// if not a valid EE_Datetime_Field then throw error
1475
+		if (! $field_settings instanceof EE_Datetime_Field) {
1476
+			throw new EE_Error(sprintf(__(
1477
+				'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.',
1478
+				'event_espresso'
1479
+			), $field_name));
1480
+		}
1481
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1482
+		// the field.
1483
+		$this->_timezone = $field_settings->get_timezone();
1484
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1485
+	}
1486
+
1487
+
1488
+
1489
+	/**
1490
+	 * This returns the current time in a format setup for a query on this model.
1491
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1492
+	 * it will return:
1493
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1494
+	 *  NOW
1495
+	 *  - or a unix timestamp (equivalent to time())
1496
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1497
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1498
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1499
+	 * @since 4.6.x
1500
+	 * @param string $field_name       The field the current time is needed for.
1501
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1502
+	 *                                 formatted string matching the set format for the field in the set timezone will
1503
+	 *                                 be returned.
1504
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1505
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1506
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1507
+	 *                                 exception is triggered.
1508
+	 */
1509
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1510
+	{
1511
+		$formats = $this->get_formats_for($field_name);
1512
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1513
+		if ($timestamp) {
1514
+			return $DateTime->format('U');
1515
+		}
1516
+		// not returning timestamp, so return formatted string in timezone.
1517
+		switch ($what) {
1518
+			case 'time':
1519
+				return $DateTime->format($formats[1]);
1520
+				break;
1521
+			case 'date':
1522
+				return $DateTime->format($formats[0]);
1523
+				break;
1524
+			default:
1525
+				return $DateTime->format(implode(' ', $formats));
1526
+				break;
1527
+		}
1528
+	}
1529
+
1530
+
1531
+
1532
+	/**
1533
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1534
+	 * for the model are.  Returns a DateTime object.
1535
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1536
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1537
+	 * ignored.
1538
+	 *
1539
+	 * @param string $field_name      The field being setup.
1540
+	 * @param string $timestring      The date time string being used.
1541
+	 * @param string $incoming_format The format for the time string.
1542
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1543
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1544
+	 *                                format is
1545
+	 *                                'U', this is ignored.
1546
+	 * @return DateTime
1547
+	 * @throws EE_Error
1548
+	 */
1549
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1550
+	{
1551
+		// just using this to ensure the timezone is set correctly internally
1552
+		$this->get_formats_for($field_name);
1553
+		// load EEH_DTT_Helper
1554
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1555
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1556
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1557
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1558
+	}
1559
+
1560
+
1561
+
1562
+	/**
1563
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1564
+	 *
1565
+	 * @return EE_Table_Base[]
1566
+	 */
1567
+	public function get_tables()
1568
+	{
1569
+		return $this->_tables;
1570
+	}
1571
+
1572
+
1573
+
1574
+	/**
1575
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1576
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1577
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1578
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1579
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1580
+	 * model object with EVT_ID = 1
1581
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1582
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1583
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1584
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1585
+	 * are not specified)
1586
+	 *
1587
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1588
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1589
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1590
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1591
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1592
+	 *                                         ID=34, we'd use this method as follows:
1593
+	 *                                         EEM_Transaction::instance()->update(
1594
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1595
+	 *                                         array(array('TXN_ID'=>34)));
1596
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1597
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1598
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1599
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1600
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1601
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1602
+	 *                                         TRUE, it is assumed that you've already called
1603
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1604
+	 *                                         malicious javascript. However, if
1605
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1606
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1607
+	 *                                         and every other field, before insertion. We provide this parameter
1608
+	 *                                         because model objects perform their prepare_for_set function on all
1609
+	 *                                         their values, and so don't need to be called again (and in many cases,
1610
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1611
+	 *                                         prepare_for_set method...)
1612
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1613
+	 *                                         in this model's entity map according to $fields_n_values that match
1614
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1615
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1616
+	 *                                         could get out-of-sync with the database
1617
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1618
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1619
+	 *                                         bad)
1620
+	 * @throws EE_Error
1621
+	 */
1622
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1623
+	{
1624
+		if (! is_array($query_params)) {
1625
+			EE_Error::doing_it_wrong(
1626
+				'EEM_Base::update',
1627
+				sprintf(
1628
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1629
+					gettype($query_params)
1630
+				),
1631
+				'4.6.0'
1632
+			);
1633
+			$query_params = array();
1634
+		}
1635
+		/**
1636
+		 * Action called before a model update call has been made.
1637
+		 *
1638
+		 * @param EEM_Base $model
1639
+		 * @param array    $fields_n_values the updated fields and their new values
1640
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1641
+		 */
1642
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1643
+		/**
1644
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1645
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1646
+		 *
1647
+		 * @param array    $fields_n_values fields and their new values
1648
+		 * @param EEM_Base $model           the model being queried
1649
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1650
+		 */
1651
+		$fields_n_values = (array) apply_filters(
1652
+			'FHEE__EEM_Base__update__fields_n_values',
1653
+			$fields_n_values,
1654
+			$this,
1655
+			$query_params
1656
+		);
1657
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1658
+		// to do that, for each table, verify that it's PK isn't null.
1659
+		$tables = $this->get_tables();
1660
+		// 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
1661
+		// NOTE: we should make this code more efficient by NOT querying twice
1662
+		// before the real update, but that needs to first go through ALPHA testing
1663
+		// as it's dangerous. says Mike August 8 2014
1664
+		// we want to make sure the default_where strategy is ignored
1665
+		$this->_ignore_where_strategy = true;
1666
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1667
+		foreach ($wpdb_select_results as $wpdb_result) {
1668
+			// type cast stdClass as array
1669
+			$wpdb_result = (array) $wpdb_result;
1670
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1671
+			if ($this->has_primary_key_field()) {
1672
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1673
+			} else {
1674
+				// 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)
1675
+				$main_table_pk_value = null;
1676
+			}
1677
+			// 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
1678
+			// 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
1679
+			if (count($tables) > 1) {
1680
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1681
+				// in that table, and so we'll want to insert one
1682
+				foreach ($tables as $table_obj) {
1683
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1684
+					// if there is no private key for this table on the results, it means there's no entry
1685
+					// in this table, right? so insert a row in the current table, using any fields available
1686
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1687
+						   && $wpdb_result[ $this_table_pk_column ])
1688
+					) {
1689
+						$success = $this->_insert_into_specific_table(
1690
+							$table_obj,
1691
+							$fields_n_values,
1692
+							$main_table_pk_value
1693
+						);
1694
+						// if we died here, report the error
1695
+						if (! $success) {
1696
+							return false;
1697
+						}
1698
+					}
1699
+				}
1700
+			}
1701
+			//              //and now check that if we have cached any models by that ID on the model, that
1702
+			//              //they also get updated properly
1703
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1704
+			//              if( $model_object ){
1705
+			//                  foreach( $fields_n_values as $field => $value ){
1706
+			//                      $model_object->set($field, $value);
1707
+			// let's make sure default_where strategy is followed now
1708
+			$this->_ignore_where_strategy = false;
1709
+		}
1710
+		// if we want to keep model objects in sync, AND
1711
+		// if this wasn't called from a model object (to update itself)
1712
+		// then we want to make sure we keep all the existing
1713
+		// model objects in sync with the db
1714
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1715
+			if ($this->has_primary_key_field()) {
1716
+				$model_objs_affected_ids = $this->get_col($query_params);
1717
+			} else {
1718
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1719
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1720
+				$model_objs_affected_ids = array();
1721
+				foreach ($models_affected_key_columns as $row) {
1722
+					$combined_index_key = $this->get_index_primary_key_string($row);
1723
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1724
+				}
1725
+			}
1726
+			if (! $model_objs_affected_ids) {
1727
+				// wait wait wait- if nothing was affected let's stop here
1728
+				return 0;
1729
+			}
1730
+			foreach ($model_objs_affected_ids as $id) {
1731
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1732
+				if ($model_obj_in_entity_map) {
1733
+					foreach ($fields_n_values as $field => $new_value) {
1734
+						$model_obj_in_entity_map->set($field, $new_value);
1735
+					}
1736
+				}
1737
+			}
1738
+			// if there is a primary key on this model, we can now do a slight optimization
1739
+			if ($this->has_primary_key_field()) {
1740
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1741
+				$query_params = array(
1742
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1743
+					'limit'                    => count($model_objs_affected_ids),
1744
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1745
+				);
1746
+			}
1747
+		}
1748
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1749
+		$SQL = "UPDATE "
1750
+			   . $model_query_info->get_full_join_sql()
1751
+			   . " SET "
1752
+			   . $this->_construct_update_sql($fields_n_values)
1753
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1754
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1755
+		/**
1756
+		 * Action called after a model update call has been made.
1757
+		 *
1758
+		 * @param EEM_Base $model
1759
+		 * @param array    $fields_n_values the updated fields and their new values
1760
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1761
+		 * @param int      $rows_affected
1762
+		 */
1763
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1764
+		return $rows_affected;// how many supposedly got updated
1765
+	}
1766
+
1767
+
1768
+
1769
+	/**
1770
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1771
+	 * are teh values of the field specified (or by default the primary key field)
1772
+	 * that matched the query params. Note that you should pass the name of the
1773
+	 * model FIELD, not the database table's column name.
1774
+	 *
1775
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1776
+	 * @param string $field_to_select
1777
+	 * @return array just like $wpdb->get_col()
1778
+	 * @throws EE_Error
1779
+	 */
1780
+	public function get_col($query_params = array(), $field_to_select = null)
1781
+	{
1782
+		if ($field_to_select) {
1783
+			$field = $this->field_settings_for($field_to_select);
1784
+		} elseif ($this->has_primary_key_field()) {
1785
+			$field = $this->get_primary_key_field();
1786
+		} else {
1787
+			// no primary key, just grab the first column
1788
+			$field = reset($this->field_settings());
1789
+		}
1790
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1791
+		$select_expressions = $field->get_qualified_column();
1792
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1793
+		return $this->_do_wpdb_query('get_col', array($SQL));
1794
+	}
1795
+
1796
+
1797
+
1798
+	/**
1799
+	 * Returns a single column value for a single row from the database
1800
+	 *
1801
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1802
+	 * @param string $field_to_select @see EEM_Base::get_col()
1803
+	 * @return string
1804
+	 * @throws EE_Error
1805
+	 */
1806
+	public function get_var($query_params = array(), $field_to_select = null)
1807
+	{
1808
+		$query_params['limit'] = 1;
1809
+		$col = $this->get_col($query_params, $field_to_select);
1810
+		if (! empty($col)) {
1811
+			return reset($col);
1812
+		}
1813
+		return null;
1814
+	}
1815
+
1816
+
1817
+
1818
+	/**
1819
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1820
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1821
+	 * injection, but currently no further filtering is done
1822
+	 *
1823
+	 * @global      $wpdb
1824
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1825
+	 *                               be updated to in the DB
1826
+	 * @return string of SQL
1827
+	 * @throws EE_Error
1828
+	 */
1829
+	public function _construct_update_sql($fields_n_values)
1830
+	{
1831
+		/** @type WPDB $wpdb */
1832
+		global $wpdb;
1833
+		$cols_n_values = array();
1834
+		foreach ($fields_n_values as $field_name => $value) {
1835
+			$field_obj = $this->field_settings_for($field_name);
1836
+			// if the value is NULL, we want to assign the value to that.
1837
+			// wpdb->prepare doesn't really handle that properly
1838
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1839
+			$value_sql = $prepared_value === null ? 'NULL'
1840
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1841
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1842
+		}
1843
+		return implode(",", $cols_n_values);
1844
+	}
1845
+
1846
+
1847
+
1848
+	/**
1849
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1850
+	 * Performs a HARD delete, meaning the database row should always be removed,
1851
+	 * not just have a flag field on it switched
1852
+	 * Wrapper for EEM_Base::delete_permanently()
1853
+	 *
1854
+	 * @param mixed $id
1855
+	 * @param boolean $allow_blocking
1856
+	 * @return int the number of rows deleted
1857
+	 * @throws EE_Error
1858
+	 */
1859
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1860
+	{
1861
+		return $this->delete_permanently(
1862
+			array(
1863
+				array($this->get_primary_key_field()->get_name() => $id),
1864
+				'limit' => 1,
1865
+			),
1866
+			$allow_blocking
1867
+		);
1868
+	}
1869
+
1870
+
1871
+
1872
+	/**
1873
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1874
+	 * Wrapper for EEM_Base::delete()
1875
+	 *
1876
+	 * @param mixed $id
1877
+	 * @param boolean $allow_blocking
1878
+	 * @return int the number of rows deleted
1879
+	 * @throws EE_Error
1880
+	 */
1881
+	public function delete_by_ID($id, $allow_blocking = true)
1882
+	{
1883
+		return $this->delete(
1884
+			array(
1885
+				array($this->get_primary_key_field()->get_name() => $id),
1886
+				'limit' => 1,
1887
+			),
1888
+			$allow_blocking
1889
+		);
1890
+	}
1891
+
1892
+
1893
+
1894
+	/**
1895
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1896
+	 * meaning if the model has a field that indicates its been "trashed" or
1897
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1898
+	 *
1899
+	 * @see EEM_Base::delete_permanently
1900
+	 * @param array   $query_params
1901
+	 * @param boolean $allow_blocking
1902
+	 * @return int how many rows got deleted
1903
+	 * @throws EE_Error
1904
+	 */
1905
+	public function delete($query_params, $allow_blocking = true)
1906
+	{
1907
+		return $this->delete_permanently($query_params, $allow_blocking);
1908
+	}
1909
+
1910
+
1911
+
1912
+	/**
1913
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1914
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1915
+	 * as archived, not actually deleted
1916
+	 *
1917
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1918
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1919
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1920
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1921
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1922
+	 *                                DB
1923
+	 * @return int how many rows got deleted
1924
+	 * @throws EE_Error
1925
+	 */
1926
+	public function delete_permanently($query_params, $allow_blocking = true)
1927
+	{
1928
+		/**
1929
+		 * Action called just before performing a real deletion query. You can use the
1930
+		 * model and its $query_params to find exactly which items will be deleted
1931
+		 *
1932
+		 * @param EEM_Base $model
1933
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1934
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1935
+		 *                                 to block (prevent) this deletion
1936
+		 */
1937
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1938
+		// some MySQL databases may be running safe mode, which may restrict
1939
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1940
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1941
+		// to delete them
1942
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1943
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1944
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1945
+			$columns_and_ids_for_deleting
1946
+		);
1947
+		/**
1948
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1949
+		 *
1950
+		 * @param EEM_Base $this  The model instance being acted on.
1951
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1952
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1953
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1954
+		 *                                                  derived from the incoming query parameters.
1955
+		 *                                                  @see details on the structure of this array in the phpdocs
1956
+		 *                                                  for the `_get_ids_for_delete_method`
1957
+		 *
1958
+		 */
1959
+		do_action(
1960
+			'AHEE__EEM_Base__delete__before_query',
1961
+			$this,
1962
+			$query_params,
1963
+			$allow_blocking,
1964
+			$columns_and_ids_for_deleting
1965
+		);
1966
+		if ($deletion_where_query_part) {
1967
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1968
+			$table_aliases = array_keys($this->_tables);
1969
+			$SQL = "DELETE "
1970
+				   . implode(", ", $table_aliases)
1971
+				   . " FROM "
1972
+				   . $model_query_info->get_full_join_sql()
1973
+				   . " WHERE "
1974
+				   . $deletion_where_query_part;
1975
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1976
+		} else {
1977
+			$rows_deleted = 0;
1978
+		}
1979
+
1980
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1981
+		// there was no error with the delete query.
1982
+		if ($this->has_primary_key_field()
1983
+			&& $rows_deleted !== false
1984
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1985
+		) {
1986
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1987
+			foreach ($ids_for_removal as $id) {
1988
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1989
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1990
+				}
1991
+			}
1992
+
1993
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1994
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1995
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1996
+			// (although it is possible).
1997
+			// Note this can be skipped by using the provided filter and returning false.
1998
+			if (apply_filters(
1999
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2000
+				! $this instanceof EEM_Extra_Meta,
2001
+				$this
2002
+			)) {
2003
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2004
+					0 => array(
2005
+						'EXM_type' => $this->get_this_model_name(),
2006
+						'OBJ_ID'   => array(
2007
+							'IN',
2008
+							$ids_for_removal
2009
+						)
2010
+					)
2011
+				));
2012
+			}
2013
+		}
2014
+
2015
+		/**
2016
+		 * Action called just after performing a real deletion query. Although at this point the
2017
+		 * items should have been deleted
2018
+		 *
2019
+		 * @param EEM_Base $model
2020
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2021
+		 * @param int      $rows_deleted
2022
+		 */
2023
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2024
+		return $rows_deleted;// how many supposedly got deleted
2025
+	}
2026
+
2027
+
2028
+
2029
+	/**
2030
+	 * Checks all the relations that throw error messages when there are blocking related objects
2031
+	 * for related model objects. If there are any related model objects on those relations,
2032
+	 * adds an EE_Error, and return true
2033
+	 *
2034
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2035
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2036
+	 *                                                 should be ignored when determining whether there are related
2037
+	 *                                                 model objects which block this model object's deletion. Useful
2038
+	 *                                                 if you know A is related to B and are considering deleting A,
2039
+	 *                                                 but want to see if A has any other objects blocking its deletion
2040
+	 *                                                 before removing the relation between A and B
2041
+	 * @return boolean
2042
+	 * @throws EE_Error
2043
+	 */
2044
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2045
+	{
2046
+		// first, if $ignore_this_model_obj was supplied, get its model
2047
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2048
+			$ignored_model = $ignore_this_model_obj->get_model();
2049
+		} else {
2050
+			$ignored_model = null;
2051
+		}
2052
+		// now check all the relations of $this_model_obj_or_id and see if there
2053
+		// are any related model objects blocking it?
2054
+		$is_blocked = false;
2055
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2056
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2057
+				// if $ignore_this_model_obj was supplied, then for the query
2058
+				// on that model needs to be told to ignore $ignore_this_model_obj
2059
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2060
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2061
+						array(
2062
+							$ignored_model->get_primary_key_field()->get_name() => array(
2063
+								'!=',
2064
+								$ignore_this_model_obj->ID(),
2065
+							),
2066
+						),
2067
+					));
2068
+				} else {
2069
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2070
+				}
2071
+				if ($related_model_objects) {
2072
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2073
+					$is_blocked = true;
2074
+				}
2075
+			}
2076
+		}
2077
+		return $is_blocked;
2078
+	}
2079
+
2080
+
2081
+	/**
2082
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2083
+	 * @param array $row_results_for_deleting
2084
+	 * @param bool  $allow_blocking
2085
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2086
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2087
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2088
+	 *                 deleted. Example:
2089
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2090
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2091
+	 *                 where each element is a group of columns and values that get deleted. Example:
2092
+	 *                      array(
2093
+	 *                          0 => array(
2094
+	 *                              'Term_Relationship.object_id' => 1
2095
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2096
+	 *                          ),
2097
+	 *                          1 => array(
2098
+	 *                              'Term_Relationship.object_id' => 1
2099
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2100
+	 *                          )
2101
+	 *                      )
2102
+	 * @throws EE_Error
2103
+	 */
2104
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2105
+	{
2106
+		$ids_to_delete_indexed_by_column = array();
2107
+		if ($this->has_primary_key_field()) {
2108
+			$primary_table = $this->_get_main_table();
2109
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2110
+			$other_tables = $this->_get_other_tables();
2111
+			$ids_to_delete_indexed_by_column = $query = array();
2112
+			foreach ($row_results_for_deleting as $item_to_delete) {
2113
+				// before we mark this item for deletion,
2114
+				// make sure there's no related entities blocking its deletion (if we're checking)
2115
+				if ($allow_blocking
2116
+					&& $this->delete_is_blocked_by_related_models(
2117
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2118
+					)
2119
+				) {
2120
+					continue;
2121
+				}
2122
+				// primary table deletes
2123
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2124
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2125
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2126
+				}
2127
+			}
2128
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2129
+			$fields = $this->get_combined_primary_key_fields();
2130
+			foreach ($row_results_for_deleting as $item_to_delete) {
2131
+				$ids_to_delete_indexed_by_column_for_row = array();
2132
+				foreach ($fields as $cpk_field) {
2133
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2134
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2135
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2136
+					}
2137
+				}
2138
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2139
+			}
2140
+		} else {
2141
+			// so there's no primary key and no combined key...
2142
+			// sorry, can't help you
2143
+			throw new EE_Error(
2144
+				sprintf(
2145
+					__(
2146
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2147
+						"event_espresso"
2148
+					),
2149
+					get_class($this)
2150
+				)
2151
+			);
2152
+		}
2153
+		return $ids_to_delete_indexed_by_column;
2154
+	}
2155
+
2156
+
2157
+	/**
2158
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2159
+	 * the corresponding query_part for the query performing the delete.
2160
+	 *
2161
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2162
+	 * @return string
2163
+	 * @throws EE_Error
2164
+	 */
2165
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2166
+	{
2167
+		$query_part = '';
2168
+		if (empty($ids_to_delete_indexed_by_column)) {
2169
+			return $query_part;
2170
+		} elseif ($this->has_primary_key_field()) {
2171
+			$query = array();
2172
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2173
+				$query[] = $column . ' IN' . $this->_construct_in_value($ids, $this->_primary_key_field);
2174
+			}
2175
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2176
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2177
+			$ways_to_identify_a_row = array();
2178
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2179
+				$values_for_each_combined_primary_key_for_a_row = array();
2180
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2181
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2182
+				}
2183
+				$ways_to_identify_a_row[] = '('
2184
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2185
+											. ')';
2186
+			}
2187
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2188
+		}
2189
+		return $query_part;
2190
+	}
2191
+
2192
+
2193
+
2194
+	/**
2195
+	 * Gets the model field by the fully qualified name
2196
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2197
+	 * @return EE_Model_Field_Base
2198
+	 */
2199
+	public function get_field_by_column($qualified_column_name)
2200
+	{
2201
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2202
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2203
+				return $field_obj;
2204
+			}
2205
+		}
2206
+		throw new EE_Error(
2207
+			sprintf(
2208
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2209
+				$this->get_this_model_name(),
2210
+				$qualified_column_name
2211
+			)
2212
+		);
2213
+	}
2214
+
2215
+
2216
+
2217
+	/**
2218
+	 * Count all the rows that match criteria the model query params.
2219
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2220
+	 * column
2221
+	 *
2222
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2223
+	 * @param string $field_to_count field on model to count by (not column name)
2224
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2225
+	 *                               that by the setting $distinct to TRUE;
2226
+	 * @return int
2227
+	 * @throws EE_Error
2228
+	 */
2229
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2230
+	{
2231
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2232
+		if ($field_to_count) {
2233
+			$field_obj = $this->field_settings_for($field_to_count);
2234
+			$column_to_count = $field_obj->get_qualified_column();
2235
+		} elseif ($this->has_primary_key_field()) {
2236
+			$pk_field_obj = $this->get_primary_key_field();
2237
+			$column_to_count = $pk_field_obj->get_qualified_column();
2238
+		} else {
2239
+			// there's no primary key
2240
+			// if we're counting distinct items, and there's no primary key,
2241
+			// we need to list out the columns for distinction;
2242
+			// otherwise we can just use star
2243
+			if ($distinct) {
2244
+				$columns_to_use = array();
2245
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2246
+					$columns_to_use[] = $field_obj->get_qualified_column();
2247
+				}
2248
+				$column_to_count = implode(',', $columns_to_use);
2249
+			} else {
2250
+				$column_to_count = '*';
2251
+			}
2252
+		}
2253
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2254
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2255
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2256
+	}
2257
+
2258
+
2259
+
2260
+	/**
2261
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2262
+	 *
2263
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2264
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2265
+	 * @return float
2266
+	 * @throws EE_Error
2267
+	 */
2268
+	public function sum($query_params, $field_to_sum = null)
2269
+	{
2270
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2271
+		if ($field_to_sum) {
2272
+			$field_obj = $this->field_settings_for($field_to_sum);
2273
+		} else {
2274
+			$field_obj = $this->get_primary_key_field();
2275
+		}
2276
+		$column_to_count = $field_obj->get_qualified_column();
2277
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2278
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2279
+		$data_type = $field_obj->get_wpdb_data_type();
2280
+		if ($data_type === '%d' || $data_type === '%s') {
2281
+			return (float) $return_value;
2282
+		}
2283
+		// must be %f
2284
+		return (float) $return_value;
2285
+	}
2286
+
2287
+
2288
+
2289
+	/**
2290
+	 * Just calls the specified method on $wpdb with the given arguments
2291
+	 * Consolidates a little extra error handling code
2292
+	 *
2293
+	 * @param string $wpdb_method
2294
+	 * @param array  $arguments_to_provide
2295
+	 * @throws EE_Error
2296
+	 * @global wpdb  $wpdb
2297
+	 * @return mixed
2298
+	 */
2299
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2300
+	{
2301
+		// if we're in maintenance mode level 2, DON'T run any queries
2302
+		// because level 2 indicates the database needs updating and
2303
+		// is probably out of sync with the code
2304
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2305
+			throw new EE_Error(sprintf(__(
2306
+				"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.",
2307
+				"event_espresso"
2308
+			)));
2309
+		}
2310
+		/** @type WPDB $wpdb */
2311
+		global $wpdb;
2312
+		if (! method_exists($wpdb, $wpdb_method)) {
2313
+			throw new EE_Error(sprintf(__(
2314
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2315
+				'event_espresso'
2316
+			), $wpdb_method));
2317
+		}
2318
+		if (WP_DEBUG) {
2319
+			$old_show_errors_value = $wpdb->show_errors;
2320
+			$wpdb->show_errors(false);
2321
+		}
2322
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2323
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2324
+		if (WP_DEBUG) {
2325
+			$wpdb->show_errors($old_show_errors_value);
2326
+			if (! empty($wpdb->last_error)) {
2327
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2328
+			}
2329
+			if ($result === false) {
2330
+				throw new EE_Error(sprintf(__(
2331
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2332
+					'event_espresso'
2333
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2334
+			}
2335
+		} elseif ($result === false) {
2336
+			EE_Error::add_error(
2337
+				sprintf(
2338
+					__(
2339
+						'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"',
2340
+						'event_espresso'
2341
+					),
2342
+					$wpdb_method,
2343
+					var_export($arguments_to_provide, true),
2344
+					$wpdb->last_error
2345
+				),
2346
+				__FILE__,
2347
+				__FUNCTION__,
2348
+				__LINE__
2349
+			);
2350
+		}
2351
+		return $result;
2352
+	}
2353
+
2354
+
2355
+
2356
+	/**
2357
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2358
+	 * and if there's an error tries to verify the DB is correct. Uses
2359
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2360
+	 * we should try to fix the EE core db, the addons, or just give up
2361
+	 *
2362
+	 * @param string $wpdb_method
2363
+	 * @param array  $arguments_to_provide
2364
+	 * @return mixed
2365
+	 */
2366
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2367
+	{
2368
+		/** @type WPDB $wpdb */
2369
+		global $wpdb;
2370
+		$wpdb->last_error = null;
2371
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2372
+		// was there an error running the query? but we don't care on new activations
2373
+		// (we're going to setup the DB anyway on new activations)
2374
+		if (($result === false || ! empty($wpdb->last_error))
2375
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2376
+		) {
2377
+			switch (EEM_Base::$_db_verification_level) {
2378
+				case EEM_Base::db_verified_none:
2379
+					// let's double-check core's DB
2380
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2381
+					break;
2382
+				case EEM_Base::db_verified_core:
2383
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2384
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2385
+					break;
2386
+				case EEM_Base::db_verified_addons:
2387
+					// ummmm... you in trouble
2388
+					return $result;
2389
+					break;
2390
+			}
2391
+			if (! empty($error_message)) {
2392
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2393
+				trigger_error($error_message);
2394
+			}
2395
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2396
+		}
2397
+		return $result;
2398
+	}
2399
+
2400
+
2401
+
2402
+	/**
2403
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2404
+	 * EEM_Base::$_db_verification_level
2405
+	 *
2406
+	 * @param string $wpdb_method
2407
+	 * @param array  $arguments_to_provide
2408
+	 * @return string
2409
+	 */
2410
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2411
+	{
2412
+		/** @type WPDB $wpdb */
2413
+		global $wpdb;
2414
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2415
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2416
+		$error_message = sprintf(
2417
+			__(
2418
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2419
+				'event_espresso'
2420
+			),
2421
+			$wpdb->last_error,
2422
+			$wpdb_method,
2423
+			wp_json_encode($arguments_to_provide)
2424
+		);
2425
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2426
+		return $error_message;
2427
+	}
2428
+
2429
+
2430
+
2431
+	/**
2432
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2433
+	 * EEM_Base::$_db_verification_level
2434
+	 *
2435
+	 * @param $wpdb_method
2436
+	 * @param $arguments_to_provide
2437
+	 * @return string
2438
+	 */
2439
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2440
+	{
2441
+		/** @type WPDB $wpdb */
2442
+		global $wpdb;
2443
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2444
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2445
+		$error_message = sprintf(
2446
+			__(
2447
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2448
+				'event_espresso'
2449
+			),
2450
+			$wpdb->last_error,
2451
+			$wpdb_method,
2452
+			wp_json_encode($arguments_to_provide)
2453
+		);
2454
+		EE_System::instance()->initialize_addons();
2455
+		return $error_message;
2456
+	}
2457
+
2458
+
2459
+
2460
+	/**
2461
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2462
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2463
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2464
+	 * ..."
2465
+	 *
2466
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2467
+	 * @return string
2468
+	 */
2469
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2470
+	{
2471
+		return " FROM " . $model_query_info->get_full_join_sql() .
2472
+			   $model_query_info->get_where_sql() .
2473
+			   $model_query_info->get_group_by_sql() .
2474
+			   $model_query_info->get_having_sql() .
2475
+			   $model_query_info->get_order_by_sql() .
2476
+			   $model_query_info->get_limit_sql();
2477
+	}
2478
+
2479
+
2480
+
2481
+	/**
2482
+	 * Set to easily debug the next X queries ran from this model.
2483
+	 *
2484
+	 * @param int $count
2485
+	 */
2486
+	public function show_next_x_db_queries($count = 1)
2487
+	{
2488
+		$this->_show_next_x_db_queries = $count;
2489
+	}
2490
+
2491
+
2492
+
2493
+	/**
2494
+	 * @param $sql_query
2495
+	 */
2496
+	public function show_db_query_if_previously_requested($sql_query)
2497
+	{
2498
+		if ($this->_show_next_x_db_queries > 0) {
2499
+			echo $sql_query;
2500
+			$this->_show_next_x_db_queries--;
2501
+		}
2502
+	}
2503
+
2504
+
2505
+
2506
+	/**
2507
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2508
+	 * There are the 3 cases:
2509
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2510
+	 * $otherModelObject has no ID, it is first saved.
2511
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2512
+	 * has no ID, it is first saved.
2513
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2514
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2515
+	 * join table
2516
+	 *
2517
+	 * @param        EE_Base_Class                     /int $thisModelObject
2518
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2519
+	 * @param string $relationName                     , key in EEM_Base::_relations
2520
+	 *                                                 an attendee to a group, you also want to specify which role they
2521
+	 *                                                 will have in that group. So you would use this parameter to
2522
+	 *                                                 specify array('role-column-name'=>'role-id')
2523
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2524
+	 *                                                 to for relation to methods that allow you to further specify
2525
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2526
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2527
+	 *                                                 because these will be inserted in any new rows created as well.
2528
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2529
+	 * @throws EE_Error
2530
+	 */
2531
+	public function add_relationship_to(
2532
+		$id_or_obj,
2533
+		$other_model_id_or_obj,
2534
+		$relationName,
2535
+		$extra_join_model_fields_n_values = array()
2536
+	) {
2537
+		$relation_obj = $this->related_settings_for($relationName);
2538
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2539
+	}
2540
+
2541
+
2542
+
2543
+	/**
2544
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2545
+	 * There are the 3 cases:
2546
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2547
+	 * error
2548
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2549
+	 * an error
2550
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2551
+	 *
2552
+	 * @param        EE_Base_Class /int $id_or_obj
2553
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2554
+	 * @param string $relationName key in EEM_Base::_relations
2555
+	 * @return boolean of success
2556
+	 * @throws EE_Error
2557
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2558
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2559
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2560
+	 *                             because these will be inserted in any new rows created as well.
2561
+	 */
2562
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2563
+	{
2564
+		$relation_obj = $this->related_settings_for($relationName);
2565
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2566
+	}
2567
+
2568
+
2569
+
2570
+	/**
2571
+	 * @param mixed           $id_or_obj
2572
+	 * @param string          $relationName
2573
+	 * @param array           $where_query_params
2574
+	 * @param EE_Base_Class[] objects to which relations were removed
2575
+	 * @return \EE_Base_Class[]
2576
+	 * @throws EE_Error
2577
+	 */
2578
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2579
+	{
2580
+		$relation_obj = $this->related_settings_for($relationName);
2581
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2582
+	}
2583
+
2584
+
2585
+
2586
+	/**
2587
+	 * Gets all the related items of the specified $model_name, using $query_params.
2588
+	 * Note: by default, we remove the "default query params"
2589
+	 * because we want to get even deleted items etc.
2590
+	 *
2591
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2592
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2593
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2594
+	 * @return EE_Base_Class[]
2595
+	 * @throws EE_Error
2596
+	 */
2597
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2598
+	{
2599
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2600
+		$relation_settings = $this->related_settings_for($model_name);
2601
+		return $relation_settings->get_all_related($model_obj, $query_params);
2602
+	}
2603
+
2604
+
2605
+
2606
+	/**
2607
+	 * Deletes all the model objects across the relation indicated by $model_name
2608
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2609
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2610
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2611
+	 *
2612
+	 * @param EE_Base_Class|int|string $id_or_obj
2613
+	 * @param string                   $model_name
2614
+	 * @param array                    $query_params
2615
+	 * @return int how many deleted
2616
+	 * @throws EE_Error
2617
+	 */
2618
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2619
+	{
2620
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2621
+		$relation_settings = $this->related_settings_for($model_name);
2622
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2623
+	}
2624
+
2625
+
2626
+
2627
+	/**
2628
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2629
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2630
+	 * the model objects can't be hard deleted because of blocking related model objects,
2631
+	 * just does a soft-delete on them instead.
2632
+	 *
2633
+	 * @param EE_Base_Class|int|string $id_or_obj
2634
+	 * @param string                   $model_name
2635
+	 * @param array                    $query_params
2636
+	 * @return int how many deleted
2637
+	 * @throws EE_Error
2638
+	 */
2639
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2640
+	{
2641
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2642
+		$relation_settings = $this->related_settings_for($model_name);
2643
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2644
+	}
2645
+
2646
+
2647
+
2648
+	/**
2649
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2650
+	 * unless otherwise specified in the $query_params
2651
+	 *
2652
+	 * @param        int             /EE_Base_Class $id_or_obj
2653
+	 * @param string $model_name     like 'Event', or 'Registration'
2654
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2655
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2656
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2657
+	 *                               that by the setting $distinct to TRUE;
2658
+	 * @return int
2659
+	 * @throws EE_Error
2660
+	 */
2661
+	public function count_related(
2662
+		$id_or_obj,
2663
+		$model_name,
2664
+		$query_params = array(),
2665
+		$field_to_count = null,
2666
+		$distinct = false
2667
+	) {
2668
+		$related_model = $this->get_related_model_obj($model_name);
2669
+		// we're just going to use the query params on the related model's normal get_all query,
2670
+		// except add a condition to say to match the current mod
2671
+		if (! isset($query_params['default_where_conditions'])) {
2672
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2673
+		}
2674
+		$this_model_name = $this->get_this_model_name();
2675
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2676
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2677
+		return $related_model->count($query_params, $field_to_count, $distinct);
2678
+	}
2679
+
2680
+
2681
+
2682
+	/**
2683
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2684
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2685
+	 *
2686
+	 * @param        int           /EE_Base_Class $id_or_obj
2687
+	 * @param string $model_name   like 'Event', or 'Registration'
2688
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2689
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2690
+	 * @return float
2691
+	 * @throws EE_Error
2692
+	 */
2693
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2694
+	{
2695
+		$related_model = $this->get_related_model_obj($model_name);
2696
+		if (! is_array($query_params)) {
2697
+			EE_Error::doing_it_wrong(
2698
+				'EEM_Base::sum_related',
2699
+				sprintf(
2700
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2701
+					gettype($query_params)
2702
+				),
2703
+				'4.6.0'
2704
+			);
2705
+			$query_params = array();
2706
+		}
2707
+		// we're just going to use the query params on the related model's normal get_all query,
2708
+		// except add a condition to say to match the current mod
2709
+		if (! isset($query_params['default_where_conditions'])) {
2710
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2711
+		}
2712
+		$this_model_name = $this->get_this_model_name();
2713
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2714
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2715
+		return $related_model->sum($query_params, $field_to_sum);
2716
+	}
2717
+
2718
+
2719
+
2720
+	/**
2721
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2722
+	 * $modelObject
2723
+	 *
2724
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2725
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2726
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2727
+	 * @return EE_Base_Class
2728
+	 * @throws EE_Error
2729
+	 */
2730
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2731
+	{
2732
+		$query_params['limit'] = 1;
2733
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2734
+		if ($results) {
2735
+			return array_shift($results);
2736
+		}
2737
+		return null;
2738
+	}
2739
+
2740
+
2741
+
2742
+	/**
2743
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2744
+	 *
2745
+	 * @return string
2746
+	 */
2747
+	public function get_this_model_name()
2748
+	{
2749
+		return str_replace("EEM_", "", get_class($this));
2750
+	}
2751
+
2752
+
2753
+
2754
+	/**
2755
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2756
+	 *
2757
+	 * @return EE_Any_Foreign_Model_Name_Field
2758
+	 * @throws EE_Error
2759
+	 */
2760
+	public function get_field_containing_related_model_name()
2761
+	{
2762
+		foreach ($this->field_settings(true) as $field) {
2763
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2764
+				$field_with_model_name = $field;
2765
+			}
2766
+		}
2767
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2768
+			throw new EE_Error(sprintf(
2769
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2770
+				$this->get_this_model_name()
2771
+			));
2772
+		}
2773
+		return $field_with_model_name;
2774
+	}
2775
+
2776
+
2777
+
2778
+	/**
2779
+	 * Inserts a new entry into the database, for each table.
2780
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2781
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2782
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2783
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2784
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2785
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2786
+	 *
2787
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2788
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2789
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2790
+	 *                              of EEM_Base)
2791
+	 * @return int|string new primary key on main table that got inserted
2792
+	 * @throws EE_Error
2793
+	 */
2794
+	public function insert($field_n_values)
2795
+	{
2796
+		/**
2797
+		 * Filters the fields and their values before inserting an item using the models
2798
+		 *
2799
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2800
+		 * @param EEM_Base $model           the model used
2801
+		 */
2802
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2803
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2804
+			$main_table = $this->_get_main_table();
2805
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2806
+			if ($new_id !== false) {
2807
+				foreach ($this->_get_other_tables() as $other_table) {
2808
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2809
+				}
2810
+			}
2811
+			/**
2812
+			 * Done just after attempting to insert a new model object
2813
+			 *
2814
+			 * @param EEM_Base   $model           used
2815
+			 * @param array      $fields_n_values fields and their values
2816
+			 * @param int|string the              ID of the newly-inserted model object
2817
+			 */
2818
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2819
+			return $new_id;
2820
+		}
2821
+		return false;
2822
+	}
2823
+
2824
+
2825
+
2826
+	/**
2827
+	 * Checks that the result would satisfy the unique indexes on this model
2828
+	 *
2829
+	 * @param array  $field_n_values
2830
+	 * @param string $action
2831
+	 * @return boolean
2832
+	 * @throws EE_Error
2833
+	 */
2834
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2835
+	{
2836
+		foreach ($this->unique_indexes() as $index_name => $index) {
2837
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2838
+			if ($this->exists(array($uniqueness_where_params))) {
2839
+				EE_Error::add_error(
2840
+					sprintf(
2841
+						__(
2842
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2843
+							"event_espresso"
2844
+						),
2845
+						$action,
2846
+						$this->_get_class_name(),
2847
+						$index_name,
2848
+						implode(",", $index->field_names()),
2849
+						http_build_query($uniqueness_where_params)
2850
+					),
2851
+					__FILE__,
2852
+					__FUNCTION__,
2853
+					__LINE__
2854
+				);
2855
+				return false;
2856
+			}
2857
+		}
2858
+		return true;
2859
+	}
2860
+
2861
+
2862
+
2863
+	/**
2864
+	 * Checks the database for an item that conflicts (ie, if this item were
2865
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2866
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2867
+	 * can be either an EE_Base_Class or an array of fields n values
2868
+	 *
2869
+	 * @param EE_Base_Class|array $obj_or_fields_array
2870
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2871
+	 *                                                 when looking for conflicts
2872
+	 *                                                 (ie, if false, we ignore the model object's primary key
2873
+	 *                                                 when finding "conflicts". If true, it's also considered).
2874
+	 *                                                 Only works for INT primary key,
2875
+	 *                                                 STRING primary keys cannot be ignored
2876
+	 * @throws EE_Error
2877
+	 * @return EE_Base_Class|array
2878
+	 */
2879
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2880
+	{
2881
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2882
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2883
+		} elseif (is_array($obj_or_fields_array)) {
2884
+			$fields_n_values = $obj_or_fields_array;
2885
+		} else {
2886
+			throw new EE_Error(
2887
+				sprintf(
2888
+					__(
2889
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2890
+						"event_espresso"
2891
+					),
2892
+					get_class($this),
2893
+					$obj_or_fields_array
2894
+				)
2895
+			);
2896
+		}
2897
+		$query_params = array();
2898
+		if ($this->has_primary_key_field()
2899
+			&& ($include_primary_key
2900
+				|| $this->get_primary_key_field()
2901
+				   instanceof
2902
+				   EE_Primary_Key_String_Field)
2903
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2904
+		) {
2905
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2906
+		}
2907
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2908
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2909
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2910
+		}
2911
+		// if there is nothing to base this search on, then we shouldn't find anything
2912
+		if (empty($query_params)) {
2913
+			return array();
2914
+		}
2915
+		return $this->get_one($query_params);
2916
+	}
2917
+
2918
+
2919
+
2920
+	/**
2921
+	 * Like count, but is optimized and returns a boolean instead of an int
2922
+	 *
2923
+	 * @param array $query_params
2924
+	 * @return boolean
2925
+	 * @throws EE_Error
2926
+	 */
2927
+	public function exists($query_params)
2928
+	{
2929
+		$query_params['limit'] = 1;
2930
+		return $this->count($query_params) > 0;
2931
+	}
2932
+
2933
+
2934
+
2935
+	/**
2936
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2937
+	 *
2938
+	 * @param int|string $id
2939
+	 * @return boolean
2940
+	 * @throws EE_Error
2941
+	 */
2942
+	public function exists_by_ID($id)
2943
+	{
2944
+		return $this->exists(
2945
+			array(
2946
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2947
+				array(
2948
+					$this->primary_key_name() => $id,
2949
+				),
2950
+			)
2951
+		);
2952
+	}
2953
+
2954
+
2955
+
2956
+	/**
2957
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2958
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2959
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2960
+	 * on the main table)
2961
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2962
+	 * cases where we want to call it directly rather than via insert().
2963
+	 *
2964
+	 * @access   protected
2965
+	 * @param EE_Table_Base $table
2966
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2967
+	 *                                       float
2968
+	 * @param int           $new_id          for now we assume only int keys
2969
+	 * @throws EE_Error
2970
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2971
+	 * @return int ID of new row inserted, or FALSE on failure
2972
+	 */
2973
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2974
+	{
2975
+		global $wpdb;
2976
+		$insertion_col_n_values = array();
2977
+		$format_for_insertion = array();
2978
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2979
+		foreach ($fields_on_table as $field_name => $field_obj) {
2980
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2981
+			if ($field_obj->is_auto_increment()) {
2982
+				continue;
2983
+			}
2984
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2985
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2986
+			if ($prepared_value !== null) {
2987
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2988
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2989
+			}
2990
+		}
2991
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2992
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2993
+			// so add the fk to the main table as a column
2994
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2995
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2996
+		}
2997
+		// insert the new entry
2998
+		$result = $this->_do_wpdb_query(
2999
+			'insert',
3000
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3001
+		);
3002
+		if ($result === false) {
3003
+			return false;
3004
+		}
3005
+		// ok, now what do we return for the ID of the newly-inserted thing?
3006
+		if ($this->has_primary_key_field()) {
3007
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3008
+				return $wpdb->insert_id;
3009
+			}
3010
+			// it's not an auto-increment primary key, so
3011
+			// it must have been supplied
3012
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3013
+		}
3014
+		// we can't return a  primary key because there is none. instead return
3015
+		// a unique string indicating this model
3016
+		return $this->get_index_primary_key_string($fields_n_values);
3017
+	}
3018
+
3019
+
3020
+
3021
+	/**
3022
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3023
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3024
+	 * and there is no default, we pass it along. WPDB will take care of it)
3025
+	 *
3026
+	 * @param EE_Model_Field_Base $field_obj
3027
+	 * @param array               $fields_n_values
3028
+	 * @return mixed string|int|float depending on what the table column will be expecting
3029
+	 * @throws EE_Error
3030
+	 */
3031
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3032
+	{
3033
+		// if this field doesn't allow nullable, don't allow it
3034
+		if (! $field_obj->is_nullable()
3035
+			&& (
3036
+				! isset($fields_n_values[ $field_obj->get_name() ])
3037
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3038
+			)
3039
+		) {
3040
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3041
+		}
3042
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3043
+			? $fields_n_values[ $field_obj->get_name() ]
3044
+			: null;
3045
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3046
+	}
3047
+
3048
+
3049
+
3050
+	/**
3051
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3052
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3053
+	 * the field's prepare_for_set() method.
3054
+	 *
3055
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3056
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3057
+	 *                                   top of file)
3058
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3059
+	 *                                   $value is a custom selection
3060
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3061
+	 */
3062
+	private function _prepare_value_for_use_in_db($value, $field)
3063
+	{
3064
+		if ($field && $field instanceof EE_Model_Field_Base) {
3065
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3066
+			switch ($this->_values_already_prepared_by_model_object) {
3067
+				/** @noinspection PhpMissingBreakStatementInspection */
3068
+				case self::not_prepared_by_model_object:
3069
+					$value = $field->prepare_for_set($value);
3070
+				// purposefully left out "return"
3071
+				case self::prepared_by_model_object:
3072
+					/** @noinspection SuspiciousAssignmentsInspection */
3073
+					$value = $field->prepare_for_use_in_db($value);
3074
+				case self::prepared_for_use_in_db:
3075
+					// leave the value alone
3076
+			}
3077
+			return $value;
3078
+			// phpcs:enable
3079
+		}
3080
+		return $value;
3081
+	}
3082
+
3083
+
3084
+
3085
+	/**
3086
+	 * Returns the main table on this model
3087
+	 *
3088
+	 * @return EE_Primary_Table
3089
+	 * @throws EE_Error
3090
+	 */
3091
+	protected function _get_main_table()
3092
+	{
3093
+		foreach ($this->_tables as $table) {
3094
+			if ($table instanceof EE_Primary_Table) {
3095
+				return $table;
3096
+			}
3097
+		}
3098
+		throw new EE_Error(sprintf(__(
3099
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3100
+			'event_espresso'
3101
+		), get_class($this)));
3102
+	}
3103
+
3104
+
3105
+
3106
+	/**
3107
+	 * table
3108
+	 * returns EE_Primary_Table table name
3109
+	 *
3110
+	 * @return string
3111
+	 * @throws EE_Error
3112
+	 */
3113
+	public function table()
3114
+	{
3115
+		return $this->_get_main_table()->get_table_name();
3116
+	}
3117
+
3118
+
3119
+
3120
+	/**
3121
+	 * table
3122
+	 * returns first EE_Secondary_Table table name
3123
+	 *
3124
+	 * @return string
3125
+	 */
3126
+	public function second_table()
3127
+	{
3128
+		// grab second table from tables array
3129
+		$second_table = end($this->_tables);
3130
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3131
+	}
3132
+
3133
+
3134
+
3135
+	/**
3136
+	 * get_table_obj_by_alias
3137
+	 * returns table name given it's alias
3138
+	 *
3139
+	 * @param string $table_alias
3140
+	 * @return EE_Primary_Table | EE_Secondary_Table
3141
+	 */
3142
+	public function get_table_obj_by_alias($table_alias = '')
3143
+	{
3144
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3145
+	}
3146
+
3147
+
3148
+
3149
+	/**
3150
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3151
+	 *
3152
+	 * @return EE_Secondary_Table[]
3153
+	 */
3154
+	protected function _get_other_tables()
3155
+	{
3156
+		$other_tables = array();
3157
+		foreach ($this->_tables as $table_alias => $table) {
3158
+			if ($table instanceof EE_Secondary_Table) {
3159
+				$other_tables[ $table_alias ] = $table;
3160
+			}
3161
+		}
3162
+		return $other_tables;
3163
+	}
3164
+
3165
+
3166
+
3167
+	/**
3168
+	 * Finds all the fields that correspond to the given table
3169
+	 *
3170
+	 * @param string $table_alias , array key in EEM_Base::_tables
3171
+	 * @return EE_Model_Field_Base[]
3172
+	 */
3173
+	public function _get_fields_for_table($table_alias)
3174
+	{
3175
+		return $this->_fields[ $table_alias ];
3176
+	}
3177
+
3178
+
3179
+
3180
+	/**
3181
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3182
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3183
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3184
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3185
+	 * related Registration, Transaction, and Payment models.
3186
+	 *
3187
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3188
+	 * @return EE_Model_Query_Info_Carrier
3189
+	 * @throws EE_Error
3190
+	 */
3191
+	public function _extract_related_models_from_query($query_params)
3192
+	{
3193
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3194
+		if (array_key_exists(0, $query_params)) {
3195
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3196
+		}
3197
+		if (array_key_exists('group_by', $query_params)) {
3198
+			if (is_array($query_params['group_by'])) {
3199
+				$this->_extract_related_models_from_sub_params_array_values(
3200
+					$query_params['group_by'],
3201
+					$query_info_carrier,
3202
+					'group_by'
3203
+				);
3204
+			} elseif (! empty($query_params['group_by'])) {
3205
+				$this->_extract_related_model_info_from_query_param(
3206
+					$query_params['group_by'],
3207
+					$query_info_carrier,
3208
+					'group_by'
3209
+				);
3210
+			}
3211
+		}
3212
+		if (array_key_exists('having', $query_params)) {
3213
+			$this->_extract_related_models_from_sub_params_array_keys(
3214
+				$query_params[0],
3215
+				$query_info_carrier,
3216
+				'having'
3217
+			);
3218
+		}
3219
+		if (array_key_exists('order_by', $query_params)) {
3220
+			if (is_array($query_params['order_by'])) {
3221
+				$this->_extract_related_models_from_sub_params_array_keys(
3222
+					$query_params['order_by'],
3223
+					$query_info_carrier,
3224
+					'order_by'
3225
+				);
3226
+			} elseif (! empty($query_params['order_by'])) {
3227
+				$this->_extract_related_model_info_from_query_param(
3228
+					$query_params['order_by'],
3229
+					$query_info_carrier,
3230
+					'order_by'
3231
+				);
3232
+			}
3233
+		}
3234
+		if (array_key_exists('force_join', $query_params)) {
3235
+			$this->_extract_related_models_from_sub_params_array_values(
3236
+				$query_params['force_join'],
3237
+				$query_info_carrier,
3238
+				'force_join'
3239
+			);
3240
+		}
3241
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3242
+		return $query_info_carrier;
3243
+	}
3244
+
3245
+
3246
+
3247
+	/**
3248
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3249
+	 *
3250
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#-0-where-conditions
3251
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3252
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3253
+	 * @throws EE_Error
3254
+	 * @return \EE_Model_Query_Info_Carrier
3255
+	 */
3256
+	private function _extract_related_models_from_sub_params_array_keys(
3257
+		$sub_query_params,
3258
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3259
+		$query_param_type
3260
+	) {
3261
+		if (! empty($sub_query_params)) {
3262
+			$sub_query_params = (array) $sub_query_params;
3263
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3264
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3265
+				$this->_extract_related_model_info_from_query_param(
3266
+					$param,
3267
+					$model_query_info_carrier,
3268
+					$query_param_type
3269
+				);
3270
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3271
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3272
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3273
+				// of array('Registration.TXN_ID'=>23)
3274
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3275
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3276
+					if (! is_array($possibly_array_of_params)) {
3277
+						throw new EE_Error(sprintf(
3278
+							__(
3279
+								"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'))",
3280
+								"event_espresso"
3281
+							),
3282
+							$param,
3283
+							$possibly_array_of_params
3284
+						));
3285
+					}
3286
+					$this->_extract_related_models_from_sub_params_array_keys(
3287
+						$possibly_array_of_params,
3288
+						$model_query_info_carrier,
3289
+						$query_param_type
3290
+					);
3291
+				} elseif ($query_param_type === 0 // ie WHERE
3292
+						  && is_array($possibly_array_of_params)
3293
+						  && isset($possibly_array_of_params[2])
3294
+						  && $possibly_array_of_params[2] == true
3295
+				) {
3296
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3297
+					// indicating that $possible_array_of_params[1] is actually a field name,
3298
+					// from which we should extract query parameters!
3299
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3300
+						throw new EE_Error(sprintf(__(
3301
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3302
+							"event_espresso"
3303
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3304
+					}
3305
+					$this->_extract_related_model_info_from_query_param(
3306
+						$possibly_array_of_params[1],
3307
+						$model_query_info_carrier,
3308
+						$query_param_type
3309
+					);
3310
+				}
3311
+			}
3312
+		}
3313
+		return $model_query_info_carrier;
3314
+	}
3315
+
3316
+
3317
+
3318
+	/**
3319
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3320
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3321
+	 *
3322
+	 * @param array                       $sub_query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3323
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3324
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3325
+	 * @throws EE_Error
3326
+	 * @return \EE_Model_Query_Info_Carrier
3327
+	 */
3328
+	private function _extract_related_models_from_sub_params_array_values(
3329
+		$sub_query_params,
3330
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3331
+		$query_param_type
3332
+	) {
3333
+		if (! empty($sub_query_params)) {
3334
+			if (! is_array($sub_query_params)) {
3335
+				throw new EE_Error(sprintf(
3336
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3337
+					$sub_query_params
3338
+				));
3339
+			}
3340
+			foreach ($sub_query_params as $param) {
3341
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3342
+				$this->_extract_related_model_info_from_query_param(
3343
+					$param,
3344
+					$model_query_info_carrier,
3345
+					$query_param_type
3346
+				);
3347
+			}
3348
+		}
3349
+		return $model_query_info_carrier;
3350
+	}
3351
+
3352
+
3353
+	/**
3354
+	 * Extract all the query parts from  model query params
3355
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3356
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3357
+	 * but use them in a different order. Eg, we need to know what models we are querying
3358
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3359
+	 * other models before we can finalize the where clause SQL.
3360
+	 *
3361
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3362
+	 * @throws EE_Error
3363
+	 * @return EE_Model_Query_Info_Carrier
3364
+	 * @throws ModelConfigurationException
3365
+	 */
3366
+	public function _create_model_query_info_carrier($query_params)
3367
+	{
3368
+		if (! is_array($query_params)) {
3369
+			EE_Error::doing_it_wrong(
3370
+				'EEM_Base::_create_model_query_info_carrier',
3371
+				sprintf(
3372
+					__(
3373
+						'$query_params should be an array, you passed a variable of type %s',
3374
+						'event_espresso'
3375
+					),
3376
+					gettype($query_params)
3377
+				),
3378
+				'4.6.0'
3379
+			);
3380
+			$query_params = array();
3381
+		}
3382
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3383
+		// first check if we should alter the query to account for caps or not
3384
+		// because the caps might require us to do extra joins
3385
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3386
+			$query_params[0] = array_replace_recursive(
3387
+				$query_params[0],
3388
+				$this->caps_where_conditions(
3389
+					$query_params['caps']
3390
+				)
3391
+			);
3392
+		}
3393
+
3394
+		// check if we should alter the query to remove data related to protected
3395
+		// custom post types
3396
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3397
+			$where_param_key_for_password = $this->modelChainAndPassword();
3398
+			// only include if related to a cpt where no password has been set
3399
+			$query_params[0]['OR*nopassword'] = array(
3400
+				$where_param_key_for_password => '',
3401
+				$where_param_key_for_password . '*' => array('IS_NULL')
3402
+			);
3403
+		}
3404
+		$query_object = $this->_extract_related_models_from_query($query_params);
3405
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3406
+		foreach ($query_params[0] as $key => $value) {
3407
+			if (is_int($key)) {
3408
+				throw new EE_Error(
3409
+					sprintf(
3410
+						__(
3411
+							"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.",
3412
+							"event_espresso"
3413
+						),
3414
+						$key,
3415
+						var_export($value, true),
3416
+						var_export($query_params, true),
3417
+						get_class($this)
3418
+					)
3419
+				);
3420
+			}
3421
+		}
3422
+		if (array_key_exists('default_where_conditions', $query_params)
3423
+			&& ! empty($query_params['default_where_conditions'])
3424
+		) {
3425
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3426
+		} else {
3427
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3428
+		}
3429
+		$query_params[0] = array_merge(
3430
+			$this->_get_default_where_conditions_for_models_in_query(
3431
+				$query_object,
3432
+				$use_default_where_conditions,
3433
+				$query_params[0]
3434
+			),
3435
+			$query_params[0]
3436
+		);
3437
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3438
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3439
+		// So we need to setup a subquery and use that for the main join.
3440
+		// Note for now this only works on the primary table for the model.
3441
+		// So for instance, you could set the limit array like this:
3442
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3443
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3444
+			$query_object->set_main_model_join_sql(
3445
+				$this->_construct_limit_join_select(
3446
+					$query_params['on_join_limit'][0],
3447
+					$query_params['on_join_limit'][1]
3448
+				)
3449
+			);
3450
+		}
3451
+		// set limit
3452
+		if (array_key_exists('limit', $query_params)) {
3453
+			if (is_array($query_params['limit'])) {
3454
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3455
+					$e = sprintf(
3456
+						__(
3457
+							"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)",
3458
+							"event_espresso"
3459
+						),
3460
+						http_build_query($query_params['limit'])
3461
+					);
3462
+					throw new EE_Error($e . "|" . $e);
3463
+				}
3464
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3465
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3466
+			} elseif (! empty($query_params['limit'])) {
3467
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3468
+			}
3469
+		}
3470
+		// set order by
3471
+		if (array_key_exists('order_by', $query_params)) {
3472
+			if (is_array($query_params['order_by'])) {
3473
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3474
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3475
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3476
+				if (array_key_exists('order', $query_params)) {
3477
+					throw new EE_Error(
3478
+						sprintf(
3479
+							__(
3480
+								"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 ",
3481
+								"event_espresso"
3482
+							),
3483
+							get_class($this),
3484
+							implode(", ", array_keys($query_params['order_by'])),
3485
+							implode(", ", $query_params['order_by']),
3486
+							$query_params['order']
3487
+						)
3488
+					);
3489
+				}
3490
+				$this->_extract_related_models_from_sub_params_array_keys(
3491
+					$query_params['order_by'],
3492
+					$query_object,
3493
+					'order_by'
3494
+				);
3495
+				// assume it's an array of fields to order by
3496
+				$order_array = array();
3497
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3498
+					$order = $this->_extract_order($order);
3499
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3500
+				}
3501
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3502
+			} elseif (! empty($query_params['order_by'])) {
3503
+				$this->_extract_related_model_info_from_query_param(
3504
+					$query_params['order_by'],
3505
+					$query_object,
3506
+					'order',
3507
+					$query_params['order_by']
3508
+				);
3509
+				$order = isset($query_params['order'])
3510
+					? $this->_extract_order($query_params['order'])
3511
+					: 'DESC';
3512
+				$query_object->set_order_by_sql(
3513
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3514
+				);
3515
+			}
3516
+		}
3517
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3518
+		if (! array_key_exists('order_by', $query_params)
3519
+			&& array_key_exists('order', $query_params)
3520
+			&& ! empty($query_params['order'])
3521
+		) {
3522
+			$pk_field = $this->get_primary_key_field();
3523
+			$order = $this->_extract_order($query_params['order']);
3524
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3525
+		}
3526
+		// set group by
3527
+		if (array_key_exists('group_by', $query_params)) {
3528
+			if (is_array($query_params['group_by'])) {
3529
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3530
+				$group_by_array = array();
3531
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3532
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3533
+				}
3534
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3535
+			} elseif (! empty($query_params['group_by'])) {
3536
+				$query_object->set_group_by_sql(
3537
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3538
+				);
3539
+			}
3540
+		}
3541
+		// set having
3542
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3543
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3544
+		}
3545
+		// now, just verify they didn't pass anything wack
3546
+		foreach ($query_params as $query_key => $query_value) {
3547
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3548
+				throw new EE_Error(
3549
+					sprintf(
3550
+						__(
3551
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3552
+							'event_espresso'
3553
+						),
3554
+						$query_key,
3555
+						get_class($this),
3556
+						//                      print_r( $this->_allowed_query_params, TRUE )
3557
+						implode(',', $this->_allowed_query_params)
3558
+					)
3559
+				);
3560
+			}
3561
+		}
3562
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3563
+		if (empty($main_model_join_sql)) {
3564
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3565
+		}
3566
+		return $query_object;
3567
+	}
3568
+
3569
+
3570
+
3571
+	/**
3572
+	 * Gets the where conditions that should be imposed on the query based on the
3573
+	 * context (eg reading frontend, backend, edit or delete).
3574
+	 *
3575
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3576
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3577
+	 * @throws EE_Error
3578
+	 */
3579
+	public function caps_where_conditions($context = self::caps_read)
3580
+	{
3581
+		EEM_Base::verify_is_valid_cap_context($context);
3582
+		$cap_where_conditions = array();
3583
+		$cap_restrictions = $this->caps_missing($context);
3584
+		/**
3585
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3586
+		 */
3587
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3588
+			$cap_where_conditions = array_replace_recursive(
3589
+				$cap_where_conditions,
3590
+				$restriction_if_no_cap->get_default_where_conditions()
3591
+			);
3592
+		}
3593
+		return apply_filters(
3594
+			'FHEE__EEM_Base__caps_where_conditions__return',
3595
+			$cap_where_conditions,
3596
+			$this,
3597
+			$context,
3598
+			$cap_restrictions
3599
+		);
3600
+	}
3601
+
3602
+
3603
+
3604
+	/**
3605
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3606
+	 * otherwise throws an exception
3607
+	 *
3608
+	 * @param string $should_be_order_string
3609
+	 * @return string either ASC, asc, DESC or desc
3610
+	 * @throws EE_Error
3611
+	 */
3612
+	private function _extract_order($should_be_order_string)
3613
+	{
3614
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3615
+			return $should_be_order_string;
3616
+		}
3617
+		throw new EE_Error(
3618
+			sprintf(
3619
+				__(
3620
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3621
+					"event_espresso"
3622
+				),
3623
+				get_class($this),
3624
+				$should_be_order_string
3625
+			)
3626
+		);
3627
+	}
3628
+
3629
+
3630
+
3631
+	/**
3632
+	 * Looks at all the models which are included in this query, and asks each
3633
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3634
+	 * so they can be merged
3635
+	 *
3636
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3637
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3638
+	 *                                                                  'none' means NO default where conditions will
3639
+	 *                                                                  be used AT ALL during this query.
3640
+	 *                                                                  'other_models_only' means default where
3641
+	 *                                                                  conditions from other models will be used, but
3642
+	 *                                                                  not for this primary model. 'all', the default,
3643
+	 *                                                                  means default where conditions will apply as
3644
+	 *                                                                  normal
3645
+	 * @param array                       $where_query_params           @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3646
+	 * @throws EE_Error
3647
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3648
+	 */
3649
+	private function _get_default_where_conditions_for_models_in_query(
3650
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3651
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3652
+		$where_query_params = array()
3653
+	) {
3654
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3655
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3656
+			throw new EE_Error(sprintf(
3657
+				__(
3658
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3659
+					"event_espresso"
3660
+				),
3661
+				$use_default_where_conditions,
3662
+				implode(", ", $allowed_used_default_where_conditions_values)
3663
+			));
3664
+		}
3665
+		$universal_query_params = array();
3666
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3667
+			$universal_query_params = $this->_get_default_where_conditions();
3668
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3669
+			$universal_query_params = $this->_get_minimum_where_conditions();
3670
+		}
3671
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3672
+			$related_model = $this->get_related_model_obj($model_name);
3673
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3674
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3675
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3676
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3677
+			} else {
3678
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3679
+				continue;
3680
+			}
3681
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3682
+				$related_model_universal_where_params,
3683
+				$where_query_params,
3684
+				$related_model,
3685
+				$model_relation_path
3686
+			);
3687
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3688
+				$universal_query_params,
3689
+				$overrides
3690
+			);
3691
+		}
3692
+		return $universal_query_params;
3693
+	}
3694
+
3695
+
3696
+
3697
+	/**
3698
+	 * Determines whether or not we should use default where conditions for the model in question
3699
+	 * (this model, or other related models).
3700
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3701
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3702
+	 * We should use default where conditions on related models when they requested to use default where conditions
3703
+	 * on all models, or specifically just on other related models
3704
+	 * @param      $default_where_conditions_value
3705
+	 * @param bool $for_this_model false means this is for OTHER related models
3706
+	 * @return bool
3707
+	 */
3708
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3709
+	{
3710
+		return (
3711
+				   $for_this_model
3712
+				   && in_array(
3713
+					   $default_where_conditions_value,
3714
+					   array(
3715
+						   EEM_Base::default_where_conditions_all,
3716
+						   EEM_Base::default_where_conditions_this_only,
3717
+						   EEM_Base::default_where_conditions_minimum_others,
3718
+					   ),
3719
+					   true
3720
+				   )
3721
+			   )
3722
+			   || (
3723
+				   ! $for_this_model
3724
+				   && in_array(
3725
+					   $default_where_conditions_value,
3726
+					   array(
3727
+						   EEM_Base::default_where_conditions_all,
3728
+						   EEM_Base::default_where_conditions_others_only,
3729
+					   ),
3730
+					   true
3731
+				   )
3732
+			   );
3733
+	}
3734
+
3735
+	/**
3736
+	 * Determines whether or not we should use default minimum conditions for the model in question
3737
+	 * (this model, or other related models).
3738
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3739
+	 * where conditions.
3740
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3741
+	 * on this model or others
3742
+	 * @param      $default_where_conditions_value
3743
+	 * @param bool $for_this_model false means this is for OTHER related models
3744
+	 * @return bool
3745
+	 */
3746
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3747
+	{
3748
+		return (
3749
+				   $for_this_model
3750
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3751
+			   )
3752
+			   || (
3753
+				   ! $for_this_model
3754
+				   && in_array(
3755
+					   $default_where_conditions_value,
3756
+					   array(
3757
+						   EEM_Base::default_where_conditions_minimum_others,
3758
+						   EEM_Base::default_where_conditions_minimum_all,
3759
+					   ),
3760
+					   true
3761
+				   )
3762
+			   );
3763
+	}
3764
+
3765
+
3766
+	/**
3767
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3768
+	 * then we also add a special where condition which allows for that model's primary key
3769
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3770
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3771
+	 *
3772
+	 * @param array    $default_where_conditions
3773
+	 * @param array    $provided_where_conditions
3774
+	 * @param EEM_Base $model
3775
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3776
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3777
+	 * @throws EE_Error
3778
+	 */
3779
+	private function _override_defaults_or_make_null_friendly(
3780
+		$default_where_conditions,
3781
+		$provided_where_conditions,
3782
+		$model,
3783
+		$model_relation_path
3784
+	) {
3785
+		$null_friendly_where_conditions = array();
3786
+		$none_overridden = true;
3787
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3788
+		foreach ($default_where_conditions as $key => $val) {
3789
+			if (isset($provided_where_conditions[ $key ])) {
3790
+				$none_overridden = false;
3791
+			} else {
3792
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3793
+			}
3794
+		}
3795
+		if ($none_overridden && $default_where_conditions) {
3796
+			if ($model->has_primary_key_field()) {
3797
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3798
+																				. "."
3799
+																				. $model->primary_key_name() ] = array('IS NULL');
3800
+			}/*else{
3801 3801
                 //@todo NO PK, use other defaults
3802 3802
             }*/
3803
-        }
3804
-        return $null_friendly_where_conditions;
3805
-    }
3806
-
3807
-
3808
-
3809
-    /**
3810
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3811
-     * default where conditions on all get_all, update, and delete queries done by this model.
3812
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3813
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3814
-     *
3815
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3816
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3817
-     */
3818
-    private function _get_default_where_conditions($model_relation_path = null)
3819
-    {
3820
-        if ($this->_ignore_where_strategy) {
3821
-            return array();
3822
-        }
3823
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3824
-    }
3825
-
3826
-
3827
-
3828
-    /**
3829
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3830
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3831
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3832
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3833
-     * Similar to _get_default_where_conditions
3834
-     *
3835
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3836
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3837
-     */
3838
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3839
-    {
3840
-        if ($this->_ignore_where_strategy) {
3841
-            return array();
3842
-        }
3843
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3844
-    }
3845
-
3846
-
3847
-
3848
-    /**
3849
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3850
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3851
-     *
3852
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3853
-     * @return string
3854
-     * @throws EE_Error
3855
-     */
3856
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3857
-    {
3858
-        $selects = $this->_get_columns_to_select_for_this_model();
3859
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3860
-            $name_of_other_model_included) {
3861
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3862
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3863
-            foreach ($other_model_selects as $key => $value) {
3864
-                $selects[] = $value;
3865
-            }
3866
-        }
3867
-        return implode(", ", $selects);
3868
-    }
3869
-
3870
-
3871
-
3872
-    /**
3873
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3874
-     * So that's going to be the columns for all the fields on the model
3875
-     *
3876
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3877
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3878
-     */
3879
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3880
-    {
3881
-        $fields = $this->field_settings();
3882
-        $selects = array();
3883
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3884
-            $model_relation_chain,
3885
-            $this->get_this_model_name()
3886
-        );
3887
-        foreach ($fields as $field_obj) {
3888
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3889
-                         . $field_obj->get_table_alias()
3890
-                         . "."
3891
-                         . $field_obj->get_table_column()
3892
-                         . " AS '"
3893
-                         . $table_alias_with_model_relation_chain_prefix
3894
-                         . $field_obj->get_table_alias()
3895
-                         . "."
3896
-                         . $field_obj->get_table_column()
3897
-                         . "'";
3898
-        }
3899
-        // make sure we are also getting the PKs of each table
3900
-        $tables = $this->get_tables();
3901
-        if (count($tables) > 1) {
3902
-            foreach ($tables as $table_obj) {
3903
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3904
-                                       . $table_obj->get_fully_qualified_pk_column();
3905
-                if (! in_array($qualified_pk_column, $selects)) {
3906
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3907
-                }
3908
-            }
3909
-        }
3910
-        return $selects;
3911
-    }
3912
-
3913
-
3914
-
3915
-    /**
3916
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3917
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3918
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3919
-     * SQL for joining, and the data types
3920
-     *
3921
-     * @param null|string                 $original_query_param
3922
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3923
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3924
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3925
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3926
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3927
-     *                                                          or 'Registration's
3928
-     * @param string                      $original_query_param what it originally was (eg
3929
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3930
-     *                                                          matches $query_param
3931
-     * @throws EE_Error
3932
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3933
-     */
3934
-    private function _extract_related_model_info_from_query_param(
3935
-        $query_param,
3936
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3937
-        $query_param_type,
3938
-        $original_query_param = null
3939
-    ) {
3940
-        if ($original_query_param === null) {
3941
-            $original_query_param = $query_param;
3942
-        }
3943
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3944
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3945
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3946
-        $allow_fields = in_array(
3947
-            $query_param_type,
3948
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3949
-            true
3950
-        );
3951
-        // check to see if we have a field on this model
3952
-        $this_model_fields = $this->field_settings(true);
3953
-        if (array_key_exists($query_param, $this_model_fields)) {
3954
-            if ($allow_fields) {
3955
-                return;
3956
-            }
3957
-            throw new EE_Error(
3958
-                sprintf(
3959
-                    __(
3960
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3961
-                        "event_espresso"
3962
-                    ),
3963
-                    $query_param,
3964
-                    get_class($this),
3965
-                    $query_param_type,
3966
-                    $original_query_param
3967
-                )
3968
-            );
3969
-        }
3970
-        // check if this is a special logic query param
3971
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3972
-            if ($allow_logic_query_params) {
3973
-                return;
3974
-            }
3975
-            throw new EE_Error(
3976
-                sprintf(
3977
-                    __(
3978
-                        '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',
3979
-                        'event_espresso'
3980
-                    ),
3981
-                    implode('", "', $this->_logic_query_param_keys),
3982
-                    $query_param,
3983
-                    get_class($this),
3984
-                    '<br />',
3985
-                    "\t"
3986
-                    . ' $passed_in_query_info = <pre>'
3987
-                    . print_r($passed_in_query_info, true)
3988
-                    . '</pre>'
3989
-                    . "\n\t"
3990
-                    . ' $query_param_type = '
3991
-                    . $query_param_type
3992
-                    . "\n\t"
3993
-                    . ' $original_query_param = '
3994
-                    . $original_query_param
3995
-                )
3996
-            );
3997
-        }
3998
-        // check if it's a custom selection
3999
-        if ($this->_custom_selections instanceof CustomSelects
4000
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4001
-        ) {
4002
-            return;
4003
-        }
4004
-        // check if has a model name at the beginning
4005
-        // and
4006
-        // check if it's a field on a related model
4007
-        if ($this->extractJoinModelFromQueryParams(
4008
-            $passed_in_query_info,
4009
-            $query_param,
4010
-            $original_query_param,
4011
-            $query_param_type
4012
-        )) {
4013
-            return;
4014
-        }
4015
-
4016
-        // ok so $query_param didn't start with a model name
4017
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4018
-        // it's wack, that's what it is
4019
-        throw new EE_Error(
4020
-            sprintf(
4021
-                esc_html__(
4022
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4023
-                    "event_espresso"
4024
-                ),
4025
-                $query_param,
4026
-                get_class($this),
4027
-                $query_param_type,
4028
-                $original_query_param
4029
-            )
4030
-        );
4031
-    }
4032
-
4033
-
4034
-    /**
4035
-     * Extracts any possible join model information from the provided possible_join_string.
4036
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4037
-     * parts that should be added to the query.
4038
-     *
4039
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4040
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4041
-     * @param null|string                 $original_query_param
4042
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4043
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4044
-     * @return bool  returns true if a join was added and false if not.
4045
-     * @throws EE_Error
4046
-     */
4047
-    private function extractJoinModelFromQueryParams(
4048
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4049
-        $possible_join_string,
4050
-        $original_query_param,
4051
-        $query_parameter_type
4052
-    ) {
4053
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4054
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4055
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4056
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4057
-                if ($possible_join_string === '') {
4058
-                    // nothing left to $query_param
4059
-                    // we should actually end in a field name, not a model like this!
4060
-                    throw new EE_Error(
4061
-                        sprintf(
4062
-                            esc_html__(
4063
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4064
-                                "event_espresso"
4065
-                            ),
4066
-                            $possible_join_string,
4067
-                            $query_parameter_type,
4068
-                            get_class($this),
4069
-                            $valid_related_model_name
4070
-                        )
4071
-                    );
4072
-                }
4073
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4074
-                $related_model_obj->_extract_related_model_info_from_query_param(
4075
-                    $possible_join_string,
4076
-                    $query_info_carrier,
4077
-                    $query_parameter_type,
4078
-                    $original_query_param
4079
-                );
4080
-                return true;
4081
-            }
4082
-            if ($possible_join_string === $valid_related_model_name) {
4083
-                $this->_add_join_to_model(
4084
-                    $valid_related_model_name,
4085
-                    $query_info_carrier,
4086
-                    $original_query_param
4087
-                );
4088
-                return true;
4089
-            }
4090
-        }
4091
-        return false;
4092
-    }
4093
-
4094
-
4095
-    /**
4096
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4097
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4098
-     * @throws EE_Error
4099
-     */
4100
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4101
-    {
4102
-        if ($this->_custom_selections instanceof CustomSelects
4103
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4104
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4105
-            )
4106
-        ) {
4107
-            $original_selects = $this->_custom_selections->originalSelects();
4108
-            foreach ($original_selects as $alias => $select_configuration) {
4109
-                $this->extractJoinModelFromQueryParams(
4110
-                    $query_info_carrier,
4111
-                    $select_configuration[0],
4112
-                    $select_configuration[0],
4113
-                    'custom_selects'
4114
-                );
4115
-            }
4116
-        }
4117
-    }
4118
-
4119
-
4120
-
4121
-    /**
4122
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4123
-     * and store it on $passed_in_query_info
4124
-     *
4125
-     * @param string                      $model_name
4126
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4127
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4128
-     *                                                          model and $model_name. Eg, if we are querying Event,
4129
-     *                                                          and are adding a join to 'Payment' with the original
4130
-     *                                                          query param key
4131
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4132
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4133
-     *                                                          Payment wants to add default query params so that it
4134
-     *                                                          will know what models to prepend onto its default query
4135
-     *                                                          params or in case it wants to rename tables (in case
4136
-     *                                                          there are multiple joins to the same table)
4137
-     * @return void
4138
-     * @throws EE_Error
4139
-     */
4140
-    private function _add_join_to_model(
4141
-        $model_name,
4142
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4143
-        $original_query_param
4144
-    ) {
4145
-        $relation_obj = $this->related_settings_for($model_name);
4146
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4147
-        // check if the relation is HABTM, because then we're essentially doing two joins
4148
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4149
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4150
-            $join_model_obj = $relation_obj->get_join_model();
4151
-            // replace the model specified with the join model for this relation chain, whi
4152
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4153
-                $model_name,
4154
-                $join_model_obj->get_this_model_name(),
4155
-                $model_relation_chain
4156
-            );
4157
-            $passed_in_query_info->merge(
4158
-                new EE_Model_Query_Info_Carrier(
4159
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4160
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4161
-                )
4162
-            );
4163
-        }
4164
-        // now just join to the other table pointed to by the relation object, and add its data types
4165
-        $passed_in_query_info->merge(
4166
-            new EE_Model_Query_Info_Carrier(
4167
-                array($model_relation_chain => $model_name),
4168
-                $relation_obj->get_join_statement($model_relation_chain)
4169
-            )
4170
-        );
4171
-    }
4172
-
4173
-
4174
-
4175
-    /**
4176
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4177
-     *
4178
-     * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4179
-     * @return string of SQL
4180
-     * @throws EE_Error
4181
-     */
4182
-    private function _construct_where_clause($where_params)
4183
-    {
4184
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4185
-        if ($SQL) {
4186
-            return " WHERE " . $SQL;
4187
-        }
4188
-        return '';
4189
-    }
4190
-
4191
-
4192
-
4193
-    /**
4194
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4195
-     * and should be passed HAVING parameters, not WHERE parameters
4196
-     *
4197
-     * @param array $having_params
4198
-     * @return string
4199
-     * @throws EE_Error
4200
-     */
4201
-    private function _construct_having_clause($having_params)
4202
-    {
4203
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4204
-        if ($SQL) {
4205
-            return " HAVING " . $SQL;
4206
-        }
4207
-        return '';
4208
-    }
4209
-
4210
-
4211
-    /**
4212
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4213
-     * Event_Meta.meta_value = 'foo'))"
4214
-     *
4215
-     * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4216
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4217
-     * @throws EE_Error
4218
-     * @return string of SQL
4219
-     */
4220
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4221
-    {
4222
-        $where_clauses = array();
4223
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4224
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4225
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4226
-                switch ($query_param) {
4227
-                    case 'not':
4228
-                    case 'NOT':
4229
-                        $where_clauses[] = "! ("
4230
-                                           . $this->_construct_condition_clause_recursive(
4231
-                                               $op_and_value_or_sub_condition,
4232
-                                               $glue
4233
-                                           )
4234
-                                           . ")";
4235
-                        break;
4236
-                    case 'and':
4237
-                    case 'AND':
4238
-                        $where_clauses[] = " ("
4239
-                                           . $this->_construct_condition_clause_recursive(
4240
-                                               $op_and_value_or_sub_condition,
4241
-                                               ' AND '
4242
-                                           )
4243
-                                           . ")";
4244
-                        break;
4245
-                    case 'or':
4246
-                    case 'OR':
4247
-                        $where_clauses[] = " ("
4248
-                                           . $this->_construct_condition_clause_recursive(
4249
-                                               $op_and_value_or_sub_condition,
4250
-                                               ' OR '
4251
-                                           )
4252
-                                           . ")";
4253
-                        break;
4254
-                }
4255
-            } else {
4256
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4257
-                // if it's not a normal field, maybe it's a custom selection?
4258
-                if (! $field_obj) {
4259
-                    if ($this->_custom_selections instanceof CustomSelects) {
4260
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4261
-                    } else {
4262
-                        throw new EE_Error(sprintf(__(
4263
-                            "%s is neither a valid model field name, nor a custom selection",
4264
-                            "event_espresso"
4265
-                        ), $query_param));
4266
-                    }
4267
-                }
4268
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4269
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4270
-            }
4271
-        }
4272
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4273
-    }
4274
-
4275
-
4276
-
4277
-    /**
4278
-     * Takes the input parameter and extract the table name (alias) and column name
4279
-     *
4280
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4281
-     * @throws EE_Error
4282
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4283
-     */
4284
-    private function _deduce_column_name_from_query_param($query_param)
4285
-    {
4286
-        $field = $this->_deduce_field_from_query_param($query_param);
4287
-        if ($field) {
4288
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4289
-                $field->get_model_name(),
4290
-                $query_param
4291
-            );
4292
-            return $table_alias_prefix . $field->get_qualified_column();
4293
-        }
4294
-        if ($this->_custom_selections instanceof CustomSelects
4295
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4296
-        ) {
4297
-            // maybe it's custom selection item?
4298
-            // if so, just use it as the "column name"
4299
-            return $query_param;
4300
-        }
4301
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4302
-            ? implode(',', $this->_custom_selections->columnAliases())
4303
-            : '';
4304
-        throw new EE_Error(
4305
-            sprintf(
4306
-                __(
4307
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4308
-                    "event_espresso"
4309
-                ),
4310
-                $query_param,
4311
-                $custom_select_aliases
4312
-            )
4313
-        );
4314
-    }
4315
-
4316
-
4317
-
4318
-    /**
4319
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4320
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4321
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4322
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4323
-     *
4324
-     * @param string $condition_query_param_key
4325
-     * @return string
4326
-     */
4327
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4328
-    {
4329
-        $pos_of_star = strpos($condition_query_param_key, '*');
4330
-        if ($pos_of_star === false) {
4331
-            return $condition_query_param_key;
4332
-        }
4333
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4334
-        return $condition_query_param_sans_star;
4335
-    }
4336
-
4337
-
4338
-
4339
-    /**
4340
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4341
-     *
4342
-     * @param                            mixed      array | string    $op_and_value
4343
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4344
-     * @throws EE_Error
4345
-     * @return string
4346
-     */
4347
-    private function _construct_op_and_value($op_and_value, $field_obj)
4348
-    {
4349
-        if (is_array($op_and_value)) {
4350
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4351
-            if (! $operator) {
4352
-                $php_array_like_string = array();
4353
-                foreach ($op_and_value as $key => $value) {
4354
-                    $php_array_like_string[] = "$key=>$value";
4355
-                }
4356
-                throw new EE_Error(
4357
-                    sprintf(
4358
-                        __(
4359
-                            "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))",
4360
-                            "event_espresso"
4361
-                        ),
4362
-                        implode(",", $php_array_like_string)
4363
-                    )
4364
-                );
4365
-            }
4366
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4367
-        } else {
4368
-            $operator = '=';
4369
-            $value = $op_and_value;
4370
-        }
4371
-        // check to see if the value is actually another field
4372
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4373
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4374
-        }
4375
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4376
-            // in this case, the value should be an array, or at least a comma-separated list
4377
-            // it will need to handle a little differently
4378
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4379
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4380
-            return $operator . SP . $cleaned_value;
4381
-        }
4382
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4383
-            // the value should be an array with count of two.
4384
-            if (count($value) !== 2) {
4385
-                throw new EE_Error(
4386
-                    sprintf(
4387
-                        __(
4388
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4389
-                            'event_espresso'
4390
-                        ),
4391
-                        "BETWEEN"
4392
-                    )
4393
-                );
4394
-            }
4395
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4396
-            return $operator . SP . $cleaned_value;
4397
-        }
4398
-        if (in_array($operator, $this->valid_null_style_operators())) {
4399
-            if ($value !== null) {
4400
-                throw new EE_Error(
4401
-                    sprintf(
4402
-                        __(
4403
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4404
-                            "event_espresso"
4405
-                        ),
4406
-                        $value,
4407
-                        $operator
4408
-                    )
4409
-                );
4410
-            }
4411
-            return $operator;
4412
-        }
4413
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4414
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4415
-            // remove other junk. So just treat it as a string.
4416
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4417
-        }
4418
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4419
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4420
-        }
4421
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4422
-            throw new EE_Error(
4423
-                sprintf(
4424
-                    __(
4425
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4426
-                        'event_espresso'
4427
-                    ),
4428
-                    $operator,
4429
-                    $operator
4430
-                )
4431
-            );
4432
-        }
4433
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4434
-            throw new EE_Error(
4435
-                sprintf(
4436
-                    __(
4437
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4438
-                        'event_espresso'
4439
-                    ),
4440
-                    $operator,
4441
-                    $operator
4442
-                )
4443
-            );
4444
-        }
4445
-        throw new EE_Error(
4446
-            sprintf(
4447
-                __(
4448
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4449
-                    "event_espresso"
4450
-                ),
4451
-                http_build_query($op_and_value)
4452
-            )
4453
-        );
4454
-    }
4455
-
4456
-
4457
-
4458
-    /**
4459
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4460
-     *
4461
-     * @param array                      $values
4462
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4463
-     *                                              '%s'
4464
-     * @return string
4465
-     * @throws EE_Error
4466
-     */
4467
-    public function _construct_between_value($values, $field_obj)
4468
-    {
4469
-        $cleaned_values = array();
4470
-        foreach ($values as $value) {
4471
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4472
-        }
4473
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4474
-    }
4475
-
4476
-
4477
-    /**
4478
-     * Takes an array or a comma-separated list of $values and cleans them
4479
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4480
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4481
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4482
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4483
-     *
4484
-     * @param mixed                      $values    array or comma-separated string
4485
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4486
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4487
-     * @throws EE_Error
4488
-     */
4489
-    public function _construct_in_value($values, $field_obj)
4490
-    {
4491
-        $prepped = [];
4492
-        // check if the value is a CSV list
4493
-        if (is_string($values)) {
4494
-            // in which case, turn it into an array
4495
-            $values = explode(',', $values);
4496
-        }
4497
-        // make sure we only have one of each value in the list
4498
-        $values = array_unique($values);
4499
-        foreach ($values as $value) {
4500
-            $prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4501
-        }
4502
-        // we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4503
-        // but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4504
-        // which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4505
-        if (empty($prepped)) {
4506
-            $all_fields = $this->field_settings();
4507
-            $first_field    = reset($all_fields);
4508
-            $main_table = $this->_get_main_table();
4509
-            $prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4510
-        }
4511
-        return '(' . implode(',', $prepped) . ')';
4512
-    }
4513
-
4514
-
4515
-
4516
-    /**
4517
-     * @param mixed                      $value
4518
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4519
-     * @throws EE_Error
4520
-     * @return false|null|string
4521
-     */
4522
-    private function _wpdb_prepare_using_field($value, $field_obj)
4523
-    {
4524
-        /** @type WPDB $wpdb */
4525
-        global $wpdb;
4526
-        if ($field_obj instanceof EE_Model_Field_Base) {
4527
-            return $wpdb->prepare(
4528
-                $field_obj->get_wpdb_data_type(),
4529
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4530
-            );
4531
-        } //$field_obj should really just be a data type
4532
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4533
-            throw new EE_Error(
4534
-                sprintf(
4535
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4536
-                    $field_obj,
4537
-                    implode(",", $this->_valid_wpdb_data_types)
4538
-                )
4539
-            );
4540
-        }
4541
-        return $wpdb->prepare($field_obj, $value);
4542
-    }
4543
-
4544
-
4545
-
4546
-    /**
4547
-     * Takes the input parameter and finds the model field that it indicates.
4548
-     *
4549
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4550
-     * @throws EE_Error
4551
-     * @return EE_Model_Field_Base
4552
-     */
4553
-    protected function _deduce_field_from_query_param($query_param_name)
4554
-    {
4555
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4556
-        // which will help us find the database table and column
4557
-        $query_param_parts = explode(".", $query_param_name);
4558
-        if (empty($query_param_parts)) {
4559
-            throw new EE_Error(sprintf(__(
4560
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4561
-                'event_espresso'
4562
-            ), $query_param_name));
4563
-        }
4564
-        $number_of_parts = count($query_param_parts);
4565
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4566
-        if ($number_of_parts === 1) {
4567
-            $field_name = $last_query_param_part;
4568
-            $model_obj = $this;
4569
-        } else {// $number_of_parts >= 2
4570
-            // the last part is the column name, and there are only 2parts. therefore...
4571
-            $field_name = $last_query_param_part;
4572
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4573
-        }
4574
-        try {
4575
-            return $model_obj->field_settings_for($field_name);
4576
-        } catch (EE_Error $e) {
4577
-            return null;
4578
-        }
4579
-    }
4580
-
4581
-
4582
-
4583
-    /**
4584
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4585
-     * alias and column which corresponds to it
4586
-     *
4587
-     * @param string $field_name
4588
-     * @throws EE_Error
4589
-     * @return string
4590
-     */
4591
-    public function _get_qualified_column_for_field($field_name)
4592
-    {
4593
-        $all_fields = $this->field_settings();
4594
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4595
-        if ($field) {
4596
-            return $field->get_qualified_column();
4597
-        }
4598
-        throw new EE_Error(
4599
-            sprintf(
4600
-                __(
4601
-                    "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.",
4602
-                    'event_espresso'
4603
-                ),
4604
-                $field_name,
4605
-                get_class($this)
4606
-            )
4607
-        );
4608
-    }
4609
-
4610
-
4611
-
4612
-    /**
4613
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4614
-     * Example usage:
4615
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4616
-     *      array(),
4617
-     *      ARRAY_A,
4618
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4619
-     *  );
4620
-     * is equivalent to
4621
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4622
-     * and
4623
-     *  EEM_Event::instance()->get_all_wpdb_results(
4624
-     *      array(
4625
-     *          array(
4626
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4627
-     *          ),
4628
-     *          ARRAY_A,
4629
-     *          implode(
4630
-     *              ', ',
4631
-     *              array_merge(
4632
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4633
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4634
-     *              )
4635
-     *          )
4636
-     *      )
4637
-     *  );
4638
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4639
-     *
4640
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4641
-     *                                            and the one whose fields you are selecting for example: when querying
4642
-     *                                            tickets model and selecting fields from the tickets model you would
4643
-     *                                            leave this parameter empty, because no models are needed to join
4644
-     *                                            between the queried model and the selected one. Likewise when
4645
-     *                                            querying the datetime model and selecting fields from the tickets
4646
-     *                                            model, it would also be left empty, because there is a direct
4647
-     *                                            relation from datetimes to tickets, so no model is needed to join
4648
-     *                                            them together. However, when querying from the event model and
4649
-     *                                            selecting fields from the ticket model, you should provide the string
4650
-     *                                            'Datetime', indicating that the event model must first join to the
4651
-     *                                            datetime model in order to find its relation to ticket model.
4652
-     *                                            Also, when querying from the venue model and selecting fields from
4653
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4654
-     *                                            indicating you need to join the venue model to the event model,
4655
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4656
-     *                                            This string is used to deduce the prefix that gets added onto the
4657
-     *                                            models' tables qualified columns
4658
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4659
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4660
-     *                                            qualified column names
4661
-     * @return array|string
4662
-     */
4663
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4664
-    {
4665
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4666
-        $qualified_columns = array();
4667
-        foreach ($this->field_settings() as $field_name => $field) {
4668
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4669
-        }
4670
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4671
-    }
4672
-
4673
-
4674
-
4675
-    /**
4676
-     * constructs the select use on special limit joins
4677
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4678
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4679
-     * (as that is typically where the limits would be set).
4680
-     *
4681
-     * @param  string       $table_alias The table the select is being built for
4682
-     * @param  mixed|string $limit       The limit for this select
4683
-     * @return string                The final select join element for the query.
4684
-     */
4685
-    public function _construct_limit_join_select($table_alias, $limit)
4686
-    {
4687
-        $SQL = '';
4688
-        foreach ($this->_tables as $table_obj) {
4689
-            if ($table_obj instanceof EE_Primary_Table) {
4690
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4691
-                    ? $table_obj->get_select_join_limit($limit)
4692
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4693
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4694
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4695
-                    ? $table_obj->get_select_join_limit_join($limit)
4696
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4697
-            }
4698
-        }
4699
-        return $SQL;
4700
-    }
4701
-
4702
-
4703
-
4704
-    /**
4705
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4706
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4707
-     *
4708
-     * @return string SQL
4709
-     * @throws EE_Error
4710
-     */
4711
-    public function _construct_internal_join()
4712
-    {
4713
-        $SQL = $this->_get_main_table()->get_table_sql();
4714
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4715
-        return $SQL;
4716
-    }
4717
-
4718
-
4719
-
4720
-    /**
4721
-     * Constructs the SQL for joining all the tables on this model.
4722
-     * Normally $alias should be the primary table's alias, but in cases where
4723
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4724
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4725
-     * alias, this will construct SQL like:
4726
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4727
-     * With $alias being a secondary table's alias, this will construct SQL like:
4728
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4729
-     *
4730
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4731
-     * @return string
4732
-     */
4733
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4734
-    {
4735
-        $SQL = '';
4736
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4737
-        foreach ($this->_tables as $table_obj) {
4738
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4739
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4740
-                    // so we're joining to this table, meaning the table is already in
4741
-                    // the FROM statement, BUT the primary table isn't. So we want
4742
-                    // to add the inverse join sql
4743
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4744
-                } else {
4745
-                    // just add a regular JOIN to this table from the primary table
4746
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4747
-                }
4748
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4749
-        }
4750
-        return $SQL;
4751
-    }
4752
-
4753
-
4754
-
4755
-    /**
4756
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4757
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4758
-     * their data type (eg, '%s', '%d', etc)
4759
-     *
4760
-     * @return array
4761
-     */
4762
-    public function _get_data_types()
4763
-    {
4764
-        $data_types = array();
4765
-        foreach ($this->field_settings() as $field_obj) {
4766
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4767
-            /** @var $field_obj EE_Model_Field_Base */
4768
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4769
-        }
4770
-        return $data_types;
4771
-    }
4772
-
4773
-
4774
-
4775
-    /**
4776
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4777
-     *
4778
-     * @param string $model_name
4779
-     * @throws EE_Error
4780
-     * @return EEM_Base
4781
-     */
4782
-    public function get_related_model_obj($model_name)
4783
-    {
4784
-        $model_classname = "EEM_" . $model_name;
4785
-        if (! class_exists($model_classname)) {
4786
-            throw new EE_Error(sprintf(__(
4787
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4788
-                'event_espresso'
4789
-            ), $model_name, $model_classname));
4790
-        }
4791
-        return call_user_func($model_classname . "::instance");
4792
-    }
4793
-
4794
-
4795
-
4796
-    /**
4797
-     * Returns the array of EE_ModelRelations for this model.
4798
-     *
4799
-     * @return EE_Model_Relation_Base[]
4800
-     */
4801
-    public function relation_settings()
4802
-    {
4803
-        return $this->_model_relations;
4804
-    }
4805
-
4806
-
4807
-
4808
-    /**
4809
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4810
-     * because without THOSE models, this model probably doesn't have much purpose.
4811
-     * (Eg, without an event, datetimes have little purpose.)
4812
-     *
4813
-     * @return EE_Belongs_To_Relation[]
4814
-     */
4815
-    public function belongs_to_relations()
4816
-    {
4817
-        $belongs_to_relations = array();
4818
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4819
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4820
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4821
-            }
4822
-        }
4823
-        return $belongs_to_relations;
4824
-    }
4825
-
4826
-
4827
-
4828
-    /**
4829
-     * Returns the specified EE_Model_Relation, or throws an exception
4830
-     *
4831
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4832
-     * @throws EE_Error
4833
-     * @return EE_Model_Relation_Base
4834
-     */
4835
-    public function related_settings_for($relation_name)
4836
-    {
4837
-        $relatedModels = $this->relation_settings();
4838
-        if (! array_key_exists($relation_name, $relatedModels)) {
4839
-            throw new EE_Error(
4840
-                sprintf(
4841
-                    __(
4842
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4843
-                        'event_espresso'
4844
-                    ),
4845
-                    $relation_name,
4846
-                    $this->_get_class_name(),
4847
-                    implode(', ', array_keys($relatedModels))
4848
-                )
4849
-            );
4850
-        }
4851
-        return $relatedModels[ $relation_name ];
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4858
-     * fields
4859
-     *
4860
-     * @param string $fieldName
4861
-     * @param boolean $include_db_only_fields
4862
-     * @throws EE_Error
4863
-     * @return EE_Model_Field_Base
4864
-     */
4865
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4866
-    {
4867
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4868
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4869
-            throw new EE_Error(sprintf(
4870
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4871
-                $fieldName,
4872
-                get_class($this)
4873
-            ));
4874
-        }
4875
-        return $fieldSettings[ $fieldName ];
4876
-    }
4877
-
4878
-
4879
-
4880
-    /**
4881
-     * Checks if this field exists on this model
4882
-     *
4883
-     * @param string $fieldName a key in the model's _field_settings array
4884
-     * @return boolean
4885
-     */
4886
-    public function has_field($fieldName)
4887
-    {
4888
-        $fieldSettings = $this->field_settings(true);
4889
-        if (isset($fieldSettings[ $fieldName ])) {
4890
-            return true;
4891
-        }
4892
-        return false;
4893
-    }
4894
-
4895
-
4896
-
4897
-    /**
4898
-     * Returns whether or not this model has a relation to the specified model
4899
-     *
4900
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4901
-     * @return boolean
4902
-     */
4903
-    public function has_relation($relation_name)
4904
-    {
4905
-        $relations = $this->relation_settings();
4906
-        if (isset($relations[ $relation_name ])) {
4907
-            return true;
4908
-        }
4909
-        return false;
4910
-    }
4911
-
4912
-
4913
-
4914
-    /**
4915
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4916
-     * Eg, on EE_Answer that would be ANS_ID field object
4917
-     *
4918
-     * @param $field_obj
4919
-     * @return boolean
4920
-     */
4921
-    public function is_primary_key_field($field_obj)
4922
-    {
4923
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4924
-    }
4925
-
4926
-
4927
-
4928
-    /**
4929
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4930
-     * Eg, on EE_Answer that would be ANS_ID field object
4931
-     *
4932
-     * @return EE_Model_Field_Base
4933
-     * @throws EE_Error
4934
-     */
4935
-    public function get_primary_key_field()
4936
-    {
4937
-        if ($this->_primary_key_field === null) {
4938
-            foreach ($this->field_settings(true) as $field_obj) {
4939
-                if ($this->is_primary_key_field($field_obj)) {
4940
-                    $this->_primary_key_field = $field_obj;
4941
-                    break;
4942
-                }
4943
-            }
4944
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4945
-                throw new EE_Error(sprintf(
4946
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4947
-                    get_class($this)
4948
-                ));
4949
-            }
4950
-        }
4951
-        return $this->_primary_key_field;
4952
-    }
4953
-
4954
-
4955
-
4956
-    /**
4957
-     * Returns whether or not not there is a primary key on this model.
4958
-     * Internally does some caching.
4959
-     *
4960
-     * @return boolean
4961
-     */
4962
-    public function has_primary_key_field()
4963
-    {
4964
-        if ($this->_has_primary_key_field === null) {
4965
-            try {
4966
-                $this->get_primary_key_field();
4967
-                $this->_has_primary_key_field = true;
4968
-            } catch (EE_Error $e) {
4969
-                $this->_has_primary_key_field = false;
4970
-            }
4971
-        }
4972
-        return $this->_has_primary_key_field;
4973
-    }
4974
-
4975
-
4976
-
4977
-    /**
4978
-     * Finds the first field of type $field_class_name.
4979
-     *
4980
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4981
-     *                                 EE_Foreign_Key_Field, etc
4982
-     * @return EE_Model_Field_Base or null if none is found
4983
-     */
4984
-    public function get_a_field_of_type($field_class_name)
4985
-    {
4986
-        foreach ($this->field_settings() as $field) {
4987
-            if ($field instanceof $field_class_name) {
4988
-                return $field;
4989
-            }
4990
-        }
4991
-        return null;
4992
-    }
4993
-
4994
-
4995
-
4996
-    /**
4997
-     * Gets a foreign key field pointing to model.
4998
-     *
4999
-     * @param string $model_name eg Event, Registration, not EEM_Event
5000
-     * @return EE_Foreign_Key_Field_Base
5001
-     * @throws EE_Error
5002
-     */
5003
-    public function get_foreign_key_to($model_name)
5004
-    {
5005
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5006
-            foreach ($this->field_settings() as $field) {
5007
-                if ($field instanceof EE_Foreign_Key_Field_Base
5008
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5009
-                ) {
5010
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5011
-                    break;
5012
-                }
5013
-            }
5014
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5015
-                throw new EE_Error(sprintf(__(
5016
-                    "There is no foreign key field pointing to model %s on model %s",
5017
-                    'event_espresso'
5018
-                ), $model_name, get_class($this)));
5019
-            }
5020
-        }
5021
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5022
-    }
5023
-
5024
-
5025
-
5026
-    /**
5027
-     * Gets the table name (including $wpdb->prefix) for the table alias
5028
-     *
5029
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5030
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5031
-     *                            Either one works
5032
-     * @return string
5033
-     */
5034
-    public function get_table_for_alias($table_alias)
5035
-    {
5036
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5037
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5038
-    }
5039
-
5040
-
5041
-
5042
-    /**
5043
-     * Returns a flat array of all field son this model, instead of organizing them
5044
-     * by table_alias as they are in the constructor.
5045
-     *
5046
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5047
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5048
-     */
5049
-    public function field_settings($include_db_only_fields = false)
5050
-    {
5051
-        if ($include_db_only_fields) {
5052
-            if ($this->_cached_fields === null) {
5053
-                $this->_cached_fields = array();
5054
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5055
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5056
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5057
-                    }
5058
-                }
5059
-            }
5060
-            return $this->_cached_fields;
5061
-        }
5062
-        if ($this->_cached_fields_non_db_only === null) {
5063
-            $this->_cached_fields_non_db_only = array();
5064
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5065
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5066
-                    /** @var $field_obj EE_Model_Field_Base */
5067
-                    if (! $field_obj->is_db_only_field()) {
5068
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5069
-                    }
5070
-                }
5071
-            }
5072
-        }
5073
-        return $this->_cached_fields_non_db_only;
5074
-    }
5075
-
5076
-
5077
-
5078
-    /**
5079
-     *        cycle though array of attendees and create objects out of each item
5080
-     *
5081
-     * @access        private
5082
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5083
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5084
-     *                           numerically indexed)
5085
-     * @throws EE_Error
5086
-     */
5087
-    protected function _create_objects($rows = array())
5088
-    {
5089
-        $array_of_objects = array();
5090
-        if (empty($rows)) {
5091
-            return array();
5092
-        }
5093
-        $count_if_model_has_no_primary_key = 0;
5094
-        $has_primary_key = $this->has_primary_key_field();
5095
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5096
-        foreach ((array) $rows as $row) {
5097
-            if (empty($row)) {
5098
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5099
-                return array();
5100
-            }
5101
-            // check if we've already set this object in the results array,
5102
-            // in which case there's no need to process it further (again)
5103
-            if ($has_primary_key) {
5104
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5105
-                    $row,
5106
-                    $primary_key_field->get_qualified_column(),
5107
-                    $primary_key_field->get_table_column()
5108
-                );
5109
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5110
-                    continue;
5111
-                }
5112
-            }
5113
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5114
-            if (! $classInstance) {
5115
-                throw new EE_Error(
5116
-                    sprintf(
5117
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5118
-                        $this->get_this_model_name(),
5119
-                        http_build_query($row)
5120
-                    )
5121
-                );
5122
-            }
5123
-            // set the timezone on the instantiated objects
5124
-            $classInstance->set_timezone($this->_timezone);
5125
-            // make sure if there is any timezone setting present that we set the timezone for the object
5126
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5127
-            $array_of_objects[ $key ] = $classInstance;
5128
-            // also, for all the relations of type BelongsTo, see if we can cache
5129
-            // those related models
5130
-            // (we could do this for other relations too, but if there are conditions
5131
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5132
-            // so it requires a little more thought than just caching them immediately...)
5133
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5134
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5135
-                    // check if this model's INFO is present. If so, cache it on the model
5136
-                    $other_model = $relation_obj->get_other_model();
5137
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5138
-                    // if we managed to make a model object from the results, cache it on the main model object
5139
-                    if ($other_model_obj_maybe) {
5140
-                        // set timezone on these other model objects if they are present
5141
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5142
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5143
-                    }
5144
-                }
5145
-            }
5146
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5147
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5148
-            // the field in the CustomSelects object
5149
-            if ($this->_custom_selections instanceof CustomSelects) {
5150
-                $classInstance->setCustomSelectsValues(
5151
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5152
-                );
5153
-            }
5154
-        }
5155
-        return $array_of_objects;
5156
-    }
5157
-
5158
-
5159
-    /**
5160
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5161
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5162
-     *
5163
-     * @param array $db_results_row
5164
-     * @return array
5165
-     */
5166
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5167
-    {
5168
-        $results = array();
5169
-        if ($this->_custom_selections instanceof CustomSelects) {
5170
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5171
-                if (isset($db_results_row[ $alias ])) {
5172
-                    $results[ $alias ] = $this->convertValueToDataType(
5173
-                        $db_results_row[ $alias ],
5174
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5175
-                    );
5176
-                }
5177
-            }
5178
-        }
5179
-        return $results;
5180
-    }
5181
-
5182
-
5183
-    /**
5184
-     * This will set the value for the given alias
5185
-     * @param string $value
5186
-     * @param string $datatype (one of %d, %s, %f)
5187
-     * @return int|string|float (int for %d, string for %s, float for %f)
5188
-     */
5189
-    protected function convertValueToDataType($value, $datatype)
5190
-    {
5191
-        switch ($datatype) {
5192
-            case '%f':
5193
-                return (float) $value;
5194
-            case '%d':
5195
-                return (int) $value;
5196
-            default:
5197
-                return (string) $value;
5198
-        }
5199
-    }
5200
-
5201
-
5202
-    /**
5203
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5204
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5205
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5206
-     * object (as set in the model_field!).
5207
-     *
5208
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5209
-     */
5210
-    public function create_default_object()
5211
-    {
5212
-        $this_model_fields_and_values = array();
5213
-        // setup the row using default values;
5214
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5215
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5216
-        }
5217
-        $className = $this->_get_class_name();
5218
-        $classInstance = EE_Registry::instance()
5219
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5220
-        return $classInstance;
5221
-    }
5222
-
5223
-
5224
-
5225
-    /**
5226
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5227
-     *                             or an stdClass where each property is the name of a column,
5228
-     * @return EE_Base_Class
5229
-     * @throws EE_Error
5230
-     */
5231
-    public function instantiate_class_from_array_or_object($cols_n_values)
5232
-    {
5233
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5234
-            $cols_n_values = get_object_vars($cols_n_values);
5235
-        }
5236
-        $primary_key = null;
5237
-        // make sure the array only has keys that are fields/columns on this model
5238
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5239
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5240
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5241
-        }
5242
-        $className = $this->_get_class_name();
5243
-        // check we actually found results that we can use to build our model object
5244
-        // if not, return null
5245
-        if ($this->has_primary_key_field()) {
5246
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5247
-                return null;
5248
-            }
5249
-        } elseif ($this->unique_indexes()) {
5250
-            $first_column = reset($this_model_fields_n_values);
5251
-            if (empty($first_column)) {
5252
-                return null;
5253
-            }
5254
-        }
5255
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5256
-        if ($primary_key) {
5257
-            $classInstance = $this->get_from_entity_map($primary_key);
5258
-            if (! $classInstance) {
5259
-                $classInstance = EE_Registry::instance()
5260
-                                            ->load_class(
5261
-                                                $className,
5262
-                                                array($this_model_fields_n_values, $this->_timezone),
5263
-                                                true,
5264
-                                                false
5265
-                                            );
5266
-                // add this new object to the entity map
5267
-                $classInstance = $this->add_to_entity_map($classInstance);
5268
-            }
5269
-        } else {
5270
-            $classInstance = EE_Registry::instance()
5271
-                                        ->load_class(
5272
-                                            $className,
5273
-                                            array($this_model_fields_n_values, $this->_timezone),
5274
-                                            true,
5275
-                                            false
5276
-                                        );
5277
-        }
5278
-        return $classInstance;
5279
-    }
5280
-
5281
-
5282
-
5283
-    /**
5284
-     * Gets the model object from the  entity map if it exists
5285
-     *
5286
-     * @param int|string $id the ID of the model object
5287
-     * @return EE_Base_Class
5288
-     */
5289
-    public function get_from_entity_map($id)
5290
-    {
5291
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5292
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5293
-    }
5294
-
5295
-
5296
-
5297
-    /**
5298
-     * add_to_entity_map
5299
-     * Adds the object to the model's entity mappings
5300
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5301
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5302
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5303
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5304
-     *        then this method should be called immediately after the update query
5305
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5306
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5307
-     *
5308
-     * @param    EE_Base_Class $object
5309
-     * @throws EE_Error
5310
-     * @return \EE_Base_Class
5311
-     */
5312
-    public function add_to_entity_map(EE_Base_Class $object)
5313
-    {
5314
-        $className = $this->_get_class_name();
5315
-        if (! $object instanceof $className) {
5316
-            throw new EE_Error(sprintf(
5317
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5318
-                is_object($object) ? get_class($object) : $object,
5319
-                $className
5320
-            ));
5321
-        }
5322
-        /** @var $object EE_Base_Class */
5323
-        if (! $object->ID()) {
5324
-            throw new EE_Error(sprintf(__(
5325
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5326
-                "event_espresso"
5327
-            ), get_class($this)));
5328
-        }
5329
-        // double check it's not already there
5330
-        $classInstance = $this->get_from_entity_map($object->ID());
5331
-        if ($classInstance) {
5332
-            return $classInstance;
5333
-        }
5334
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5335
-        return $object;
5336
-    }
5337
-
5338
-
5339
-
5340
-    /**
5341
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5342
-     * if no identifier is provided, then the entire entity map is emptied
5343
-     *
5344
-     * @param int|string $id the ID of the model object
5345
-     * @return boolean
5346
-     */
5347
-    public function clear_entity_map($id = null)
5348
-    {
5349
-        if (empty($id)) {
5350
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5351
-            return true;
5352
-        }
5353
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5354
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5355
-            return true;
5356
-        }
5357
-        return false;
5358
-    }
5359
-
5360
-
5361
-
5362
-    /**
5363
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5364
-     * Given an array where keys are column (or column alias) names and values,
5365
-     * returns an array of their corresponding field names and database values
5366
-     *
5367
-     * @param array $cols_n_values
5368
-     * @return array
5369
-     */
5370
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5371
-    {
5372
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5373
-    }
5374
-
5375
-
5376
-
5377
-    /**
5378
-     * _deduce_fields_n_values_from_cols_n_values
5379
-     * Given an array where keys are column (or column alias) names and values,
5380
-     * returns an array of their corresponding field names and database values
5381
-     *
5382
-     * @param string $cols_n_values
5383
-     * @return array
5384
-     */
5385
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5386
-    {
5387
-        $this_model_fields_n_values = array();
5388
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5389
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5390
-                $cols_n_values,
5391
-                $table_obj->get_fully_qualified_pk_column(),
5392
-                $table_obj->get_pk_column()
5393
-            );
5394
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5395
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5396
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5397
-                    if (! $field_obj->is_db_only_field()) {
5398
-                        // prepare field as if its coming from db
5399
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5400
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5401
-                    }
5402
-                }
5403
-            } else {
5404
-                // the table's rows existed. Use their values
5405
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5406
-                    if (! $field_obj->is_db_only_field()) {
5407
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5408
-                            $cols_n_values,
5409
-                            $field_obj->get_qualified_column(),
5410
-                            $field_obj->get_table_column()
5411
-                        );
5412
-                    }
5413
-                }
5414
-            }
5415
-        }
5416
-        return $this_model_fields_n_values;
5417
-    }
5418
-
5419
-
5420
-    /**
5421
-     * @param $cols_n_values
5422
-     * @param $qualified_column
5423
-     * @param $regular_column
5424
-     * @return null
5425
-     * @throws EE_Error
5426
-     * @throws ReflectionException
5427
-     */
5428
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5429
-    {
5430
-        $value = null;
5431
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5432
-        // does the field on the model relate to this column retrieved from the db?
5433
-        // or is it a db-only field? (not relating to the model)
5434
-        if (isset($cols_n_values[ $qualified_column ])) {
5435
-            $value = $cols_n_values[ $qualified_column ];
5436
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5437
-            $value = $cols_n_values[ $regular_column ];
5438
-        } elseif (! empty($this->foreign_key_aliases)) {
5439
-            // no PK?  ok check if there is a foreign key alias set for this table
5440
-            // then check if that alias exists in the incoming data
5441
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5442
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5443
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5444
-                    $value = $cols_n_values[ $FK_alias ];
5445
-                    list($pk_class) = explode('.', $PK_column);
5446
-                    $pk_model_name = "EEM_{$pk_class}";
5447
-                    /** @var EEM_Base $pk_model */
5448
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5449
-                    if ($pk_model instanceof EEM_Base) {
5450
-                        // make sure object is pulled from db and added to entity map
5451
-                        $pk_model->get_one_by_ID($value);
5452
-                    }
5453
-                    break;
5454
-                }
5455
-            }
5456
-        }
5457
-        return $value;
5458
-    }
5459
-
5460
-
5461
-
5462
-    /**
5463
-     * refresh_entity_map_from_db
5464
-     * Makes sure the model object in the entity map at $id assumes the values
5465
-     * of the database (opposite of EE_base_Class::save())
5466
-     *
5467
-     * @param int|string $id
5468
-     * @return EE_Base_Class
5469
-     * @throws EE_Error
5470
-     */
5471
-    public function refresh_entity_map_from_db($id)
5472
-    {
5473
-        $obj_in_map = $this->get_from_entity_map($id);
5474
-        if ($obj_in_map) {
5475
-            $wpdb_results = $this->_get_all_wpdb_results(
5476
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5477
-            );
5478
-            if ($wpdb_results && is_array($wpdb_results)) {
5479
-                $one_row = reset($wpdb_results);
5480
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5481
-                    $obj_in_map->set_from_db($field_name, $db_value);
5482
-                }
5483
-                // clear the cache of related model objects
5484
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5485
-                    $obj_in_map->clear_cache($relation_name, null, true);
5486
-                }
5487
-            }
5488
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5489
-            return $obj_in_map;
5490
-        }
5491
-        return $this->get_one_by_ID($id);
5492
-    }
5493
-
5494
-
5495
-
5496
-    /**
5497
-     * refresh_entity_map_with
5498
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5499
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5500
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5501
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5502
-     *
5503
-     * @param int|string    $id
5504
-     * @param EE_Base_Class $replacing_model_obj
5505
-     * @return \EE_Base_Class
5506
-     * @throws EE_Error
5507
-     */
5508
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5509
-    {
5510
-        $obj_in_map = $this->get_from_entity_map($id);
5511
-        if ($obj_in_map) {
5512
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5513
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5514
-                    $obj_in_map->set($field_name, $value);
5515
-                }
5516
-                // make the model object in the entity map's cache match the $replacing_model_obj
5517
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5518
-                    $obj_in_map->clear_cache($relation_name, null, true);
5519
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5520
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5521
-                    }
5522
-                }
5523
-            }
5524
-            return $obj_in_map;
5525
-        }
5526
-        $this->add_to_entity_map($replacing_model_obj);
5527
-        return $replacing_model_obj;
5528
-    }
5529
-
5530
-
5531
-
5532
-    /**
5533
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5534
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5535
-     * require_once($this->_getClassName().".class.php");
5536
-     *
5537
-     * @return string
5538
-     */
5539
-    private function _get_class_name()
5540
-    {
5541
-        return "EE_" . $this->get_this_model_name();
5542
-    }
5543
-
5544
-
5545
-
5546
-    /**
5547
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5548
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5549
-     * it would be 'Events'.
5550
-     *
5551
-     * @param int $quantity
5552
-     * @return string
5553
-     */
5554
-    public function item_name($quantity = 1)
5555
-    {
5556
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5557
-    }
5558
-
5559
-
5560
-
5561
-    /**
5562
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5563
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5564
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5565
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5566
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5567
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5568
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5569
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5570
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5571
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5572
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5573
-     *        return $previousReturnValue.$returnString;
5574
-     * }
5575
-     * require('EEM_Answer.model.php');
5576
-     * $answer=EEM_Answer::instance();
5577
-     * echo $answer->my_callback('monkeys',100);
5578
-     * //will output "you called my_callback! and passed args:monkeys,100"
5579
-     *
5580
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5581
-     * @param array  $args       array of original arguments passed to the function
5582
-     * @throws EE_Error
5583
-     * @return mixed whatever the plugin which calls add_filter decides
5584
-     */
5585
-    public function __call($methodName, $args)
5586
-    {
5587
-        $className = get_class($this);
5588
-        $tagName = "FHEE__{$className}__{$methodName}";
5589
-        if (! has_filter($tagName)) {
5590
-            throw new EE_Error(
5591
-                sprintf(
5592
-                    __(
5593
-                        '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 );',
5594
-                        'event_espresso'
5595
-                    ),
5596
-                    $methodName,
5597
-                    $className,
5598
-                    $tagName,
5599
-                    '<br />'
5600
-                )
5601
-            );
5602
-        }
5603
-        return apply_filters($tagName, null, $this, $args);
5604
-    }
5605
-
5606
-
5607
-
5608
-    /**
5609
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5610
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5611
-     *
5612
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5613
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5614
-     *                                                       the object's class name
5615
-     *                                                       or object's ID
5616
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5617
-     *                                                       exists in the database. If it does not, we add it
5618
-     * @throws EE_Error
5619
-     * @return EE_Base_Class
5620
-     */
5621
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5622
-    {
5623
-        $className = $this->_get_class_name();
5624
-        if ($base_class_obj_or_id instanceof $className) {
5625
-            $model_object = $base_class_obj_or_id;
5626
-        } else {
5627
-            $primary_key_field = $this->get_primary_key_field();
5628
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5629
-                && (
5630
-                    is_int($base_class_obj_or_id)
5631
-                    || is_string($base_class_obj_or_id)
5632
-                )
5633
-            ) {
5634
-                // assume it's an ID.
5635
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5636
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5637
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5638
-                && is_string($base_class_obj_or_id)
5639
-            ) {
5640
-                // assume its a string representation of the object
5641
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5642
-            } else {
5643
-                throw new EE_Error(
5644
-                    sprintf(
5645
-                        __(
5646
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5647
-                            'event_espresso'
5648
-                        ),
5649
-                        $base_class_obj_or_id,
5650
-                        $this->_get_class_name(),
5651
-                        print_r($base_class_obj_or_id, true)
5652
-                    )
5653
-                );
5654
-            }
5655
-        }
5656
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5657
-            $model_object->save();
5658
-        }
5659
-        return $model_object;
5660
-    }
5661
-
5662
-
5663
-
5664
-    /**
5665
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5666
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5667
-     * returns it ID.
5668
-     *
5669
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5670
-     * @return int|string depending on the type of this model object's ID
5671
-     * @throws EE_Error
5672
-     */
5673
-    public function ensure_is_ID($base_class_obj_or_id)
5674
-    {
5675
-        $className = $this->_get_class_name();
5676
-        if ($base_class_obj_or_id instanceof $className) {
5677
-            /** @var $base_class_obj_or_id EE_Base_Class */
5678
-            $id = $base_class_obj_or_id->ID();
5679
-        } elseif (is_int($base_class_obj_or_id)) {
5680
-            // assume it's an ID
5681
-            $id = $base_class_obj_or_id;
5682
-        } elseif (is_string($base_class_obj_or_id)) {
5683
-            // assume its a string representation of the object
5684
-            $id = $base_class_obj_or_id;
5685
-        } else {
5686
-            throw new EE_Error(sprintf(
5687
-                __(
5688
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5689
-                    'event_espresso'
5690
-                ),
5691
-                $base_class_obj_or_id,
5692
-                $this->_get_class_name(),
5693
-                print_r($base_class_obj_or_id, true)
5694
-            ));
5695
-        }
5696
-        return $id;
5697
-    }
5698
-
5699
-
5700
-
5701
-    /**
5702
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5703
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5704
-     * been sanitized and converted into the appropriate domain.
5705
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5706
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5707
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5708
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5709
-     * $EVT = EEM_Event::instance(); $old_setting =
5710
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5711
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5712
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5713
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5714
-     *
5715
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5716
-     * @return void
5717
-     */
5718
-    public function assume_values_already_prepared_by_model_object(
5719
-        $values_already_prepared = self::not_prepared_by_model_object
5720
-    ) {
5721
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5722
-    }
5723
-
5724
-
5725
-
5726
-    /**
5727
-     * Read comments for assume_values_already_prepared_by_model_object()
5728
-     *
5729
-     * @return int
5730
-     */
5731
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5732
-    {
5733
-        return $this->_values_already_prepared_by_model_object;
5734
-    }
5735
-
5736
-
5737
-
5738
-    /**
5739
-     * Gets all the indexes on this model
5740
-     *
5741
-     * @return EE_Index[]
5742
-     */
5743
-    public function indexes()
5744
-    {
5745
-        return $this->_indexes;
5746
-    }
5747
-
5748
-
5749
-
5750
-    /**
5751
-     * Gets all the Unique Indexes on this model
5752
-     *
5753
-     * @return EE_Unique_Index[]
5754
-     */
5755
-    public function unique_indexes()
5756
-    {
5757
-        $unique_indexes = array();
5758
-        foreach ($this->_indexes as $name => $index) {
5759
-            if ($index instanceof EE_Unique_Index) {
5760
-                $unique_indexes [ $name ] = $index;
5761
-            }
5762
-        }
5763
-        return $unique_indexes;
5764
-    }
5765
-
5766
-
5767
-
5768
-    /**
5769
-     * Gets all the fields which, when combined, make the primary key.
5770
-     * This is usually just an array with 1 element (the primary key), but in cases
5771
-     * where there is no primary key, it's a combination of fields as defined
5772
-     * on a primary index
5773
-     *
5774
-     * @return EE_Model_Field_Base[] indexed by the field's name
5775
-     * @throws EE_Error
5776
-     */
5777
-    public function get_combined_primary_key_fields()
5778
-    {
5779
-        foreach ($this->indexes() as $index) {
5780
-            if ($index instanceof EE_Primary_Key_Index) {
5781
-                return $index->fields();
5782
-            }
5783
-        }
5784
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5785
-    }
5786
-
5787
-
5788
-
5789
-    /**
5790
-     * Used to build a primary key string (when the model has no primary key),
5791
-     * which can be used a unique string to identify this model object.
5792
-     *
5793
-     * @param array $fields_n_values keys are field names, values are their values.
5794
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5795
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5796
-     *                               before passing it to this function (that will convert it from columns-n-values
5797
-     *                               to field-names-n-values).
5798
-     * @return string
5799
-     * @throws EE_Error
5800
-     */
5801
-    public function get_index_primary_key_string($fields_n_values)
5802
-    {
5803
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5804
-            $fields_n_values,
5805
-            $this->get_combined_primary_key_fields()
5806
-        );
5807
-        return http_build_query($cols_n_values_for_primary_key_index);
5808
-    }
5809
-
5810
-
5811
-
5812
-    /**
5813
-     * Gets the field values from the primary key string
5814
-     *
5815
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5816
-     * @param string $index_primary_key_string
5817
-     * @return null|array
5818
-     * @throws EE_Error
5819
-     */
5820
-    public function parse_index_primary_key_string($index_primary_key_string)
5821
-    {
5822
-        $key_fields = $this->get_combined_primary_key_fields();
5823
-        // check all of them are in the $id
5824
-        $key_vals_in_combined_pk = array();
5825
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5826
-        foreach ($key_fields as $key_field_name => $field_obj) {
5827
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5828
-                return null;
5829
-            }
5830
-        }
5831
-        return $key_vals_in_combined_pk;
5832
-    }
5833
-
5834
-
5835
-
5836
-    /**
5837
-     * verifies that an array of key-value pairs for model fields has a key
5838
-     * for each field comprising the primary key index
5839
-     *
5840
-     * @param array $key_vals
5841
-     * @return boolean
5842
-     * @throws EE_Error
5843
-     */
5844
-    public function has_all_combined_primary_key_fields($key_vals)
5845
-    {
5846
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5847
-        foreach ($keys_it_should_have as $key) {
5848
-            if (! isset($key_vals[ $key ])) {
5849
-                return false;
5850
-            }
5851
-        }
5852
-        return true;
5853
-    }
5854
-
5855
-
5856
-
5857
-    /**
5858
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5859
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5860
-     *
5861
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5862
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5863
-     * @throws EE_Error
5864
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5865
-     *                                                              indexed)
5866
-     */
5867
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5868
-    {
5869
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5870
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5871
-        } elseif (is_array($model_object_or_attributes_array)) {
5872
-            $attributes_array = $model_object_or_attributes_array;
5873
-        } else {
5874
-            throw new EE_Error(sprintf(__(
5875
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5876
-                "event_espresso"
5877
-            ), $model_object_or_attributes_array));
5878
-        }
5879
-        // even copies obviously won't have the same ID, so remove the primary key
5880
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5881
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5882
-            unset($attributes_array[ $this->primary_key_name() ]);
5883
-        }
5884
-        if (isset($query_params[0])) {
5885
-            $query_params[0] = array_merge($attributes_array, $query_params);
5886
-        } else {
5887
-            $query_params[0] = $attributes_array;
5888
-        }
5889
-        return $this->get_all($query_params);
5890
-    }
5891
-
5892
-
5893
-
5894
-    /**
5895
-     * Gets the first copy we find. See get_all_copies for more details
5896
-     *
5897
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5898
-     * @param array $query_params
5899
-     * @return EE_Base_Class
5900
-     * @throws EE_Error
5901
-     */
5902
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5903
-    {
5904
-        if (! is_array($query_params)) {
5905
-            EE_Error::doing_it_wrong(
5906
-                'EEM_Base::get_one_copy',
5907
-                sprintf(
5908
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5909
-                    gettype($query_params)
5910
-                ),
5911
-                '4.6.0'
5912
-            );
5913
-            $query_params = array();
5914
-        }
5915
-        $query_params['limit'] = 1;
5916
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5917
-        if (is_array($copies)) {
5918
-            return array_shift($copies);
5919
-        }
5920
-        return null;
5921
-    }
5922
-
5923
-
5924
-
5925
-    /**
5926
-     * Updates the item with the specified id. Ignores default query parameters because
5927
-     * we have specified the ID, and its assumed we KNOW what we're doing
5928
-     *
5929
-     * @param array      $fields_n_values keys are field names, values are their new values
5930
-     * @param int|string $id              the value of the primary key to update
5931
-     * @return int number of rows updated
5932
-     * @throws EE_Error
5933
-     */
5934
-    public function update_by_ID($fields_n_values, $id)
5935
-    {
5936
-        $query_params = array(
5937
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5938
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5939
-        );
5940
-        return $this->update($fields_n_values, $query_params);
5941
-    }
5942
-
5943
-
5944
-
5945
-    /**
5946
-     * Changes an operator which was supplied to the models into one usable in SQL
5947
-     *
5948
-     * @param string $operator_supplied
5949
-     * @return string an operator which can be used in SQL
5950
-     * @throws EE_Error
5951
-     */
5952
-    private function _prepare_operator_for_sql($operator_supplied)
5953
-    {
5954
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5955
-            : null;
5956
-        if ($sql_operator) {
5957
-            return $sql_operator;
5958
-        }
5959
-        throw new EE_Error(
5960
-            sprintf(
5961
-                __(
5962
-                    "The operator '%s' is not in the list of valid operators: %s",
5963
-                    "event_espresso"
5964
-                ),
5965
-                $operator_supplied,
5966
-                implode(",", array_keys($this->_valid_operators))
5967
-            )
5968
-        );
5969
-    }
5970
-
5971
-
5972
-
5973
-    /**
5974
-     * Gets the valid operators
5975
-     * @return array keys are accepted strings, values are the SQL they are converted to
5976
-     */
5977
-    public function valid_operators()
5978
-    {
5979
-        return $this->_valid_operators;
5980
-    }
5981
-
5982
-
5983
-
5984
-    /**
5985
-     * Gets the between-style operators (take 2 arguments).
5986
-     * @return array keys are accepted strings, values are the SQL they are converted to
5987
-     */
5988
-    public function valid_between_style_operators()
5989
-    {
5990
-        return array_intersect(
5991
-            $this->valid_operators(),
5992
-            $this->_between_style_operators
5993
-        );
5994
-    }
5995
-
5996
-    /**
5997
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5998
-     * @return array keys are accepted strings, values are the SQL they are converted to
5999
-     */
6000
-    public function valid_like_style_operators()
6001
-    {
6002
-        return array_intersect(
6003
-            $this->valid_operators(),
6004
-            $this->_like_style_operators
6005
-        );
6006
-    }
6007
-
6008
-    /**
6009
-     * Gets the "in"-style operators
6010
-     * @return array keys are accepted strings, values are the SQL they are converted to
6011
-     */
6012
-    public function valid_in_style_operators()
6013
-    {
6014
-        return array_intersect(
6015
-            $this->valid_operators(),
6016
-            $this->_in_style_operators
6017
-        );
6018
-    }
6019
-
6020
-    /**
6021
-     * Gets the "null"-style operators (accept no arguments)
6022
-     * @return array keys are accepted strings, values are the SQL they are converted to
6023
-     */
6024
-    public function valid_null_style_operators()
6025
-    {
6026
-        return array_intersect(
6027
-            $this->valid_operators(),
6028
-            $this->_null_style_operators
6029
-        );
6030
-    }
6031
-
6032
-    /**
6033
-     * Gets an array where keys are the primary keys and values are their 'names'
6034
-     * (as determined by the model object's name() function, which is often overridden)
6035
-     *
6036
-     * @param array $query_params like get_all's
6037
-     * @return string[]
6038
-     * @throws EE_Error
6039
-     */
6040
-    public function get_all_names($query_params = array())
6041
-    {
6042
-        $objs = $this->get_all($query_params);
6043
-        $names = array();
6044
-        foreach ($objs as $obj) {
6045
-            $names[ $obj->ID() ] = $obj->name();
6046
-        }
6047
-        return $names;
6048
-    }
6049
-
6050
-
6051
-
6052
-    /**
6053
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6054
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6055
-     * this is duplicated effort and reduces efficiency) you would be better to use
6056
-     * array_keys() on $model_objects.
6057
-     *
6058
-     * @param \EE_Base_Class[] $model_objects
6059
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6060
-     *                                               in the returned array
6061
-     * @return array
6062
-     * @throws EE_Error
6063
-     */
6064
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6065
-    {
6066
-        if (! $this->has_primary_key_field()) {
6067
-            if (WP_DEBUG) {
6068
-                EE_Error::add_error(
6069
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6070
-                    __FILE__,
6071
-                    __FUNCTION__,
6072
-                    __LINE__
6073
-                );
6074
-            }
6075
-        }
6076
-        $IDs = array();
6077
-        foreach ($model_objects as $model_object) {
6078
-            $id = $model_object->ID();
6079
-            if (! $id) {
6080
-                if ($filter_out_empty_ids) {
6081
-                    continue;
6082
-                }
6083
-                if (WP_DEBUG) {
6084
-                    EE_Error::add_error(
6085
-                        __(
6086
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6087
-                            'event_espresso'
6088
-                        ),
6089
-                        __FILE__,
6090
-                        __FUNCTION__,
6091
-                        __LINE__
6092
-                    );
6093
-                }
6094
-            }
6095
-            $IDs[] = $id;
6096
-        }
6097
-        return $IDs;
6098
-    }
6099
-
6100
-
6101
-
6102
-    /**
6103
-     * Returns the string used in capabilities relating to this model. If there
6104
-     * are no capabilities that relate to this model returns false
6105
-     *
6106
-     * @return string|false
6107
-     */
6108
-    public function cap_slug()
6109
-    {
6110
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6111
-    }
6112
-
6113
-
6114
-
6115
-    /**
6116
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6117
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6118
-     * only returns the cap restrictions array in that context (ie, the array
6119
-     * at that key)
6120
-     *
6121
-     * @param string $context
6122
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6123
-     * @throws EE_Error
6124
-     */
6125
-    public function cap_restrictions($context = EEM_Base::caps_read)
6126
-    {
6127
-        EEM_Base::verify_is_valid_cap_context($context);
6128
-        // check if we ought to run the restriction generator first
6129
-        if (isset($this->_cap_restriction_generators[ $context ])
6130
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6131
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6132
-        ) {
6133
-            $this->_cap_restrictions[ $context ] = array_merge(
6134
-                $this->_cap_restrictions[ $context ],
6135
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6136
-            );
6137
-        }
6138
-        // and make sure we've finalized the construction of each restriction
6139
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6140
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6141
-                $where_conditions_obj->_finalize_construct($this);
6142
-            }
6143
-        }
6144
-        return $this->_cap_restrictions[ $context ];
6145
-    }
6146
-
6147
-
6148
-
6149
-    /**
6150
-     * Indicating whether or not this model thinks its a wp core model
6151
-     *
6152
-     * @return boolean
6153
-     */
6154
-    public function is_wp_core_model()
6155
-    {
6156
-        return $this->_wp_core_model;
6157
-    }
6158
-
6159
-
6160
-
6161
-    /**
6162
-     * Gets all the caps that are missing which impose a restriction on
6163
-     * queries made in this context
6164
-     *
6165
-     * @param string $context one of EEM_Base::caps_ constants
6166
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6167
-     * @throws EE_Error
6168
-     */
6169
-    public function caps_missing($context = EEM_Base::caps_read)
6170
-    {
6171
-        $missing_caps = array();
6172
-        $cap_restrictions = $this->cap_restrictions($context);
6173
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6174
-            if (! EE_Capabilities::instance()
6175
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6176
-            ) {
6177
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6178
-            }
6179
-        }
6180
-        return $missing_caps;
6181
-    }
6182
-
6183
-
6184
-
6185
-    /**
6186
-     * Gets the mapping from capability contexts to action strings used in capability names
6187
-     *
6188
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6189
-     * one of 'read', 'edit', or 'delete'
6190
-     */
6191
-    public function cap_contexts_to_cap_action_map()
6192
-    {
6193
-        return apply_filters(
6194
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6195
-            $this->_cap_contexts_to_cap_action_map,
6196
-            $this
6197
-        );
6198
-    }
6199
-
6200
-
6201
-
6202
-    /**
6203
-     * Gets the action string for the specified capability context
6204
-     *
6205
-     * @param string $context
6206
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6207
-     * @throws EE_Error
6208
-     */
6209
-    public function cap_action_for_context($context)
6210
-    {
6211
-        $mapping = $this->cap_contexts_to_cap_action_map();
6212
-        if (isset($mapping[ $context ])) {
6213
-            return $mapping[ $context ];
6214
-        }
6215
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6216
-            return $action;
6217
-        }
6218
-        throw new EE_Error(
6219
-            sprintf(
6220
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6221
-                $context,
6222
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6223
-            )
6224
-        );
6225
-    }
6226
-
6227
-
6228
-
6229
-    /**
6230
-     * Returns all the capability contexts which are valid when querying models
6231
-     *
6232
-     * @return array
6233
-     */
6234
-    public static function valid_cap_contexts()
6235
-    {
6236
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6237
-            self::caps_read,
6238
-            self::caps_read_admin,
6239
-            self::caps_edit,
6240
-            self::caps_delete,
6241
-        ));
6242
-    }
6243
-
6244
-
6245
-
6246
-    /**
6247
-     * Returns all valid options for 'default_where_conditions'
6248
-     *
6249
-     * @return array
6250
-     */
6251
-    public static function valid_default_where_conditions()
6252
-    {
6253
-        return array(
6254
-            EEM_Base::default_where_conditions_all,
6255
-            EEM_Base::default_where_conditions_this_only,
6256
-            EEM_Base::default_where_conditions_others_only,
6257
-            EEM_Base::default_where_conditions_minimum_all,
6258
-            EEM_Base::default_where_conditions_minimum_others,
6259
-            EEM_Base::default_where_conditions_none
6260
-        );
6261
-    }
6262
-
6263
-    // public static function default_where_conditions_full
6264
-    /**
6265
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6266
-     *
6267
-     * @param string $context
6268
-     * @return bool
6269
-     * @throws EE_Error
6270
-     */
6271
-    public static function verify_is_valid_cap_context($context)
6272
-    {
6273
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6274
-        if (in_array($context, $valid_cap_contexts)) {
6275
-            return true;
6276
-        }
6277
-        throw new EE_Error(
6278
-            sprintf(
6279
-                __(
6280
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6281
-                    'event_espresso'
6282
-                ),
6283
-                $context,
6284
-                'EEM_Base',
6285
-                implode(',', $valid_cap_contexts)
6286
-            )
6287
-        );
6288
-    }
6289
-
6290
-
6291
-
6292
-    /**
6293
-     * Clears all the models field caches. This is only useful when a sub-class
6294
-     * might have added a field or something and these caches might be invalidated
6295
-     */
6296
-    protected function _invalidate_field_caches()
6297
-    {
6298
-        $this->_cache_foreign_key_to_fields = array();
6299
-        $this->_cached_fields = null;
6300
-        $this->_cached_fields_non_db_only = null;
6301
-    }
6302
-
6303
-
6304
-
6305
-    /**
6306
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6307
-     * (eg "and", "or", "not").
6308
-     *
6309
-     * @return array
6310
-     */
6311
-    public function logic_query_param_keys()
6312
-    {
6313
-        return $this->_logic_query_param_keys;
6314
-    }
6315
-
6316
-
6317
-
6318
-    /**
6319
-     * Determines whether or not the where query param array key is for a logic query param.
6320
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6321
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6322
-     *
6323
-     * @param $query_param_key
6324
-     * @return bool
6325
-     */
6326
-    public function is_logic_query_param_key($query_param_key)
6327
-    {
6328
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6329
-            if ($query_param_key === $logic_query_param_key
6330
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6331
-            ) {
6332
-                return true;
6333
-            }
6334
-        }
6335
-        return false;
6336
-    }
6337
-
6338
-    /**
6339
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6340
-     * @since 4.9.74.p
6341
-     * @return boolean
6342
-     */
6343
-    public function hasPassword()
6344
-    {
6345
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6346
-        if ($this->has_password_field === null) {
6347
-            $password_field = $this->getPasswordField();
6348
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6349
-        }
6350
-        return $this->has_password_field;
6351
-    }
6352
-
6353
-    /**
6354
-     * Returns the password field on this model, if there is one
6355
-     * @since 4.9.74.p
6356
-     * @return EE_Password_Field|null
6357
-     */
6358
-    public function getPasswordField()
6359
-    {
6360
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6361
-        // there's no need to search for it. If we don't know yet, then find out
6362
-        if ($this->has_password_field === null && $this->password_field === null) {
6363
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6364
-        }
6365
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6366
-        return $this->password_field;
6367
-    }
6368
-
6369
-
6370
-    /**
6371
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6372
-     * @since 4.9.74.p
6373
-     * @return EE_Model_Field_Base[]
6374
-     * @throws EE_Error
6375
-     */
6376
-    public function getPasswordProtectedFields()
6377
-    {
6378
-        $password_field = $this->getPasswordField();
6379
-        $fields = array();
6380
-        if ($password_field instanceof EE_Password_Field) {
6381
-            $field_names = $password_field->protectedFields();
6382
-            foreach ($field_names as $field_name) {
6383
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6384
-            }
6385
-        }
6386
-        return $fields;
6387
-    }
6388
-
6389
-
6390
-    /**
6391
-     * Checks if the current user can perform the requested action on this model
6392
-     * @since 4.9.74.p
6393
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6394
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6395
-     * @return bool
6396
-     * @throws EE_Error
6397
-     * @throws InvalidArgumentException
6398
-     * @throws InvalidDataTypeException
6399
-     * @throws InvalidInterfaceException
6400
-     * @throws ReflectionException
6401
-     * @throws UnexpectedEntityException
6402
-     */
6403
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6404
-    {
6405
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6406
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6407
-        }
6408
-        if (!is_array($model_obj_or_fields_n_values)) {
6409
-            throw new UnexpectedEntityException(
6410
-                $model_obj_or_fields_n_values,
6411
-                'EE_Base_Class',
6412
-                sprintf(
6413
-                    esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6414
-                    __FUNCTION__
6415
-                )
6416
-            );
6417
-        }
6418
-        return $this->exists(
6419
-            $this->alter_query_params_to_restrict_by_ID(
6420
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6421
-                array(
6422
-                    'default_where_conditions' => 'none',
6423
-                    'caps'                     => $cap_to_check,
6424
-                )
6425
-            )
6426
-        );
6427
-    }
6428
-
6429
-    /**
6430
-     * Returns the query param where conditions key to the password affecting this model.
6431
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6432
-     * @since 4.9.74.p
6433
-     * @return null|string
6434
-     * @throws EE_Error
6435
-     * @throws InvalidArgumentException
6436
-     * @throws InvalidDataTypeException
6437
-     * @throws InvalidInterfaceException
6438
-     * @throws ModelConfigurationException
6439
-     * @throws ReflectionException
6440
-     */
6441
-    public function modelChainAndPassword()
6442
-    {
6443
-        if ($this->model_chain_to_password === null) {
6444
-            throw new ModelConfigurationException(
6445
-                $this,
6446
-                esc_html_x(
6447
-                // @codingStandardsIgnoreStart
6448
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6449
-                    // @codingStandardsIgnoreEnd
6450
-                    '1: model name',
6451
-                    'event_espresso'
6452
-                )
6453
-            );
6454
-        }
6455
-        if ($this->model_chain_to_password === '') {
6456
-            $model_with_password = $this;
6457
-        } else {
6458
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6459
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6460
-            } else {
6461
-                $last_model_in_chain = $this->model_chain_to_password;
6462
-            }
6463
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6464
-        }
6465
-
6466
-        $password_field = $model_with_password->getPasswordField();
6467
-        if ($password_field instanceof EE_Password_Field) {
6468
-            $password_field_name = $password_field->get_name();
6469
-        } else {
6470
-            throw new ModelConfigurationException(
6471
-                $this,
6472
-                sprintf(
6473
-                    esc_html_x(
6474
-                        'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6475
-                        '1: model name, 2: special string',
6476
-                        'event_espresso'
6477
-                    ),
6478
-                    $model_with_password->get_this_model_name(),
6479
-                    $this->model_chain_to_password
6480
-                )
6481
-            );
6482
-        }
6483
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6484
-    }
6485
-
6486
-    /**
6487
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6488
-     * or if this model itself has a password affecting access to some of its other fields.
6489
-     * @since 4.9.74.p
6490
-     * @return boolean
6491
-     */
6492
-    public function restrictedByRelatedModelPassword()
6493
-    {
6494
-        return $this->model_chain_to_password !== null;
6495
-    }
3803
+		}
3804
+		return $null_friendly_where_conditions;
3805
+	}
3806
+
3807
+
3808
+
3809
+	/**
3810
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3811
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3812
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3813
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3814
+	 *
3815
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3816
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3817
+	 */
3818
+	private function _get_default_where_conditions($model_relation_path = null)
3819
+	{
3820
+		if ($this->_ignore_where_strategy) {
3821
+			return array();
3822
+		}
3823
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3824
+	}
3825
+
3826
+
3827
+
3828
+	/**
3829
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3830
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3831
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3832
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3833
+	 * Similar to _get_default_where_conditions
3834
+	 *
3835
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3836
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3837
+	 */
3838
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3839
+	{
3840
+		if ($this->_ignore_where_strategy) {
3841
+			return array();
3842
+		}
3843
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3844
+	}
3845
+
3846
+
3847
+
3848
+	/**
3849
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3850
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3851
+	 *
3852
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3853
+	 * @return string
3854
+	 * @throws EE_Error
3855
+	 */
3856
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3857
+	{
3858
+		$selects = $this->_get_columns_to_select_for_this_model();
3859
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3860
+			$name_of_other_model_included) {
3861
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3862
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3863
+			foreach ($other_model_selects as $key => $value) {
3864
+				$selects[] = $value;
3865
+			}
3866
+		}
3867
+		return implode(", ", $selects);
3868
+	}
3869
+
3870
+
3871
+
3872
+	/**
3873
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3874
+	 * So that's going to be the columns for all the fields on the model
3875
+	 *
3876
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3877
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3878
+	 */
3879
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3880
+	{
3881
+		$fields = $this->field_settings();
3882
+		$selects = array();
3883
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3884
+			$model_relation_chain,
3885
+			$this->get_this_model_name()
3886
+		);
3887
+		foreach ($fields as $field_obj) {
3888
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3889
+						 . $field_obj->get_table_alias()
3890
+						 . "."
3891
+						 . $field_obj->get_table_column()
3892
+						 . " AS '"
3893
+						 . $table_alias_with_model_relation_chain_prefix
3894
+						 . $field_obj->get_table_alias()
3895
+						 . "."
3896
+						 . $field_obj->get_table_column()
3897
+						 . "'";
3898
+		}
3899
+		// make sure we are also getting the PKs of each table
3900
+		$tables = $this->get_tables();
3901
+		if (count($tables) > 1) {
3902
+			foreach ($tables as $table_obj) {
3903
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3904
+									   . $table_obj->get_fully_qualified_pk_column();
3905
+				if (! in_array($qualified_pk_column, $selects)) {
3906
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3907
+				}
3908
+			}
3909
+		}
3910
+		return $selects;
3911
+	}
3912
+
3913
+
3914
+
3915
+	/**
3916
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3917
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3918
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3919
+	 * SQL for joining, and the data types
3920
+	 *
3921
+	 * @param null|string                 $original_query_param
3922
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3923
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3924
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3925
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3926
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3927
+	 *                                                          or 'Registration's
3928
+	 * @param string                      $original_query_param what it originally was (eg
3929
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3930
+	 *                                                          matches $query_param
3931
+	 * @throws EE_Error
3932
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3933
+	 */
3934
+	private function _extract_related_model_info_from_query_param(
3935
+		$query_param,
3936
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3937
+		$query_param_type,
3938
+		$original_query_param = null
3939
+	) {
3940
+		if ($original_query_param === null) {
3941
+			$original_query_param = $query_param;
3942
+		}
3943
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3944
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3945
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3946
+		$allow_fields = in_array(
3947
+			$query_param_type,
3948
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3949
+			true
3950
+		);
3951
+		// check to see if we have a field on this model
3952
+		$this_model_fields = $this->field_settings(true);
3953
+		if (array_key_exists($query_param, $this_model_fields)) {
3954
+			if ($allow_fields) {
3955
+				return;
3956
+			}
3957
+			throw new EE_Error(
3958
+				sprintf(
3959
+					__(
3960
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3961
+						"event_espresso"
3962
+					),
3963
+					$query_param,
3964
+					get_class($this),
3965
+					$query_param_type,
3966
+					$original_query_param
3967
+				)
3968
+			);
3969
+		}
3970
+		// check if this is a special logic query param
3971
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3972
+			if ($allow_logic_query_params) {
3973
+				return;
3974
+			}
3975
+			throw new EE_Error(
3976
+				sprintf(
3977
+					__(
3978
+						'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',
3979
+						'event_espresso'
3980
+					),
3981
+					implode('", "', $this->_logic_query_param_keys),
3982
+					$query_param,
3983
+					get_class($this),
3984
+					'<br />',
3985
+					"\t"
3986
+					. ' $passed_in_query_info = <pre>'
3987
+					. print_r($passed_in_query_info, true)
3988
+					. '</pre>'
3989
+					. "\n\t"
3990
+					. ' $query_param_type = '
3991
+					. $query_param_type
3992
+					. "\n\t"
3993
+					. ' $original_query_param = '
3994
+					. $original_query_param
3995
+				)
3996
+			);
3997
+		}
3998
+		// check if it's a custom selection
3999
+		if ($this->_custom_selections instanceof CustomSelects
4000
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4001
+		) {
4002
+			return;
4003
+		}
4004
+		// check if has a model name at the beginning
4005
+		// and
4006
+		// check if it's a field on a related model
4007
+		if ($this->extractJoinModelFromQueryParams(
4008
+			$passed_in_query_info,
4009
+			$query_param,
4010
+			$original_query_param,
4011
+			$query_param_type
4012
+		)) {
4013
+			return;
4014
+		}
4015
+
4016
+		// ok so $query_param didn't start with a model name
4017
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4018
+		// it's wack, that's what it is
4019
+		throw new EE_Error(
4020
+			sprintf(
4021
+				esc_html__(
4022
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4023
+					"event_espresso"
4024
+				),
4025
+				$query_param,
4026
+				get_class($this),
4027
+				$query_param_type,
4028
+				$original_query_param
4029
+			)
4030
+		);
4031
+	}
4032
+
4033
+
4034
+	/**
4035
+	 * Extracts any possible join model information from the provided possible_join_string.
4036
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4037
+	 * parts that should be added to the query.
4038
+	 *
4039
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4040
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4041
+	 * @param null|string                 $original_query_param
4042
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4043
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4044
+	 * @return bool  returns true if a join was added and false if not.
4045
+	 * @throws EE_Error
4046
+	 */
4047
+	private function extractJoinModelFromQueryParams(
4048
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4049
+		$possible_join_string,
4050
+		$original_query_param,
4051
+		$query_parameter_type
4052
+	) {
4053
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4054
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4055
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4056
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4057
+				if ($possible_join_string === '') {
4058
+					// nothing left to $query_param
4059
+					// we should actually end in a field name, not a model like this!
4060
+					throw new EE_Error(
4061
+						sprintf(
4062
+							esc_html__(
4063
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4064
+								"event_espresso"
4065
+							),
4066
+							$possible_join_string,
4067
+							$query_parameter_type,
4068
+							get_class($this),
4069
+							$valid_related_model_name
4070
+						)
4071
+					);
4072
+				}
4073
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4074
+				$related_model_obj->_extract_related_model_info_from_query_param(
4075
+					$possible_join_string,
4076
+					$query_info_carrier,
4077
+					$query_parameter_type,
4078
+					$original_query_param
4079
+				);
4080
+				return true;
4081
+			}
4082
+			if ($possible_join_string === $valid_related_model_name) {
4083
+				$this->_add_join_to_model(
4084
+					$valid_related_model_name,
4085
+					$query_info_carrier,
4086
+					$original_query_param
4087
+				);
4088
+				return true;
4089
+			}
4090
+		}
4091
+		return false;
4092
+	}
4093
+
4094
+
4095
+	/**
4096
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4097
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4098
+	 * @throws EE_Error
4099
+	 */
4100
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4101
+	{
4102
+		if ($this->_custom_selections instanceof CustomSelects
4103
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4104
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4105
+			)
4106
+		) {
4107
+			$original_selects = $this->_custom_selections->originalSelects();
4108
+			foreach ($original_selects as $alias => $select_configuration) {
4109
+				$this->extractJoinModelFromQueryParams(
4110
+					$query_info_carrier,
4111
+					$select_configuration[0],
4112
+					$select_configuration[0],
4113
+					'custom_selects'
4114
+				);
4115
+			}
4116
+		}
4117
+	}
4118
+
4119
+
4120
+
4121
+	/**
4122
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4123
+	 * and store it on $passed_in_query_info
4124
+	 *
4125
+	 * @param string                      $model_name
4126
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4127
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4128
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4129
+	 *                                                          and are adding a join to 'Payment' with the original
4130
+	 *                                                          query param key
4131
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4132
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4133
+	 *                                                          Payment wants to add default query params so that it
4134
+	 *                                                          will know what models to prepend onto its default query
4135
+	 *                                                          params or in case it wants to rename tables (in case
4136
+	 *                                                          there are multiple joins to the same table)
4137
+	 * @return void
4138
+	 * @throws EE_Error
4139
+	 */
4140
+	private function _add_join_to_model(
4141
+		$model_name,
4142
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4143
+		$original_query_param
4144
+	) {
4145
+		$relation_obj = $this->related_settings_for($model_name);
4146
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4147
+		// check if the relation is HABTM, because then we're essentially doing two joins
4148
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4149
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4150
+			$join_model_obj = $relation_obj->get_join_model();
4151
+			// replace the model specified with the join model for this relation chain, whi
4152
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4153
+				$model_name,
4154
+				$join_model_obj->get_this_model_name(),
4155
+				$model_relation_chain
4156
+			);
4157
+			$passed_in_query_info->merge(
4158
+				new EE_Model_Query_Info_Carrier(
4159
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4160
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4161
+				)
4162
+			);
4163
+		}
4164
+		// now just join to the other table pointed to by the relation object, and add its data types
4165
+		$passed_in_query_info->merge(
4166
+			new EE_Model_Query_Info_Carrier(
4167
+				array($model_relation_chain => $model_name),
4168
+				$relation_obj->get_join_statement($model_relation_chain)
4169
+			)
4170
+		);
4171
+	}
4172
+
4173
+
4174
+
4175
+	/**
4176
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4177
+	 *
4178
+	 * @param array $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4179
+	 * @return string of SQL
4180
+	 * @throws EE_Error
4181
+	 */
4182
+	private function _construct_where_clause($where_params)
4183
+	{
4184
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4185
+		if ($SQL) {
4186
+			return " WHERE " . $SQL;
4187
+		}
4188
+		return '';
4189
+	}
4190
+
4191
+
4192
+
4193
+	/**
4194
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4195
+	 * and should be passed HAVING parameters, not WHERE parameters
4196
+	 *
4197
+	 * @param array $having_params
4198
+	 * @return string
4199
+	 * @throws EE_Error
4200
+	 */
4201
+	private function _construct_having_clause($having_params)
4202
+	{
4203
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4204
+		if ($SQL) {
4205
+			return " HAVING " . $SQL;
4206
+		}
4207
+		return '';
4208
+	}
4209
+
4210
+
4211
+	/**
4212
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4213
+	 * Event_Meta.meta_value = 'foo'))"
4214
+	 *
4215
+	 * @param array  $where_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
4216
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4217
+	 * @throws EE_Error
4218
+	 * @return string of SQL
4219
+	 */
4220
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4221
+	{
4222
+		$where_clauses = array();
4223
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4224
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4225
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4226
+				switch ($query_param) {
4227
+					case 'not':
4228
+					case 'NOT':
4229
+						$where_clauses[] = "! ("
4230
+										   . $this->_construct_condition_clause_recursive(
4231
+											   $op_and_value_or_sub_condition,
4232
+											   $glue
4233
+										   )
4234
+										   . ")";
4235
+						break;
4236
+					case 'and':
4237
+					case 'AND':
4238
+						$where_clauses[] = " ("
4239
+										   . $this->_construct_condition_clause_recursive(
4240
+											   $op_and_value_or_sub_condition,
4241
+											   ' AND '
4242
+										   )
4243
+										   . ")";
4244
+						break;
4245
+					case 'or':
4246
+					case 'OR':
4247
+						$where_clauses[] = " ("
4248
+										   . $this->_construct_condition_clause_recursive(
4249
+											   $op_and_value_or_sub_condition,
4250
+											   ' OR '
4251
+										   )
4252
+										   . ")";
4253
+						break;
4254
+				}
4255
+			} else {
4256
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4257
+				// if it's not a normal field, maybe it's a custom selection?
4258
+				if (! $field_obj) {
4259
+					if ($this->_custom_selections instanceof CustomSelects) {
4260
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4261
+					} else {
4262
+						throw new EE_Error(sprintf(__(
4263
+							"%s is neither a valid model field name, nor a custom selection",
4264
+							"event_espresso"
4265
+						), $query_param));
4266
+					}
4267
+				}
4268
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4269
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4270
+			}
4271
+		}
4272
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4273
+	}
4274
+
4275
+
4276
+
4277
+	/**
4278
+	 * Takes the input parameter and extract the table name (alias) and column name
4279
+	 *
4280
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4281
+	 * @throws EE_Error
4282
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4283
+	 */
4284
+	private function _deduce_column_name_from_query_param($query_param)
4285
+	{
4286
+		$field = $this->_deduce_field_from_query_param($query_param);
4287
+		if ($field) {
4288
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4289
+				$field->get_model_name(),
4290
+				$query_param
4291
+			);
4292
+			return $table_alias_prefix . $field->get_qualified_column();
4293
+		}
4294
+		if ($this->_custom_selections instanceof CustomSelects
4295
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4296
+		) {
4297
+			// maybe it's custom selection item?
4298
+			// if so, just use it as the "column name"
4299
+			return $query_param;
4300
+		}
4301
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4302
+			? implode(',', $this->_custom_selections->columnAliases())
4303
+			: '';
4304
+		throw new EE_Error(
4305
+			sprintf(
4306
+				__(
4307
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4308
+					"event_espresso"
4309
+				),
4310
+				$query_param,
4311
+				$custom_select_aliases
4312
+			)
4313
+		);
4314
+	}
4315
+
4316
+
4317
+
4318
+	/**
4319
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4320
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4321
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4322
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4323
+	 *
4324
+	 * @param string $condition_query_param_key
4325
+	 * @return string
4326
+	 */
4327
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4328
+	{
4329
+		$pos_of_star = strpos($condition_query_param_key, '*');
4330
+		if ($pos_of_star === false) {
4331
+			return $condition_query_param_key;
4332
+		}
4333
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4334
+		return $condition_query_param_sans_star;
4335
+	}
4336
+
4337
+
4338
+
4339
+	/**
4340
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4341
+	 *
4342
+	 * @param                            mixed      array | string    $op_and_value
4343
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4344
+	 * @throws EE_Error
4345
+	 * @return string
4346
+	 */
4347
+	private function _construct_op_and_value($op_and_value, $field_obj)
4348
+	{
4349
+		if (is_array($op_and_value)) {
4350
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4351
+			if (! $operator) {
4352
+				$php_array_like_string = array();
4353
+				foreach ($op_and_value as $key => $value) {
4354
+					$php_array_like_string[] = "$key=>$value";
4355
+				}
4356
+				throw new EE_Error(
4357
+					sprintf(
4358
+						__(
4359
+							"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))",
4360
+							"event_espresso"
4361
+						),
4362
+						implode(",", $php_array_like_string)
4363
+					)
4364
+				);
4365
+			}
4366
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4367
+		} else {
4368
+			$operator = '=';
4369
+			$value = $op_and_value;
4370
+		}
4371
+		// check to see if the value is actually another field
4372
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4373
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4374
+		}
4375
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4376
+			// in this case, the value should be an array, or at least a comma-separated list
4377
+			// it will need to handle a little differently
4378
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4379
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4380
+			return $operator . SP . $cleaned_value;
4381
+		}
4382
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4383
+			// the value should be an array with count of two.
4384
+			if (count($value) !== 2) {
4385
+				throw new EE_Error(
4386
+					sprintf(
4387
+						__(
4388
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4389
+							'event_espresso'
4390
+						),
4391
+						"BETWEEN"
4392
+					)
4393
+				);
4394
+			}
4395
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4396
+			return $operator . SP . $cleaned_value;
4397
+		}
4398
+		if (in_array($operator, $this->valid_null_style_operators())) {
4399
+			if ($value !== null) {
4400
+				throw new EE_Error(
4401
+					sprintf(
4402
+						__(
4403
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4404
+							"event_espresso"
4405
+						),
4406
+						$value,
4407
+						$operator
4408
+					)
4409
+				);
4410
+			}
4411
+			return $operator;
4412
+		}
4413
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4414
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4415
+			// remove other junk. So just treat it as a string.
4416
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4417
+		}
4418
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4419
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4420
+		}
4421
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4422
+			throw new EE_Error(
4423
+				sprintf(
4424
+					__(
4425
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4426
+						'event_espresso'
4427
+					),
4428
+					$operator,
4429
+					$operator
4430
+				)
4431
+			);
4432
+		}
4433
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4434
+			throw new EE_Error(
4435
+				sprintf(
4436
+					__(
4437
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4438
+						'event_espresso'
4439
+					),
4440
+					$operator,
4441
+					$operator
4442
+				)
4443
+			);
4444
+		}
4445
+		throw new EE_Error(
4446
+			sprintf(
4447
+				__(
4448
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4449
+					"event_espresso"
4450
+				),
4451
+				http_build_query($op_and_value)
4452
+			)
4453
+		);
4454
+	}
4455
+
4456
+
4457
+
4458
+	/**
4459
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4460
+	 *
4461
+	 * @param array                      $values
4462
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4463
+	 *                                              '%s'
4464
+	 * @return string
4465
+	 * @throws EE_Error
4466
+	 */
4467
+	public function _construct_between_value($values, $field_obj)
4468
+	{
4469
+		$cleaned_values = array();
4470
+		foreach ($values as $value) {
4471
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4472
+		}
4473
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4474
+	}
4475
+
4476
+
4477
+	/**
4478
+	 * Takes an array or a comma-separated list of $values and cleans them
4479
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4480
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4481
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4482
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4483
+	 *
4484
+	 * @param mixed                      $values    array or comma-separated string
4485
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4486
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4487
+	 * @throws EE_Error
4488
+	 */
4489
+	public function _construct_in_value($values, $field_obj)
4490
+	{
4491
+		$prepped = [];
4492
+		// check if the value is a CSV list
4493
+		if (is_string($values)) {
4494
+			// in which case, turn it into an array
4495
+			$values = explode(',', $values);
4496
+		}
4497
+		// make sure we only have one of each value in the list
4498
+		$values = array_unique($values);
4499
+		foreach ($values as $value) {
4500
+			$prepped[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4501
+		}
4502
+		// we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4503
+		// but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4504
+		// which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4505
+		if (empty($prepped)) {
4506
+			$all_fields = $this->field_settings();
4507
+			$first_field    = reset($all_fields);
4508
+			$main_table = $this->_get_main_table();
4509
+			$prepped[]  = "SELECT {$first_field->get_table_column()} FROM {$main_table->get_table_name()} WHERE FALSE";
4510
+		}
4511
+		return '(' . implode(',', $prepped) . ')';
4512
+	}
4513
+
4514
+
4515
+
4516
+	/**
4517
+	 * @param mixed                      $value
4518
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4519
+	 * @throws EE_Error
4520
+	 * @return false|null|string
4521
+	 */
4522
+	private function _wpdb_prepare_using_field($value, $field_obj)
4523
+	{
4524
+		/** @type WPDB $wpdb */
4525
+		global $wpdb;
4526
+		if ($field_obj instanceof EE_Model_Field_Base) {
4527
+			return $wpdb->prepare(
4528
+				$field_obj->get_wpdb_data_type(),
4529
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4530
+			);
4531
+		} //$field_obj should really just be a data type
4532
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4533
+			throw new EE_Error(
4534
+				sprintf(
4535
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4536
+					$field_obj,
4537
+					implode(",", $this->_valid_wpdb_data_types)
4538
+				)
4539
+			);
4540
+		}
4541
+		return $wpdb->prepare($field_obj, $value);
4542
+	}
4543
+
4544
+
4545
+
4546
+	/**
4547
+	 * Takes the input parameter and finds the model field that it indicates.
4548
+	 *
4549
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4550
+	 * @throws EE_Error
4551
+	 * @return EE_Model_Field_Base
4552
+	 */
4553
+	protected function _deduce_field_from_query_param($query_param_name)
4554
+	{
4555
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4556
+		// which will help us find the database table and column
4557
+		$query_param_parts = explode(".", $query_param_name);
4558
+		if (empty($query_param_parts)) {
4559
+			throw new EE_Error(sprintf(__(
4560
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4561
+				'event_espresso'
4562
+			), $query_param_name));
4563
+		}
4564
+		$number_of_parts = count($query_param_parts);
4565
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4566
+		if ($number_of_parts === 1) {
4567
+			$field_name = $last_query_param_part;
4568
+			$model_obj = $this;
4569
+		} else {// $number_of_parts >= 2
4570
+			// the last part is the column name, and there are only 2parts. therefore...
4571
+			$field_name = $last_query_param_part;
4572
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4573
+		}
4574
+		try {
4575
+			return $model_obj->field_settings_for($field_name);
4576
+		} catch (EE_Error $e) {
4577
+			return null;
4578
+		}
4579
+	}
4580
+
4581
+
4582
+
4583
+	/**
4584
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4585
+	 * alias and column which corresponds to it
4586
+	 *
4587
+	 * @param string $field_name
4588
+	 * @throws EE_Error
4589
+	 * @return string
4590
+	 */
4591
+	public function _get_qualified_column_for_field($field_name)
4592
+	{
4593
+		$all_fields = $this->field_settings();
4594
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4595
+		if ($field) {
4596
+			return $field->get_qualified_column();
4597
+		}
4598
+		throw new EE_Error(
4599
+			sprintf(
4600
+				__(
4601
+					"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.",
4602
+					'event_espresso'
4603
+				),
4604
+				$field_name,
4605
+				get_class($this)
4606
+			)
4607
+		);
4608
+	}
4609
+
4610
+
4611
+
4612
+	/**
4613
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4614
+	 * Example usage:
4615
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4616
+	 *      array(),
4617
+	 *      ARRAY_A,
4618
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4619
+	 *  );
4620
+	 * is equivalent to
4621
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4622
+	 * and
4623
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4624
+	 *      array(
4625
+	 *          array(
4626
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4627
+	 *          ),
4628
+	 *          ARRAY_A,
4629
+	 *          implode(
4630
+	 *              ', ',
4631
+	 *              array_merge(
4632
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4633
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4634
+	 *              )
4635
+	 *          )
4636
+	 *      )
4637
+	 *  );
4638
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4639
+	 *
4640
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4641
+	 *                                            and the one whose fields you are selecting for example: when querying
4642
+	 *                                            tickets model and selecting fields from the tickets model you would
4643
+	 *                                            leave this parameter empty, because no models are needed to join
4644
+	 *                                            between the queried model and the selected one. Likewise when
4645
+	 *                                            querying the datetime model and selecting fields from the tickets
4646
+	 *                                            model, it would also be left empty, because there is a direct
4647
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4648
+	 *                                            them together. However, when querying from the event model and
4649
+	 *                                            selecting fields from the ticket model, you should provide the string
4650
+	 *                                            'Datetime', indicating that the event model must first join to the
4651
+	 *                                            datetime model in order to find its relation to ticket model.
4652
+	 *                                            Also, when querying from the venue model and selecting fields from
4653
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4654
+	 *                                            indicating you need to join the venue model to the event model,
4655
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4656
+	 *                                            This string is used to deduce the prefix that gets added onto the
4657
+	 *                                            models' tables qualified columns
4658
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4659
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4660
+	 *                                            qualified column names
4661
+	 * @return array|string
4662
+	 */
4663
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4664
+	{
4665
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4666
+		$qualified_columns = array();
4667
+		foreach ($this->field_settings() as $field_name => $field) {
4668
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4669
+		}
4670
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4671
+	}
4672
+
4673
+
4674
+
4675
+	/**
4676
+	 * constructs the select use on special limit joins
4677
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4678
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4679
+	 * (as that is typically where the limits would be set).
4680
+	 *
4681
+	 * @param  string       $table_alias The table the select is being built for
4682
+	 * @param  mixed|string $limit       The limit for this select
4683
+	 * @return string                The final select join element for the query.
4684
+	 */
4685
+	public function _construct_limit_join_select($table_alias, $limit)
4686
+	{
4687
+		$SQL = '';
4688
+		foreach ($this->_tables as $table_obj) {
4689
+			if ($table_obj instanceof EE_Primary_Table) {
4690
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4691
+					? $table_obj->get_select_join_limit($limit)
4692
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4693
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4694
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4695
+					? $table_obj->get_select_join_limit_join($limit)
4696
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4697
+			}
4698
+		}
4699
+		return $SQL;
4700
+	}
4701
+
4702
+
4703
+
4704
+	/**
4705
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4706
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4707
+	 *
4708
+	 * @return string SQL
4709
+	 * @throws EE_Error
4710
+	 */
4711
+	public function _construct_internal_join()
4712
+	{
4713
+		$SQL = $this->_get_main_table()->get_table_sql();
4714
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4715
+		return $SQL;
4716
+	}
4717
+
4718
+
4719
+
4720
+	/**
4721
+	 * Constructs the SQL for joining all the tables on this model.
4722
+	 * Normally $alias should be the primary table's alias, but in cases where
4723
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4724
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4725
+	 * alias, this will construct SQL like:
4726
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4727
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4728
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4729
+	 *
4730
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4731
+	 * @return string
4732
+	 */
4733
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4734
+	{
4735
+		$SQL = '';
4736
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4737
+		foreach ($this->_tables as $table_obj) {
4738
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4739
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4740
+					// so we're joining to this table, meaning the table is already in
4741
+					// the FROM statement, BUT the primary table isn't. So we want
4742
+					// to add the inverse join sql
4743
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4744
+				} else {
4745
+					// just add a regular JOIN to this table from the primary table
4746
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4747
+				}
4748
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4749
+		}
4750
+		return $SQL;
4751
+	}
4752
+
4753
+
4754
+
4755
+	/**
4756
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4757
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4758
+	 * their data type (eg, '%s', '%d', etc)
4759
+	 *
4760
+	 * @return array
4761
+	 */
4762
+	public function _get_data_types()
4763
+	{
4764
+		$data_types = array();
4765
+		foreach ($this->field_settings() as $field_obj) {
4766
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4767
+			/** @var $field_obj EE_Model_Field_Base */
4768
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4769
+		}
4770
+		return $data_types;
4771
+	}
4772
+
4773
+
4774
+
4775
+	/**
4776
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4777
+	 *
4778
+	 * @param string $model_name
4779
+	 * @throws EE_Error
4780
+	 * @return EEM_Base
4781
+	 */
4782
+	public function get_related_model_obj($model_name)
4783
+	{
4784
+		$model_classname = "EEM_" . $model_name;
4785
+		if (! class_exists($model_classname)) {
4786
+			throw new EE_Error(sprintf(__(
4787
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4788
+				'event_espresso'
4789
+			), $model_name, $model_classname));
4790
+		}
4791
+		return call_user_func($model_classname . "::instance");
4792
+	}
4793
+
4794
+
4795
+
4796
+	/**
4797
+	 * Returns the array of EE_ModelRelations for this model.
4798
+	 *
4799
+	 * @return EE_Model_Relation_Base[]
4800
+	 */
4801
+	public function relation_settings()
4802
+	{
4803
+		return $this->_model_relations;
4804
+	}
4805
+
4806
+
4807
+
4808
+	/**
4809
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4810
+	 * because without THOSE models, this model probably doesn't have much purpose.
4811
+	 * (Eg, without an event, datetimes have little purpose.)
4812
+	 *
4813
+	 * @return EE_Belongs_To_Relation[]
4814
+	 */
4815
+	public function belongs_to_relations()
4816
+	{
4817
+		$belongs_to_relations = array();
4818
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4819
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4820
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4821
+			}
4822
+		}
4823
+		return $belongs_to_relations;
4824
+	}
4825
+
4826
+
4827
+
4828
+	/**
4829
+	 * Returns the specified EE_Model_Relation, or throws an exception
4830
+	 *
4831
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4832
+	 * @throws EE_Error
4833
+	 * @return EE_Model_Relation_Base
4834
+	 */
4835
+	public function related_settings_for($relation_name)
4836
+	{
4837
+		$relatedModels = $this->relation_settings();
4838
+		if (! array_key_exists($relation_name, $relatedModels)) {
4839
+			throw new EE_Error(
4840
+				sprintf(
4841
+					__(
4842
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4843
+						'event_espresso'
4844
+					),
4845
+					$relation_name,
4846
+					$this->_get_class_name(),
4847
+					implode(', ', array_keys($relatedModels))
4848
+				)
4849
+			);
4850
+		}
4851
+		return $relatedModels[ $relation_name ];
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4858
+	 * fields
4859
+	 *
4860
+	 * @param string $fieldName
4861
+	 * @param boolean $include_db_only_fields
4862
+	 * @throws EE_Error
4863
+	 * @return EE_Model_Field_Base
4864
+	 */
4865
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4866
+	{
4867
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4868
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4869
+			throw new EE_Error(sprintf(
4870
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4871
+				$fieldName,
4872
+				get_class($this)
4873
+			));
4874
+		}
4875
+		return $fieldSettings[ $fieldName ];
4876
+	}
4877
+
4878
+
4879
+
4880
+	/**
4881
+	 * Checks if this field exists on this model
4882
+	 *
4883
+	 * @param string $fieldName a key in the model's _field_settings array
4884
+	 * @return boolean
4885
+	 */
4886
+	public function has_field($fieldName)
4887
+	{
4888
+		$fieldSettings = $this->field_settings(true);
4889
+		if (isset($fieldSettings[ $fieldName ])) {
4890
+			return true;
4891
+		}
4892
+		return false;
4893
+	}
4894
+
4895
+
4896
+
4897
+	/**
4898
+	 * Returns whether or not this model has a relation to the specified model
4899
+	 *
4900
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4901
+	 * @return boolean
4902
+	 */
4903
+	public function has_relation($relation_name)
4904
+	{
4905
+		$relations = $this->relation_settings();
4906
+		if (isset($relations[ $relation_name ])) {
4907
+			return true;
4908
+		}
4909
+		return false;
4910
+	}
4911
+
4912
+
4913
+
4914
+	/**
4915
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4916
+	 * Eg, on EE_Answer that would be ANS_ID field object
4917
+	 *
4918
+	 * @param $field_obj
4919
+	 * @return boolean
4920
+	 */
4921
+	public function is_primary_key_field($field_obj)
4922
+	{
4923
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4924
+	}
4925
+
4926
+
4927
+
4928
+	/**
4929
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4930
+	 * Eg, on EE_Answer that would be ANS_ID field object
4931
+	 *
4932
+	 * @return EE_Model_Field_Base
4933
+	 * @throws EE_Error
4934
+	 */
4935
+	public function get_primary_key_field()
4936
+	{
4937
+		if ($this->_primary_key_field === null) {
4938
+			foreach ($this->field_settings(true) as $field_obj) {
4939
+				if ($this->is_primary_key_field($field_obj)) {
4940
+					$this->_primary_key_field = $field_obj;
4941
+					break;
4942
+				}
4943
+			}
4944
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4945
+				throw new EE_Error(sprintf(
4946
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4947
+					get_class($this)
4948
+				));
4949
+			}
4950
+		}
4951
+		return $this->_primary_key_field;
4952
+	}
4953
+
4954
+
4955
+
4956
+	/**
4957
+	 * Returns whether or not not there is a primary key on this model.
4958
+	 * Internally does some caching.
4959
+	 *
4960
+	 * @return boolean
4961
+	 */
4962
+	public function has_primary_key_field()
4963
+	{
4964
+		if ($this->_has_primary_key_field === null) {
4965
+			try {
4966
+				$this->get_primary_key_field();
4967
+				$this->_has_primary_key_field = true;
4968
+			} catch (EE_Error $e) {
4969
+				$this->_has_primary_key_field = false;
4970
+			}
4971
+		}
4972
+		return $this->_has_primary_key_field;
4973
+	}
4974
+
4975
+
4976
+
4977
+	/**
4978
+	 * Finds the first field of type $field_class_name.
4979
+	 *
4980
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4981
+	 *                                 EE_Foreign_Key_Field, etc
4982
+	 * @return EE_Model_Field_Base or null if none is found
4983
+	 */
4984
+	public function get_a_field_of_type($field_class_name)
4985
+	{
4986
+		foreach ($this->field_settings() as $field) {
4987
+			if ($field instanceof $field_class_name) {
4988
+				return $field;
4989
+			}
4990
+		}
4991
+		return null;
4992
+	}
4993
+
4994
+
4995
+
4996
+	/**
4997
+	 * Gets a foreign key field pointing to model.
4998
+	 *
4999
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5000
+	 * @return EE_Foreign_Key_Field_Base
5001
+	 * @throws EE_Error
5002
+	 */
5003
+	public function get_foreign_key_to($model_name)
5004
+	{
5005
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5006
+			foreach ($this->field_settings() as $field) {
5007
+				if ($field instanceof EE_Foreign_Key_Field_Base
5008
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5009
+				) {
5010
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5011
+					break;
5012
+				}
5013
+			}
5014
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5015
+				throw new EE_Error(sprintf(__(
5016
+					"There is no foreign key field pointing to model %s on model %s",
5017
+					'event_espresso'
5018
+				), $model_name, get_class($this)));
5019
+			}
5020
+		}
5021
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5022
+	}
5023
+
5024
+
5025
+
5026
+	/**
5027
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5028
+	 *
5029
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5030
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5031
+	 *                            Either one works
5032
+	 * @return string
5033
+	 */
5034
+	public function get_table_for_alias($table_alias)
5035
+	{
5036
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5037
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5038
+	}
5039
+
5040
+
5041
+
5042
+	/**
5043
+	 * Returns a flat array of all field son this model, instead of organizing them
5044
+	 * by table_alias as they are in the constructor.
5045
+	 *
5046
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5047
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5048
+	 */
5049
+	public function field_settings($include_db_only_fields = false)
5050
+	{
5051
+		if ($include_db_only_fields) {
5052
+			if ($this->_cached_fields === null) {
5053
+				$this->_cached_fields = array();
5054
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5055
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5056
+						$this->_cached_fields[ $field_name ] = $field_obj;
5057
+					}
5058
+				}
5059
+			}
5060
+			return $this->_cached_fields;
5061
+		}
5062
+		if ($this->_cached_fields_non_db_only === null) {
5063
+			$this->_cached_fields_non_db_only = array();
5064
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5065
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5066
+					/** @var $field_obj EE_Model_Field_Base */
5067
+					if (! $field_obj->is_db_only_field()) {
5068
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5069
+					}
5070
+				}
5071
+			}
5072
+		}
5073
+		return $this->_cached_fields_non_db_only;
5074
+	}
5075
+
5076
+
5077
+
5078
+	/**
5079
+	 *        cycle though array of attendees and create objects out of each item
5080
+	 *
5081
+	 * @access        private
5082
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5083
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5084
+	 *                           numerically indexed)
5085
+	 * @throws EE_Error
5086
+	 */
5087
+	protected function _create_objects($rows = array())
5088
+	{
5089
+		$array_of_objects = array();
5090
+		if (empty($rows)) {
5091
+			return array();
5092
+		}
5093
+		$count_if_model_has_no_primary_key = 0;
5094
+		$has_primary_key = $this->has_primary_key_field();
5095
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5096
+		foreach ((array) $rows as $row) {
5097
+			if (empty($row)) {
5098
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5099
+				return array();
5100
+			}
5101
+			// check if we've already set this object in the results array,
5102
+			// in which case there's no need to process it further (again)
5103
+			if ($has_primary_key) {
5104
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5105
+					$row,
5106
+					$primary_key_field->get_qualified_column(),
5107
+					$primary_key_field->get_table_column()
5108
+				);
5109
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5110
+					continue;
5111
+				}
5112
+			}
5113
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5114
+			if (! $classInstance) {
5115
+				throw new EE_Error(
5116
+					sprintf(
5117
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5118
+						$this->get_this_model_name(),
5119
+						http_build_query($row)
5120
+					)
5121
+				);
5122
+			}
5123
+			// set the timezone on the instantiated objects
5124
+			$classInstance->set_timezone($this->_timezone);
5125
+			// make sure if there is any timezone setting present that we set the timezone for the object
5126
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5127
+			$array_of_objects[ $key ] = $classInstance;
5128
+			// also, for all the relations of type BelongsTo, see if we can cache
5129
+			// those related models
5130
+			// (we could do this for other relations too, but if there are conditions
5131
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5132
+			// so it requires a little more thought than just caching them immediately...)
5133
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5134
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5135
+					// check if this model's INFO is present. If so, cache it on the model
5136
+					$other_model = $relation_obj->get_other_model();
5137
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5138
+					// if we managed to make a model object from the results, cache it on the main model object
5139
+					if ($other_model_obj_maybe) {
5140
+						// set timezone on these other model objects if they are present
5141
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5142
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5143
+					}
5144
+				}
5145
+			}
5146
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5147
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5148
+			// the field in the CustomSelects object
5149
+			if ($this->_custom_selections instanceof CustomSelects) {
5150
+				$classInstance->setCustomSelectsValues(
5151
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5152
+				);
5153
+			}
5154
+		}
5155
+		return $array_of_objects;
5156
+	}
5157
+
5158
+
5159
+	/**
5160
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5161
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5162
+	 *
5163
+	 * @param array $db_results_row
5164
+	 * @return array
5165
+	 */
5166
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5167
+	{
5168
+		$results = array();
5169
+		if ($this->_custom_selections instanceof CustomSelects) {
5170
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5171
+				if (isset($db_results_row[ $alias ])) {
5172
+					$results[ $alias ] = $this->convertValueToDataType(
5173
+						$db_results_row[ $alias ],
5174
+						$this->_custom_selections->getDataTypeForAlias($alias)
5175
+					);
5176
+				}
5177
+			}
5178
+		}
5179
+		return $results;
5180
+	}
5181
+
5182
+
5183
+	/**
5184
+	 * This will set the value for the given alias
5185
+	 * @param string $value
5186
+	 * @param string $datatype (one of %d, %s, %f)
5187
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5188
+	 */
5189
+	protected function convertValueToDataType($value, $datatype)
5190
+	{
5191
+		switch ($datatype) {
5192
+			case '%f':
5193
+				return (float) $value;
5194
+			case '%d':
5195
+				return (int) $value;
5196
+			default:
5197
+				return (string) $value;
5198
+		}
5199
+	}
5200
+
5201
+
5202
+	/**
5203
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5204
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5205
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5206
+	 * object (as set in the model_field!).
5207
+	 *
5208
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5209
+	 */
5210
+	public function create_default_object()
5211
+	{
5212
+		$this_model_fields_and_values = array();
5213
+		// setup the row using default values;
5214
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5215
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5216
+		}
5217
+		$className = $this->_get_class_name();
5218
+		$classInstance = EE_Registry::instance()
5219
+									->load_class($className, array($this_model_fields_and_values), false, false);
5220
+		return $classInstance;
5221
+	}
5222
+
5223
+
5224
+
5225
+	/**
5226
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5227
+	 *                             or an stdClass where each property is the name of a column,
5228
+	 * @return EE_Base_Class
5229
+	 * @throws EE_Error
5230
+	 */
5231
+	public function instantiate_class_from_array_or_object($cols_n_values)
5232
+	{
5233
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5234
+			$cols_n_values = get_object_vars($cols_n_values);
5235
+		}
5236
+		$primary_key = null;
5237
+		// make sure the array only has keys that are fields/columns on this model
5238
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5239
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5240
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5241
+		}
5242
+		$className = $this->_get_class_name();
5243
+		// check we actually found results that we can use to build our model object
5244
+		// if not, return null
5245
+		if ($this->has_primary_key_field()) {
5246
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5247
+				return null;
5248
+			}
5249
+		} elseif ($this->unique_indexes()) {
5250
+			$first_column = reset($this_model_fields_n_values);
5251
+			if (empty($first_column)) {
5252
+				return null;
5253
+			}
5254
+		}
5255
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5256
+		if ($primary_key) {
5257
+			$classInstance = $this->get_from_entity_map($primary_key);
5258
+			if (! $classInstance) {
5259
+				$classInstance = EE_Registry::instance()
5260
+											->load_class(
5261
+												$className,
5262
+												array($this_model_fields_n_values, $this->_timezone),
5263
+												true,
5264
+												false
5265
+											);
5266
+				// add this new object to the entity map
5267
+				$classInstance = $this->add_to_entity_map($classInstance);
5268
+			}
5269
+		} else {
5270
+			$classInstance = EE_Registry::instance()
5271
+										->load_class(
5272
+											$className,
5273
+											array($this_model_fields_n_values, $this->_timezone),
5274
+											true,
5275
+											false
5276
+										);
5277
+		}
5278
+		return $classInstance;
5279
+	}
5280
+
5281
+
5282
+
5283
+	/**
5284
+	 * Gets the model object from the  entity map if it exists
5285
+	 *
5286
+	 * @param int|string $id the ID of the model object
5287
+	 * @return EE_Base_Class
5288
+	 */
5289
+	public function get_from_entity_map($id)
5290
+	{
5291
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5292
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5293
+	}
5294
+
5295
+
5296
+
5297
+	/**
5298
+	 * add_to_entity_map
5299
+	 * Adds the object to the model's entity mappings
5300
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5301
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5302
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5303
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5304
+	 *        then this method should be called immediately after the update query
5305
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5306
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5307
+	 *
5308
+	 * @param    EE_Base_Class $object
5309
+	 * @throws EE_Error
5310
+	 * @return \EE_Base_Class
5311
+	 */
5312
+	public function add_to_entity_map(EE_Base_Class $object)
5313
+	{
5314
+		$className = $this->_get_class_name();
5315
+		if (! $object instanceof $className) {
5316
+			throw new EE_Error(sprintf(
5317
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5318
+				is_object($object) ? get_class($object) : $object,
5319
+				$className
5320
+			));
5321
+		}
5322
+		/** @var $object EE_Base_Class */
5323
+		if (! $object->ID()) {
5324
+			throw new EE_Error(sprintf(__(
5325
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5326
+				"event_espresso"
5327
+			), get_class($this)));
5328
+		}
5329
+		// double check it's not already there
5330
+		$classInstance = $this->get_from_entity_map($object->ID());
5331
+		if ($classInstance) {
5332
+			return $classInstance;
5333
+		}
5334
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5335
+		return $object;
5336
+	}
5337
+
5338
+
5339
+
5340
+	/**
5341
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5342
+	 * if no identifier is provided, then the entire entity map is emptied
5343
+	 *
5344
+	 * @param int|string $id the ID of the model object
5345
+	 * @return boolean
5346
+	 */
5347
+	public function clear_entity_map($id = null)
5348
+	{
5349
+		if (empty($id)) {
5350
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5351
+			return true;
5352
+		}
5353
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5354
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5355
+			return true;
5356
+		}
5357
+		return false;
5358
+	}
5359
+
5360
+
5361
+
5362
+	/**
5363
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5364
+	 * Given an array where keys are column (or column alias) names and values,
5365
+	 * returns an array of their corresponding field names and database values
5366
+	 *
5367
+	 * @param array $cols_n_values
5368
+	 * @return array
5369
+	 */
5370
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5371
+	{
5372
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5373
+	}
5374
+
5375
+
5376
+
5377
+	/**
5378
+	 * _deduce_fields_n_values_from_cols_n_values
5379
+	 * Given an array where keys are column (or column alias) names and values,
5380
+	 * returns an array of their corresponding field names and database values
5381
+	 *
5382
+	 * @param string $cols_n_values
5383
+	 * @return array
5384
+	 */
5385
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5386
+	{
5387
+		$this_model_fields_n_values = array();
5388
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5389
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5390
+				$cols_n_values,
5391
+				$table_obj->get_fully_qualified_pk_column(),
5392
+				$table_obj->get_pk_column()
5393
+			);
5394
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5395
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5396
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5397
+					if (! $field_obj->is_db_only_field()) {
5398
+						// prepare field as if its coming from db
5399
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5400
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5401
+					}
5402
+				}
5403
+			} else {
5404
+				// the table's rows existed. Use their values
5405
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5406
+					if (! $field_obj->is_db_only_field()) {
5407
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5408
+							$cols_n_values,
5409
+							$field_obj->get_qualified_column(),
5410
+							$field_obj->get_table_column()
5411
+						);
5412
+					}
5413
+				}
5414
+			}
5415
+		}
5416
+		return $this_model_fields_n_values;
5417
+	}
5418
+
5419
+
5420
+	/**
5421
+	 * @param $cols_n_values
5422
+	 * @param $qualified_column
5423
+	 * @param $regular_column
5424
+	 * @return null
5425
+	 * @throws EE_Error
5426
+	 * @throws ReflectionException
5427
+	 */
5428
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5429
+	{
5430
+		$value = null;
5431
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5432
+		// does the field on the model relate to this column retrieved from the db?
5433
+		// or is it a db-only field? (not relating to the model)
5434
+		if (isset($cols_n_values[ $qualified_column ])) {
5435
+			$value = $cols_n_values[ $qualified_column ];
5436
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5437
+			$value = $cols_n_values[ $regular_column ];
5438
+		} elseif (! empty($this->foreign_key_aliases)) {
5439
+			// no PK?  ok check if there is a foreign key alias set for this table
5440
+			// then check if that alias exists in the incoming data
5441
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5442
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5443
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5444
+					$value = $cols_n_values[ $FK_alias ];
5445
+					list($pk_class) = explode('.', $PK_column);
5446
+					$pk_model_name = "EEM_{$pk_class}";
5447
+					/** @var EEM_Base $pk_model */
5448
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5449
+					if ($pk_model instanceof EEM_Base) {
5450
+						// make sure object is pulled from db and added to entity map
5451
+						$pk_model->get_one_by_ID($value);
5452
+					}
5453
+					break;
5454
+				}
5455
+			}
5456
+		}
5457
+		return $value;
5458
+	}
5459
+
5460
+
5461
+
5462
+	/**
5463
+	 * refresh_entity_map_from_db
5464
+	 * Makes sure the model object in the entity map at $id assumes the values
5465
+	 * of the database (opposite of EE_base_Class::save())
5466
+	 *
5467
+	 * @param int|string $id
5468
+	 * @return EE_Base_Class
5469
+	 * @throws EE_Error
5470
+	 */
5471
+	public function refresh_entity_map_from_db($id)
5472
+	{
5473
+		$obj_in_map = $this->get_from_entity_map($id);
5474
+		if ($obj_in_map) {
5475
+			$wpdb_results = $this->_get_all_wpdb_results(
5476
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5477
+			);
5478
+			if ($wpdb_results && is_array($wpdb_results)) {
5479
+				$one_row = reset($wpdb_results);
5480
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5481
+					$obj_in_map->set_from_db($field_name, $db_value);
5482
+				}
5483
+				// clear the cache of related model objects
5484
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5485
+					$obj_in_map->clear_cache($relation_name, null, true);
5486
+				}
5487
+			}
5488
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5489
+			return $obj_in_map;
5490
+		}
5491
+		return $this->get_one_by_ID($id);
5492
+	}
5493
+
5494
+
5495
+
5496
+	/**
5497
+	 * refresh_entity_map_with
5498
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5499
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5500
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5501
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5502
+	 *
5503
+	 * @param int|string    $id
5504
+	 * @param EE_Base_Class $replacing_model_obj
5505
+	 * @return \EE_Base_Class
5506
+	 * @throws EE_Error
5507
+	 */
5508
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5509
+	{
5510
+		$obj_in_map = $this->get_from_entity_map($id);
5511
+		if ($obj_in_map) {
5512
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5513
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5514
+					$obj_in_map->set($field_name, $value);
5515
+				}
5516
+				// make the model object in the entity map's cache match the $replacing_model_obj
5517
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5518
+					$obj_in_map->clear_cache($relation_name, null, true);
5519
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5520
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5521
+					}
5522
+				}
5523
+			}
5524
+			return $obj_in_map;
5525
+		}
5526
+		$this->add_to_entity_map($replacing_model_obj);
5527
+		return $replacing_model_obj;
5528
+	}
5529
+
5530
+
5531
+
5532
+	/**
5533
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5534
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5535
+	 * require_once($this->_getClassName().".class.php");
5536
+	 *
5537
+	 * @return string
5538
+	 */
5539
+	private function _get_class_name()
5540
+	{
5541
+		return "EE_" . $this->get_this_model_name();
5542
+	}
5543
+
5544
+
5545
+
5546
+	/**
5547
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5548
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5549
+	 * it would be 'Events'.
5550
+	 *
5551
+	 * @param int $quantity
5552
+	 * @return string
5553
+	 */
5554
+	public function item_name($quantity = 1)
5555
+	{
5556
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5557
+	}
5558
+
5559
+
5560
+
5561
+	/**
5562
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5563
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5564
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5565
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5566
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5567
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5568
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5569
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5570
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5571
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5572
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5573
+	 *        return $previousReturnValue.$returnString;
5574
+	 * }
5575
+	 * require('EEM_Answer.model.php');
5576
+	 * $answer=EEM_Answer::instance();
5577
+	 * echo $answer->my_callback('monkeys',100);
5578
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5579
+	 *
5580
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5581
+	 * @param array  $args       array of original arguments passed to the function
5582
+	 * @throws EE_Error
5583
+	 * @return mixed whatever the plugin which calls add_filter decides
5584
+	 */
5585
+	public function __call($methodName, $args)
5586
+	{
5587
+		$className = get_class($this);
5588
+		$tagName = "FHEE__{$className}__{$methodName}";
5589
+		if (! has_filter($tagName)) {
5590
+			throw new EE_Error(
5591
+				sprintf(
5592
+					__(
5593
+						'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 );',
5594
+						'event_espresso'
5595
+					),
5596
+					$methodName,
5597
+					$className,
5598
+					$tagName,
5599
+					'<br />'
5600
+				)
5601
+			);
5602
+		}
5603
+		return apply_filters($tagName, null, $this, $args);
5604
+	}
5605
+
5606
+
5607
+
5608
+	/**
5609
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5610
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5611
+	 *
5612
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5613
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5614
+	 *                                                       the object's class name
5615
+	 *                                                       or object's ID
5616
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5617
+	 *                                                       exists in the database. If it does not, we add it
5618
+	 * @throws EE_Error
5619
+	 * @return EE_Base_Class
5620
+	 */
5621
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5622
+	{
5623
+		$className = $this->_get_class_name();
5624
+		if ($base_class_obj_or_id instanceof $className) {
5625
+			$model_object = $base_class_obj_or_id;
5626
+		} else {
5627
+			$primary_key_field = $this->get_primary_key_field();
5628
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5629
+				&& (
5630
+					is_int($base_class_obj_or_id)
5631
+					|| is_string($base_class_obj_or_id)
5632
+				)
5633
+			) {
5634
+				// assume it's an ID.
5635
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5636
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5637
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5638
+				&& is_string($base_class_obj_or_id)
5639
+			) {
5640
+				// assume its a string representation of the object
5641
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5642
+			} else {
5643
+				throw new EE_Error(
5644
+					sprintf(
5645
+						__(
5646
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5647
+							'event_espresso'
5648
+						),
5649
+						$base_class_obj_or_id,
5650
+						$this->_get_class_name(),
5651
+						print_r($base_class_obj_or_id, true)
5652
+					)
5653
+				);
5654
+			}
5655
+		}
5656
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5657
+			$model_object->save();
5658
+		}
5659
+		return $model_object;
5660
+	}
5661
+
5662
+
5663
+
5664
+	/**
5665
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5666
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5667
+	 * returns it ID.
5668
+	 *
5669
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5670
+	 * @return int|string depending on the type of this model object's ID
5671
+	 * @throws EE_Error
5672
+	 */
5673
+	public function ensure_is_ID($base_class_obj_or_id)
5674
+	{
5675
+		$className = $this->_get_class_name();
5676
+		if ($base_class_obj_or_id instanceof $className) {
5677
+			/** @var $base_class_obj_or_id EE_Base_Class */
5678
+			$id = $base_class_obj_or_id->ID();
5679
+		} elseif (is_int($base_class_obj_or_id)) {
5680
+			// assume it's an ID
5681
+			$id = $base_class_obj_or_id;
5682
+		} elseif (is_string($base_class_obj_or_id)) {
5683
+			// assume its a string representation of the object
5684
+			$id = $base_class_obj_or_id;
5685
+		} else {
5686
+			throw new EE_Error(sprintf(
5687
+				__(
5688
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5689
+					'event_espresso'
5690
+				),
5691
+				$base_class_obj_or_id,
5692
+				$this->_get_class_name(),
5693
+				print_r($base_class_obj_or_id, true)
5694
+			));
5695
+		}
5696
+		return $id;
5697
+	}
5698
+
5699
+
5700
+
5701
+	/**
5702
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5703
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5704
+	 * been sanitized and converted into the appropriate domain.
5705
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5706
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5707
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5708
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5709
+	 * $EVT = EEM_Event::instance(); $old_setting =
5710
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5711
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5712
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5713
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5714
+	 *
5715
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5716
+	 * @return void
5717
+	 */
5718
+	public function assume_values_already_prepared_by_model_object(
5719
+		$values_already_prepared = self::not_prepared_by_model_object
5720
+	) {
5721
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5722
+	}
5723
+
5724
+
5725
+
5726
+	/**
5727
+	 * Read comments for assume_values_already_prepared_by_model_object()
5728
+	 *
5729
+	 * @return int
5730
+	 */
5731
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5732
+	{
5733
+		return $this->_values_already_prepared_by_model_object;
5734
+	}
5735
+
5736
+
5737
+
5738
+	/**
5739
+	 * Gets all the indexes on this model
5740
+	 *
5741
+	 * @return EE_Index[]
5742
+	 */
5743
+	public function indexes()
5744
+	{
5745
+		return $this->_indexes;
5746
+	}
5747
+
5748
+
5749
+
5750
+	/**
5751
+	 * Gets all the Unique Indexes on this model
5752
+	 *
5753
+	 * @return EE_Unique_Index[]
5754
+	 */
5755
+	public function unique_indexes()
5756
+	{
5757
+		$unique_indexes = array();
5758
+		foreach ($this->_indexes as $name => $index) {
5759
+			if ($index instanceof EE_Unique_Index) {
5760
+				$unique_indexes [ $name ] = $index;
5761
+			}
5762
+		}
5763
+		return $unique_indexes;
5764
+	}
5765
+
5766
+
5767
+
5768
+	/**
5769
+	 * Gets all the fields which, when combined, make the primary key.
5770
+	 * This is usually just an array with 1 element (the primary key), but in cases
5771
+	 * where there is no primary key, it's a combination of fields as defined
5772
+	 * on a primary index
5773
+	 *
5774
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5775
+	 * @throws EE_Error
5776
+	 */
5777
+	public function get_combined_primary_key_fields()
5778
+	{
5779
+		foreach ($this->indexes() as $index) {
5780
+			if ($index instanceof EE_Primary_Key_Index) {
5781
+				return $index->fields();
5782
+			}
5783
+		}
5784
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5785
+	}
5786
+
5787
+
5788
+
5789
+	/**
5790
+	 * Used to build a primary key string (when the model has no primary key),
5791
+	 * which can be used a unique string to identify this model object.
5792
+	 *
5793
+	 * @param array $fields_n_values keys are field names, values are their values.
5794
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5795
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5796
+	 *                               before passing it to this function (that will convert it from columns-n-values
5797
+	 *                               to field-names-n-values).
5798
+	 * @return string
5799
+	 * @throws EE_Error
5800
+	 */
5801
+	public function get_index_primary_key_string($fields_n_values)
5802
+	{
5803
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5804
+			$fields_n_values,
5805
+			$this->get_combined_primary_key_fields()
5806
+		);
5807
+		return http_build_query($cols_n_values_for_primary_key_index);
5808
+	}
5809
+
5810
+
5811
+
5812
+	/**
5813
+	 * Gets the field values from the primary key string
5814
+	 *
5815
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5816
+	 * @param string $index_primary_key_string
5817
+	 * @return null|array
5818
+	 * @throws EE_Error
5819
+	 */
5820
+	public function parse_index_primary_key_string($index_primary_key_string)
5821
+	{
5822
+		$key_fields = $this->get_combined_primary_key_fields();
5823
+		// check all of them are in the $id
5824
+		$key_vals_in_combined_pk = array();
5825
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5826
+		foreach ($key_fields as $key_field_name => $field_obj) {
5827
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5828
+				return null;
5829
+			}
5830
+		}
5831
+		return $key_vals_in_combined_pk;
5832
+	}
5833
+
5834
+
5835
+
5836
+	/**
5837
+	 * verifies that an array of key-value pairs for model fields has a key
5838
+	 * for each field comprising the primary key index
5839
+	 *
5840
+	 * @param array $key_vals
5841
+	 * @return boolean
5842
+	 * @throws EE_Error
5843
+	 */
5844
+	public function has_all_combined_primary_key_fields($key_vals)
5845
+	{
5846
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5847
+		foreach ($keys_it_should_have as $key) {
5848
+			if (! isset($key_vals[ $key ])) {
5849
+				return false;
5850
+			}
5851
+		}
5852
+		return true;
5853
+	}
5854
+
5855
+
5856
+
5857
+	/**
5858
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5859
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5860
+	 *
5861
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5862
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5863
+	 * @throws EE_Error
5864
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5865
+	 *                                                              indexed)
5866
+	 */
5867
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5868
+	{
5869
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5870
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5871
+		} elseif (is_array($model_object_or_attributes_array)) {
5872
+			$attributes_array = $model_object_or_attributes_array;
5873
+		} else {
5874
+			throw new EE_Error(sprintf(__(
5875
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5876
+				"event_espresso"
5877
+			), $model_object_or_attributes_array));
5878
+		}
5879
+		// even copies obviously won't have the same ID, so remove the primary key
5880
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5881
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5882
+			unset($attributes_array[ $this->primary_key_name() ]);
5883
+		}
5884
+		if (isset($query_params[0])) {
5885
+			$query_params[0] = array_merge($attributes_array, $query_params);
5886
+		} else {
5887
+			$query_params[0] = $attributes_array;
5888
+		}
5889
+		return $this->get_all($query_params);
5890
+	}
5891
+
5892
+
5893
+
5894
+	/**
5895
+	 * Gets the first copy we find. See get_all_copies for more details
5896
+	 *
5897
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5898
+	 * @param array $query_params
5899
+	 * @return EE_Base_Class
5900
+	 * @throws EE_Error
5901
+	 */
5902
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5903
+	{
5904
+		if (! is_array($query_params)) {
5905
+			EE_Error::doing_it_wrong(
5906
+				'EEM_Base::get_one_copy',
5907
+				sprintf(
5908
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5909
+					gettype($query_params)
5910
+				),
5911
+				'4.6.0'
5912
+			);
5913
+			$query_params = array();
5914
+		}
5915
+		$query_params['limit'] = 1;
5916
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5917
+		if (is_array($copies)) {
5918
+			return array_shift($copies);
5919
+		}
5920
+		return null;
5921
+	}
5922
+
5923
+
5924
+
5925
+	/**
5926
+	 * Updates the item with the specified id. Ignores default query parameters because
5927
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5928
+	 *
5929
+	 * @param array      $fields_n_values keys are field names, values are their new values
5930
+	 * @param int|string $id              the value of the primary key to update
5931
+	 * @return int number of rows updated
5932
+	 * @throws EE_Error
5933
+	 */
5934
+	public function update_by_ID($fields_n_values, $id)
5935
+	{
5936
+		$query_params = array(
5937
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5938
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5939
+		);
5940
+		return $this->update($fields_n_values, $query_params);
5941
+	}
5942
+
5943
+
5944
+
5945
+	/**
5946
+	 * Changes an operator which was supplied to the models into one usable in SQL
5947
+	 *
5948
+	 * @param string $operator_supplied
5949
+	 * @return string an operator which can be used in SQL
5950
+	 * @throws EE_Error
5951
+	 */
5952
+	private function _prepare_operator_for_sql($operator_supplied)
5953
+	{
5954
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5955
+			: null;
5956
+		if ($sql_operator) {
5957
+			return $sql_operator;
5958
+		}
5959
+		throw new EE_Error(
5960
+			sprintf(
5961
+				__(
5962
+					"The operator '%s' is not in the list of valid operators: %s",
5963
+					"event_espresso"
5964
+				),
5965
+				$operator_supplied,
5966
+				implode(",", array_keys($this->_valid_operators))
5967
+			)
5968
+		);
5969
+	}
5970
+
5971
+
5972
+
5973
+	/**
5974
+	 * Gets the valid operators
5975
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5976
+	 */
5977
+	public function valid_operators()
5978
+	{
5979
+		return $this->_valid_operators;
5980
+	}
5981
+
5982
+
5983
+
5984
+	/**
5985
+	 * Gets the between-style operators (take 2 arguments).
5986
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5987
+	 */
5988
+	public function valid_between_style_operators()
5989
+	{
5990
+		return array_intersect(
5991
+			$this->valid_operators(),
5992
+			$this->_between_style_operators
5993
+		);
5994
+	}
5995
+
5996
+	/**
5997
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5998
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5999
+	 */
6000
+	public function valid_like_style_operators()
6001
+	{
6002
+		return array_intersect(
6003
+			$this->valid_operators(),
6004
+			$this->_like_style_operators
6005
+		);
6006
+	}
6007
+
6008
+	/**
6009
+	 * Gets the "in"-style operators
6010
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6011
+	 */
6012
+	public function valid_in_style_operators()
6013
+	{
6014
+		return array_intersect(
6015
+			$this->valid_operators(),
6016
+			$this->_in_style_operators
6017
+		);
6018
+	}
6019
+
6020
+	/**
6021
+	 * Gets the "null"-style operators (accept no arguments)
6022
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6023
+	 */
6024
+	public function valid_null_style_operators()
6025
+	{
6026
+		return array_intersect(
6027
+			$this->valid_operators(),
6028
+			$this->_null_style_operators
6029
+		);
6030
+	}
6031
+
6032
+	/**
6033
+	 * Gets an array where keys are the primary keys and values are their 'names'
6034
+	 * (as determined by the model object's name() function, which is often overridden)
6035
+	 *
6036
+	 * @param array $query_params like get_all's
6037
+	 * @return string[]
6038
+	 * @throws EE_Error
6039
+	 */
6040
+	public function get_all_names($query_params = array())
6041
+	{
6042
+		$objs = $this->get_all($query_params);
6043
+		$names = array();
6044
+		foreach ($objs as $obj) {
6045
+			$names[ $obj->ID() ] = $obj->name();
6046
+		}
6047
+		return $names;
6048
+	}
6049
+
6050
+
6051
+
6052
+	/**
6053
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6054
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6055
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6056
+	 * array_keys() on $model_objects.
6057
+	 *
6058
+	 * @param \EE_Base_Class[] $model_objects
6059
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6060
+	 *                                               in the returned array
6061
+	 * @return array
6062
+	 * @throws EE_Error
6063
+	 */
6064
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6065
+	{
6066
+		if (! $this->has_primary_key_field()) {
6067
+			if (WP_DEBUG) {
6068
+				EE_Error::add_error(
6069
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6070
+					__FILE__,
6071
+					__FUNCTION__,
6072
+					__LINE__
6073
+				);
6074
+			}
6075
+		}
6076
+		$IDs = array();
6077
+		foreach ($model_objects as $model_object) {
6078
+			$id = $model_object->ID();
6079
+			if (! $id) {
6080
+				if ($filter_out_empty_ids) {
6081
+					continue;
6082
+				}
6083
+				if (WP_DEBUG) {
6084
+					EE_Error::add_error(
6085
+						__(
6086
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6087
+							'event_espresso'
6088
+						),
6089
+						__FILE__,
6090
+						__FUNCTION__,
6091
+						__LINE__
6092
+					);
6093
+				}
6094
+			}
6095
+			$IDs[] = $id;
6096
+		}
6097
+		return $IDs;
6098
+	}
6099
+
6100
+
6101
+
6102
+	/**
6103
+	 * Returns the string used in capabilities relating to this model. If there
6104
+	 * are no capabilities that relate to this model returns false
6105
+	 *
6106
+	 * @return string|false
6107
+	 */
6108
+	public function cap_slug()
6109
+	{
6110
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6111
+	}
6112
+
6113
+
6114
+
6115
+	/**
6116
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6117
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6118
+	 * only returns the cap restrictions array in that context (ie, the array
6119
+	 * at that key)
6120
+	 *
6121
+	 * @param string $context
6122
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6123
+	 * @throws EE_Error
6124
+	 */
6125
+	public function cap_restrictions($context = EEM_Base::caps_read)
6126
+	{
6127
+		EEM_Base::verify_is_valid_cap_context($context);
6128
+		// check if we ought to run the restriction generator first
6129
+		if (isset($this->_cap_restriction_generators[ $context ])
6130
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6131
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6132
+		) {
6133
+			$this->_cap_restrictions[ $context ] = array_merge(
6134
+				$this->_cap_restrictions[ $context ],
6135
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6136
+			);
6137
+		}
6138
+		// and make sure we've finalized the construction of each restriction
6139
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6140
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6141
+				$where_conditions_obj->_finalize_construct($this);
6142
+			}
6143
+		}
6144
+		return $this->_cap_restrictions[ $context ];
6145
+	}
6146
+
6147
+
6148
+
6149
+	/**
6150
+	 * Indicating whether or not this model thinks its a wp core model
6151
+	 *
6152
+	 * @return boolean
6153
+	 */
6154
+	public function is_wp_core_model()
6155
+	{
6156
+		return $this->_wp_core_model;
6157
+	}
6158
+
6159
+
6160
+
6161
+	/**
6162
+	 * Gets all the caps that are missing which impose a restriction on
6163
+	 * queries made in this context
6164
+	 *
6165
+	 * @param string $context one of EEM_Base::caps_ constants
6166
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6167
+	 * @throws EE_Error
6168
+	 */
6169
+	public function caps_missing($context = EEM_Base::caps_read)
6170
+	{
6171
+		$missing_caps = array();
6172
+		$cap_restrictions = $this->cap_restrictions($context);
6173
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6174
+			if (! EE_Capabilities::instance()
6175
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6176
+			) {
6177
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6178
+			}
6179
+		}
6180
+		return $missing_caps;
6181
+	}
6182
+
6183
+
6184
+
6185
+	/**
6186
+	 * Gets the mapping from capability contexts to action strings used in capability names
6187
+	 *
6188
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6189
+	 * one of 'read', 'edit', or 'delete'
6190
+	 */
6191
+	public function cap_contexts_to_cap_action_map()
6192
+	{
6193
+		return apply_filters(
6194
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6195
+			$this->_cap_contexts_to_cap_action_map,
6196
+			$this
6197
+		);
6198
+	}
6199
+
6200
+
6201
+
6202
+	/**
6203
+	 * Gets the action string for the specified capability context
6204
+	 *
6205
+	 * @param string $context
6206
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6207
+	 * @throws EE_Error
6208
+	 */
6209
+	public function cap_action_for_context($context)
6210
+	{
6211
+		$mapping = $this->cap_contexts_to_cap_action_map();
6212
+		if (isset($mapping[ $context ])) {
6213
+			return $mapping[ $context ];
6214
+		}
6215
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6216
+			return $action;
6217
+		}
6218
+		throw new EE_Error(
6219
+			sprintf(
6220
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6221
+				$context,
6222
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6223
+			)
6224
+		);
6225
+	}
6226
+
6227
+
6228
+
6229
+	/**
6230
+	 * Returns all the capability contexts which are valid when querying models
6231
+	 *
6232
+	 * @return array
6233
+	 */
6234
+	public static function valid_cap_contexts()
6235
+	{
6236
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6237
+			self::caps_read,
6238
+			self::caps_read_admin,
6239
+			self::caps_edit,
6240
+			self::caps_delete,
6241
+		));
6242
+	}
6243
+
6244
+
6245
+
6246
+	/**
6247
+	 * Returns all valid options for 'default_where_conditions'
6248
+	 *
6249
+	 * @return array
6250
+	 */
6251
+	public static function valid_default_where_conditions()
6252
+	{
6253
+		return array(
6254
+			EEM_Base::default_where_conditions_all,
6255
+			EEM_Base::default_where_conditions_this_only,
6256
+			EEM_Base::default_where_conditions_others_only,
6257
+			EEM_Base::default_where_conditions_minimum_all,
6258
+			EEM_Base::default_where_conditions_minimum_others,
6259
+			EEM_Base::default_where_conditions_none
6260
+		);
6261
+	}
6262
+
6263
+	// public static function default_where_conditions_full
6264
+	/**
6265
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6266
+	 *
6267
+	 * @param string $context
6268
+	 * @return bool
6269
+	 * @throws EE_Error
6270
+	 */
6271
+	public static function verify_is_valid_cap_context($context)
6272
+	{
6273
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6274
+		if (in_array($context, $valid_cap_contexts)) {
6275
+			return true;
6276
+		}
6277
+		throw new EE_Error(
6278
+			sprintf(
6279
+				__(
6280
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6281
+					'event_espresso'
6282
+				),
6283
+				$context,
6284
+				'EEM_Base',
6285
+				implode(',', $valid_cap_contexts)
6286
+			)
6287
+		);
6288
+	}
6289
+
6290
+
6291
+
6292
+	/**
6293
+	 * Clears all the models field caches. This is only useful when a sub-class
6294
+	 * might have added a field or something and these caches might be invalidated
6295
+	 */
6296
+	protected function _invalidate_field_caches()
6297
+	{
6298
+		$this->_cache_foreign_key_to_fields = array();
6299
+		$this->_cached_fields = null;
6300
+		$this->_cached_fields_non_db_only = null;
6301
+	}
6302
+
6303
+
6304
+
6305
+	/**
6306
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6307
+	 * (eg "and", "or", "not").
6308
+	 *
6309
+	 * @return array
6310
+	 */
6311
+	public function logic_query_param_keys()
6312
+	{
6313
+		return $this->_logic_query_param_keys;
6314
+	}
6315
+
6316
+
6317
+
6318
+	/**
6319
+	 * Determines whether or not the where query param array key is for a logic query param.
6320
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6321
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6322
+	 *
6323
+	 * @param $query_param_key
6324
+	 * @return bool
6325
+	 */
6326
+	public function is_logic_query_param_key($query_param_key)
6327
+	{
6328
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6329
+			if ($query_param_key === $logic_query_param_key
6330
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6331
+			) {
6332
+				return true;
6333
+			}
6334
+		}
6335
+		return false;
6336
+	}
6337
+
6338
+	/**
6339
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6340
+	 * @since 4.9.74.p
6341
+	 * @return boolean
6342
+	 */
6343
+	public function hasPassword()
6344
+	{
6345
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6346
+		if ($this->has_password_field === null) {
6347
+			$password_field = $this->getPasswordField();
6348
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6349
+		}
6350
+		return $this->has_password_field;
6351
+	}
6352
+
6353
+	/**
6354
+	 * Returns the password field on this model, if there is one
6355
+	 * @since 4.9.74.p
6356
+	 * @return EE_Password_Field|null
6357
+	 */
6358
+	public function getPasswordField()
6359
+	{
6360
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6361
+		// there's no need to search for it. If we don't know yet, then find out
6362
+		if ($this->has_password_field === null && $this->password_field === null) {
6363
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6364
+		}
6365
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6366
+		return $this->password_field;
6367
+	}
6368
+
6369
+
6370
+	/**
6371
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6372
+	 * @since 4.9.74.p
6373
+	 * @return EE_Model_Field_Base[]
6374
+	 * @throws EE_Error
6375
+	 */
6376
+	public function getPasswordProtectedFields()
6377
+	{
6378
+		$password_field = $this->getPasswordField();
6379
+		$fields = array();
6380
+		if ($password_field instanceof EE_Password_Field) {
6381
+			$field_names = $password_field->protectedFields();
6382
+			foreach ($field_names as $field_name) {
6383
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6384
+			}
6385
+		}
6386
+		return $fields;
6387
+	}
6388
+
6389
+
6390
+	/**
6391
+	 * Checks if the current user can perform the requested action on this model
6392
+	 * @since 4.9.74.p
6393
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6394
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6395
+	 * @return bool
6396
+	 * @throws EE_Error
6397
+	 * @throws InvalidArgumentException
6398
+	 * @throws InvalidDataTypeException
6399
+	 * @throws InvalidInterfaceException
6400
+	 * @throws ReflectionException
6401
+	 * @throws UnexpectedEntityException
6402
+	 */
6403
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6404
+	{
6405
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6406
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6407
+		}
6408
+		if (!is_array($model_obj_or_fields_n_values)) {
6409
+			throw new UnexpectedEntityException(
6410
+				$model_obj_or_fields_n_values,
6411
+				'EE_Base_Class',
6412
+				sprintf(
6413
+					esc_html__('%1$s must be passed an `EE_Base_Class or an array of fields names with their values. You passed in something different.', 'event_espresso'),
6414
+					__FUNCTION__
6415
+				)
6416
+			);
6417
+		}
6418
+		return $this->exists(
6419
+			$this->alter_query_params_to_restrict_by_ID(
6420
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6421
+				array(
6422
+					'default_where_conditions' => 'none',
6423
+					'caps'                     => $cap_to_check,
6424
+				)
6425
+			)
6426
+		);
6427
+	}
6428
+
6429
+	/**
6430
+	 * Returns the query param where conditions key to the password affecting this model.
6431
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6432
+	 * @since 4.9.74.p
6433
+	 * @return null|string
6434
+	 * @throws EE_Error
6435
+	 * @throws InvalidArgumentException
6436
+	 * @throws InvalidDataTypeException
6437
+	 * @throws InvalidInterfaceException
6438
+	 * @throws ModelConfigurationException
6439
+	 * @throws ReflectionException
6440
+	 */
6441
+	public function modelChainAndPassword()
6442
+	{
6443
+		if ($this->model_chain_to_password === null) {
6444
+			throw new ModelConfigurationException(
6445
+				$this,
6446
+				esc_html_x(
6447
+				// @codingStandardsIgnoreStart
6448
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6449
+					// @codingStandardsIgnoreEnd
6450
+					'1: model name',
6451
+					'event_espresso'
6452
+				)
6453
+			);
6454
+		}
6455
+		if ($this->model_chain_to_password === '') {
6456
+			$model_with_password = $this;
6457
+		} else {
6458
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6459
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6460
+			} else {
6461
+				$last_model_in_chain = $this->model_chain_to_password;
6462
+			}
6463
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6464
+		}
6465
+
6466
+		$password_field = $model_with_password->getPasswordField();
6467
+		if ($password_field instanceof EE_Password_Field) {
6468
+			$password_field_name = $password_field->get_name();
6469
+		} else {
6470
+			throw new ModelConfigurationException(
6471
+				$this,
6472
+				sprintf(
6473
+					esc_html_x(
6474
+						'This model claims related model "%1$s" should have a password field on it, but none was found. The model relation chain is "%2$s"',
6475
+						'1: model name, 2: special string',
6476
+						'event_espresso'
6477
+					),
6478
+					$model_with_password->get_this_model_name(),
6479
+					$this->model_chain_to_password
6480
+				)
6481
+			);
6482
+		}
6483
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6484
+	}
6485
+
6486
+	/**
6487
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6488
+	 * or if this model itself has a password affecting access to some of its other fields.
6489
+	 * @since 4.9.74.p
6490
+	 * @return boolean
6491
+	 */
6492
+	public function restrictedByRelatedModelPassword()
6493
+	{
6494
+		return $this->model_chain_to_password !== null;
6495
+	}
6496 6496
 }
Please login to merge, or discard this patch.
core/db_classes/EE_Payment_Method.class.php 1 patch
Indentation   +570 added lines, -570 removed lines patch added patch discarded remove patch
@@ -14,580 +14,580 @@
 block discarded – undo
14 14
 class EE_Payment_Method extends EE_Base_Class
15 15
 {
16 16
 
17
-    /**
18
-     * Payment Method type object, which has all the info about this type of payment method,
19
-     * including functions for processing payments, to get settings forms, etc.
20
-     *
21
-     * @var EE_PMT_Base
22
-     */
23
-    protected $_type_obj;
24
-
25
-
26
-    /**
27
-     * @param array $props_n_values
28
-     * @return EE_Payment_Method
29
-     * @throws \EE_Error
30
-     */
31
-    public static function new_instance($props_n_values = array())
32
-    {
33
-        $has_object = parent::_check_for_object($props_n_values, __CLASS__);
34
-        return $has_object ? $has_object : new self($props_n_values, false);
35
-    }
36
-
37
-
38
-    /**
39
-     * @param array $props_n_values
40
-     * @return EE_Payment_Method
41
-     * @throws \EE_Error
42
-     */
43
-    public static function new_instance_from_db($props_n_values = array())
44
-    {
45
-        return new self($props_n_values, true);
46
-    }
47
-
48
-
49
-
50
-    /**
51
-     * Checks if there is a payment method class of the given 'PMD_type', and if so returns the classname.
52
-     * Otherwise returns a normal EE_Payment_Method
53
-     *
54
-     * @param array $props_n_values where 'PMD_type' is a gateway name like 'Paypal_Standard','Invoice',etc (basically
55
-     *                              the classname minus 'EEPM_')
56
-     * @return string
57
-     */
58
-    // private static function _payment_method_type($props_n_values)
59
-    // {
60
-    //     EE_Registry::instance()->load_lib('Payment_Method_Manager');
61
-    //     $type_string = isset($props_n_values['PMD_type']) ? $props_n_values['PMD_type'] : null;
62
-    //     if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($type_string)) {
63
-    //         return 'EEPM_' . $type_string;
64
-    //     } else {
65
-    //         return __CLASS__;
66
-    //     }
67
-    // }
68
-
69
-
70
-    /**
71
-     * Gets whether this payment method can be used anywhere at all (ie frontend cart, admin, etc)
72
-     *
73
-     * @return boolean
74
-     */
75
-    public function active()
76
-    {
77
-        return array_intersect(array_keys(EEM_Payment_Method::instance()->scopes()), $this->scope());
78
-    }
79
-
80
-
81
-    /**
82
-     * Sets this PM as active by making it usable within the CART scope. Offline gateways
83
-     * are also usable from the admin-scope as well. DOES NOT SAVE it
84
-     *
85
-     * @throws \EE_Error
86
-     */
87
-    public function set_active()
88
-    {
89
-        $default_scopes = array(EEM_Payment_Method::scope_cart);
90
-        if ($this->type_obj() &&
91
-            $this->type_obj()->payment_occurs() === EE_PMT_Base::offline) {
92
-            $default_scopes[] = EEM_Payment_Method::scope_admin;
93
-        }
94
-        $this->set_scope($default_scopes);
95
-    }
96
-
97
-
98
-    /**
99
-     * Makes this payment method apply to NO scopes at all. DOES NOT SAVE it.
100
-     */
101
-    public function deactivate()
102
-    {
103
-        $this->set_scope(array());
104
-    }
105
-
106
-
107
-    /**
108
-     * Gets button_url
109
-     *
110
-     * @return string
111
-     */
112
-    public function button_url()
113
-    {
114
-        return $this->get('PMD_button_url');
115
-    }
116
-
117
-
118
-    /**
119
-     * Sets button_url
120
-     *
121
-     * @param string $button_url
122
-     */
123
-    public function set_button_url($button_url)
124
-    {
125
-        $this->set('PMD_button_url', $button_url);
126
-    }
127
-
128
-
129
-    /**
130
-     * Gets debug_mode
131
-     *
132
-     * @return boolean
133
-     */
134
-    public function debug_mode()
135
-    {
136
-        return $this->get('PMD_debug_mode');
137
-    }
138
-
139
-
140
-    /**
141
-     * Sets debug_mode
142
-     *
143
-     * @param boolean $debug_mode
144
-     */
145
-    public function set_debug_mode($debug_mode)
146
-    {
147
-        $this->set('PMD_debug_mode', $debug_mode);
148
-    }
149
-
150
-
151
-    /**
152
-     * Gets description
153
-     *
154
-     * @return string
155
-     */
156
-    public function description()
157
-    {
158
-        return $this->get('PMD_desc');
159
-    }
160
-
161
-
162
-    /**
163
-     * Sets description
164
-     *
165
-     * @param string $description
166
-     */
167
-    public function set_description($description)
168
-    {
169
-        $this->set('PMD_desc', $description);
170
-    }
171
-
172
-
173
-    /**
174
-     * Gets name
175
-     *
176
-     * @return string
177
-     */
178
-    public function name()
179
-    {
180
-        return $this->get('PMD_name');
181
-    }
182
-
183
-
184
-    /**
185
-     * Sets name
186
-     *
187
-     * @param string $name
188
-     */
189
-    public function set_name($name)
190
-    {
191
-        $this->set('PMD_name', $name);
192
-    }
193
-
194
-
195
-    /**
196
-     * Gets open_by_default
197
-     *
198
-     * @return boolean
199
-     */
200
-    public function open_by_default()
201
-    {
202
-        return $this->get('PMD_open_by_default');
203
-    }
204
-
205
-
206
-    /**
207
-     * Sets open_by_default
208
-     *
209
-     * @param boolean $open_by_default
210
-     */
211
-    public function set_open_by_default($open_by_default)
212
-    {
213
-        $this->set('PMD_open_by_default', $open_by_default);
214
-    }
215
-
216
-
217
-    /**
218
-     * Gets order
219
-     *
220
-     * @return int
221
-     */
222
-    public function order()
223
-    {
224
-        return $this->get('PMD_order');
225
-    }
226
-
227
-
228
-    /**
229
-     * Sets order
230
-     *
231
-     * @param int $order
232
-     */
233
-    public function set_order($order)
234
-    {
235
-        $this->set('PMD_order', $order);
236
-    }
237
-
238
-
239
-    /**
240
-     * Gets slug
241
-     *
242
-     * @return string
243
-     */
244
-    public function slug()
245
-    {
246
-        return $this->get('PMD_slug');
247
-    }
248
-
249
-
250
-    /**
251
-     * Sets slug
252
-     *
253
-     * @param string $slug
254
-     */
255
-    public function set_slug($slug)
256
-    {
257
-        $this->set('PMD_slug', $slug);
258
-    }
259
-
260
-
261
-    /**
262
-     * Gets type
263
-     *
264
-     * @return string
265
-     */
266
-    public function type()
267
-    {
268
-        return $this->get('PMD_type');
269
-    }
270
-
271
-
272
-    /**
273
-     * Sets type
274
-     *
275
-     * @param string $type
276
-     */
277
-    public function set_type($type)
278
-    {
279
-        $this->set('PMD_type', $type);
280
-    }
281
-
282
-
283
-    /**
284
-     * Gets wp_user
285
-     *
286
-     * @return int
287
-     */
288
-    public function wp_user()
289
-    {
290
-        return $this->get('PMD_wp_user');
291
-    }
292
-
293
-
294
-    /**
295
-     * Sets wp_user
296
-     *
297
-     * @param int $wp_user_id
298
-     */
299
-    public function set_wp_user($wp_user_id)
300
-    {
301
-        $this->set('PMD_wp_user', $wp_user_id);
302
-    }
303
-
304
-    /**
305
-     * Overrides parent so when PMD_type is changed we refresh the _type_obj
306
-     *
307
-     * @param string $field_name
308
-     * @param mixed $field_value
309
-     * @param boolean $use_default
310
-     */
311
-    public function set($field_name, $field_value, $use_default = false)
312
-    {
313
-        if ($field_name === 'PMD_type') {
314
-            // the type has probably changed, so forget about its old type object
315
-            $this->_type_obj = null;
316
-        }
317
-        parent::set($field_name, $field_value, $use_default);
318
-    }
319
-
320
-
321
-    /**
322
-     * Gets admin_name
323
-     *
324
-     * @return string
325
-     */
326
-    public function admin_name()
327
-    {
328
-        return $this->get('PMD_admin_name');
329
-    }
330
-
331
-
332
-    /**
333
-     * Sets admin_name
334
-     *
335
-     * @param string $admin_name
336
-     */
337
-    public function set_admin_name($admin_name)
338
-    {
339
-        $this->set('PMD_admin_name', $admin_name);
340
-    }
341
-
342
-
343
-    /**
344
-     * Gets admin_desc
345
-     *
346
-     * @return string
347
-     */
348
-    public function admin_desc()
349
-    {
350
-        return $this->get('PMD_admin_desc');
351
-    }
352
-
353
-
354
-    /**
355
-     * Sets admin_desc
356
-     *
357
-     * @param string $admin_desc
358
-     */
359
-    public function set_admin_desc($admin_desc)
360
-    {
361
-        $this->set('PMD_admin_desc', $admin_desc);
362
-    }
363
-
364
-
365
-    /**
366
-     * Gets scope
367
-     *
368
-     * @return array
369
-     */
370
-    public function scope()
371
-    {
372
-        return $this->get('PMD_scope');
373
-    }
374
-
375
-
376
-    /**
377
-     * Sets scope
378
-     *
379
-     * @param array $scope
380
-     */
381
-    public function set_scope($scope)
382
-    {
383
-        $this->set('PMD_scope', $scope);
384
-    }
385
-
386
-
387
-    /**
388
-     * Gets the payment method type for this payment method instance
389
-     *
390
-     * @return EE_PMT_Base
391
-     * @throws EE_Error
392
-     */
393
-    public function type_obj()
394
-    {
395
-        if (! $this->_type_obj) {
396
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
397
-            if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->type())) {
398
-                $class_name = EE_Payment_Method_Manager::instance()->payment_method_class_from_type($this->type());
399
-                if (! class_exists($class_name)) {
400
-                    throw new EE_Error(
401
-                        sprintf(
402
-                            __(
403
-                                'An attempt to use the "%1$s" payment method failed, so it was deactivated.%2$sWas the "%1$s" Plugin recently deactivated? It can be reactivated on the %3$sPlugins Admin Page%4$s',
404
-                                'event_espresso'
405
-                            ),
406
-                            $class_name,
407
-                            '<br />',
408
-                            '<a href="' . admin_url('plugins.php') . '">',
409
-                            '</a>'
410
-                        )
411
-                    );
412
-                }
413
-                $r = new ReflectionClass($class_name);
414
-                $this->_type_obj = $r->newInstanceArgs(array($this));
415
-            } else {
416
-                throw new EE_Error(
417
-                    sprintf(
418
-                        __(
419
-                            'A payment method of type "%1$s" does not exist. Only ones existing are: %2$s',
420
-                            'event_espresso'
421
-                        ),
422
-                        $this->type(),
423
-                        implode(',', EE_Payment_Method_Manager::instance()->payment_method_type_names())
424
-                    )
425
-                );
426
-            }
427
-        }
428
-        return $this->_type_obj;
429
-    }
430
-
431
-
432
-    /**
433
-     * Returns a simple array of key-value pairs combining the payment method's fields (without the 'PMD_' prefix)
434
-     * and the extra meta. Mostly used for passing off ot gateways.     *
435
-     *
436
-     * @return array
437
-     */
438
-    public function settings_array()
439
-    {
440
-        $fields = $this->model_field_array();
441
-        $extra_meta = $this->all_extra_meta_array();
442
-        // remove the model's prefix from the fields
443
-        $combined_settings_array = array();
444
-        foreach ($fields as $key => $value) {
445
-            if (strpos($key, 'PMD_') === 0) {
446
-                $key_sans_model_prefix = str_replace('PMD_', '', $key);
447
-                $combined_settings_array [ $key_sans_model_prefix ] = $value;
448
-            }
449
-        }
450
-        $combined_settings_array = array_merge($extra_meta, $combined_settings_array);
451
-        return $combined_settings_array;
452
-    }
453
-
454
-
455
-    /**
456
-     * Gets the HTML for displaying the payment method on a page.
457
-     *
458
-     * @param string $url
459
-     * @param string $css_class
460
-     * @return string of HTML for displaying the button
461
-     * @throws \EE_Error
462
-     */
463
-    public function button_html($url = '', $css_class = '')
464
-    {
465
-        $payment_occurs = $this->type_obj()->payment_occurs();
466
-        return '
17
+	/**
18
+	 * Payment Method type object, which has all the info about this type of payment method,
19
+	 * including functions for processing payments, to get settings forms, etc.
20
+	 *
21
+	 * @var EE_PMT_Base
22
+	 */
23
+	protected $_type_obj;
24
+
25
+
26
+	/**
27
+	 * @param array $props_n_values
28
+	 * @return EE_Payment_Method
29
+	 * @throws \EE_Error
30
+	 */
31
+	public static function new_instance($props_n_values = array())
32
+	{
33
+		$has_object = parent::_check_for_object($props_n_values, __CLASS__);
34
+		return $has_object ? $has_object : new self($props_n_values, false);
35
+	}
36
+
37
+
38
+	/**
39
+	 * @param array $props_n_values
40
+	 * @return EE_Payment_Method
41
+	 * @throws \EE_Error
42
+	 */
43
+	public static function new_instance_from_db($props_n_values = array())
44
+	{
45
+		return new self($props_n_values, true);
46
+	}
47
+
48
+
49
+
50
+	/**
51
+	 * Checks if there is a payment method class of the given 'PMD_type', and if so returns the classname.
52
+	 * Otherwise returns a normal EE_Payment_Method
53
+	 *
54
+	 * @param array $props_n_values where 'PMD_type' is a gateway name like 'Paypal_Standard','Invoice',etc (basically
55
+	 *                              the classname minus 'EEPM_')
56
+	 * @return string
57
+	 */
58
+	// private static function _payment_method_type($props_n_values)
59
+	// {
60
+	//     EE_Registry::instance()->load_lib('Payment_Method_Manager');
61
+	//     $type_string = isset($props_n_values['PMD_type']) ? $props_n_values['PMD_type'] : null;
62
+	//     if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($type_string)) {
63
+	//         return 'EEPM_' . $type_string;
64
+	//     } else {
65
+	//         return __CLASS__;
66
+	//     }
67
+	// }
68
+
69
+
70
+	/**
71
+	 * Gets whether this payment method can be used anywhere at all (ie frontend cart, admin, etc)
72
+	 *
73
+	 * @return boolean
74
+	 */
75
+	public function active()
76
+	{
77
+		return array_intersect(array_keys(EEM_Payment_Method::instance()->scopes()), $this->scope());
78
+	}
79
+
80
+
81
+	/**
82
+	 * Sets this PM as active by making it usable within the CART scope. Offline gateways
83
+	 * are also usable from the admin-scope as well. DOES NOT SAVE it
84
+	 *
85
+	 * @throws \EE_Error
86
+	 */
87
+	public function set_active()
88
+	{
89
+		$default_scopes = array(EEM_Payment_Method::scope_cart);
90
+		if ($this->type_obj() &&
91
+			$this->type_obj()->payment_occurs() === EE_PMT_Base::offline) {
92
+			$default_scopes[] = EEM_Payment_Method::scope_admin;
93
+		}
94
+		$this->set_scope($default_scopes);
95
+	}
96
+
97
+
98
+	/**
99
+	 * Makes this payment method apply to NO scopes at all. DOES NOT SAVE it.
100
+	 */
101
+	public function deactivate()
102
+	{
103
+		$this->set_scope(array());
104
+	}
105
+
106
+
107
+	/**
108
+	 * Gets button_url
109
+	 *
110
+	 * @return string
111
+	 */
112
+	public function button_url()
113
+	{
114
+		return $this->get('PMD_button_url');
115
+	}
116
+
117
+
118
+	/**
119
+	 * Sets button_url
120
+	 *
121
+	 * @param string $button_url
122
+	 */
123
+	public function set_button_url($button_url)
124
+	{
125
+		$this->set('PMD_button_url', $button_url);
126
+	}
127
+
128
+
129
+	/**
130
+	 * Gets debug_mode
131
+	 *
132
+	 * @return boolean
133
+	 */
134
+	public function debug_mode()
135
+	{
136
+		return $this->get('PMD_debug_mode');
137
+	}
138
+
139
+
140
+	/**
141
+	 * Sets debug_mode
142
+	 *
143
+	 * @param boolean $debug_mode
144
+	 */
145
+	public function set_debug_mode($debug_mode)
146
+	{
147
+		$this->set('PMD_debug_mode', $debug_mode);
148
+	}
149
+
150
+
151
+	/**
152
+	 * Gets description
153
+	 *
154
+	 * @return string
155
+	 */
156
+	public function description()
157
+	{
158
+		return $this->get('PMD_desc');
159
+	}
160
+
161
+
162
+	/**
163
+	 * Sets description
164
+	 *
165
+	 * @param string $description
166
+	 */
167
+	public function set_description($description)
168
+	{
169
+		$this->set('PMD_desc', $description);
170
+	}
171
+
172
+
173
+	/**
174
+	 * Gets name
175
+	 *
176
+	 * @return string
177
+	 */
178
+	public function name()
179
+	{
180
+		return $this->get('PMD_name');
181
+	}
182
+
183
+
184
+	/**
185
+	 * Sets name
186
+	 *
187
+	 * @param string $name
188
+	 */
189
+	public function set_name($name)
190
+	{
191
+		$this->set('PMD_name', $name);
192
+	}
193
+
194
+
195
+	/**
196
+	 * Gets open_by_default
197
+	 *
198
+	 * @return boolean
199
+	 */
200
+	public function open_by_default()
201
+	{
202
+		return $this->get('PMD_open_by_default');
203
+	}
204
+
205
+
206
+	/**
207
+	 * Sets open_by_default
208
+	 *
209
+	 * @param boolean $open_by_default
210
+	 */
211
+	public function set_open_by_default($open_by_default)
212
+	{
213
+		$this->set('PMD_open_by_default', $open_by_default);
214
+	}
215
+
216
+
217
+	/**
218
+	 * Gets order
219
+	 *
220
+	 * @return int
221
+	 */
222
+	public function order()
223
+	{
224
+		return $this->get('PMD_order');
225
+	}
226
+
227
+
228
+	/**
229
+	 * Sets order
230
+	 *
231
+	 * @param int $order
232
+	 */
233
+	public function set_order($order)
234
+	{
235
+		$this->set('PMD_order', $order);
236
+	}
237
+
238
+
239
+	/**
240
+	 * Gets slug
241
+	 *
242
+	 * @return string
243
+	 */
244
+	public function slug()
245
+	{
246
+		return $this->get('PMD_slug');
247
+	}
248
+
249
+
250
+	/**
251
+	 * Sets slug
252
+	 *
253
+	 * @param string $slug
254
+	 */
255
+	public function set_slug($slug)
256
+	{
257
+		$this->set('PMD_slug', $slug);
258
+	}
259
+
260
+
261
+	/**
262
+	 * Gets type
263
+	 *
264
+	 * @return string
265
+	 */
266
+	public function type()
267
+	{
268
+		return $this->get('PMD_type');
269
+	}
270
+
271
+
272
+	/**
273
+	 * Sets type
274
+	 *
275
+	 * @param string $type
276
+	 */
277
+	public function set_type($type)
278
+	{
279
+		$this->set('PMD_type', $type);
280
+	}
281
+
282
+
283
+	/**
284
+	 * Gets wp_user
285
+	 *
286
+	 * @return int
287
+	 */
288
+	public function wp_user()
289
+	{
290
+		return $this->get('PMD_wp_user');
291
+	}
292
+
293
+
294
+	/**
295
+	 * Sets wp_user
296
+	 *
297
+	 * @param int $wp_user_id
298
+	 */
299
+	public function set_wp_user($wp_user_id)
300
+	{
301
+		$this->set('PMD_wp_user', $wp_user_id);
302
+	}
303
+
304
+	/**
305
+	 * Overrides parent so when PMD_type is changed we refresh the _type_obj
306
+	 *
307
+	 * @param string $field_name
308
+	 * @param mixed $field_value
309
+	 * @param boolean $use_default
310
+	 */
311
+	public function set($field_name, $field_value, $use_default = false)
312
+	{
313
+		if ($field_name === 'PMD_type') {
314
+			// the type has probably changed, so forget about its old type object
315
+			$this->_type_obj = null;
316
+		}
317
+		parent::set($field_name, $field_value, $use_default);
318
+	}
319
+
320
+
321
+	/**
322
+	 * Gets admin_name
323
+	 *
324
+	 * @return string
325
+	 */
326
+	public function admin_name()
327
+	{
328
+		return $this->get('PMD_admin_name');
329
+	}
330
+
331
+
332
+	/**
333
+	 * Sets admin_name
334
+	 *
335
+	 * @param string $admin_name
336
+	 */
337
+	public function set_admin_name($admin_name)
338
+	{
339
+		$this->set('PMD_admin_name', $admin_name);
340
+	}
341
+
342
+
343
+	/**
344
+	 * Gets admin_desc
345
+	 *
346
+	 * @return string
347
+	 */
348
+	public function admin_desc()
349
+	{
350
+		return $this->get('PMD_admin_desc');
351
+	}
352
+
353
+
354
+	/**
355
+	 * Sets admin_desc
356
+	 *
357
+	 * @param string $admin_desc
358
+	 */
359
+	public function set_admin_desc($admin_desc)
360
+	{
361
+		$this->set('PMD_admin_desc', $admin_desc);
362
+	}
363
+
364
+
365
+	/**
366
+	 * Gets scope
367
+	 *
368
+	 * @return array
369
+	 */
370
+	public function scope()
371
+	{
372
+		return $this->get('PMD_scope');
373
+	}
374
+
375
+
376
+	/**
377
+	 * Sets scope
378
+	 *
379
+	 * @param array $scope
380
+	 */
381
+	public function set_scope($scope)
382
+	{
383
+		$this->set('PMD_scope', $scope);
384
+	}
385
+
386
+
387
+	/**
388
+	 * Gets the payment method type for this payment method instance
389
+	 *
390
+	 * @return EE_PMT_Base
391
+	 * @throws EE_Error
392
+	 */
393
+	public function type_obj()
394
+	{
395
+		if (! $this->_type_obj) {
396
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
397
+			if (EE_Payment_Method_Manager::instance()->payment_method_type_exists($this->type())) {
398
+				$class_name = EE_Payment_Method_Manager::instance()->payment_method_class_from_type($this->type());
399
+				if (! class_exists($class_name)) {
400
+					throw new EE_Error(
401
+						sprintf(
402
+							__(
403
+								'An attempt to use the "%1$s" payment method failed, so it was deactivated.%2$sWas the "%1$s" Plugin recently deactivated? It can be reactivated on the %3$sPlugins Admin Page%4$s',
404
+								'event_espresso'
405
+							),
406
+							$class_name,
407
+							'<br />',
408
+							'<a href="' . admin_url('plugins.php') . '">',
409
+							'</a>'
410
+						)
411
+					);
412
+				}
413
+				$r = new ReflectionClass($class_name);
414
+				$this->_type_obj = $r->newInstanceArgs(array($this));
415
+			} else {
416
+				throw new EE_Error(
417
+					sprintf(
418
+						__(
419
+							'A payment method of type "%1$s" does not exist. Only ones existing are: %2$s',
420
+							'event_espresso'
421
+						),
422
+						$this->type(),
423
+						implode(',', EE_Payment_Method_Manager::instance()->payment_method_type_names())
424
+					)
425
+				);
426
+			}
427
+		}
428
+		return $this->_type_obj;
429
+	}
430
+
431
+
432
+	/**
433
+	 * Returns a simple array of key-value pairs combining the payment method's fields (without the 'PMD_' prefix)
434
+	 * and the extra meta. Mostly used for passing off ot gateways.     *
435
+	 *
436
+	 * @return array
437
+	 */
438
+	public function settings_array()
439
+	{
440
+		$fields = $this->model_field_array();
441
+		$extra_meta = $this->all_extra_meta_array();
442
+		// remove the model's prefix from the fields
443
+		$combined_settings_array = array();
444
+		foreach ($fields as $key => $value) {
445
+			if (strpos($key, 'PMD_') === 0) {
446
+				$key_sans_model_prefix = str_replace('PMD_', '', $key);
447
+				$combined_settings_array [ $key_sans_model_prefix ] = $value;
448
+			}
449
+		}
450
+		$combined_settings_array = array_merge($extra_meta, $combined_settings_array);
451
+		return $combined_settings_array;
452
+	}
453
+
454
+
455
+	/**
456
+	 * Gets the HTML for displaying the payment method on a page.
457
+	 *
458
+	 * @param string $url
459
+	 * @param string $css_class
460
+	 * @return string of HTML for displaying the button
461
+	 * @throws \EE_Error
462
+	 */
463
+	public function button_html($url = '', $css_class = '')
464
+	{
465
+		$payment_occurs = $this->type_obj()->payment_occurs();
466
+		return '
467 467
 		 <div id="'
468
-               . $this->slug()
469
-               . '-payment-option-dv" class="'
470
-               . $payment_occurs . '-payment-gateway reg-page-payment-option-dv' . $css_class . '">
468
+			   . $this->slug()
469
+			   . '-payment-option-dv" class="'
470
+			   . $payment_occurs . '-payment-gateway reg-page-payment-option-dv' . $css_class . '">
471 471
 			<a id="payment-gateway-button-' . $this->slug()
472
-               . '" class="reg-page-payment-option-lnk" rel="'
473
-               . $this->slug() . '" href="' . $url . '" >
472
+			   . '" class="reg-page-payment-option-lnk" rel="'
473
+			   . $this->slug() . '" href="' . $url . '" >
474 474
 				<img src="' . $this->button_url() . '" alt="' . sprintf(
475
-                   esc_attr__('Pay using %s', 'event_espresso'),
476
-                   $this->get_pretty('PMD_name', 'form_input')
477
-               ) . '" />
475
+				   esc_attr__('Pay using %s', 'event_espresso'),
476
+				   $this->get_pretty('PMD_name', 'form_input')
477
+			   ) . '" />
478 478
 			</a>
479 479
 		</div>
480 480
 ';
481
-    }
482
-
483
-
484
-    /**
485
-     * Gets all the currencies which are an option for this payment method
486
-     * (as defined by the gateway and the currently active currencies)
487
-     *
488
-     * @return EE_Currency[]
489
-     * @throws \EE_Error
490
-     */
491
-    public function get_all_usable_currencies()
492
-    {
493
-        return EEM_Currency::instance()->get_all_currencies_usable_by($this->type_obj());
494
-    }
495
-
496
-
497
-    /**
498
-     * Reports whether or not this payment method can be used for this payment method
499
-     *
500
-     * @param string $currency_code currency ID (code)
501
-     * @return boolean
502
-     * @throws \EE_Error
503
-     */
504
-    public function usable_for_currency($currency_code)
505
-    {
506
-        foreach ($this->get_all_usable_currencies() as $currency_obj) {
507
-            if ($currency_obj->ID() === $currency_code) {
508
-                return true;
509
-            }
510
-        }
511
-        return false;
512
-    }
513
-
514
-
515
-    /**
516
-     * Returns TRUE if this payment method's gateway is an instance of EE_Onsite_Gateway
517
-     *
518
-     * @return bool
519
-     * @throws \EE_Error
520
-     */
521
-    public function is_on_site()
522
-    {
523
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::onsite;
524
-    }
525
-
526
-
527
-    /**
528
-     * Returns TRUE if this payment method's gateway is an instance of EE_Offsite_Gateway
529
-     *
530
-     * @return bool
531
-     * @throws \EE_Error
532
-     */
533
-    public function is_off_site()
534
-    {
535
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::offsite;
536
-    }
537
-
538
-
539
-    /**
540
-     * Returns TRUE if this payment method does not utilize a gateway
541
-     *
542
-     * @return bool
543
-     * @throws \EE_Error
544
-     */
545
-    public function is_off_line()
546
-    {
547
-        return $this->type_obj()->payment_occurs() === EE_PMT_Base::offline;
548
-    }
549
-
550
-    /**
551
-     * Overrides default __sleep so the object type is NOT cached.
552
-     * This way we can rely on the normal EE_Payment_Method::type_obj() logic
553
-     * to load the required classes, and don't need them at the time of unserialization
554
-     *
555
-     * @return array
556
-     */
557
-    public function __sleep()
558
-    {
559
-        $properties = get_object_vars($this);
560
-        unset($properties['_type_obj']);
561
-        return array_keys($properties);
562
-    }
563
-
564
-
565
-    /**
566
-     * Overrides parent to add some logging for when payment methods get deactivated
567
-     *
568
-     * @param array $set_cols_n_values
569
-     * @return int @see EE_Base_Class::save()
570
-     * @throws \EE_Error
571
-     */
572
-    public function save($set_cols_n_values = array())
573
-    {
574
-        $results = parent::save($set_cols_n_values);
575
-        if ($this->get_original('PMD_scope') !== $this->get('PMD_scope')) {
576
-            /** @var CurrentPage $current_page */
577
-            $current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
578
-            EE_Log::instance()->log(
579
-                __FILE__,
580
-                __FUNCTION__,
581
-                sprintf(
582
-                    __('Set new scope on payment method %1$s to %2$s from %3$s on URL %4$s', 'event_espresso'),
583
-                    $this->name(),
584
-                    serialize($this->get_original('PMD_scope')),
585
-                    serialize($this->get('PMD_scope')),
586
-                    $current_page->getPermalink()
587
-                ),
588
-                'payment_method_change'
589
-            );
590
-        }
591
-        return $results;
592
-    }
481
+	}
482
+
483
+
484
+	/**
485
+	 * Gets all the currencies which are an option for this payment method
486
+	 * (as defined by the gateway and the currently active currencies)
487
+	 *
488
+	 * @return EE_Currency[]
489
+	 * @throws \EE_Error
490
+	 */
491
+	public function get_all_usable_currencies()
492
+	{
493
+		return EEM_Currency::instance()->get_all_currencies_usable_by($this->type_obj());
494
+	}
495
+
496
+
497
+	/**
498
+	 * Reports whether or not this payment method can be used for this payment method
499
+	 *
500
+	 * @param string $currency_code currency ID (code)
501
+	 * @return boolean
502
+	 * @throws \EE_Error
503
+	 */
504
+	public function usable_for_currency($currency_code)
505
+	{
506
+		foreach ($this->get_all_usable_currencies() as $currency_obj) {
507
+			if ($currency_obj->ID() === $currency_code) {
508
+				return true;
509
+			}
510
+		}
511
+		return false;
512
+	}
513
+
514
+
515
+	/**
516
+	 * Returns TRUE if this payment method's gateway is an instance of EE_Onsite_Gateway
517
+	 *
518
+	 * @return bool
519
+	 * @throws \EE_Error
520
+	 */
521
+	public function is_on_site()
522
+	{
523
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::onsite;
524
+	}
525
+
526
+
527
+	/**
528
+	 * Returns TRUE if this payment method's gateway is an instance of EE_Offsite_Gateway
529
+	 *
530
+	 * @return bool
531
+	 * @throws \EE_Error
532
+	 */
533
+	public function is_off_site()
534
+	{
535
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::offsite;
536
+	}
537
+
538
+
539
+	/**
540
+	 * Returns TRUE if this payment method does not utilize a gateway
541
+	 *
542
+	 * @return bool
543
+	 * @throws \EE_Error
544
+	 */
545
+	public function is_off_line()
546
+	{
547
+		return $this->type_obj()->payment_occurs() === EE_PMT_Base::offline;
548
+	}
549
+
550
+	/**
551
+	 * Overrides default __sleep so the object type is NOT cached.
552
+	 * This way we can rely on the normal EE_Payment_Method::type_obj() logic
553
+	 * to load the required classes, and don't need them at the time of unserialization
554
+	 *
555
+	 * @return array
556
+	 */
557
+	public function __sleep()
558
+	{
559
+		$properties = get_object_vars($this);
560
+		unset($properties['_type_obj']);
561
+		return array_keys($properties);
562
+	}
563
+
564
+
565
+	/**
566
+	 * Overrides parent to add some logging for when payment methods get deactivated
567
+	 *
568
+	 * @param array $set_cols_n_values
569
+	 * @return int @see EE_Base_Class::save()
570
+	 * @throws \EE_Error
571
+	 */
572
+	public function save($set_cols_n_values = array())
573
+	{
574
+		$results = parent::save($set_cols_n_values);
575
+		if ($this->get_original('PMD_scope') !== $this->get('PMD_scope')) {
576
+			/** @var CurrentPage $current_page */
577
+			$current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
578
+			EE_Log::instance()->log(
579
+				__FILE__,
580
+				__FUNCTION__,
581
+				sprintf(
582
+					__('Set new scope on payment method %1$s to %2$s from %3$s on URL %4$s', 'event_espresso'),
583
+					$this->name(),
584
+					serialize($this->get_original('PMD_scope')),
585
+					serialize($this->get('PMD_scope')),
586
+					$current_page->getPermalink()
587
+				),
588
+				'payment_method_change'
589
+			);
590
+		}
591
+		return $results;
592
+	}
593 593
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin.core.php 1 patch
Indentation   +1020 added lines, -1020 removed lines patch added patch discarded remove patch
@@ -21,482 +21,482 @@  discard block
 block discarded – undo
21 21
 final class EE_Admin implements InterminableInterface
22 22
 {
23 23
 
24
-    /**
25
-     * @var EE_Admin $_instance
26
-     */
27
-    private static $_instance;
28
-
29
-    /**
30
-     * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
31
-     */
32
-    private $persistent_admin_notice_manager;
33
-
34
-    /**
35
-     * @var LoaderInterface
36
-     */
37
-    protected $loader;
38
-
39
-    /**
40
-     * @singleton method used to instantiate class object
41
-     * @return EE_Admin
42
-     * @throws EE_Error
43
-     */
44
-    public static function instance()
45
-    {
46
-        // check if class object is instantiated
47
-        if (! self::$_instance instanceof EE_Admin) {
48
-            self::$_instance = new self();
49
-        }
50
-        return self::$_instance;
51
-    }
52
-
53
-
54
-    /**
55
-     * @return EE_Admin
56
-     * @throws EE_Error
57
-     */
58
-    public static function reset()
59
-    {
60
-        self::$_instance = null;
61
-        return self::instance();
62
-    }
63
-
64
-
65
-    /**
66
-     * class constructor
67
-     *
68
-     * @throws EE_Error
69
-     * @throws InvalidDataTypeException
70
-     * @throws InvalidInterfaceException
71
-     * @throws InvalidArgumentException
72
-     */
73
-    protected function __construct()
74
-    {
75
-        // define global EE_Admin constants
76
-        $this->_define_all_constants();
77
-        // set autoloaders for our admin page classes based on included path information
78
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
79
-        // admin hooks
80
-        add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
81
-        add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
82
-        add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
83
-        add_action('wp_loaded', array($this, 'wp_loaded'), 100);
84
-        add_action('admin_init', array($this, 'admin_init'), 100);
85
-        add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
86
-        add_action('admin_notices', array($this, 'display_admin_notices'), 10);
87
-        add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
88
-        add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
89
-        add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
90
-        add_action('load-plugins.php', array($this, 'hookIntoWpPluginsPage'));
91
-        add_action('display_post_states', array($this, 'displayStateForCriticalPages'), 10, 2);
92
-        add_filter('plugin_row_meta', array($this, 'addLinksToPluginRowMeta'), 10, 2);
93
-        // reset Environment config (we only do this on admin page loads);
94
-        EE_Registry::instance()->CFG->environment->recheck_values();
95
-        do_action('AHEE__EE_Admin__loaded');
96
-    }
97
-
98
-
99
-    /**
100
-     * _define_all_constants
101
-     * define constants that are set globally for all admin pages
102
-     *
103
-     * @return void
104
-     */
105
-    private function _define_all_constants()
106
-    {
107
-        if (! defined('EE_ADMIN_URL')) {
108
-            define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
109
-            define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
110
-            define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates/');
111
-            define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
112
-            define('WP_AJAX_URL', admin_url('admin-ajax.php'));
113
-        }
114
-    }
115
-
116
-
117
-    /**
118
-     * filter_plugin_actions - adds links to the Plugins page listing
119
-     *
120
-     * @param    array  $links
121
-     * @param    string $plugin
122
-     * @return    array
123
-     */
124
-    public function filter_plugin_actions($links, $plugin)
125
-    {
126
-        // set $main_file in stone
127
-        static $main_file;
128
-        // if $main_file is not set yet
129
-        if (! $main_file) {
130
-            $main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
131
-        }
132
-        if ($plugin === $main_file) {
133
-            // compare current plugin to this one
134
-            if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
135
-                $maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
136
-                                    . ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
137
-                                    . esc_html__('Maintenance Mode Active', 'event_espresso')
138
-                                    . '</a>';
139
-                array_unshift($links, $maintenance_link);
140
-            } else {
141
-                $org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
142
-                                     . esc_html__('Settings', 'event_espresso')
143
-                                     . '</a>';
144
-                $events_link = '<a href="admin.php?page=espresso_events">'
145
-                               . esc_html__('Events', 'event_espresso')
146
-                               . '</a>';
147
-                // add before other links
148
-                array_unshift($links, $org_settings_link, $events_link);
149
-            }
150
-        }
151
-        return $links;
152
-    }
153
-
154
-
155
-    /**
156
-     * @deprecated $VID:$
157
-     */
158
-    public function get_request()
159
-    {
160
-    }
161
-
162
-
163
-    /**
164
-     * hide_admin_pages_except_maintenance_mode
165
-     *
166
-     * @param array $admin_page_folder_names
167
-     * @return array
168
-     */
169
-    public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
170
-    {
171
-        return array(
172
-            'maintenance' => EE_ADMIN_PAGES . 'maintenance/',
173
-            'about'       => EE_ADMIN_PAGES . 'about/',
174
-            'support'     => EE_ADMIN_PAGES . 'support/',
175
-        );
176
-    }
177
-
178
-
179
-    /**
180
-     * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
181
-     * EE_Front_Controller's init phases have run
182
-     *
183
-     * @return void
184
-     * @throws EE_Error
185
-     * @throws InvalidArgumentException
186
-     * @throws InvalidDataTypeException
187
-     * @throws InvalidInterfaceException
188
-     * @throws ReflectionException
189
-     * @throws ServiceNotFoundException
190
-     */
191
-    public function init()
192
-    {
193
-        // only enable most of the EE_Admin IF we're not in full maintenance mode
194
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
195
-            $this->initModelsReady();
196
-        }
197
-        // run the admin page factory but ONLY if we are doing an ee admin ajax request
198
-        if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
199
-            try {
200
-                // this loads the controller for the admin pages which will setup routing etc
201
-                EE_Registry::instance()->load_core('Admin_Page_Loader');
202
-            } catch (EE_Error $e) {
203
-                $e->get_error();
204
-            }
205
-        }
206
-        add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
207
-        // make sure our CPTs and custom taxonomy metaboxes get shown for first time users
208
-        add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
209
-        add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
210
-        // exclude EE critical pages from all nav menus and wp_list_pages
211
-        add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
212
-    }
213
-
214
-
215
-    /**
216
-     * Gets the loader (and if it wasn't previously set, sets it)
217
-     * @return LoaderInterface
218
-     * @throws InvalidArgumentException
219
-     * @throws InvalidDataTypeException
220
-     * @throws InvalidInterfaceException
221
-     */
222
-    protected function getLoader()
223
-    {
224
-        if (! $this->loader instanceof LoaderInterface) {
225
-            $this->loader = LoaderFactory::getLoader();
226
-        }
227
-        return $this->loader;
228
-    }
229
-
230
-
231
-    /**
232
-     * Method that's fired on admin requests (including admin ajax) but only when the models are usable
233
-     * (ie, the site isn't in maintenance mode)
234
-     *
235
-     * @return void
236
-     * @throws EE_Error
237
-     * @since 4.9.63.p
238
-     */
239
-    protected function initModelsReady()
240
-    {
241
-        // ok so we want to enable the entire admin
242
-        $this->persistent_admin_notice_manager = $this->getLoader()->getShared(
243
-            'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
244
-        );
245
-        /** @var RequestInterface $request */
246
-        $request = $this->getLoader()->getShared(RequestInterface::class);
247
-        $this->persistent_admin_notice_manager->setReturnUrl(
248
-            EE_Admin_Page::add_query_args_and_nonce(
249
-                array(
250
-                    'page'   => $request->getRequestParam('page'),
251
-                    'action' => $request->getRequestParam('action'),
252
-                ),
253
-                EE_ADMIN_URL
254
-            )
255
-        );
256
-        $this->maybeSetDatetimeWarningNotice();
257
-        // at a glance dashboard widget
258
-        add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
259
-        // filter for get_edit_post_link used on comments for custom post types
260
-        add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
261
-    }
262
-
263
-
264
-    /**
265
-     *    get_persistent_admin_notices
266
-     *
267
-     * @access    public
268
-     * @return void
269
-     * @throws EE_Error
270
-     * @throws InvalidArgumentException
271
-     * @throws InvalidDataTypeException
272
-     * @throws InvalidInterfaceException
273
-     */
274
-    public function maybeSetDatetimeWarningNotice()
275
-    {
276
-        // add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
277
-        // @todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
278
-        // with this.  But after enough time (indeterminate at this point) we can just remove this notice.
279
-        // this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
280
-        if (apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
281
-            && ! get_option('timezone_string')
282
-            && EEM_Event::instance()->count() > 0
283
-        ) {
284
-            new PersistentAdminNotice(
285
-                'datetime_fix_notice',
286
-                sprintf(
287
-                    esc_html__(
288
-                        '%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.',
289
-                        'event_espresso'
290
-                    ),
291
-                    '<strong>',
292
-                    '</strong>',
293
-                    '<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
294
-                    '</a>',
295
-                    '<a href="' . EE_Admin_Page::add_query_args_and_nonce(
296
-                        array(
297
-                            'page'   => 'espresso_maintenance_settings',
298
-                            'action' => 'datetime_tools',
299
-                        ),
300
-                        admin_url('admin.php')
301
-                    ) . '">'
302
-                ),
303
-                false,
304
-                'manage_options',
305
-                'datetime_fix_persistent_notice'
306
-            );
307
-        }
308
-    }
309
-
310
-
311
-    /**
312
-     * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
313
-     * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
314
-     * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
315
-     * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
316
-     * normal property on the post_type object.  It's found ONLY in this particular context.
317
-     *
318
-     * @param WP_Post $post_type WP post type object
319
-     * @return WP_Post
320
-     * @throws InvalidArgumentException
321
-     * @throws InvalidDataTypeException
322
-     * @throws InvalidInterfaceException
323
-     */
324
-    public function remove_pages_from_nav_menu($post_type)
325
-    {
326
-        // if this isn't the "pages" post type let's get out
327
-        if ($post_type->name !== 'page') {
328
-            return $post_type;
329
-        }
330
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
331
-        $post_type->_default_query = array(
332
-            'post__not_in' => $critical_pages,
333
-        );
334
-        return $post_type;
335
-    }
336
-
337
-
338
-    /**
339
-     * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
340
-     * metaboxes get shown as well
341
-     *
342
-     * @return void
343
-     */
344
-    public function enable_hidden_ee_nav_menu_metaboxes()
345
-    {
346
-        global $wp_meta_boxes, $pagenow;
347
-        if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
348
-            return;
349
-        }
350
-        $user = wp_get_current_user();
351
-        // has this been done yet?
352
-        if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
353
-            return;
354
-        }
355
-
356
-        $hidden_meta_boxes = get_user_option('metaboxhidden_nav-menus', $user->ID);
357
-        $initial_meta_boxes = apply_filters(
358
-            'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
359
-            array(
360
-                'nav-menu-theme-locations',
361
-                'add-page',
362
-                'add-custom-links',
363
-                'add-category',
364
-                'add-espresso_events',
365
-                'add-espresso_venues',
366
-                'add-espresso_event_categories',
367
-                'add-espresso_venue_categories',
368
-                'add-post-type-post',
369
-                'add-post-type-page',
370
-            )
371
-        );
372
-
373
-        if (is_array($hidden_meta_boxes)) {
374
-            foreach ($hidden_meta_boxes as $key => $meta_box_id) {
375
-                if (in_array($meta_box_id, $initial_meta_boxes, true)) {
376
-                    unset($hidden_meta_boxes[ $key ]);
377
-                }
378
-            }
379
-        }
380
-        update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
381
-        update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
382
-    }
383
-
384
-
385
-    /**
386
-     * This method simply registers custom nav menu boxes for "nav_menus.php route"
387
-     * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
388
-     *
389
-     * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
390
-     *         addons etc.
391
-     * @return void
392
-     */
393
-    public function register_custom_nav_menu_boxes()
394
-    {
395
-        add_meta_box(
396
-            'add-extra-nav-menu-pages',
397
-            esc_html__('Event Espresso Pages', 'event_espresso'),
398
-            array($this, 'ee_cpt_archive_pages'),
399
-            'nav-menus',
400
-            'side',
401
-            'core'
402
-        );
403
-    }
404
-
405
-
406
-    /**
407
-     * Use this to edit the post link for our cpts so that the edit link points to the correct page.
408
-     *
409
-     * @since   4.3.0
410
-     * @param string $link the original link generated by wp
411
-     * @param int    $id   post id
412
-     * @return string  the (maybe) modified link
413
-     */
414
-    public function modify_edit_post_link($link, $id)
415
-    {
416
-        if (! $post = get_post($id)) {
417
-            return $link;
418
-        }
419
-        if ($post->post_type === 'espresso_attendees') {
420
-            $query_args = array(
421
-                'action' => 'edit_attendee',
422
-                'post'   => $id,
423
-            );
424
-            return EEH_URL::add_query_args_and_nonce(
425
-                $query_args,
426
-                admin_url('admin.php?page=espresso_registrations')
427
-            );
428
-        }
429
-        return $link;
430
-    }
431
-
432
-
433
-    public function ee_cpt_archive_pages()
434
-    {
435
-        global $nav_menu_selected_id;
436
-        $db_fields = false;
437
-        $walker = new Walker_Nav_Menu_Checklist($db_fields);
438
-        $current_tab = 'event-archives';
439
-        $removed_args = array(
440
-            'action',
441
-            'customlink-tab',
442
-            'edit-menu-item',
443
-            'menu-item',
444
-            'page-tab',
445
-            '_wpnonce',
446
-        );
447
-        ?>
24
+	/**
25
+	 * @var EE_Admin $_instance
26
+	 */
27
+	private static $_instance;
28
+
29
+	/**
30
+	 * @var PersistentAdminNoticeManager $persistent_admin_notice_manager
31
+	 */
32
+	private $persistent_admin_notice_manager;
33
+
34
+	/**
35
+	 * @var LoaderInterface
36
+	 */
37
+	protected $loader;
38
+
39
+	/**
40
+	 * @singleton method used to instantiate class object
41
+	 * @return EE_Admin
42
+	 * @throws EE_Error
43
+	 */
44
+	public static function instance()
45
+	{
46
+		// check if class object is instantiated
47
+		if (! self::$_instance instanceof EE_Admin) {
48
+			self::$_instance = new self();
49
+		}
50
+		return self::$_instance;
51
+	}
52
+
53
+
54
+	/**
55
+	 * @return EE_Admin
56
+	 * @throws EE_Error
57
+	 */
58
+	public static function reset()
59
+	{
60
+		self::$_instance = null;
61
+		return self::instance();
62
+	}
63
+
64
+
65
+	/**
66
+	 * class constructor
67
+	 *
68
+	 * @throws EE_Error
69
+	 * @throws InvalidDataTypeException
70
+	 * @throws InvalidInterfaceException
71
+	 * @throws InvalidArgumentException
72
+	 */
73
+	protected function __construct()
74
+	{
75
+		// define global EE_Admin constants
76
+		$this->_define_all_constants();
77
+		// set autoloaders for our admin page classes based on included path information
78
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_ADMIN);
79
+		// admin hooks
80
+		add_filter('plugin_action_links', array($this, 'filter_plugin_actions'), 10, 2);
81
+		add_action('AHEE__EE_System__initialize_last', array($this, 'init'));
82
+		add_action('AHEE__EE_Admin_Page__route_admin_request', array($this, 'route_admin_request'), 100, 2);
83
+		add_action('wp_loaded', array($this, 'wp_loaded'), 100);
84
+		add_action('admin_init', array($this, 'admin_init'), 100);
85
+		add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'), 20);
86
+		add_action('admin_notices', array($this, 'display_admin_notices'), 10);
87
+		add_action('network_admin_notices', array($this, 'display_admin_notices'), 10);
88
+		add_filter('pre_update_option', array($this, 'check_for_invalid_datetime_formats'), 100, 2);
89
+		add_filter('admin_footer_text', array($this, 'espresso_admin_footer'));
90
+		add_action('load-plugins.php', array($this, 'hookIntoWpPluginsPage'));
91
+		add_action('display_post_states', array($this, 'displayStateForCriticalPages'), 10, 2);
92
+		add_filter('plugin_row_meta', array($this, 'addLinksToPluginRowMeta'), 10, 2);
93
+		// reset Environment config (we only do this on admin page loads);
94
+		EE_Registry::instance()->CFG->environment->recheck_values();
95
+		do_action('AHEE__EE_Admin__loaded');
96
+	}
97
+
98
+
99
+	/**
100
+	 * _define_all_constants
101
+	 * define constants that are set globally for all admin pages
102
+	 *
103
+	 * @return void
104
+	 */
105
+	private function _define_all_constants()
106
+	{
107
+		if (! defined('EE_ADMIN_URL')) {
108
+			define('EE_ADMIN_URL', EE_PLUGIN_DIR_URL . 'core/admin/');
109
+			define('EE_ADMIN_PAGES_URL', EE_PLUGIN_DIR_URL . 'admin_pages/');
110
+			define('EE_ADMIN_TEMPLATE', EE_ADMIN . 'templates/');
111
+			define('WP_ADMIN_PATH', ABSPATH . 'wp-admin/');
112
+			define('WP_AJAX_URL', admin_url('admin-ajax.php'));
113
+		}
114
+	}
115
+
116
+
117
+	/**
118
+	 * filter_plugin_actions - adds links to the Plugins page listing
119
+	 *
120
+	 * @param    array  $links
121
+	 * @param    string $plugin
122
+	 * @return    array
123
+	 */
124
+	public function filter_plugin_actions($links, $plugin)
125
+	{
126
+		// set $main_file in stone
127
+		static $main_file;
128
+		// if $main_file is not set yet
129
+		if (! $main_file) {
130
+			$main_file = plugin_basename(EVENT_ESPRESSO_MAIN_FILE);
131
+		}
132
+		if ($plugin === $main_file) {
133
+			// compare current plugin to this one
134
+			if (EE_Maintenance_Mode::instance()->level() === EE_Maintenance_Mode::level_2_complete_maintenance) {
135
+				$maintenance_link = '<a href="admin.php?page=espresso_maintenance_settings"'
136
+									. ' title="Event Espresso is in maintenance mode.  Click this link to learn why.">'
137
+									. esc_html__('Maintenance Mode Active', 'event_espresso')
138
+									. '</a>';
139
+				array_unshift($links, $maintenance_link);
140
+			} else {
141
+				$org_settings_link = '<a href="admin.php?page=espresso_general_settings">'
142
+									 . esc_html__('Settings', 'event_espresso')
143
+									 . '</a>';
144
+				$events_link = '<a href="admin.php?page=espresso_events">'
145
+							   . esc_html__('Events', 'event_espresso')
146
+							   . '</a>';
147
+				// add before other links
148
+				array_unshift($links, $org_settings_link, $events_link);
149
+			}
150
+		}
151
+		return $links;
152
+	}
153
+
154
+
155
+	/**
156
+	 * @deprecated $VID:$
157
+	 */
158
+	public function get_request()
159
+	{
160
+	}
161
+
162
+
163
+	/**
164
+	 * hide_admin_pages_except_maintenance_mode
165
+	 *
166
+	 * @param array $admin_page_folder_names
167
+	 * @return array
168
+	 */
169
+	public function hide_admin_pages_except_maintenance_mode($admin_page_folder_names = array())
170
+	{
171
+		return array(
172
+			'maintenance' => EE_ADMIN_PAGES . 'maintenance/',
173
+			'about'       => EE_ADMIN_PAGES . 'about/',
174
+			'support'     => EE_ADMIN_PAGES . 'support/',
175
+		);
176
+	}
177
+
178
+
179
+	/**
180
+	 * init- should fire after shortcode, module,  addon, other plugin (default priority), and even
181
+	 * EE_Front_Controller's init phases have run
182
+	 *
183
+	 * @return void
184
+	 * @throws EE_Error
185
+	 * @throws InvalidArgumentException
186
+	 * @throws InvalidDataTypeException
187
+	 * @throws InvalidInterfaceException
188
+	 * @throws ReflectionException
189
+	 * @throws ServiceNotFoundException
190
+	 */
191
+	public function init()
192
+	{
193
+		// only enable most of the EE_Admin IF we're not in full maintenance mode
194
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
195
+			$this->initModelsReady();
196
+		}
197
+		// run the admin page factory but ONLY if we are doing an ee admin ajax request
198
+		if (! defined('DOING_AJAX') || EE_ADMIN_AJAX) {
199
+			try {
200
+				// this loads the controller for the admin pages which will setup routing etc
201
+				EE_Registry::instance()->load_core('Admin_Page_Loader');
202
+			} catch (EE_Error $e) {
203
+				$e->get_error();
204
+			}
205
+		}
206
+		add_filter('content_save_pre', array($this, 'its_eSpresso'), 10, 1);
207
+		// make sure our CPTs and custom taxonomy metaboxes get shown for first time users
208
+		add_action('admin_head', array($this, 'enable_hidden_ee_nav_menu_metaboxes'), 10);
209
+		add_action('admin_head', array($this, 'register_custom_nav_menu_boxes'), 10);
210
+		// exclude EE critical pages from all nav menus and wp_list_pages
211
+		add_filter('nav_menu_meta_box_object', array($this, 'remove_pages_from_nav_menu'), 10);
212
+	}
213
+
214
+
215
+	/**
216
+	 * Gets the loader (and if it wasn't previously set, sets it)
217
+	 * @return LoaderInterface
218
+	 * @throws InvalidArgumentException
219
+	 * @throws InvalidDataTypeException
220
+	 * @throws InvalidInterfaceException
221
+	 */
222
+	protected function getLoader()
223
+	{
224
+		if (! $this->loader instanceof LoaderInterface) {
225
+			$this->loader = LoaderFactory::getLoader();
226
+		}
227
+		return $this->loader;
228
+	}
229
+
230
+
231
+	/**
232
+	 * Method that's fired on admin requests (including admin ajax) but only when the models are usable
233
+	 * (ie, the site isn't in maintenance mode)
234
+	 *
235
+	 * @return void
236
+	 * @throws EE_Error
237
+	 * @since 4.9.63.p
238
+	 */
239
+	protected function initModelsReady()
240
+	{
241
+		// ok so we want to enable the entire admin
242
+		$this->persistent_admin_notice_manager = $this->getLoader()->getShared(
243
+			'EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
244
+		);
245
+		/** @var RequestInterface $request */
246
+		$request = $this->getLoader()->getShared(RequestInterface::class);
247
+		$this->persistent_admin_notice_manager->setReturnUrl(
248
+			EE_Admin_Page::add_query_args_and_nonce(
249
+				array(
250
+					'page'   => $request->getRequestParam('page'),
251
+					'action' => $request->getRequestParam('action'),
252
+				),
253
+				EE_ADMIN_URL
254
+			)
255
+		);
256
+		$this->maybeSetDatetimeWarningNotice();
257
+		// at a glance dashboard widget
258
+		add_filter('dashboard_glance_items', array($this, 'dashboard_glance_items'), 10);
259
+		// filter for get_edit_post_link used on comments for custom post types
260
+		add_filter('get_edit_post_link', array($this, 'modify_edit_post_link'), 10, 2);
261
+	}
262
+
263
+
264
+	/**
265
+	 *    get_persistent_admin_notices
266
+	 *
267
+	 * @access    public
268
+	 * @return void
269
+	 * @throws EE_Error
270
+	 * @throws InvalidArgumentException
271
+	 * @throws InvalidDataTypeException
272
+	 * @throws InvalidInterfaceException
273
+	 */
274
+	public function maybeSetDatetimeWarningNotice()
275
+	{
276
+		// add dismissable notice for datetime changes.  Only valid if site does not have a timezone_string set.
277
+		// @todo This needs to stay in core for a bit to catch anyone upgrading from a version without this to a version
278
+		// with this.  But after enough time (indeterminate at this point) we can just remove this notice.
279
+		// this was added with https://events.codebasehq.com/projects/event-espresso/tickets/10626
280
+		if (apply_filters('FHEE__EE_Admin__maybeSetDatetimeWarningNotice', true)
281
+			&& ! get_option('timezone_string')
282
+			&& EEM_Event::instance()->count() > 0
283
+		) {
284
+			new PersistentAdminNotice(
285
+				'datetime_fix_notice',
286
+				sprintf(
287
+					esc_html__(
288
+						'%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.',
289
+						'event_espresso'
290
+					),
291
+					'<strong>',
292
+					'</strong>',
293
+					'<a href="https://eventespresso.com/2017/08/important-upcoming-changes-dates-times">',
294
+					'</a>',
295
+					'<a href="' . EE_Admin_Page::add_query_args_and_nonce(
296
+						array(
297
+							'page'   => 'espresso_maintenance_settings',
298
+							'action' => 'datetime_tools',
299
+						),
300
+						admin_url('admin.php')
301
+					) . '">'
302
+				),
303
+				false,
304
+				'manage_options',
305
+				'datetime_fix_persistent_notice'
306
+			);
307
+		}
308
+	}
309
+
310
+
311
+	/**
312
+	 * this simply hooks into the nav menu setup of pages metabox and makes sure that we remove EE critical pages from
313
+	 * the list of options. the wp function "wp_nav_menu_item_post_type_meta_box" found in
314
+	 * wp-admin/includes/nav-menu.php looks for the "_default_query" property on the post_type object and it uses that
315
+	 * to override any queries found in the existing query for the given post type.  Note that _default_query is not a
316
+	 * normal property on the post_type object.  It's found ONLY in this particular context.
317
+	 *
318
+	 * @param WP_Post $post_type WP post type object
319
+	 * @return WP_Post
320
+	 * @throws InvalidArgumentException
321
+	 * @throws InvalidDataTypeException
322
+	 * @throws InvalidInterfaceException
323
+	 */
324
+	public function remove_pages_from_nav_menu($post_type)
325
+	{
326
+		// if this isn't the "pages" post type let's get out
327
+		if ($post_type->name !== 'page') {
328
+			return $post_type;
329
+		}
330
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
331
+		$post_type->_default_query = array(
332
+			'post__not_in' => $critical_pages,
333
+		);
334
+		return $post_type;
335
+	}
336
+
337
+
338
+	/**
339
+	 * WP by default only shows three metaboxes in "nav-menus.php" for first times users.  We want to make sure our
340
+	 * metaboxes get shown as well
341
+	 *
342
+	 * @return void
343
+	 */
344
+	public function enable_hidden_ee_nav_menu_metaboxes()
345
+	{
346
+		global $wp_meta_boxes, $pagenow;
347
+		if (! is_array($wp_meta_boxes) || $pagenow !== 'nav-menus.php') {
348
+			return;
349
+		}
350
+		$user = wp_get_current_user();
351
+		// has this been done yet?
352
+		if (get_user_option('ee_nav_menu_initialized', $user->ID)) {
353
+			return;
354
+		}
355
+
356
+		$hidden_meta_boxes = get_user_option('metaboxhidden_nav-menus', $user->ID);
357
+		$initial_meta_boxes = apply_filters(
358
+			'FHEE__EE_Admin__enable_hidden_ee_nav_menu_boxes__initial_meta_boxes',
359
+			array(
360
+				'nav-menu-theme-locations',
361
+				'add-page',
362
+				'add-custom-links',
363
+				'add-category',
364
+				'add-espresso_events',
365
+				'add-espresso_venues',
366
+				'add-espresso_event_categories',
367
+				'add-espresso_venue_categories',
368
+				'add-post-type-post',
369
+				'add-post-type-page',
370
+			)
371
+		);
372
+
373
+		if (is_array($hidden_meta_boxes)) {
374
+			foreach ($hidden_meta_boxes as $key => $meta_box_id) {
375
+				if (in_array($meta_box_id, $initial_meta_boxes, true)) {
376
+					unset($hidden_meta_boxes[ $key ]);
377
+				}
378
+			}
379
+		}
380
+		update_user_option($user->ID, 'metaboxhidden_nav-menus', $hidden_meta_boxes, true);
381
+		update_user_option($user->ID, 'ee_nav_menu_initialized', 1, true);
382
+	}
383
+
384
+
385
+	/**
386
+	 * This method simply registers custom nav menu boxes for "nav_menus.php route"
387
+	 * Currently EE is using this to make sure there are menu options for our CPT archive page routes.
388
+	 *
389
+	 * @todo   modify this so its more dynamic and automatic for all ee CPTs and setups and can also be hooked into by
390
+	 *         addons etc.
391
+	 * @return void
392
+	 */
393
+	public function register_custom_nav_menu_boxes()
394
+	{
395
+		add_meta_box(
396
+			'add-extra-nav-menu-pages',
397
+			esc_html__('Event Espresso Pages', 'event_espresso'),
398
+			array($this, 'ee_cpt_archive_pages'),
399
+			'nav-menus',
400
+			'side',
401
+			'core'
402
+		);
403
+	}
404
+
405
+
406
+	/**
407
+	 * Use this to edit the post link for our cpts so that the edit link points to the correct page.
408
+	 *
409
+	 * @since   4.3.0
410
+	 * @param string $link the original link generated by wp
411
+	 * @param int    $id   post id
412
+	 * @return string  the (maybe) modified link
413
+	 */
414
+	public function modify_edit_post_link($link, $id)
415
+	{
416
+		if (! $post = get_post($id)) {
417
+			return $link;
418
+		}
419
+		if ($post->post_type === 'espresso_attendees') {
420
+			$query_args = array(
421
+				'action' => 'edit_attendee',
422
+				'post'   => $id,
423
+			);
424
+			return EEH_URL::add_query_args_and_nonce(
425
+				$query_args,
426
+				admin_url('admin.php?page=espresso_registrations')
427
+			);
428
+		}
429
+		return $link;
430
+	}
431
+
432
+
433
+	public function ee_cpt_archive_pages()
434
+	{
435
+		global $nav_menu_selected_id;
436
+		$db_fields = false;
437
+		$walker = new Walker_Nav_Menu_Checklist($db_fields);
438
+		$current_tab = 'event-archives';
439
+		$removed_args = array(
440
+			'action',
441
+			'customlink-tab',
442
+			'edit-menu-item',
443
+			'menu-item',
444
+			'page-tab',
445
+			'_wpnonce',
446
+		);
447
+		?>
448 448
         <div id="posttype-extra-nav-menu-pages" class="posttypediv">
449 449
             <ul id="posttype-extra-nav-menu-pages-tabs" class="posttype-tabs add-menu-item-tabs">
450 450
                 <li <?php echo('event-archives' === $current_tab ? ' class="tabs"' : ''); ?>>
451 451
                     <a class="nav-tab-link" data-type="tabs-panel-posttype-extra-nav-menu-pages-event-archives"
452 452
                        href="<?php
453
-                        if ($nav_menu_selected_id) {
454
-                            echo esc_url(
455
-                                add_query_arg(
456
-                                    'extra-nav-menu-pages-tab',
457
-                                    'event-archives',
458
-                                    remove_query_arg($removed_args)
459
-                                )
460
-                            );
461
-                        }
462
-                        ?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
453
+						if ($nav_menu_selected_id) {
454
+							echo esc_url(
455
+								add_query_arg(
456
+									'extra-nav-menu-pages-tab',
457
+									'event-archives',
458
+									remove_query_arg($removed_args)
459
+								)
460
+							);
461
+						}
462
+						?>#tabs-panel-posttype-extra-nav-menu-pages-event-archives">
463 463
                         <?php esc_html_e('Event Archive Pages', 'event_espresso'); ?>
464 464
                     </a>
465 465
                 </li>
466 466
             </ul><!-- .posttype-tabs -->
467 467
 
468 468
             <div id="tabs-panel-posttype-extra-nav-menu-pages-event-archives" class="tabs-panel <?php
469
-            echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
470
-            ?>">
469
+			echo('event-archives' === $current_tab ? 'tabs-panel-active' : 'tabs-panel-inactive');
470
+			?>">
471 471
                 <ul id="extra-nav-menu-pageschecklist-event-archives" class="categorychecklist form-no-clear">
472 472
                     <?php
473
-                    $pages = $this->_get_extra_nav_menu_pages_items();
474
-                    $args['walker'] = $walker;
475
-                    echo walk_nav_menu_tree(
476
-                        array_map(
477
-                            array($this, '_setup_extra_nav_menu_pages_items'),
478
-                            $pages
479
-                        ),
480
-                        0,
481
-                        (object) $args
482
-                    );
483
-                    ?>
473
+					$pages = $this->_get_extra_nav_menu_pages_items();
474
+					$args['walker'] = $walker;
475
+					echo walk_nav_menu_tree(
476
+						array_map(
477
+							array($this, '_setup_extra_nav_menu_pages_items'),
478
+							$pages
479
+						),
480
+						0,
481
+						(object) $args
482
+					);
483
+					?>
484 484
                 </ul>
485 485
             </div><!-- /.tabs-panel -->
486 486
 
487 487
             <p class="button-controls">
488 488
                 <span class="list-controls">
489 489
                     <a href="<?php
490
-                             echo esc_url(
491
-                                 add_query_arg(
492
-                                     array(
493
-                                         'extra-nav-menu-pages-tab' => 'event-archives',
494
-                                         'selectall'                => 1,
495
-                                     ),
496
-                                     remove_query_arg($removed_args)
497
-                                 )
498
-                             );
499
-                        ?>#posttype-extra-nav-menu-pages" class="select-all"><?php esc_html_e('Select All', 'event_espresso'); ?></a>
490
+							 echo esc_url(
491
+								 add_query_arg(
492
+									 array(
493
+										 'extra-nav-menu-pages-tab' => 'event-archives',
494
+										 'selectall'                => 1,
495
+									 ),
496
+									 remove_query_arg($removed_args)
497
+								 )
498
+							 );
499
+						?>#posttype-extra-nav-menu-pages" class="select-all"><?php esc_html_e('Select All', 'event_espresso'); ?></a>
500 500
                 </span>
501 501
                 <span class="add-to-menu">
502 502
                     <input type="submit"<?php wp_nav_menu_disabled_check($nav_menu_selected_id); ?>
@@ -509,567 +509,567 @@  discard block
 block discarded – undo
509 509
 
510 510
         </div><!-- /.posttypediv -->
511 511
         <?php
512
-    }
513
-
514
-
515
-    /**
516
-     * Returns an array of event archive nav items.
517
-     *
518
-     * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
519
-     *        method we use for getting the extra nav menu items
520
-     * @return array
521
-     */
522
-    private function _get_extra_nav_menu_pages_items()
523
-    {
524
-        $menuitems[] = array(
525
-            'title'       => esc_html__('Event List', 'event_espresso'),
526
-            'url'         => get_post_type_archive_link('espresso_events'),
527
-            'description' => esc_html__('Archive page for all events.', 'event_espresso'),
528
-        );
529
-        return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
530
-    }
531
-
532
-
533
-    /**
534
-     * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
535
-     * the properties and converts it to the menu item object.
536
-     *
537
-     * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
538
-     * @param $menu_item_values
539
-     * @return stdClass
540
-     */
541
-    private function _setup_extra_nav_menu_pages_items($menu_item_values)
542
-    {
543
-        $menu_item = new stdClass();
544
-        $keys = array(
545
-            'ID'               => 0,
546
-            'db_id'            => 0,
547
-            'menu_item_parent' => 0,
548
-            'object_id'        => -1,
549
-            'post_parent'      => 0,
550
-            'type'             => 'custom',
551
-            'object'           => '',
552
-            'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
553
-            'title'            => '',
554
-            'url'              => '',
555
-            'target'           => '',
556
-            'attr_title'       => '',
557
-            'description'      => '',
558
-            'classes'          => array(),
559
-            'xfn'              => '',
560
-        );
561
-
562
-        foreach ($keys as $key => $value) {
563
-            $menu_item->{$key} = isset($menu_item_values[ $key ]) ? $menu_item_values[ $key ] : $value;
564
-        }
565
-        return $menu_item;
566
-    }
567
-
568
-
569
-    /**
570
-     * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
571
-     * EE_Admin_Page route is called.
572
-     *
573
-     * @return void
574
-     */
575
-    public function route_admin_request()
576
-    {
577
-    }
578
-
579
-
580
-    /**
581
-     * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
582
-     *
583
-     * @return void
584
-     */
585
-    public function wp_loaded()
586
-    {
587
-    }
588
-
589
-
590
-    /**
591
-     * admin_init
592
-     *
593
-     * @return void
594
-     * @throws EE_Error
595
-     * @throws InvalidArgumentException
596
-     * @throws InvalidDataTypeException
597
-     * @throws InvalidInterfaceException
598
-     * @throws ReflectionException
599
-     */
600
-    public function admin_init()
601
-    {
602
-        /**
603
-         * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
604
-         * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
605
-         * - check if doing post processing.
606
-         * - check if doing post processing of one of EE CPTs
607
-         * - instantiate the corresponding EE CPT model for the post_type being processed.
608
-         */
609
-        if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
610
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
611
-            $custom_post_types = $this->getLoader()->getShared(
612
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
613
-            );
614
-            $custom_post_types->getCustomPostTypeModels($_POST['post_type']);
615
-        }
616
-
617
-
618
-        /**
619
-         * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
620
-         * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
621
-         * Pages" tab in the EE General Settings Admin page.
622
-         * This is for user-proofing.
623
-         */
624
-        add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
625
-        if (EE_Maintenance_Mode::instance()->models_can_query()) {
626
-            $this->adminInitModelsReady();
627
-        }
628
-    }
629
-
630
-
631
-    /**
632
-     * Runs on admin_init but only if models are usable (ie, we're not in maintenanc emode)
633
-     */
634
-    protected function adminInitModelsReady()
635
-    {
636
-        if (function_exists('wp_add_privacy_policy_content')) {
637
-            $this->getLoader()->getShared('EventEspresso\core\services\privacy\policy\PrivacyPolicyManager');
638
-        }
639
-    }
640
-
641
-
642
-    /**
643
-     * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
644
-     *
645
-     * @param string $output Current output.
646
-     * @return string
647
-     * @throws InvalidArgumentException
648
-     * @throws InvalidDataTypeException
649
-     * @throws InvalidInterfaceException
650
-     */
651
-    public function modify_dropdown_pages($output)
652
-    {
653
-        // get critical pages
654
-        $critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
655
-
656
-        // split current output by line break for easier parsing.
657
-        $split_output = explode("\n", $output);
658
-
659
-        // loop through to remove any critical pages from the array.
660
-        foreach ($critical_pages as $page_id) {
661
-            $needle = 'value="' . $page_id . '"';
662
-            foreach ($split_output as $key => $haystack) {
663
-                if (strpos($haystack, $needle) !== false) {
664
-                    unset($split_output[ $key ]);
665
-                }
666
-            }
667
-        }
668
-        // replace output with the new contents
669
-        return implode("\n", $split_output);
670
-    }
671
-
672
-
673
-    /**
674
-     * enqueue all admin scripts that need loaded for admin pages
675
-     *
676
-     * @return void
677
-     */
678
-    public function enqueue_admin_scripts()
679
-    {
680
-        // this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
681
-        // Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
682
-        // calls.
683
-        wp_enqueue_script(
684
-            'ee-inject-wp',
685
-            EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
686
-            array('jquery'),
687
-            EVENT_ESPRESSO_VERSION,
688
-            true
689
-        );
690
-        // register cookie script for future dependencies
691
-        wp_register_script(
692
-            'jquery-cookie',
693
-            EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
694
-            array('jquery'),
695
-            '2.1',
696
-            true
697
-        );
698
-        // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
699
-        // joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
700
-        // via: add_filter('FHEE_load_joyride', '__return_true' );
701
-        // if (apply_filters('FHEE_load_joyride', false)) {
702
-        //     // joyride style
703
-        //     wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
704
-        //     wp_register_style(
705
-        //         'ee-joyride-css',
706
-        //         EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
707
-        //         array('joyride-css'),
708
-        //         EVENT_ESPRESSO_VERSION
709
-        //     );
710
-        //     wp_register_script(
711
-        //         'joyride-modernizr',
712
-        //         EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
713
-        //         array(),
714
-        //         '2.1',
715
-        //         true
716
-        //     );
717
-        //     // joyride JS
718
-        //     wp_register_script(
719
-        //         'jquery-joyride',
720
-        //         EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
721
-        //         array('jquery-cookie', 'joyride-modernizr'),
722
-        //         '2.1',
723
-        //         true
724
-        //     );
725
-        //     // wanna go for a joyride?
726
-        //     wp_enqueue_style('ee-joyride-css');
727
-        //     wp_enqueue_script('jquery-joyride');
728
-        // }
729
-    }
730
-
731
-
732
-    /**
733
-     * display_admin_notices
734
-     *
735
-     * @return void
736
-     */
737
-    public function display_admin_notices()
738
-    {
739
-        echo EE_Error::get_notices();
740
-    }
741
-
742
-
743
-    /**
744
-     * @param array $elements
745
-     * @return array
746
-     * @throws EE_Error
747
-     * @throws InvalidArgumentException
748
-     * @throws InvalidDataTypeException
749
-     * @throws InvalidInterfaceException
750
-     */
751
-    public function dashboard_glance_items($elements)
752
-    {
753
-        $elements = is_array($elements) ? $elements : array($elements);
754
-        $events = EEM_Event::instance()->count();
755
-        $items['events']['url'] = EE_Admin_Page::add_query_args_and_nonce(
756
-            array('page' => 'espresso_events'),
757
-            admin_url('admin.php')
758
-        );
759
-        $items['events']['text'] = sprintf(
760
-            esc_html(
761
-                _n('%s Event', '%s Events', $events, 'event_espresso')
762
-            ),
763
-            number_format_i18n($events)
764
-        );
765
-        $items['events']['title'] = esc_html__('Click to view all Events', 'event_espresso');
766
-        $registrations = EEM_Registration::instance()->count(
767
-            array(
768
-                array(
769
-                    'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
770
-                ),
771
-            )
772
-        );
773
-        $items['registrations']['url'] = EE_Admin_Page::add_query_args_and_nonce(
774
-            array('page' => 'espresso_registrations'),
775
-            admin_url('admin.php')
776
-        );
777
-        $items['registrations']['text'] = sprintf(
778
-            esc_html(
779
-                _n('%s Registration', '%s Registrations', $registrations, 'event_espresso')
780
-            ),
781
-            number_format_i18n($registrations)
782
-        );
783
-        $items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
784
-
785
-        $items = (array) apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
786
-
787
-        foreach ($items as $type => $item_properties) {
788
-            $elements[] = sprintf(
789
-                '<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
790
-                $item_properties['url'],
791
-                $item_properties['title'],
792
-                $item_properties['text']
793
-            );
794
-        }
795
-        return $elements;
796
-    }
797
-
798
-
799
-    /**
800
-     * check_for_invalid_datetime_formats
801
-     * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
802
-     * their selected format can be parsed by PHP
803
-     *
804
-     * @param    $value
805
-     * @param    $option
806
-     * @throws EE_Error
807
-     * @return    string
808
-     */
809
-    public function check_for_invalid_datetime_formats($value, $option)
810
-    {
811
-        // check for date_format or time_format
812
-        switch ($option) {
813
-            case 'date_format':
814
-                $date_time_format = $value . ' ' . get_option('time_format');
815
-                break;
816
-            case 'time_format':
817
-                $date_time_format = get_option('date_format') . ' ' . $value;
818
-                break;
819
-            default:
820
-                $date_time_format = false;
821
-        }
822
-        // do we have a date_time format to check ?
823
-        if ($date_time_format) {
824
-            $error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
825
-
826
-            if (is_array($error_msg)) {
827
-                $msg = '<p>'
828
-                       . sprintf(
829
-                           esc_html__(
830
-                               'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
831
-                               'event_espresso'
832
-                           ),
833
-                           date($date_time_format),
834
-                           $date_time_format
835
-                       )
836
-                       . '</p><p><ul>';
837
-
838
-
839
-                foreach ($error_msg as $error) {
840
-                    $msg .= '<li>' . $error . '</li>';
841
-                }
842
-
843
-                $msg .= '</ul></p><p>'
844
-                        . sprintf(
845
-                            esc_html__(
846
-                                '%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
847
-                                'event_espresso'
848
-                            ),
849
-                            '<span style="color:#D54E21;">',
850
-                            '</span>'
851
-                        )
852
-                        . '</p>';
853
-
854
-                // trigger WP settings error
855
-                add_settings_error(
856
-                    'date_format',
857
-                    'date_format',
858
-                    $msg
859
-                );
860
-
861
-                // set format to something valid
862
-                switch ($option) {
863
-                    case 'date_format':
864
-                        $value = 'F j, Y';
865
-                        break;
866
-                    case 'time_format':
867
-                        $value = 'g:i a';
868
-                        break;
869
-                }
870
-            }
871
-        }
872
-        return $value;
873
-    }
874
-
875
-
876
-    /**
877
-     * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
878
-     *
879
-     * @param $content
880
-     * @return    string
881
-     */
882
-    public function its_eSpresso($content)
883
-    {
884
-        return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
885
-    }
886
-
887
-
888
-    /**
889
-     * espresso_admin_footer
890
-     *
891
-     * @return    string
892
-     */
893
-    public function espresso_admin_footer()
894
-    {
895
-        return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
896
-    }
897
-
898
-
899
-    /**
900
-     * static method for registering ee admin page.
901
-     * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
902
-     *
903
-     * @since      4.3.0
904
-     * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
905
-     * @see        EE_Register_Admin_Page::register()
906
-     * @param       $page_basename
907
-     * @param       $page_path
908
-     * @param array $config
909
-     * @return void
910
-     * @throws EE_Error
911
-     */
912
-    public static function register_ee_admin_page($page_basename, $page_path, $config = array())
913
-    {
914
-        EE_Error::doing_it_wrong(
915
-            __METHOD__,
916
-            sprintf(
917
-                esc_html__(
918
-                    'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
919
-                    'event_espresso'
920
-                ),
921
-                $page_basename
922
-            ),
923
-            '4.3'
924
-        );
925
-        if (class_exists('EE_Register_Admin_Page')) {
926
-            $config['page_path'] = $page_path;
927
-        }
928
-        EE_Register_Admin_Page::register($page_basename, $config);
929
-    }
930
-
931
-
932
-    /**
933
-     * @deprecated 4.8.41
934
-     * @param  int      $post_ID
935
-     * @param  \WP_Post $post
936
-     * @return void
937
-     */
938
-    public static function parse_post_content_on_save($post_ID, $post)
939
-    {
940
-        EE_Error::doing_it_wrong(
941
-            __METHOD__,
942
-            esc_html__('Usage is deprecated', 'event_espresso'),
943
-            '4.8.41'
944
-        );
945
-    }
946
-
947
-
948
-    /**
949
-     * @deprecated 4.8.41
950
-     * @param  $option
951
-     * @param  $old_value
952
-     * @param  $value
953
-     * @return void
954
-     */
955
-    public function reset_page_for_posts_on_change($option, $old_value, $value)
956
-    {
957
-        EE_Error::doing_it_wrong(
958
-            __METHOD__,
959
-            esc_html__('Usage is deprecated', 'event_espresso'),
960
-            '4.8.41'
961
-        );
962
-    }
963
-
964
-
965
-    /**
966
-     * @deprecated 4.9.27
967
-     * @return void
968
-     */
969
-    public function get_persistent_admin_notices()
970
-    {
971
-        EE_Error::doing_it_wrong(
972
-            __METHOD__,
973
-            sprintf(
974
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
975
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
976
-            ),
977
-            '4.9.27'
978
-        );
979
-    }
980
-
981
-
982
-    /**
983
-     * @deprecated 4.9.27
984
-     * @throws InvalidInterfaceException
985
-     * @throws InvalidDataTypeException
986
-     * @throws DomainException
987
-     */
988
-    public function dismiss_ee_nag_notice_callback()
989
-    {
990
-        EE_Error::doing_it_wrong(
991
-            __METHOD__,
992
-            sprintf(
993
-                esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
994
-                '\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
995
-            ),
996
-            '4.9.27'
997
-        );
998
-        $this->persistent_admin_notice_manager->dismissNotice();
999
-    }
1000
-
1001
-
1002
-    /**
1003
-     * Callback on load-plugins.php hook for setting up anything hooking into the wp plugins page.
1004
-     *
1005
-     * @throws InvalidArgumentException
1006
-     * @throws InvalidDataTypeException
1007
-     * @throws InvalidInterfaceException
1008
-     */
1009
-    public function hookIntoWpPluginsPage()
1010
-    {
1011
-        $this->getLoader()->getShared('EventEspresso\core\domain\services\admin\ExitModal');
1012
-        $this->getLoader()
1013
-                     ->getShared('EventEspresso\core\domain\services\admin\PluginUpsells')
1014
-                     ->decafUpsells();
1015
-    }
1016
-
1017
-
1018
-    /**
1019
-     * Hooks into the "post states" filter in a wp post type list table.
1020
-     *
1021
-     * @param array   $post_states
1022
-     * @param WP_Post $post
1023
-     * @return array
1024
-     * @throws InvalidArgumentException
1025
-     * @throws InvalidDataTypeException
1026
-     * @throws InvalidInterfaceException
1027
-     */
1028
-    public function displayStateForCriticalPages($post_states, $post)
1029
-    {
1030
-        $post_states = (array) $post_states;
1031
-        if (! $post instanceof WP_Post || $post->post_type !== 'page') {
1032
-            return $post_states;
1033
-        }
1034
-        /** @var EE_Core_Config $config */
1035
-        $config = $this->getLoader()->getShared('EE_Config')->core;
1036
-        if (in_array($post->ID, $config->get_critical_pages_array(), true)) {
1037
-            $post_states[] = sprintf(
1038
-                /* Translators: Using company name - Event Espresso Critical Page */
1039
-                esc_html__('%s Critical Page', 'event_espresso'),
1040
-                'Event Espresso'
1041
-            );
1042
-        }
1043
-        return $post_states;
1044
-    }
1045
-
1046
-
1047
-    /**
1048
-     * Show documentation links on the plugins page
1049
-     *
1050
-     * @param mixed $meta Plugin Row Meta
1051
-     * @param mixed $file Plugin Base file
1052
-     * @return array
1053
-     */
1054
-    public function addLinksToPluginRowMeta($meta, $file)
1055
-    {
1056
-        if (EE_PLUGIN_BASENAME === $file) {
1057
-            $row_meta = array(
1058
-                'docs' => '<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4"'
1059
-                          . ' aria-label="'
1060
-                          . esc_attr__('View Event Espresso documentation', 'event_espresso')
1061
-                          . '">'
1062
-                          . esc_html__('Docs', 'event_espresso')
1063
-                          . '</a>',
1064
-                'api'  => '<a href="https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API"'
1065
-                          . ' aria-label="'
1066
-                          . esc_attr__('View Event Espresso API docs', 'event_espresso')
1067
-                          . '">'
1068
-                          . esc_html__('API docs', 'event_espresso')
1069
-                          . '</a>',
1070
-            );
1071
-            return array_merge($meta, $row_meta);
1072
-        }
1073
-        return (array) $meta;
1074
-    }
512
+	}
513
+
514
+
515
+	/**
516
+	 * Returns an array of event archive nav items.
517
+	 *
518
+	 * @todo  for now this method is just in place so when it gets abstracted further we can substitute in whatever
519
+	 *        method we use for getting the extra nav menu items
520
+	 * @return array
521
+	 */
522
+	private function _get_extra_nav_menu_pages_items()
523
+	{
524
+		$menuitems[] = array(
525
+			'title'       => esc_html__('Event List', 'event_espresso'),
526
+			'url'         => get_post_type_archive_link('espresso_events'),
527
+			'description' => esc_html__('Archive page for all events.', 'event_espresso'),
528
+		);
529
+		return apply_filters('FHEE__EE_Admin__get_extra_nav_menu_pages_items', $menuitems);
530
+	}
531
+
532
+
533
+	/**
534
+	 * Setup nav menu walker item for usage in the event archive nav menu metabox.  It receives a menu_item array with
535
+	 * the properties and converts it to the menu item object.
536
+	 *
537
+	 * @see wp_setup_nav_menu_item() in wp-includes/nav-menu.php
538
+	 * @param $menu_item_values
539
+	 * @return stdClass
540
+	 */
541
+	private function _setup_extra_nav_menu_pages_items($menu_item_values)
542
+	{
543
+		$menu_item = new stdClass();
544
+		$keys = array(
545
+			'ID'               => 0,
546
+			'db_id'            => 0,
547
+			'menu_item_parent' => 0,
548
+			'object_id'        => -1,
549
+			'post_parent'      => 0,
550
+			'type'             => 'custom',
551
+			'object'           => '',
552
+			'type_label'       => esc_html__('Extra Nav Menu Item', 'event_espresso'),
553
+			'title'            => '',
554
+			'url'              => '',
555
+			'target'           => '',
556
+			'attr_title'       => '',
557
+			'description'      => '',
558
+			'classes'          => array(),
559
+			'xfn'              => '',
560
+		);
561
+
562
+		foreach ($keys as $key => $value) {
563
+			$menu_item->{$key} = isset($menu_item_values[ $key ]) ? $menu_item_values[ $key ] : $value;
564
+		}
565
+		return $menu_item;
566
+	}
567
+
568
+
569
+	/**
570
+	 * This is the action hook for the AHEE__EE_Admin_Page__route_admin_request hook that fires off right before an
571
+	 * EE_Admin_Page route is called.
572
+	 *
573
+	 * @return void
574
+	 */
575
+	public function route_admin_request()
576
+	{
577
+	}
578
+
579
+
580
+	/**
581
+	 * wp_loaded should fire on the WordPress wp_loaded hook.  This fires on a VERY late priority.
582
+	 *
583
+	 * @return void
584
+	 */
585
+	public function wp_loaded()
586
+	{
587
+	}
588
+
589
+
590
+	/**
591
+	 * admin_init
592
+	 *
593
+	 * @return void
594
+	 * @throws EE_Error
595
+	 * @throws InvalidArgumentException
596
+	 * @throws InvalidDataTypeException
597
+	 * @throws InvalidInterfaceException
598
+	 * @throws ReflectionException
599
+	 */
600
+	public function admin_init()
601
+	{
602
+		/**
603
+		 * our cpt models must be instantiated on WordPress post processing routes (wp-admin/post.php),
604
+		 * so any hooking into core WP routes is taken care of.  So in this next few lines of code:
605
+		 * - check if doing post processing.
606
+		 * - check if doing post processing of one of EE CPTs
607
+		 * - instantiate the corresponding EE CPT model for the post_type being processed.
608
+		 */
609
+		if (isset($_POST['action'], $_POST['post_type']) && $_POST['action'] === 'editpost') {
610
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
611
+			$custom_post_types = $this->getLoader()->getShared(
612
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
613
+			);
614
+			$custom_post_types->getCustomPostTypeModels($_POST['post_type']);
615
+		}
616
+
617
+
618
+		/**
619
+		 * This code excludes EE critical pages anywhere `wp_dropdown_pages` is used to create a dropdown for selecting
620
+		 * critical pages.  The only place critical pages need included in a generated dropdown is on the "Critical
621
+		 * Pages" tab in the EE General Settings Admin page.
622
+		 * This is for user-proofing.
623
+		 */
624
+		add_filter('wp_dropdown_pages', array($this, 'modify_dropdown_pages'));
625
+		if (EE_Maintenance_Mode::instance()->models_can_query()) {
626
+			$this->adminInitModelsReady();
627
+		}
628
+	}
629
+
630
+
631
+	/**
632
+	 * Runs on admin_init but only if models are usable (ie, we're not in maintenanc emode)
633
+	 */
634
+	protected function adminInitModelsReady()
635
+	{
636
+		if (function_exists('wp_add_privacy_policy_content')) {
637
+			$this->getLoader()->getShared('EventEspresso\core\services\privacy\policy\PrivacyPolicyManager');
638
+		}
639
+	}
640
+
641
+
642
+	/**
643
+	 * Callback for wp_dropdown_pages hook to remove ee critical pages from the dropdown selection.
644
+	 *
645
+	 * @param string $output Current output.
646
+	 * @return string
647
+	 * @throws InvalidArgumentException
648
+	 * @throws InvalidDataTypeException
649
+	 * @throws InvalidInterfaceException
650
+	 */
651
+	public function modify_dropdown_pages($output)
652
+	{
653
+		// get critical pages
654
+		$critical_pages = EE_Registry::instance()->CFG->core->get_critical_pages_array();
655
+
656
+		// split current output by line break for easier parsing.
657
+		$split_output = explode("\n", $output);
658
+
659
+		// loop through to remove any critical pages from the array.
660
+		foreach ($critical_pages as $page_id) {
661
+			$needle = 'value="' . $page_id . '"';
662
+			foreach ($split_output as $key => $haystack) {
663
+				if (strpos($haystack, $needle) !== false) {
664
+					unset($split_output[ $key ]);
665
+				}
666
+			}
667
+		}
668
+		// replace output with the new contents
669
+		return implode("\n", $split_output);
670
+	}
671
+
672
+
673
+	/**
674
+	 * enqueue all admin scripts that need loaded for admin pages
675
+	 *
676
+	 * @return void
677
+	 */
678
+	public function enqueue_admin_scripts()
679
+	{
680
+		// this javascript is loaded on every admin page to catch any injections ee needs to add to wp run js.
681
+		// Note: the intention of this script is to only do TARGETED injections.  I.E, only injecting on certain script
682
+		// calls.
683
+		wp_enqueue_script(
684
+			'ee-inject-wp',
685
+			EE_ADMIN_URL . 'assets/ee-cpt-wp-injects.js',
686
+			array('jquery'),
687
+			EVENT_ESPRESSO_VERSION,
688
+			true
689
+		);
690
+		// register cookie script for future dependencies
691
+		wp_register_script(
692
+			'jquery-cookie',
693
+			EE_THIRD_PARTY_URL . 'joyride/jquery.cookie.js',
694
+			array('jquery'),
695
+			'2.1',
696
+			true
697
+		);
698
+		// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
699
+		// joyride is turned OFF by default, but prior to the admin_enqueue_scripts hook, can be turned back on again
700
+		// via: add_filter('FHEE_load_joyride', '__return_true' );
701
+		// if (apply_filters('FHEE_load_joyride', false)) {
702
+		//     // joyride style
703
+		//     wp_register_style('joyride-css', EE_THIRD_PARTY_URL . 'joyride/joyride-2.1.css', array(), '2.1');
704
+		//     wp_register_style(
705
+		//         'ee-joyride-css',
706
+		//         EE_GLOBAL_ASSETS_URL . 'css/ee-joyride-styles.css',
707
+		//         array('joyride-css'),
708
+		//         EVENT_ESPRESSO_VERSION
709
+		//     );
710
+		//     wp_register_script(
711
+		//         'joyride-modernizr',
712
+		//         EE_THIRD_PARTY_URL . 'joyride/modernizr.mq.js',
713
+		//         array(),
714
+		//         '2.1',
715
+		//         true
716
+		//     );
717
+		//     // joyride JS
718
+		//     wp_register_script(
719
+		//         'jquery-joyride',
720
+		//         EE_THIRD_PARTY_URL . 'joyride/jquery.joyride-2.1.js',
721
+		//         array('jquery-cookie', 'joyride-modernizr'),
722
+		//         '2.1',
723
+		//         true
724
+		//     );
725
+		//     // wanna go for a joyride?
726
+		//     wp_enqueue_style('ee-joyride-css');
727
+		//     wp_enqueue_script('jquery-joyride');
728
+		// }
729
+	}
730
+
731
+
732
+	/**
733
+	 * display_admin_notices
734
+	 *
735
+	 * @return void
736
+	 */
737
+	public function display_admin_notices()
738
+	{
739
+		echo EE_Error::get_notices();
740
+	}
741
+
742
+
743
+	/**
744
+	 * @param array $elements
745
+	 * @return array
746
+	 * @throws EE_Error
747
+	 * @throws InvalidArgumentException
748
+	 * @throws InvalidDataTypeException
749
+	 * @throws InvalidInterfaceException
750
+	 */
751
+	public function dashboard_glance_items($elements)
752
+	{
753
+		$elements = is_array($elements) ? $elements : array($elements);
754
+		$events = EEM_Event::instance()->count();
755
+		$items['events']['url'] = EE_Admin_Page::add_query_args_and_nonce(
756
+			array('page' => 'espresso_events'),
757
+			admin_url('admin.php')
758
+		);
759
+		$items['events']['text'] = sprintf(
760
+			esc_html(
761
+				_n('%s Event', '%s Events', $events, 'event_espresso')
762
+			),
763
+			number_format_i18n($events)
764
+		);
765
+		$items['events']['title'] = esc_html__('Click to view all Events', 'event_espresso');
766
+		$registrations = EEM_Registration::instance()->count(
767
+			array(
768
+				array(
769
+					'STS_ID' => array('!=', EEM_Registration::status_id_incomplete),
770
+				),
771
+			)
772
+		);
773
+		$items['registrations']['url'] = EE_Admin_Page::add_query_args_and_nonce(
774
+			array('page' => 'espresso_registrations'),
775
+			admin_url('admin.php')
776
+		);
777
+		$items['registrations']['text'] = sprintf(
778
+			esc_html(
779
+				_n('%s Registration', '%s Registrations', $registrations, 'event_espresso')
780
+			),
781
+			number_format_i18n($registrations)
782
+		);
783
+		$items['registrations']['title'] = esc_html__('Click to view all registrations', 'event_espresso');
784
+
785
+		$items = (array) apply_filters('FHEE__EE_Admin__dashboard_glance_items__items', $items);
786
+
787
+		foreach ($items as $type => $item_properties) {
788
+			$elements[] = sprintf(
789
+				'<a class="ee-dashboard-link-' . $type . '" href="%s" title="%s">%s</a>',
790
+				$item_properties['url'],
791
+				$item_properties['title'],
792
+				$item_properties['text']
793
+			);
794
+		}
795
+		return $elements;
796
+	}
797
+
798
+
799
+	/**
800
+	 * check_for_invalid_datetime_formats
801
+	 * if an admin changes their date or time format settings on the WP General Settings admin page, verify that
802
+	 * their selected format can be parsed by PHP
803
+	 *
804
+	 * @param    $value
805
+	 * @param    $option
806
+	 * @throws EE_Error
807
+	 * @return    string
808
+	 */
809
+	public function check_for_invalid_datetime_formats($value, $option)
810
+	{
811
+		// check for date_format or time_format
812
+		switch ($option) {
813
+			case 'date_format':
814
+				$date_time_format = $value . ' ' . get_option('time_format');
815
+				break;
816
+			case 'time_format':
817
+				$date_time_format = get_option('date_format') . ' ' . $value;
818
+				break;
819
+			default:
820
+				$date_time_format = false;
821
+		}
822
+		// do we have a date_time format to check ?
823
+		if ($date_time_format) {
824
+			$error_msg = EEH_DTT_Helper::validate_format_string($date_time_format);
825
+
826
+			if (is_array($error_msg)) {
827
+				$msg = '<p>'
828
+					   . sprintf(
829
+						   esc_html__(
830
+							   'The following date time "%s" ( %s ) is difficult to be properly parsed by PHP for the following reasons:',
831
+							   'event_espresso'
832
+						   ),
833
+						   date($date_time_format),
834
+						   $date_time_format
835
+					   )
836
+					   . '</p><p><ul>';
837
+
838
+
839
+				foreach ($error_msg as $error) {
840
+					$msg .= '<li>' . $error . '</li>';
841
+				}
842
+
843
+				$msg .= '</ul></p><p>'
844
+						. sprintf(
845
+							esc_html__(
846
+								'%sPlease note that your date and time formats have been reset to "F j, Y" and "g:i a" respectively.%s',
847
+								'event_espresso'
848
+							),
849
+							'<span style="color:#D54E21;">',
850
+							'</span>'
851
+						)
852
+						. '</p>';
853
+
854
+				// trigger WP settings error
855
+				add_settings_error(
856
+					'date_format',
857
+					'date_format',
858
+					$msg
859
+				);
860
+
861
+				// set format to something valid
862
+				switch ($option) {
863
+					case 'date_format':
864
+						$value = 'F j, Y';
865
+						break;
866
+					case 'time_format':
867
+						$value = 'g:i a';
868
+						break;
869
+				}
870
+			}
871
+		}
872
+		return $value;
873
+	}
874
+
875
+
876
+	/**
877
+	 * its_eSpresso - converts the less commonly used spelling of "Expresso" to "Espresso"
878
+	 *
879
+	 * @param $content
880
+	 * @return    string
881
+	 */
882
+	public function its_eSpresso($content)
883
+	{
884
+		return str_replace('[EXPRESSO_', '[ESPRESSO_', $content);
885
+	}
886
+
887
+
888
+	/**
889
+	 * espresso_admin_footer
890
+	 *
891
+	 * @return    string
892
+	 */
893
+	public function espresso_admin_footer()
894
+	{
895
+		return \EEH_Template::powered_by_event_espresso('aln-cntr', '', array('utm_content' => 'admin_footer'));
896
+	}
897
+
898
+
899
+	/**
900
+	 * static method for registering ee admin page.
901
+	 * This method is deprecated in favor of the new location in EE_Register_Admin_Page::register.
902
+	 *
903
+	 * @since      4.3.0
904
+	 * @deprecated 4.3.0    Use EE_Register_Admin_Page::register() instead
905
+	 * @see        EE_Register_Admin_Page::register()
906
+	 * @param       $page_basename
907
+	 * @param       $page_path
908
+	 * @param array $config
909
+	 * @return void
910
+	 * @throws EE_Error
911
+	 */
912
+	public static function register_ee_admin_page($page_basename, $page_path, $config = array())
913
+	{
914
+		EE_Error::doing_it_wrong(
915
+			__METHOD__,
916
+			sprintf(
917
+				esc_html__(
918
+					'Usage is deprecated.  Use EE_Register_Admin_Page::register() for registering the %s admin page.',
919
+					'event_espresso'
920
+				),
921
+				$page_basename
922
+			),
923
+			'4.3'
924
+		);
925
+		if (class_exists('EE_Register_Admin_Page')) {
926
+			$config['page_path'] = $page_path;
927
+		}
928
+		EE_Register_Admin_Page::register($page_basename, $config);
929
+	}
930
+
931
+
932
+	/**
933
+	 * @deprecated 4.8.41
934
+	 * @param  int      $post_ID
935
+	 * @param  \WP_Post $post
936
+	 * @return void
937
+	 */
938
+	public static function parse_post_content_on_save($post_ID, $post)
939
+	{
940
+		EE_Error::doing_it_wrong(
941
+			__METHOD__,
942
+			esc_html__('Usage is deprecated', 'event_espresso'),
943
+			'4.8.41'
944
+		);
945
+	}
946
+
947
+
948
+	/**
949
+	 * @deprecated 4.8.41
950
+	 * @param  $option
951
+	 * @param  $old_value
952
+	 * @param  $value
953
+	 * @return void
954
+	 */
955
+	public function reset_page_for_posts_on_change($option, $old_value, $value)
956
+	{
957
+		EE_Error::doing_it_wrong(
958
+			__METHOD__,
959
+			esc_html__('Usage is deprecated', 'event_espresso'),
960
+			'4.8.41'
961
+		);
962
+	}
963
+
964
+
965
+	/**
966
+	 * @deprecated 4.9.27
967
+	 * @return void
968
+	 */
969
+	public function get_persistent_admin_notices()
970
+	{
971
+		EE_Error::doing_it_wrong(
972
+			__METHOD__,
973
+			sprintf(
974
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
975
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
976
+			),
977
+			'4.9.27'
978
+		);
979
+	}
980
+
981
+
982
+	/**
983
+	 * @deprecated 4.9.27
984
+	 * @throws InvalidInterfaceException
985
+	 * @throws InvalidDataTypeException
986
+	 * @throws DomainException
987
+	 */
988
+	public function dismiss_ee_nag_notice_callback()
989
+	{
990
+		EE_Error::doing_it_wrong(
991
+			__METHOD__,
992
+			sprintf(
993
+				esc_html__('Usage is deprecated. Use "%1$s" instead.', 'event_espresso'),
994
+				'\EventEspresso\core\services\notifications\PersistentAdminNoticeManager'
995
+			),
996
+			'4.9.27'
997
+		);
998
+		$this->persistent_admin_notice_manager->dismissNotice();
999
+	}
1000
+
1001
+
1002
+	/**
1003
+	 * Callback on load-plugins.php hook for setting up anything hooking into the wp plugins page.
1004
+	 *
1005
+	 * @throws InvalidArgumentException
1006
+	 * @throws InvalidDataTypeException
1007
+	 * @throws InvalidInterfaceException
1008
+	 */
1009
+	public function hookIntoWpPluginsPage()
1010
+	{
1011
+		$this->getLoader()->getShared('EventEspresso\core\domain\services\admin\ExitModal');
1012
+		$this->getLoader()
1013
+					 ->getShared('EventEspresso\core\domain\services\admin\PluginUpsells')
1014
+					 ->decafUpsells();
1015
+	}
1016
+
1017
+
1018
+	/**
1019
+	 * Hooks into the "post states" filter in a wp post type list table.
1020
+	 *
1021
+	 * @param array   $post_states
1022
+	 * @param WP_Post $post
1023
+	 * @return array
1024
+	 * @throws InvalidArgumentException
1025
+	 * @throws InvalidDataTypeException
1026
+	 * @throws InvalidInterfaceException
1027
+	 */
1028
+	public function displayStateForCriticalPages($post_states, $post)
1029
+	{
1030
+		$post_states = (array) $post_states;
1031
+		if (! $post instanceof WP_Post || $post->post_type !== 'page') {
1032
+			return $post_states;
1033
+		}
1034
+		/** @var EE_Core_Config $config */
1035
+		$config = $this->getLoader()->getShared('EE_Config')->core;
1036
+		if (in_array($post->ID, $config->get_critical_pages_array(), true)) {
1037
+			$post_states[] = sprintf(
1038
+				/* Translators: Using company name - Event Espresso Critical Page */
1039
+				esc_html__('%s Critical Page', 'event_espresso'),
1040
+				'Event Espresso'
1041
+			);
1042
+		}
1043
+		return $post_states;
1044
+	}
1045
+
1046
+
1047
+	/**
1048
+	 * Show documentation links on the plugins page
1049
+	 *
1050
+	 * @param mixed $meta Plugin Row Meta
1051
+	 * @param mixed $file Plugin Base file
1052
+	 * @return array
1053
+	 */
1054
+	public function addLinksToPluginRowMeta($meta, $file)
1055
+	{
1056
+		if (EE_PLUGIN_BASENAME === $file) {
1057
+			$row_meta = array(
1058
+				'docs' => '<a href="https://eventespresso.com/support/documentation/versioned-docs/?doc_ver=ee4"'
1059
+						  . ' aria-label="'
1060
+						  . esc_attr__('View Event Espresso documentation', 'event_espresso')
1061
+						  . '">'
1062
+						  . esc_html__('Docs', 'event_espresso')
1063
+						  . '</a>',
1064
+				'api'  => '<a href="https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API"'
1065
+						  . ' aria-label="'
1066
+						  . esc_attr__('View Event Espresso API docs', 'event_espresso')
1067
+						  . '">'
1068
+						  . esc_html__('API docs', 'event_espresso')
1069
+						  . '</a>',
1070
+			);
1071
+			return array_merge($meta, $row_meta);
1072
+		}
1073
+		return (array) $meta;
1074
+	}
1075 1075
 }
Please login to merge, or discard this patch.
core/admin/EE_Admin_Page.core.php 2 patches
Indentation   +4064 added lines, -4064 removed lines patch added patch discarded remove patch
@@ -18,4133 +18,4133 @@
 block discarded – undo
18 18
 abstract class EE_Admin_Page extends EE_Base implements InterminableInterface
19 19
 {
20 20
 
21
-    /**
22
-     * @var LoaderInterface
23
-     */
24
-    protected $loader;
21
+	/**
22
+	 * @var LoaderInterface
23
+	 */
24
+	protected $loader;
25 25
 
26
-    /**
27
-     * @var RequestInterface
28
-     */
29
-    protected $request;
26
+	/**
27
+	 * @var RequestInterface
28
+	 */
29
+	protected $request;
30 30
 
31
-    // set in _init_page_props()
32
-    public $page_slug;
31
+	// set in _init_page_props()
32
+	public $page_slug;
33 33
 
34
-    public $page_label;
34
+	public $page_label;
35 35
 
36
-    public $page_folder;
36
+	public $page_folder;
37 37
 
38
-    // set in define_page_props()
39
-    protected $_admin_base_url;
38
+	// set in define_page_props()
39
+	protected $_admin_base_url;
40 40
 
41
-    protected $_admin_base_path;
41
+	protected $_admin_base_path;
42 42
 
43
-    protected $_admin_page_title;
43
+	protected $_admin_page_title;
44 44
 
45
-    protected $_labels;
45
+	protected $_labels;
46 46
 
47 47
 
48
-    // set early within EE_Admin_Init
49
-    protected $_wp_page_slug;
48
+	// set early within EE_Admin_Init
49
+	protected $_wp_page_slug;
50 50
 
51
-    // navtabs
52
-    protected $_nav_tabs;
51
+	// navtabs
52
+	protected $_nav_tabs;
53 53
 
54
-    protected $_default_nav_tab_name;
54
+	protected $_default_nav_tab_name;
55 55
 
56
-    /**
57
-     * @var array $_help_tour
58
-     */
59
-    protected $_help_tour = [];
56
+	/**
57
+	 * @var array $_help_tour
58
+	 */
59
+	protected $_help_tour = [];
60 60
 
61 61
 
62
-    // template variables (used by templates)
63
-    protected $_template_path;
62
+	// template variables (used by templates)
63
+	protected $_template_path;
64 64
 
65
-    protected $_column_template_path;
65
+	protected $_column_template_path;
66 66
 
67
-    /**
68
-     * @var array $_template_args
69
-     */
70
-    protected $_template_args = [];
67
+	/**
68
+	 * @var array $_template_args
69
+	 */
70
+	protected $_template_args = [];
71 71
 
72
-    /**
73
-     * this will hold the list table object for a given view.
74
-     *
75
-     * @var EE_Admin_List_Table $_list_table_object
76
-     */
77
-    protected $_list_table_object;
72
+	/**
73
+	 * this will hold the list table object for a given view.
74
+	 *
75
+	 * @var EE_Admin_List_Table $_list_table_object
76
+	 */
77
+	protected $_list_table_object;
78 78
 
79
-    // bools
80
-    protected $_is_UI_request = null; // this starts at null so we can have no header routes progress through two states.
79
+	// bools
80
+	protected $_is_UI_request = null; // this starts at null so we can have no header routes progress through two states.
81 81
 
82
-    protected $_routing;
82
+	protected $_routing;
83 83
 
84
-    // list table args
85
-    protected $_view;
84
+	// list table args
85
+	protected $_view;
86 86
 
87
-    protected $_views;
87
+	protected $_views;
88 88
 
89 89
 
90
-    // action => method pairs used for routing incoming requests
91
-    protected $_page_routes;
90
+	// action => method pairs used for routing incoming requests
91
+	protected $_page_routes;
92 92
 
93
-    /**
94
-     * @var array $_page_config
95
-     */
96
-    protected $_page_config;
93
+	/**
94
+	 * @var array $_page_config
95
+	 */
96
+	protected $_page_config;
97 97
 
98
-    /**
99
-     * the current page route and route config
100
-     *
101
-     * @var string $_route
102
-     */
103
-    protected $_route;
98
+	/**
99
+	 * the current page route and route config
100
+	 *
101
+	 * @var string $_route
102
+	 */
103
+	protected $_route;
104 104
 
105
-    /**
106
-     * @var string $_cpt_route
107
-     */
108
-    protected $_cpt_route;
105
+	/**
106
+	 * @var string $_cpt_route
107
+	 */
108
+	protected $_cpt_route;
109 109
 
110
-    /**
111
-     * @var array $_route_config
112
-     */
113
-    protected $_route_config;
110
+	/**
111
+	 * @var array $_route_config
112
+	 */
113
+	protected $_route_config;
114 114
 
115
-    /**
116
-     * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
117
-     * actions.
118
-     *
119
-     * @since 4.6.x
120
-     * @var array.
121
-     */
122
-    protected $_default_route_query_args;
123
-
124
-    // set via request page and action args.
125
-    protected $_current_page;
126
-
127
-    protected $_current_view;
128
-
129
-    protected $_current_page_view_url;
130
-
131
-    // sanitized request action (and nonce)
132
-
133
-    /**
134
-     * @var string $_req_action
135
-     */
136
-    protected $_req_action;
137
-
138
-    /**
139
-     * @var string $_req_nonce
140
-     */
141
-    protected $_req_nonce;
142
-
143
-    // search related
144
-    protected $_search_btn_label;
145
-
146
-    protected $_search_box_callback;
147
-
148
-    /**
149
-     * WP Current Screen object
150
-     *
151
-     * @var WP_Screen
152
-     */
153
-    protected $_current_screen;
154
-
155
-    // for holding EE_Admin_Hooks object when needed (set via set_hook_object())
156
-    protected $_hook_obj;
157
-
158
-    // for holding incoming request data
159
-    protected $_req_data = [];
160
-
161
-    // yes / no array for admin form fields
162
-    protected $_yes_no_values = [];
163
-
164
-    // some default things shared by all child classes
165
-    protected $_default_espresso_metaboxes;
166
-
167
-    /**
168
-     *    EE_Registry Object
169
-     *
170
-     * @var    EE_Registry
171
-     */
172
-    protected $EE = null;
173
-
174
-
175
-    /**
176
-     * This is just a property that flags whether the given route is a caffeinated route or not.
177
-     *
178
-     * @var boolean
179
-     */
180
-    protected $_is_caf = false;
181
-
182
-
183
-    /**
184
-     * @Constructor
185
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
186
-     * @throws EE_Error
187
-     * @throws InvalidArgumentException
188
-     * @throws ReflectionException
189
-     * @throws InvalidDataTypeException
190
-     * @throws InvalidInterfaceException
191
-     */
192
-    public function __construct($routing = true)
193
-    {
194
-        $this->loader  = LoaderFactory::getLoader();
195
-        $this->request = $this->loader->getShared(RequestInterface::class);
196
-
197
-        if (strpos($this->_get_dir(), 'caffeinated') !== false) {
198
-            $this->_is_caf = true;
199
-        }
200
-        $this->_yes_no_values = [
201
-            ['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
202
-            ['id' => false, 'text' => esc_html__('No', 'event_espresso')],
203
-        ];
204
-        // set the _req_data property.
205
-        $this->_req_data = $this->request->requestParams();
206
-        // routing enabled?
207
-        $this->_routing = $routing;
208
-        // set initial page props (child method)
209
-        $this->_init_page_props();
210
-        // set global defaults
211
-        $this->_set_defaults();
212
-        // set early because incoming requests could be ajax related and we need to register those hooks.
213
-        $this->_global_ajax_hooks();
214
-        $this->_ajax_hooks();
215
-        // other_page_hooks have to be early too.
216
-        $this->_do_other_page_hooks();
217
-        // This just allows us to have extending classes do something specific
218
-        // before the parent constructor runs _page_setup().
219
-        if (method_exists($this, '_before_page_setup')) {
220
-            $this->_before_page_setup();
221
-        }
222
-        // set up page dependencies
223
-        $this->_page_setup();
224
-    }
225
-
226
-
227
-    /**
228
-     * _init_page_props
229
-     * Child classes use to set at least the following properties:
230
-     * $page_slug.
231
-     * $page_label.
232
-     *
233
-     * @abstract
234
-     * @return void
235
-     */
236
-    abstract protected function _init_page_props();
237
-
238
-
239
-    /**
240
-     * _ajax_hooks
241
-     * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
242
-     * Note: within the ajax callback methods.
243
-     *
244
-     * @abstract
245
-     * @return void
246
-     */
247
-    abstract protected function _ajax_hooks();
248
-
249
-
250
-    /**
251
-     * _define_page_props
252
-     * child classes define page properties in here.  Must include at least:
253
-     * $_admin_base_url = base_url for all admin pages
254
-     * $_admin_page_title = default admin_page_title for admin pages
255
-     * $_labels = array of default labels for various automatically generated elements:
256
-     *    array(
257
-     *        'buttons' => array(
258
-     *            'add' => esc_html__('label for add new button'),
259
-     *            'edit' => esc_html__('label for edit button'),
260
-     *            'delete' => esc_html__('label for delete button')
261
-     *            )
262
-     *        )
263
-     *
264
-     * @abstract
265
-     * @return void
266
-     */
267
-    abstract protected function _define_page_props();
268
-
269
-
270
-    /**
271
-     * _set_page_routes
272
-     * child classes use this to define the page routes for all subpages handled by the class.  Page routes are
273
-     * assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also
274
-     * have a 'default' route. Here's the format
275
-     * $this->_page_routes = array(
276
-     *        'default' => array(
277
-     *            'func' => '_default_method_handling_route',
278
-     *            'args' => array('array','of','args'),
279
-     *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e.
280
-     *            ajax request, backend processing)
281
-     *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a
282
-     *            headers route after.  The string you enter here should match the defined route reference for a
283
-     *            headers sent route.
284
-     *            'capability' => 'route_capability', //indicate a string for minimum capability required to access
285
-     *            this route.
286
-     *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability
287
-     *            checks).
288
-     *        ),
289
-     *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a
290
-     *        handling method.
291
-     *        )
292
-     * )
293
-     *
294
-     * @abstract
295
-     * @return void
296
-     */
297
-    abstract protected function _set_page_routes();
298
-
299
-
300
-    /**
301
-     * _set_page_config
302
-     * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the
303
-     * array corresponds to the page_route for the loaded page. Format:
304
-     * $this->_page_config = array(
305
-     *        'default' => array(
306
-     *            'labels' => array(
307
-     *                'buttons' => array(
308
-     *                    'add' => esc_html__('label for adding item'),
309
-     *                    'edit' => esc_html__('label for editing item'),
310
-     *                    'delete' => esc_html__('label for deleting item')
311
-     *                ),
312
-     *                'publishbox' => esc_html__('Localized Title for Publish metabox', 'event_espresso')
313
-     *            ), //optional an array of custom labels for various automatically generated elements to use on the
314
-     *            page. If this isn't present then the defaults will be used as set for the $this->_labels in
315
-     *            _define_page_props() method
316
-     *            'nav' => array(
317
-     *                'label' => esc_html__('Label for Tab', 'event_espresso').
318
-     *                'url' => 'http://someurl', //automatically generated UNLESS you define
319
-     *                'css_class' => 'css-class', //automatically generated UNLESS you define
320
-     *                'order' => 10, //required to indicate tab position.
321
-     *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is
322
-     *                displayed then add this parameter.
323
-     *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
324
-     *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load
325
-     *            metaboxes set for eventespresso admin pages.
326
-     *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have
327
-     *            metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added
328
-     *            later.  We just use this flag to make sure the necessary js gets enqueued on page load.
329
-     *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the
330
-     *            given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
331
-     *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The
332
-     *            array indicates the max number of columns (4) and the default number of columns on page load (2).
333
-     *            There is an option in the "screen_options" dropdown that is setup so users can pick what columns they
334
-     *            want to display.
335
-     *            'help_tabs' => array( //this is used for adding help tabs to a page
336
-     *                'tab_id' => array(
337
-     *                    'title' => 'tab_title',
338
-     *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting
339
-     *                    help tab content.  The fallback if it isn't present is to try a the callback.  Filename
340
-     *                    should match a file in the admin folder's "help_tabs" dir (ie..
341
-     *                    events/help_tabs/name_of_file_containing_content.help_tab.php)
342
-     *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will
343
-     *                    attempt to use the callback which should match the name of a method in the class
344
-     *                    ),
345
-     *                'tab2_id' => array(
346
-     *                    'title' => 'tab2 title',
347
-     *                    'filename' => 'file_name_2'
348
-     *                    'callback' => 'callback_method_for_content',
349
-     *                 ),
350
-     *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the
351
-     *            help tab area on an admin page. @return void
352
-     *
353
-     * @link
354
-     *                http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
355
-     *                'help_tour' => array(
356
-     *                'name_of_help_tour_class', //all help tours should be a child class of EE_Help_Tour and located
357
-     *                in a folder for this admin page named "help_tours", a file name matching the key given here
358
-     *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
359
-     *                ),
360
-     *                'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default
361
-     *                is true if it isn't present).  To remove the requirement for a nonce check when this route is
362
-     *                visited just set
363
-     *                'require_nonce' to FALSE
364
-     *                )
365
-     *                )
366
-     *
367
-     * @abstract
368
-     */
369
-    abstract protected function _set_page_config();
370
-
371
-
372
-
373
-
374
-
375
-    /** end sample help_tour methods **/
376
-    /**
377
-     * _add_screen_options
378
-     * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for
379
-     * doing so. Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options
380
-     * to a particular view.
381
-     *
382
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
383
-     *         see also WP_Screen object documents...
384
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
385
-     * @abstract
386
-     * @return void
387
-     */
388
-    abstract protected function _add_screen_options();
389
-
390
-
391
-    /**
392
-     * _add_feature_pointers
393
-     * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
394
-     * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a
395
-     * particular view. Note: this is just a placeholder for now.  Implementation will come down the road See:
396
-     * WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
397
-     * extended) also see:
398
-     *
399
-     * @link   http://eamann.com/tech/wordpress-portland/
400
-     * @abstract
401
-     * @return void
402
-     */
403
-    abstract protected function _add_feature_pointers();
404
-
405
-
406
-    /**
407
-     * load_scripts_styles
408
-     * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for
409
-     * their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific
410
-     * scripts/styles per view by putting them in a dynamic function in this format
411
-     * (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
412
-     *
413
-     * @abstract
414
-     * @return void
415
-     */
416
-    abstract public function load_scripts_styles();
417
-
418
-
419
-    /**
420
-     * admin_init
421
-     * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to
422
-     * all pages/views loaded by child class.
423
-     *
424
-     * @abstract
425
-     * @return void
426
-     */
427
-    abstract public function admin_init();
428
-
429
-
430
-    /**
431
-     * admin_notices
432
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to
433
-     * all pages/views loaded by child class.
434
-     *
435
-     * @abstract
436
-     * @return void
437
-     */
438
-    abstract public function admin_notices();
439
-
440
-
441
-    /**
442
-     * admin_footer_scripts
443
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
444
-     * will apply to all pages/views loaded by child class.
445
-     *
446
-     * @return void
447
-     */
448
-    abstract public function admin_footer_scripts();
449
-
450
-
451
-    /**
452
-     * admin_footer
453
-     * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will
454
-     * apply to all pages/views loaded by child class.
455
-     *
456
-     * @return void
457
-     */
458
-    public function admin_footer()
459
-    {
460
-    }
461
-
462
-
463
-    /**
464
-     * _global_ajax_hooks
465
-     * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
466
-     * Note: within the ajax callback methods.
467
-     *
468
-     * @abstract
469
-     * @return void
470
-     */
471
-    protected function _global_ajax_hooks()
472
-    {
473
-        // for lazy loading of metabox content
474
-        add_action('wp_ajax_espresso-ajax-content', [$this, 'ajax_metabox_content'], 10);
475
-    }
476
-
477
-
478
-    public function ajax_metabox_content()
479
-    {
480
-        $content_id  = $this->request->getRequestParam('contentid', '');
481
-        $content_url = $this->request->getRequestParam('contenturl', '', 'url');
482
-        self::cached_rss_display($content_id, $content_url);
483
-        wp_die();
484
-    }
485
-
486
-
487
-    /**
488
-     * _page_setup
489
-     * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested
490
-     * doesn't match the object.
491
-     *
492
-     * @final
493
-     * @return void
494
-     * @throws EE_Error
495
-     * @throws InvalidArgumentException
496
-     * @throws ReflectionException
497
-     * @throws InvalidDataTypeException
498
-     * @throws InvalidInterfaceException
499
-     */
500
-    final protected function _page_setup()
501
-    {
502
-        // requires?
503
-        // admin_init stuff - global - we're setting this REALLY early
504
-        // so if EE_Admin pages have to hook into other WP pages they can.
505
-        // But keep in mind, not everything is available from the EE_Admin Page object at this point.
506
-        add_action('admin_init', [$this, 'admin_init_global'], 5);
507
-        // next verify if we need to load anything...
508
-        $this->_current_page = $this->request->getRequestParam('page', '', 'key');
509
-        $this->page_folder   = strtolower(
510
-            str_replace(['_Admin_Page', 'Extend_'], '', get_class($this))
511
-        );
512
-        global $ee_menu_slugs;
513
-        $ee_menu_slugs = (array) $ee_menu_slugs;
514
-        if (
515
-            ! defined('DOING_AJAX')
516
-            && (! $this->_current_page || ! isset($ee_menu_slugs[ $this->_current_page ]))
517
-        ) {
518
-            return;
519
-        }
520
-        // because WP List tables have two duplicate select inputs for choosing bulk actions,
521
-        // we need to copy the action from the second to the first
522
-        $action     = $this->request->getRequestParam('action', '-1', 'key');
523
-        $action2    = $this->request->getRequestParam('action2', '-1', 'key');
524
-        $action     = $action !== '-1' ? $action : $action2;
525
-        $req_action = $action !== '-1' ? $action : 'default';
526
-
527
-        // if a specific 'route' has been set, and the action is 'default' OR we are doing_ajax
528
-        // then let's use the route as the action.
529
-        // This covers cases where we're coming in from a list table that isn't on the default route.
530
-        $route = $this->request->getRequestParam('route');
531
-        $this->_req_action = $route && ($req_action === 'default' || $this->request->isAjax())
532
-            ? $route
533
-            : $req_action;
534
-        $this->_current_view = $this->_req_action;
535
-        $this->_req_nonce    = $this->_req_action . '_nonce';
536
-        $this->_define_page_props();
537
-        $this->_current_page_view_url = add_query_arg(
538
-            ['page' => $this->_current_page, 'action' => $this->_current_view],
539
-            $this->_admin_base_url
540
-        );
541
-        // default things
542
-        $this->_default_espresso_metaboxes = [
543
-            '_espresso_news_post_box',
544
-            '_espresso_links_post_box',
545
-            '_espresso_ratings_request',
546
-            '_espresso_sponsors_post_box',
547
-        ];
548
-        // set page configs
549
-        $this->_set_page_routes();
550
-        $this->_set_page_config();
551
-        // let's include any referrer data in our default_query_args for this route for "stickiness".
552
-        if ($this->request->requestParamIsSet('wp_referer')) {
553
-            $this->_default_route_query_args['wp_referer'] = $this->request->getRequestParam(
554
-                'wp_referer',
555
-                null,
556
-                'url'
557
-            );
558
-        }
559
-        // for caffeinated and other extended functionality.
560
-        //  If there is a _extend_page_config method
561
-        // then let's run that to modify the all the various page configuration arrays
562
-        if (method_exists($this, '_extend_page_config')) {
563
-            $this->_extend_page_config();
564
-        }
565
-        // for CPT and other extended functionality.
566
-        // If there is an _extend_page_config_for_cpt
567
-        // then let's run that to modify all the various page configuration arrays.
568
-        if (method_exists($this, '_extend_page_config_for_cpt')) {
569
-            $this->_extend_page_config_for_cpt();
570
-        }
571
-        // filter routes and page_config so addons can add their stuff. Filtering done per class
572
-        $this->_page_routes = apply_filters(
573
-            'FHEE__' . get_class($this) . '__page_setup__page_routes',
574
-            $this->_page_routes,
575
-            $this
576
-        );
577
-        $this->_page_config = apply_filters(
578
-            'FHEE__' . get_class($this) . '__page_setup__page_config',
579
-            $this->_page_config,
580
-            $this
581
-        );
582
-        // if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
583
-        // then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
584
-        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
585
-            add_action(
586
-                'AHEE__EE_Admin_Page__route_admin_request',
587
-                [$this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view],
588
-                10,
589
-                2
590
-            );
591
-        }
592
-        // next route only if routing enabled
593
-        if ($this->_routing && ! defined('DOING_AJAX')) {
594
-            $this->_verify_routes();
595
-            // next let's just check user_access and kill if no access
596
-            $this->check_user_access();
597
-            if ($this->_is_UI_request) {
598
-                // admin_init stuff - global, all views for this page class, specific view
599
-                add_action('admin_init', [$this, 'admin_init'], 10);
600
-                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
601
-                    add_action('admin_init', [$this, 'admin_init_' . $this->_current_view], 15);
602
-                }
603
-            } else {
604
-                // hijack regular WP loading and route admin request immediately
605
-                @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
606
-                $this->route_admin_request();
607
-            }
608
-        }
609
-    }
610
-
611
-
612
-    /**
613
-     * Provides a way for related child admin pages to load stuff on the loaded admin page.
614
-     *
615
-     * @return void
616
-     * @throws ReflectionException
617
-     * @throws EE_Error
618
-     */
619
-    private function _do_other_page_hooks()
620
-    {
621
-        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, []);
622
-        foreach ($registered_pages as $page) {
623
-            // now let's setup the file name and class that should be present
624
-            $classname = str_replace('.class.php', '', $page);
625
-            // autoloaders should take care of loading file
626
-            if (! class_exists($classname)) {
627
-                $error_msg[] = sprintf(
628
-                    esc_html__(
629
-                        'Something went wrong with loading the %s admin hooks page.',
630
-                        'event_espresso'
631
-                    ),
632
-                    $page
633
-                );
634
-                $error_msg[] = $error_msg[0]
635
-                               . "\r\n"
636
-                               . sprintf(
637
-                                   esc_html__(
638
-                                       'There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
639
-                                       'event_espresso'
640
-                                   ),
641
-                                   $page,
642
-                                   '<br />',
643
-                                   '<strong>' . $classname . '</strong>'
644
-                               );
645
-                throw new EE_Error(implode('||', $error_msg));
646
-            }
647
-            $a = new ReflectionClass($classname);
648
-            // notice we are passing the instance of this class to the hook object.
649
-            $hookobj[] = $a->newInstance($this);
650
-        }
651
-    }
652
-
653
-
654
-    /**
655
-     * @throws ReflectionException
656
-     * @throws EE_Error
657
-     */
658
-    public function load_page_dependencies()
659
-    {
660
-        try {
661
-            $this->_load_page_dependencies();
662
-        } catch (EE_Error $e) {
663
-            $e->get_error();
664
-        }
665
-    }
666
-
667
-
668
-    /**
669
-     * load_page_dependencies
670
-     * loads things specific to this page class when its loaded.  Really helps with efficiency.
671
-     *
672
-     * @return void
673
-     * @throws DomainException
674
-     * @throws EE_Error
675
-     * @throws InvalidArgumentException
676
-     * @throws InvalidDataTypeException
677
-     * @throws InvalidInterfaceException
678
-     */
679
-    protected function _load_page_dependencies()
680
-    {
681
-        // let's set the current_screen and screen options to override what WP set
682
-        $this->_current_screen = get_current_screen();
683
-        // load admin_notices - global, page class, and view specific
684
-        add_action('admin_notices', [$this, 'admin_notices_global'], 5);
685
-        add_action('admin_notices', [$this, 'admin_notices'], 10);
686
-        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
687
-            add_action('admin_notices', [$this, 'admin_notices_' . $this->_current_view], 15);
688
-        }
689
-        // load network admin_notices - global, page class, and view specific
690
-        add_action('network_admin_notices', [$this, 'network_admin_notices_global'], 5);
691
-        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
692
-            add_action('network_admin_notices', [$this, 'network_admin_notices_' . $this->_current_view]);
693
-        }
694
-        // this will save any per_page screen options if they are present
695
-        $this->_set_per_page_screen_options();
696
-        // setup list table properties
697
-        $this->_set_list_table();
698
-        // child classes can "register" a metabox to be automatically handled via the _page_config array property.
699
-        // However in some cases the metaboxes will need to be added within a route handling callback.
700
-        $this->_add_registered_meta_boxes();
701
-        $this->_add_screen_columns();
702
-        // add screen options - global, page child class, and view specific
703
-        $this->_add_global_screen_options();
704
-        $this->_add_screen_options();
705
-        $add_screen_options = "_add_screen_options_{$this->_current_view}";
706
-        if (method_exists($this, $add_screen_options)) {
707
-            $this->{$add_screen_options}();
708
-        }
709
-        // add help tab(s) and tours- set via page_config and qtips.
710
-        // $this->_add_help_tour();
711
-        $this->_add_help_tabs();
712
-        $this->_add_qtips();
713
-        // add feature_pointers - global, page child class, and view specific
714
-        $this->_add_feature_pointers();
715
-        $this->_add_global_feature_pointers();
716
-        $add_feature_pointer = "_add_feature_pointer_{$this->_current_view}";
717
-        if (method_exists($this, $add_feature_pointer)) {
718
-            $this->{$add_feature_pointer}();
719
-        }
720
-        // enqueue scripts/styles - global, page class, and view specific
721
-        add_action('admin_enqueue_scripts', [$this, 'load_global_scripts_styles'], 5);
722
-        add_action('admin_enqueue_scripts', [$this, 'load_scripts_styles'], 10);
723
-        if (method_exists($this, "load_scripts_styles_{$this->_current_view}")) {
724
-            add_action('admin_enqueue_scripts', [$this, "load_scripts_styles_{$this->_current_view}"], 15);
725
-        }
726
-        add_action('admin_enqueue_scripts', [$this, 'admin_footer_scripts_eei18n_js_strings'], 100);
727
-        // admin_print_footer_scripts - global, page child class, and view specific.
728
-        // NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.
729
-        // In most cases that's doing_it_wrong().  But adding hidden container elements etc.
730
-        // is a good use case. Notice the late priority we're giving these
731
-        add_action('admin_print_footer_scripts', [$this, 'admin_footer_scripts_global'], 99);
732
-        add_action('admin_print_footer_scripts', [$this, 'admin_footer_scripts'], 100);
733
-        if (method_exists($this, "admin_footer_scripts_{$this->_current_view}")) {
734
-            add_action('admin_print_footer_scripts', [$this, "admin_footer_scripts_{$this->_current_view}"], 101);
735
-        }
736
-        // admin footer scripts
737
-        add_action('admin_footer', [$this, 'admin_footer_global'], 99);
738
-        add_action('admin_footer', [$this, 'admin_footer'], 100);
739
-        if (method_exists($this, "admin_footer_{$this->_current_view}")) {
740
-            add_action('admin_footer', [$this, "admin_footer_{$this->_current_view}"], 101);
741
-        }
742
-        do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
743
-        // targeted hook
744
-        do_action(
745
-            "FHEE__EE_Admin_Page___load_page_dependencies__after_load__{$this->page_slug}__{$this->_req_action}"
746
-        );
747
-    }
748
-
749
-
750
-    /**
751
-     * _set_defaults
752
-     * This sets some global defaults for class properties.
753
-     */
754
-    private function _set_defaults()
755
-    {
756
-        $this->_current_screen       = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = null;
757
-        $this->_event                = $this->_template_path = $this->_column_template_path = null;
758
-        $this->_nav_tabs             = $this->_views = $this->_page_routes = [];
759
-        $this->_page_config          = $this->_default_route_query_args = [];
760
-        $this->_default_nav_tab_name = 'overview';
761
-        // init template args
762
-        $this->_template_args = [
763
-            'admin_page_header'  => '',
764
-            'admin_page_content' => '',
765
-            'post_body_content'  => '',
766
-            'before_list_table'  => '',
767
-            'after_list_table'   => '',
768
-        ];
769
-    }
770
-
771
-
772
-    /**
773
-     * route_admin_request
774
-     *
775
-     * @return void
776
-     * @throws InvalidArgumentException
777
-     * @throws InvalidInterfaceException
778
-     * @throws InvalidDataTypeException
779
-     * @throws EE_Error
780
-     * @throws ReflectionException
781
-     * @see    _route_admin_request()
782
-     */
783
-    public function route_admin_request()
784
-    {
785
-        try {
786
-            $this->_route_admin_request();
787
-        } catch (EE_Error $e) {
788
-            $e->get_error();
789
-        }
790
-    }
791
-
792
-
793
-    public function set_wp_page_slug($wp_page_slug)
794
-    {
795
-        $this->_wp_page_slug = $wp_page_slug;
796
-        // if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
797
-        if (is_network_admin()) {
798
-            $this->_wp_page_slug .= '-network';
799
-        }
800
-    }
801
-
802
-
803
-    /**
804
-     * _verify_routes
805
-     * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so
806
-     * we know if we need to drop out.
807
-     *
808
-     * @return bool
809
-     * @throws EE_Error
810
-     */
811
-    protected function _verify_routes()
812
-    {
813
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
814
-        if (! $this->_current_page && ! defined('DOING_AJAX')) {
815
-            return false;
816
-        }
817
-        $this->_route = false;
818
-        // check that the page_routes array is not empty
819
-        if (empty($this->_page_routes)) {
820
-            // user error msg
821
-            $error_msg = sprintf(
822
-                esc_html__('No page routes have been set for the %s admin page.', 'event_espresso'),
823
-                $this->_admin_page_title
824
-            );
825
-            // developer error msg
826
-            $error_msg .= '||' . $error_msg
827
-                          . esc_html__(
828
-                              ' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
829
-                              'event_espresso'
830
-                          );
831
-            throw new EE_Error($error_msg);
832
-        }
833
-        // and that the requested page route exists
834
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
835
-            $this->_route        = $this->_page_routes[ $this->_req_action ];
836
-            $this->_route_config = isset($this->_page_config[ $this->_req_action ])
837
-                ? $this->_page_config[ $this->_req_action ] : [];
838
-        } else {
839
-            // user error msg
840
-            $error_msg = sprintf(
841
-                esc_html__(
842
-                    'The requested page route does not exist for the %s admin page.',
843
-                    'event_espresso'
844
-                ),
845
-                $this->_admin_page_title
846
-            );
847
-            // developer error msg
848
-            $error_msg .= '||' . $error_msg
849
-                          . sprintf(
850
-                              esc_html__(
851
-                                  ' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
852
-                                  'event_espresso'
853
-                              ),
854
-                              $this->_req_action
855
-                          );
856
-            throw new EE_Error($error_msg);
857
-        }
858
-        // and that a default route exists
859
-        if (! array_key_exists('default', $this->_page_routes)) {
860
-            // user error msg
861
-            $error_msg = sprintf(
862
-                esc_html__(
863
-                    'A default page route has not been set for the % admin page.',
864
-                    'event_espresso'
865
-                ),
866
-                $this->_admin_page_title
867
-            );
868
-            // developer error msg
869
-            $error_msg .= '||' . $error_msg
870
-                          . esc_html__(
871
-                              ' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
872
-                              'event_espresso'
873
-                          );
874
-            throw new EE_Error($error_msg);
875
-        }
876
-        // first lets' catch if the UI request has EVER been set.
877
-        if ($this->_is_UI_request === null) {
878
-            // lets set if this is a UI request or not.
879
-            $this->_is_UI_request = ! $this->request->getRequestParam('noheader', false, 'bool');
880
-            // wait a minute... we might have a noheader in the route array
881
-            $this->_is_UI_request = ! (
882
-                is_array($this->_route) && isset($this->_route['noheader']) && $this->_route['noheader']
883
-            )
884
-                ? $this->_is_UI_request
885
-                : false;
886
-        }
887
-        $this->_set_current_labels();
888
-        return true;
889
-    }
890
-
891
-
892
-    /**
893
-     * this method simply verifies a given route and makes sure its an actual route available for the loaded page
894
-     *
895
-     * @param string $route the route name we're verifying
896
-     * @return bool we'll throw an exception if this isn't a valid route.
897
-     * @throws EE_Error
898
-     */
899
-    protected function _verify_route($route)
900
-    {
901
-        if (array_key_exists($this->_req_action, $this->_page_routes)) {
902
-            return true;
903
-        }
904
-        // user error msg
905
-        $error_msg = sprintf(
906
-            esc_html__('The given page route does not exist for the %s admin page.', 'event_espresso'),
907
-            $this->_admin_page_title
908
-        );
909
-        // developer error msg
910
-        $error_msg .= '||' . $error_msg
911
-                      . sprintf(
912
-                          esc_html__(
913
-                              ' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
914
-                              'event_espresso'
915
-                          ),
916
-                          $route
917
-                      );
918
-        throw new EE_Error($error_msg);
919
-    }
920
-
921
-
922
-    /**
923
-     * perform nonce verification
924
-     * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces
925
-     * using this method (and save retyping!)
926
-     *
927
-     * @param string $nonce     The nonce sent
928
-     * @param string $nonce_ref The nonce reference string (name0)
929
-     * @return void
930
-     * @throws EE_Error
931
-     */
932
-    protected function _verify_nonce($nonce, $nonce_ref)
933
-    {
934
-        // verify nonce against expected value
935
-        if (! wp_verify_nonce($nonce, $nonce_ref)) {
936
-            // these are not the droids you are looking for !!!
937
-            $msg = sprintf(
938
-                esc_html__('%sNonce Fail.%s', 'event_espresso'),
939
-                '<a href="https://www.youtube.com/watch?v=56_S0WeTkzs">',
940
-                '</a>'
941
-            );
942
-            if (WP_DEBUG) {
943
-                $msg .= "\n  ";
944
-                $msg .= sprintf(
945
-                    esc_html__(
946
-                        'In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!',
947
-                        'event_espresso'
948
-                    ),
949
-                    __CLASS__
950
-                );
951
-            }
952
-            if (! defined('DOING_AJAX')) {
953
-                wp_die($msg);
954
-            }
955
-            EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
956
-            $this->_return_json();
957
-        }
958
-    }
959
-
960
-
961
-    /**
962
-     * _route_admin_request()
963
-     * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
964
-     * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
965
-     * in the page routes and then will try to load the corresponding method.
966
-     *
967
-     * @return void
968
-     * @throws EE_Error
969
-     * @throws InvalidArgumentException
970
-     * @throws InvalidDataTypeException
971
-     * @throws InvalidInterfaceException
972
-     * @throws ReflectionException
973
-     */
974
-    protected function _route_admin_request()
975
-    {
976
-        if (! $this->_is_UI_request) {
977
-            $this->_verify_routes();
978
-        }
979
-        $nonce_check = ! isset($this->_route_config['require_nonce']) || $this->_route_config['require_nonce'];
980
-        if ($this->_req_action !== 'default' && $nonce_check) {
981
-            // set nonce from post data
982
-            $nonce = $this->request->getRequestParam($this->_req_nonce, '');
983
-            $this->_verify_nonce($nonce, $this->_req_nonce);
984
-        }
985
-        // set the nav_tabs array but ONLY if this is  UI_request
986
-        if ($this->_is_UI_request) {
987
-            $this->_set_nav_tabs();
988
-        }
989
-        // grab callback function
990
-        $func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
991
-        // check if callback has args
992
-        $args      = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : [];
993
-        $error_msg = '';
994
-        // action right before calling route
995
-        // (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
996
-        if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
997
-            do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
998
-        }
999
-        // right before calling the route, let's remove _wp_http_referer from the
1000
-        // $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
1001
-        $_SERVER['REQUEST_URI'] = remove_query_arg(
1002
-            '_wp_http_referer',
1003
-            wp_unslash($_SERVER['REQUEST_URI'])
1004
-        );
1005
-        if (! empty($func)) {
1006
-            if (is_array($func)) {
1007
-                list($class, $method) = $func;
1008
-            } elseif (strpos($func, '::') !== false) {
1009
-                list($class, $method) = explode('::', $func);
1010
-            } else {
1011
-                $class  = $this;
1012
-                $method = $func;
1013
-            }
1014
-            if (! (is_object($class) && $class === $this)) {
1015
-                // send along this admin page object for access by addons.
1016
-                $args['admin_page_object'] = $this;
1017
-            }
1018
-            if (// is it a method on a class that doesn't work?
1019
-                (
1020
-                    (
1021
-                        method_exists($class, $method)
1022
-                        && call_user_func_array([$class, $method], $args) === false
1023
-                    )
1024
-                    && (
1025
-                        // is it a standalone function that doesn't work?
1026
-                        function_exists($method)
1027
-                        && call_user_func_array(
1028
-                               $func,
1029
-                               array_merge(['admin_page_object' => $this], $args)
1030
-                           ) === false
1031
-                    )
1032
-                )
1033
-                || (
1034
-                    // is it neither a class method NOR a standalone function?
1035
-                    ! method_exists($class, $method)
1036
-                    && ! function_exists($method)
1037
-                )
1038
-            ) {
1039
-                // user error msg
1040
-                $error_msg = esc_html__(
1041
-                    'An error occurred. The  requested page route could not be found.',
1042
-                    'event_espresso'
1043
-                );
1044
-                // developer error msg
1045
-                $error_msg .= '||';
1046
-                $error_msg .= sprintf(
1047
-                    esc_html__(
1048
-                        'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
1049
-                        'event_espresso'
1050
-                    ),
1051
-                    $method
1052
-                );
1053
-            }
1054
-            if (! empty($error_msg)) {
1055
-                throw new EE_Error($error_msg);
1056
-            }
1057
-        }
1058
-        // if we've routed and this route has a no headers route AND a sent_headers_route,
1059
-        // then we need to reset the routing properties to the new route.
1060
-        // now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
1061
-        if ($this->_is_UI_request === false
1062
-            && is_array($this->_route)
1063
-            && ! empty($this->_route['headers_sent_route'])
1064
-        ) {
1065
-            $this->_reset_routing_properties($this->_route['headers_sent_route']);
1066
-        }
1067
-    }
1068
-
1069
-
1070
-    /**
1071
-     * This method just allows the resetting of page properties in the case where a no headers
1072
-     * route redirects to a headers route in its route config.
1073
-     *
1074
-     * @param string $new_route New (non header) route to redirect to.
1075
-     * @return   void
1076
-     * @throws ReflectionException
1077
-     * @throws InvalidArgumentException
1078
-     * @throws InvalidInterfaceException
1079
-     * @throws InvalidDataTypeException
1080
-     * @throws EE_Error
1081
-     * @since   4.3.0
1082
-     */
1083
-    protected function _reset_routing_properties($new_route)
1084
-    {
1085
-        $this->_is_UI_request = true;
1086
-        // now we set the current route to whatever the headers_sent_route is set at
1087
-        $this->request->setRequestParam('action', $new_route);
1088
-        // rerun page setup
1089
-        $this->_page_setup();
1090
-    }
1091
-
1092
-
1093
-    /**
1094
-     * _add_query_arg
1095
-     * adds nonce to array of arguments then calls WP add_query_arg function
1096
-     *(internally just uses EEH_URL's function with the same name)
1097
-     *
1098
-     * @param array  $args
1099
-     * @param string $url
1100
-     * @param bool   $sticky                  if true, then the existing Request params will be appended to the
1101
-     *                                        generated url in an associative array indexed by the key 'wp_referer';
1102
-     *                                        Example usage: If the current page is:
1103
-     *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
1104
-     *                                        &action=default&event_id=20&month_range=March%202015
1105
-     *                                        &_wpnonce=5467821
1106
-     *                                        and you call:
1107
-     *                                        EE_Admin_Page::add_query_args_and_nonce(
1108
-     *                                        array(
1109
-     *                                        'action' => 'resend_something',
1110
-     *                                        'page=>espresso_registrations'
1111
-     *                                        ),
1112
-     *                                        $some_url,
1113
-     *                                        true
1114
-     *                                        );
1115
-     *                                        It will produce a url in this structure:
1116
-     *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
1117
-     *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
1118
-     *                                        month_range]=March%202015
1119
-     * @param bool   $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
1120
-     * @return string
1121
-     */
1122
-    public static function add_query_args_and_nonce(
1123
-        $args = [],
1124
-        $url = false,
1125
-        $sticky = false,
1126
-        $exclude_nonce = false
1127
-    ) {
1128
-        // if there is a _wp_http_referer include the values from the request but only if sticky = true
1129
-        if ($sticky) {
1130
-            $request = $_REQUEST;
1131
-            unset($request['_wp_http_referer']);
1132
-            unset($request['wp_referer']);
1133
-            foreach ($request as $key => $value) {
1134
-                // do not add nonces
1135
-                if (strpos($key, 'nonce') !== false) {
1136
-                    continue;
1137
-                }
1138
-                $args[ 'wp_referer[' . $key . ']' ] = $value;
1139
-            }
1140
-        }
1141
-        return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
1142
-    }
1143
-
1144
-
1145
-    /**
1146
-     * This returns a generated link that will load the related help tab.
1147
-     *
1148
-     * @param string $help_tab_id the id for the connected help tab
1149
-     * @param string $icon_style  (optional) include css class for the style you want to use for the help icon.
1150
-     * @param string $help_text   (optional) send help text you want to use for the link if default not to be used
1151
-     * @return string              generated link
1152
-     * @uses EEH_Template::get_help_tab_link()
1153
-     */
1154
-    protected function _get_help_tab_link($help_tab_id, $icon_style = '', $help_text = '')
1155
-    {
1156
-        return EEH_Template::get_help_tab_link(
1157
-            $help_tab_id,
1158
-            $this->page_slug,
1159
-            $this->_req_action,
1160
-            $icon_style,
1161
-            $help_text
1162
-        );
1163
-    }
1164
-
1165
-
1166
-    /**
1167
-     * _add_help_tabs
1168
-     * Note child classes define their help tabs within the page_config array.
1169
-     *
1170
-     * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
1171
-     * @return void
1172
-     * @throws DomainException
1173
-     * @throws EE_Error
1174
-     */
1175
-    protected function _add_help_tabs()
1176
-    {
1177
-        $tour_buttons = '';
1178
-        if (isset($this->_page_config[ $this->_req_action ])) {
1179
-            $config = $this->_page_config[ $this->_req_action ];
1180
-            // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1181
-            // is there a help tour for the current route?  if there is let's setup the tour buttons
1182
-            // if (isset($this->_help_tour[ $this->_req_action ])) {
1183
-            //     $tb = array();
1184
-            //     $tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1185
-            //     foreach ($this->_help_tour['tours'] as $tour) {
1186
-            //         // if this is the end tour then we don't need to setup a button
1187
-            //         if ($tour instanceof EE_Help_Tour_final_stop || ! $tour instanceof EE_Help_Tour) {
1188
-            //             continue;
1189
-            //         }
1190
-            //         $tb[] = '<button id="trigger-tour-'
1191
-            //                 . $tour->get_slug()
1192
-            //                 . '" class="button-primary trigger-ee-help-tour">'
1193
-            //                 . $tour->get_label()
1194
-            //                 . '</button>';
1195
-            //     }
1196
-            //     $tour_buttons .= implode('<br />', $tb);
1197
-            //     $tour_buttons .= '</div></div>';
1198
-            // }
1199
-            // let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1200
-            if (is_array($config) && isset($config['help_sidebar'])) {
1201
-                // check that the callback given is valid
1202
-                if (! method_exists($this, $config['help_sidebar'])) {
1203
-                    throw new EE_Error(
1204
-                        sprintf(
1205
-                            esc_html__(
1206
-                                'The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1207
-                                'event_espresso'
1208
-                            ),
1209
-                            $config['help_sidebar'],
1210
-                            get_class($this)
1211
-                        )
1212
-                    );
1213
-                }
1214
-                $content = apply_filters(
1215
-                    'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1216
-                    $this->{$config['help_sidebar']}()
1217
-                );
1218
-                $content .= $tour_buttons; // add help tour buttons.
1219
-                // do we have any help tours setup?  Cause if we do we want to add the buttons
1220
-                $this->_current_screen->set_help_sidebar($content);
1221
-            }
1222
-            // if we DON'T have config help sidebar and there ARE tour buttons then we'll just add the tour buttons to the sidebar.
1223
-            if (! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1224
-                $this->_current_screen->set_help_sidebar($tour_buttons);
1225
-            }
1226
-            // handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1227
-            if (! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1228
-                $_ht['id']      = $this->page_slug;
1229
-                $_ht['title']   = esc_html__('Help Tours', 'event_espresso');
1230
-                $_ht['content'] = '<p>'
1231
-                                  . esc_html__(
1232
-                                      'The buttons to the right allow you to start/restart any help tours available for this page',
1233
-                                      'event_espresso'
1234
-                                  ) . '</p>';
1235
-                $this->_current_screen->add_help_tab($_ht);
1236
-            }
1237
-            if (! isset($config['help_tabs'])) {
1238
-                return;
1239
-            } //no help tabs for this route
1240
-            foreach ((array) $config['help_tabs'] as $tab_id => $cfg) {
1241
-                // we're here so there ARE help tabs!
1242
-                // make sure we've got what we need
1243
-                if (! isset($cfg['title'])) {
1244
-                    throw new EE_Error(
1245
-                        esc_html__(
1246
-                            'The _page_config array is not set up properly for help tabs.  It is missing a title',
1247
-                            'event_espresso'
1248
-                        )
1249
-                    );
1250
-                }
1251
-                if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1252
-                    throw new EE_Error(
1253
-                        esc_html__(
1254
-                            'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1255
-                            'event_espresso'
1256
-                        )
1257
-                    );
1258
-                }
1259
-                // first priority goes to content.
1260
-                if (! empty($cfg['content'])) {
1261
-                    $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1262
-                    // second priority goes to filename
1263
-                } elseif (! empty($cfg['filename'])) {
1264
-                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1265
-                    // it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1266
-                    $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1267
-                                                             . basename($this->_get_dir())
1268
-                                                             . '/help_tabs/'
1269
-                                                             . $cfg['filename']
1270
-                                                             . '.help_tab.php' : $file_path;
1271
-                    // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1272
-                    if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1273
-                        EE_Error::add_error(
1274
-                            sprintf(
1275
-                                esc_html__(
1276
-                                    'The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1277
-                                    'event_espresso'
1278
-                                ),
1279
-                                $tab_id,
1280
-                                key($config),
1281
-                                $file_path
1282
-                            ),
1283
-                            __FILE__,
1284
-                            __FUNCTION__,
1285
-                            __LINE__
1286
-                        );
1287
-                        return;
1288
-                    }
1289
-                    $template_args['admin_page_obj'] = $this;
1290
-                    $content                         = EEH_Template::display_template(
1291
-                        $file_path,
1292
-                        $template_args,
1293
-                        true
1294
-                    );
1295
-                } else {
1296
-                    $content = '';
1297
-                }
1298
-                // check if callback is valid
1299
-                if (empty($content)
1300
-                    && (
1301
-                        ! isset($cfg['callback']) || ! method_exists($this, $cfg['callback'])
1302
-                    )
1303
-                ) {
1304
-                    EE_Error::add_error(
1305
-                        sprintf(
1306
-                            esc_html__(
1307
-                                'The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1308
-                                'event_espresso'
1309
-                            ),
1310
-                            $cfg['title']
1311
-                        ),
1312
-                        __FILE__,
1313
-                        __FUNCTION__,
1314
-                        __LINE__
1315
-                    );
1316
-                    return;
1317
-                }
1318
-                // setup config array for help tab method
1319
-                $id  = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1320
-                $_ht = [
1321
-                    'id'       => $id,
1322
-                    'title'    => $cfg['title'],
1323
-                    'callback' => isset($cfg['callback']) && empty($content) ? [$this, $cfg['callback']] : null,
1324
-                    'content'  => $content,
1325
-                ];
1326
-                $this->_current_screen->add_help_tab($_ht);
1327
-            }
1328
-        }
1329
-    }
1330
-
1331
-
1332
-    /**
1333
-     * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is
1334
-     * an array with properties for setting up usage of the joyride plugin
1335
-     *
1336
-     * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1337
-     * @see    instructions regarding the format and construction of the "help_tour" array element is found in the
1338
-     *         _set_page_config() comments
1339
-     * @return void
1340
-     * @throws InvalidArgumentException
1341
-     * @throws InvalidDataTypeException
1342
-     * @throws InvalidInterfaceException
1343
-     */
1344
-    protected function _add_help_tour()
1345
-    {
1346
-        // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1347
-        // $tours = array();
1348
-        // $this->_help_tour = array();
1349
-        // // exit early if help tours are turned off globally
1350
-        // if ((defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)
1351
-        //     || ! EE_Registry::instance()->CFG->admin->help_tour_activation
1352
-        // ) {
1353
-        //     return;
1354
-        // }
1355
-        // // loop through _page_config to find any help_tour defined
1356
-        // foreach ($this->_page_config as $route => $config) {
1357
-        //     // we're only going to set things up for this route
1358
-        //     if ($route !== $this->_req_action) {
1359
-        //         continue;
1360
-        //     }
1361
-        //     if (isset($config['help_tour'])) {
1362
-        //         foreach ($config['help_tour'] as $tour) {
1363
-        //             $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1364
-        //             // let's see if we can get that file...
1365
-        //             // if not its possible this is a decaf route not set in caffeinated
1366
-        //             // so lets try and get the caffeinated equivalent
1367
-        //             $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1368
-        //                                                      . basename($this->_get_dir())
1369
-        //                                                      . '/help_tours/'
1370
-        //                                                      . $tour
1371
-        //                                                      . '.class.php' : $file_path;
1372
-        //             // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1373
-        //             if (! is_readable($file_path)) {
1374
-        //                 EE_Error::add_error(
1375
-        //                     sprintf(
1376
-        //                         esc_html__(
1377
-        //                             'The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling',
1378
-        //                             'event_espresso'
1379
-        //                         ),
1380
-        //                         $file_path,
1381
-        //                         $tour
1382
-        //                     ),
1383
-        //                     __FILE__,
1384
-        //                     __FUNCTION__,
1385
-        //                     __LINE__
1386
-        //                 );
1387
-        //                 return;
1388
-        //             }
1389
-        //             require_once $file_path;
1390
-        //             if (! class_exists($tour)) {
1391
-        //                 $error_msg[] = sprintf(
1392
-        //                     esc_html__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'),
1393
-        //                     $tour
1394
-        //                 );
1395
-        //                 $error_msg[] = $error_msg[0] . "\r\n"
1396
-        //                                . sprintf(
1397
-        //                                    esc_html__(
1398
-        //                                        'There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1399
-        //                                        'event_espresso'
1400
-        //                                    ),
1401
-        //                                    $tour,
1402
-        //                                    '<br />',
1403
-        //                                    $tour,
1404
-        //                                    $this->_req_action,
1405
-        //                                    get_class($this)
1406
-        //                                );
1407
-        //                 throw new EE_Error(implode('||', $error_msg));
1408
-        //             }
1409
-        //             $tour_obj = new $tour($this->_is_caf);
1410
-        //             $tours[] = $tour_obj;
1411
-        //             $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($tour_obj);
1412
-        //         }
1413
-        //         // let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1414
-        //         $end_stop_tour = new EE_Help_Tour_final_stop($this->_is_caf);
1415
-        //         $tours[] = $end_stop_tour;
1416
-        //         $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1417
-        //     }
1418
-        // }
1419
-        //
1420
-        // if (! empty($tours)) {
1421
-        //     $this->_help_tour['tours'] = $tours;
1422
-        // }
1423
-        // // that's it!  Now that the $_help_tours property is set (or not)
1424
-        // // the scripts and html should be taken care of automatically.
1425
-        //
1426
-        // /**
1427
-        //  * Allow extending the help tours variable.
1428
-        //  *
1429
-        //  * @param Array $_help_tour The array containing all help tour information to be displayed.
1430
-        //  */
1431
-        // $this->_help_tour = apply_filters('FHEE__EE_Admin_Page___add_help_tour___help_tour', $this->_help_tour);
1432
-    }
1433
-
1434
-
1435
-    /**
1436
-     * This simply sets up any qtips that have been defined in the page config
1437
-     *
1438
-     * @return void
1439
-     */
1440
-    protected function _add_qtips()
1441
-    {
1442
-        if (isset($this->_route_config['qtips'])) {
1443
-            $qtips = (array) $this->_route_config['qtips'];
1444
-            // load qtip loader
1445
-            $path = [
1446
-                $this->_get_dir() . '/qtips/',
1447
-                EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1448
-            ];
1449
-            EEH_Qtip_Loader::instance()->register($qtips, $path);
1450
-        }
1451
-    }
1452
-
1453
-
1454
-    /**
1455
-     * _set_nav_tabs
1456
-     * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you
1457
-     * wish to add additional tabs or modify accordingly.
1458
-     *
1459
-     * @return void
1460
-     * @throws InvalidArgumentException
1461
-     * @throws InvalidInterfaceException
1462
-     * @throws InvalidDataTypeException
1463
-     */
1464
-    protected function _set_nav_tabs()
1465
-    {
1466
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1467
-        $i = 0;
1468
-        foreach ($this->_page_config as $slug => $config) {
1469
-            if (! is_array($config) || empty($config['nav'])) {
1470
-                continue;
1471
-            }
1472
-            // no nav tab for this config
1473
-            // check for persistent flag
1474
-            if ($slug !== $this->_req_action && isset($config['nav']['persistent']) && ! $config['nav']['persistent']) {
1475
-                // nav tab is only to appear when route requested.
1476
-                continue;
1477
-            }
1478
-            if (! $this->check_user_access($slug, true)) {
1479
-                // no nav tab because current user does not have access.
1480
-                continue;
1481
-            }
1482
-            $css_class                = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1483
-            $this->_nav_tabs[ $slug ] = [
1484
-                'url'       => isset($config['nav']['url'])
1485
-                    ? $config['nav']['url']
1486
-                    : self::add_query_args_and_nonce(
1487
-                        ['action' => $slug],
1488
-                        $this->_admin_base_url
1489
-                    ),
1490
-                'link_text' => isset($config['nav']['label'])
1491
-                    ? $config['nav']['label']
1492
-                    : ucwords(
1493
-                        str_replace('_', ' ', $slug)
1494
-                    ),
1495
-                'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1496
-                'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1497
-            ];
1498
-            $i++;
1499
-        }
1500
-        // if $this->_nav_tabs is empty then lets set the default
1501
-        if (empty($this->_nav_tabs)) {
1502
-            $this->_nav_tabs[ $this->_default_nav_tab_name ] = [
1503
-                'url'       => $this->_admin_base_url,
1504
-                'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1505
-                'css_class' => 'nav-tab-active',
1506
-                'order'     => 10,
1507
-            ];
1508
-        }
1509
-        // now let's sort the tabs according to order
1510
-        usort($this->_nav_tabs, [$this, '_sort_nav_tabs']);
1511
-    }
1512
-
1513
-
1514
-    /**
1515
-     * _set_current_labels
1516
-     * This method modifies the _labels property with any optional specific labels indicated in the _page_routes
1517
-     * property array
1518
-     *
1519
-     * @return void
1520
-     */
1521
-    private function _set_current_labels()
1522
-    {
1523
-        if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1524
-            foreach ($this->_route_config['labels'] as $label => $text) {
1525
-                if (is_array($text)) {
1526
-                    foreach ($text as $sublabel => $subtext) {
1527
-                        $this->_labels[ $label ][ $sublabel ] = $subtext;
1528
-                    }
1529
-                } else {
1530
-                    $this->_labels[ $label ] = $text;
1531
-                }
1532
-            }
1533
-        }
1534
-    }
1535
-
1536
-
1537
-    /**
1538
-     *        verifies user access for this admin page
1539
-     *
1540
-     * @param string $route_to_check if present then the capability for the route matching this string is checked.
1541
-     * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just
1542
-     *                               return false if verify fail.
1543
-     * @return bool
1544
-     * @throws InvalidArgumentException
1545
-     * @throws InvalidDataTypeException
1546
-     * @throws InvalidInterfaceException
1547
-     */
1548
-    public function check_user_access($route_to_check = '', $verify_only = false)
1549
-    {
1550
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1551
-        $route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1552
-        $capability     = ! empty($route_to_check) && isset($this->_page_routes[ $route_to_check ])
1553
-                          && is_array(
1554
-                              $this->_page_routes[ $route_to_check ]
1555
-                          )
1556
-                          && ! empty($this->_page_routes[ $route_to_check ]['capability'])
1557
-            ? $this->_page_routes[ $route_to_check ]['capability'] : null;
1558
-        if (empty($capability) && empty($route_to_check)) {
1559
-            $capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1560
-                : $this->_route['capability'];
1561
-        } else {
1562
-            $capability = empty($capability) ? 'manage_options' : $capability;
1563
-        }
1564
-        $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1565
-        if (! defined('DOING_AJAX')
1566
-            && (
1567
-                ! function_exists('is_admin')
1568
-                || ! EE_Registry::instance()->CAP->current_user_can(
1569
-                    $capability,
1570
-                    $this->page_slug
1571
-                    . '_'
1572
-                    . $route_to_check,
1573
-                    $id
1574
-                )
1575
-            )
1576
-        ) {
1577
-            if ($verify_only) {
1578
-                return false;
1579
-            }
1580
-            if (is_user_logged_in()) {
1581
-                wp_die(__('You do not have access to this route.', 'event_espresso'));
1582
-            } else {
1583
-                return false;
1584
-            }
1585
-        }
1586
-        return true;
1587
-    }
1588
-
1589
-
1590
-    /**
1591
-     * admin_init_global
1592
-     * This runs all the code that we want executed within the WP admin_init hook.
1593
-     * This method executes for ALL EE Admin pages.
1594
-     *
1595
-     * @return void
1596
-     */
1597
-    public function admin_init_global()
1598
-    {
1599
-    }
1600
-
1601
-
1602
-    /**
1603
-     * wp_loaded_global
1604
-     * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an
1605
-     * EE_Admin page and will execute on every EE Admin Page load
1606
-     *
1607
-     * @return void
1608
-     */
1609
-    public function wp_loaded()
1610
-    {
1611
-    }
1612
-
1613
-
1614
-    /**
1615
-     * admin_notices
1616
-     * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on
1617
-     * ALL EE_Admin pages.
1618
-     *
1619
-     * @return void
1620
-     */
1621
-    public function admin_notices_global()
1622
-    {
1623
-        $this->_display_no_javascript_warning();
1624
-        $this->_display_espresso_notices();
1625
-    }
1626
-
1627
-
1628
-    public function network_admin_notices_global()
1629
-    {
1630
-        $this->_display_no_javascript_warning();
1631
-        $this->_display_espresso_notices();
1632
-    }
1633
-
1634
-
1635
-    /**
1636
-     * admin_footer_scripts_global
1637
-     * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
1638
-     * will apply on ALL EE_Admin pages.
1639
-     *
1640
-     * @return void
1641
-     */
1642
-    public function admin_footer_scripts_global()
1643
-    {
1644
-        $this->_add_admin_page_ajax_loading_img();
1645
-        $this->_add_admin_page_overlay();
1646
-        // if metaboxes are present we need to add the nonce field
1647
-        if (isset($this->_route_config['metaboxes'])
1648
-            || isset($this->_route_config['list_table'])
1649
-            || (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes'])
1650
-        ) {
1651
-            wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1652
-            wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1653
-        }
1654
-    }
1655
-
1656
-
1657
-    /**
1658
-     * admin_footer_global
1659
-     * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particular method will apply on
1660
-     * ALL EE_Admin Pages.
1661
-     *
1662
-     * @return void
1663
-     */
1664
-    public function admin_footer_global()
1665
-    {
1666
-        // dialog container for dialog helper
1667
-        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1668
-        $d_cont .= '<div class="ee-notices"></div>';
1669
-        $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1670
-        $d_cont .= '</div>';
1671
-        echo $d_cont;
1672
-        // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1673
-        // help tour stuff?
1674
-        // if (isset($this->_help_tour[ $this->_req_action ])) {
1675
-        //     echo implode('<br />', $this->_help_tour[ $this->_req_action ]);
1676
-        // }
1677
-        // current set timezone for timezone js
1678
-        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1679
-    }
1680
-
1681
-
1682
-    /**
1683
-     * This function sees if there is a method for help popup content existing for the given route.  If there is then
1684
-     * we'll use the retrieved array to output the content using the template. For child classes: If you want to have
1685
-     * help popups then in your templates or your content you set "triggers" for the content using the
1686
-     * "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method
1687
-     * for the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup
1688
-     * method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content
1689
-     * for the
1690
-     * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined
1691
-     * "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1692
-     *    'help_trigger_id' => array(
1693
-     *        'title' => esc_html__('localized title for popup', 'event_espresso'),
1694
-     *        'content' => esc_html__('localized content for popup', 'event_espresso')
1695
-     *    )
1696
-     * );
1697
-     * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1698
-     *
1699
-     * @param array $help_array
1700
-     * @param bool  $display
1701
-     * @return string content
1702
-     * @throws DomainException
1703
-     * @throws EE_Error
1704
-     */
1705
-    protected function _set_help_popup_content($help_array = [], $display = false)
1706
-    {
1707
-        $content    = '';
1708
-        $help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1709
-        // loop through the array and setup content
1710
-        foreach ($help_array as $trigger => $help) {
1711
-            // make sure the array is setup properly
1712
-            if (! isset($help['title']) || ! isset($help['content'])) {
1713
-                throw new EE_Error(
1714
-                    esc_html__(
1715
-                        'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1716
-                        'event_espresso'
1717
-                    )
1718
-                );
1719
-            }
1720
-            // we're good so let'd setup the template vars and then assign parsed template content to our content.
1721
-            $template_args = [
1722
-                'help_popup_id'      => $trigger,
1723
-                'help_popup_title'   => $help['title'],
1724
-                'help_popup_content' => $help['content'],
1725
-            ];
1726
-            $content       .= EEH_Template::display_template(
1727
-                EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1728
-                $template_args,
1729
-                true
1730
-            );
1731
-        }
1732
-        if ($display) {
1733
-            echo $content;
1734
-            return '';
1735
-        }
1736
-        return $content;
1737
-    }
1738
-
1739
-
1740
-    /**
1741
-     * All this does is retrieve the help content array if set by the EE_Admin_Page child
1742
-     *
1743
-     * @return array properly formatted array for help popup content
1744
-     * @throws EE_Error
1745
-     */
1746
-    private function _get_help_content()
1747
-    {
1748
-        // what is the method we're looking for?
1749
-        $method_name = '_help_popup_content_' . $this->_req_action;
1750
-        // if method doesn't exist let's get out.
1751
-        if (! method_exists($this, $method_name)) {
1752
-            return [];
1753
-        }
1754
-        // k we're good to go let's retrieve the help array
1755
-        $help_array = call_user_func([$this, $method_name]);
1756
-        // make sure we've got an array!
1757
-        if (! is_array($help_array)) {
1758
-            throw new EE_Error(
1759
-                esc_html__(
1760
-                    'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
1761
-                    'event_espresso'
1762
-                )
1763
-            );
1764
-        }
1765
-        return $help_array;
1766
-    }
1767
-
1768
-
1769
-    /**
1770
-     * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1771
-     * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1772
-     * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1773
-     *
1774
-     * @param string  $trigger_id reference for retrieving the trigger content for the popup
1775
-     * @param boolean $display    if false then we return the trigger string
1776
-     * @param array   $dimensions an array of dimensions for the box (array(h,w))
1777
-     * @return string
1778
-     * @throws DomainException
1779
-     * @throws EE_Error
1780
-     */
1781
-    protected function _set_help_trigger($trigger_id, $display = true, $dimensions = ['400', '640'])
1782
-    {
1783
-        if (defined('DOING_AJAX')) {
1784
-            return '';
1785
-        }
1786
-        // let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1787
-        $help_array   = $this->_get_help_content();
1788
-        $help_content = '';
1789
-        if (empty($help_array) || ! isset($help_array[ $trigger_id ])) {
1790
-            $help_array[ $trigger_id ] = [
1791
-                'title'   => esc_html__('Missing Content', 'event_espresso'),
1792
-                'content' => esc_html__(
1793
-                    'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1794
-                    'event_espresso'
1795
-                ),
1796
-            ];
1797
-            $help_content              = $this->_set_help_popup_content($help_array, false);
1798
-        }
1799
-        // let's setup the trigger
1800
-        $content = '<a class="ee-dialog" href="?height='
1801
-                   . $dimensions[0]
1802
-                   . '&width='
1803
-                   . $dimensions[1]
1804
-                   . '&inlineId='
1805
-                   . $trigger_id
1806
-                   . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1807
-        $content .= $help_content;
1808
-        if ($display) {
1809
-            echo $content;
1810
-            return '';
1811
-        }
1812
-        return $content;
1813
-    }
1814
-
1815
-
1816
-    /**
1817
-     * _add_global_screen_options
1818
-     * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1819
-     * This particular method will add_screen_options on ALL EE_Admin Pages
1820
-     *
1821
-     * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1822
-     *         see also WP_Screen object documents...
1823
-     * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1824
-     * @abstract
1825
-     * @return void
1826
-     */
1827
-    private function _add_global_screen_options()
1828
-    {
1829
-    }
1830
-
1831
-
1832
-    /**
1833
-     * _add_global_feature_pointers
1834
-     * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1835
-     * This particular method will implement feature pointers for ALL EE_Admin pages.
1836
-     * Note: this is just a placeholder for now.  Implementation will come down the road
1837
-     *
1838
-     * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
1839
-     *         extended) also see:
1840
-     * @link   http://eamann.com/tech/wordpress-portland/
1841
-     * @abstract
1842
-     * @return void
1843
-     */
1844
-    private function _add_global_feature_pointers()
1845
-    {
1846
-    }
1847
-
1848
-
1849
-    /**
1850
-     * load_global_scripts_styles
1851
-     * The scripts and styles enqueued in here will be loaded on every EE Admin page
1852
-     *
1853
-     * @return void
1854
-     */
1855
-    public function load_global_scripts_styles()
1856
-    {
1857
-        /** STYLES **/
1858
-        // add debugging styles
1859
-        if (WP_DEBUG) {
1860
-            add_action('admin_head', [$this, 'add_xdebug_style']);
1861
-        }
1862
-        // register all styles
1863
-        wp_register_style(
1864
-            'espresso-ui-theme',
1865
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1866
-            [],
1867
-            EVENT_ESPRESSO_VERSION
1868
-        );
1869
-        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', [], EVENT_ESPRESSO_VERSION);
1870
-        // helpers styles
1871
-        wp_register_style(
1872
-            'ee-text-links',
1873
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1874
-            [],
1875
-            EVENT_ESPRESSO_VERSION
1876
-        );
1877
-        /** SCRIPTS **/
1878
-        // register all scripts
1879
-        wp_register_script(
1880
-            'ee-dialog',
1881
-            EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1882
-            ['jquery', 'jquery-ui-draggable'],
1883
-            EVENT_ESPRESSO_VERSION,
1884
-            true
1885
-        );
1886
-        wp_register_script(
1887
-            'ee_admin_js',
1888
-            EE_ADMIN_URL . 'assets/ee-admin-page.js',
1889
-            ['espresso_core', 'ee-parse-uri', 'ee-dialog'],
1890
-            EVENT_ESPRESSO_VERSION,
1891
-            true
1892
-        );
1893
-        wp_register_script(
1894
-            'jquery-ui-timepicker-addon',
1895
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1896
-            ['jquery-ui-datepicker', 'jquery-ui-slider'],
1897
-            EVENT_ESPRESSO_VERSION,
1898
-            true
1899
-        );
1900
-        // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1901
-        // if (EE_Registry::instance()->CFG->admin->help_tour_activation) {
1902
-        //     add_filter('FHEE_load_joyride', '__return_true');
1903
-        // }
1904
-        // script for sorting tables
1905
-        wp_register_script(
1906
-            'espresso_ajax_table_sorting',
1907
-            EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1908
-            ['ee_admin_js', 'jquery-ui-sortable'],
1909
-            EVENT_ESPRESSO_VERSION,
1910
-            true
1911
-        );
1912
-        // script for parsing uri's
1913
-        wp_register_script(
1914
-            'ee-parse-uri',
1915
-            EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1916
-            [],
1917
-            EVENT_ESPRESSO_VERSION,
1918
-            true
1919
-        );
1920
-        // and parsing associative serialized form elements
1921
-        wp_register_script(
1922
-            'ee-serialize-full-array',
1923
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1924
-            ['jquery'],
1925
-            EVENT_ESPRESSO_VERSION,
1926
-            true
1927
-        );
1928
-        // helpers scripts
1929
-        wp_register_script(
1930
-            'ee-text-links',
1931
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1932
-            ['jquery'],
1933
-            EVENT_ESPRESSO_VERSION,
1934
-            true
1935
-        );
1936
-        wp_register_script(
1937
-            'ee-moment-core',
1938
-            EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1939
-            [],
1940
-            EVENT_ESPRESSO_VERSION,
1941
-            true
1942
-        );
1943
-        wp_register_script(
1944
-            'ee-moment',
1945
-            EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1946
-            ['ee-moment-core'],
1947
-            EVENT_ESPRESSO_VERSION,
1948
-            true
1949
-        );
1950
-        wp_register_script(
1951
-            'ee-datepicker',
1952
-            EE_ADMIN_URL . 'assets/ee-datepicker.js',
1953
-            ['jquery-ui-timepicker-addon', 'ee-moment'],
1954
-            EVENT_ESPRESSO_VERSION,
1955
-            true
1956
-        );
1957
-        // google charts
1958
-        wp_register_script(
1959
-            'google-charts',
1960
-            'https://www.gstatic.com/charts/loader.js',
1961
-            [],
1962
-            EVENT_ESPRESSO_VERSION,
1963
-            false
1964
-        );
1965
-        // ENQUEUE ALL BASICS BY DEFAULT
1966
-        wp_enqueue_style('ee-admin-css');
1967
-        wp_enqueue_script('ee_admin_js');
1968
-        wp_enqueue_script('ee-accounting');
1969
-        wp_enqueue_script('jquery-validate');
1970
-        // taking care of metaboxes
1971
-        if (empty($this->_cpt_route)
1972
-            && (isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes']))
1973
-        ) {
1974
-            wp_enqueue_script('dashboard');
1975
-        }
1976
-        // LOCALIZED DATA
1977
-        // localize script for ajax lazy loading
1978
-        $lazy_loader_container_ids = apply_filters(
1979
-            'FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers',
1980
-            ['espresso_news_post_box_content']
1981
-        );
1982
-        wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
1983
-        // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1984
-        // /**
1985
-        //  * help tour stuff
1986
-        //  */
1987
-        // if (! empty($this->_help_tour)) {
1988
-        //     // register the js for kicking things off
1989
-        //     wp_enqueue_script(
1990
-        //         'ee-help-tour',
1991
-        //         EE_ADMIN_URL . 'assets/ee-help-tour.js',
1992
-        //         array('jquery-joyride'),
1993
-        //         EVENT_ESPRESSO_VERSION,
1994
-        //         true
1995
-        //     );
1996
-        //     $tours = array();
1997
-        //     // setup tours for the js tour object
1998
-        //     foreach ($this->_help_tour['tours'] as $tour) {
1999
-        //         if ($tour instanceof EE_Help_Tour) {
2000
-        //             $tours[] = array(
2001
-        //                 'id'      => $tour->get_slug(),
2002
-        //                 'options' => $tour->get_options(),
2003
-        //             );
2004
-        //         }
2005
-        //     }
2006
-        //     wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
2007
-        //     // admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
2008
-        // }
2009
-    }
2010
-
2011
-
2012
-    /**
2013
-     *        admin_footer_scripts_eei18n_js_strings
2014
-     *
2015
-     * @return        void
2016
-     */
2017
-    public function admin_footer_scripts_eei18n_js_strings()
2018
-    {
2019
-        EE_Registry::$i18n_js_strings['ajax_url']       = WP_AJAX_URL;
2020
-        EE_Registry::$i18n_js_strings['confirm_delete'] = esc_html__(
2021
-            'Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!',
2022
-            'event_espresso'
2023
-        );
2024
-        EE_Registry::$i18n_js_strings['January']        = esc_html__('January', 'event_espresso');
2025
-        EE_Registry::$i18n_js_strings['February']       = esc_html__('February', 'event_espresso');
2026
-        EE_Registry::$i18n_js_strings['March']          = esc_html__('March', 'event_espresso');
2027
-        EE_Registry::$i18n_js_strings['April']          = esc_html__('April', 'event_espresso');
2028
-        EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2029
-        EE_Registry::$i18n_js_strings['June']           = esc_html__('June', 'event_espresso');
2030
-        EE_Registry::$i18n_js_strings['July']           = esc_html__('July', 'event_espresso');
2031
-        EE_Registry::$i18n_js_strings['August']         = esc_html__('August', 'event_espresso');
2032
-        EE_Registry::$i18n_js_strings['September']      = esc_html__('September', 'event_espresso');
2033
-        EE_Registry::$i18n_js_strings['October']        = esc_html__('October', 'event_espresso');
2034
-        EE_Registry::$i18n_js_strings['November']       = esc_html__('November', 'event_espresso');
2035
-        EE_Registry::$i18n_js_strings['December']       = esc_html__('December', 'event_espresso');
2036
-        EE_Registry::$i18n_js_strings['Jan']            = esc_html__('Jan', 'event_espresso');
2037
-        EE_Registry::$i18n_js_strings['Feb']            = esc_html__('Feb', 'event_espresso');
2038
-        EE_Registry::$i18n_js_strings['Mar']            = esc_html__('Mar', 'event_espresso');
2039
-        EE_Registry::$i18n_js_strings['Apr']            = esc_html__('Apr', 'event_espresso');
2040
-        EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2041
-        EE_Registry::$i18n_js_strings['Jun']            = esc_html__('Jun', 'event_espresso');
2042
-        EE_Registry::$i18n_js_strings['Jul']            = esc_html__('Jul', 'event_espresso');
2043
-        EE_Registry::$i18n_js_strings['Aug']            = esc_html__('Aug', 'event_espresso');
2044
-        EE_Registry::$i18n_js_strings['Sep']            = esc_html__('Sep', 'event_espresso');
2045
-        EE_Registry::$i18n_js_strings['Oct']            = esc_html__('Oct', 'event_espresso');
2046
-        EE_Registry::$i18n_js_strings['Nov']            = esc_html__('Nov', 'event_espresso');
2047
-        EE_Registry::$i18n_js_strings['Dec']            = esc_html__('Dec', 'event_espresso');
2048
-        EE_Registry::$i18n_js_strings['Sunday']         = esc_html__('Sunday', 'event_espresso');
2049
-        EE_Registry::$i18n_js_strings['Monday']         = esc_html__('Monday', 'event_espresso');
2050
-        EE_Registry::$i18n_js_strings['Tuesday']        = esc_html__('Tuesday', 'event_espresso');
2051
-        EE_Registry::$i18n_js_strings['Wednesday']      = esc_html__('Wednesday', 'event_espresso');
2052
-        EE_Registry::$i18n_js_strings['Thursday']       = esc_html__('Thursday', 'event_espresso');
2053
-        EE_Registry::$i18n_js_strings['Friday']         = esc_html__('Friday', 'event_espresso');
2054
-        EE_Registry::$i18n_js_strings['Saturday']       = esc_html__('Saturday', 'event_espresso');
2055
-        EE_Registry::$i18n_js_strings['Sun']            = esc_html__('Sun', 'event_espresso');
2056
-        EE_Registry::$i18n_js_strings['Mon']            = esc_html__('Mon', 'event_espresso');
2057
-        EE_Registry::$i18n_js_strings['Tue']            = esc_html__('Tue', 'event_espresso');
2058
-        EE_Registry::$i18n_js_strings['Wed']            = esc_html__('Wed', 'event_espresso');
2059
-        EE_Registry::$i18n_js_strings['Thu']            = esc_html__('Thu', 'event_espresso');
2060
-        EE_Registry::$i18n_js_strings['Fri']            = esc_html__('Fri', 'event_espresso');
2061
-        EE_Registry::$i18n_js_strings['Sat']            = esc_html__('Sat', 'event_espresso');
2062
-    }
2063
-
2064
-
2065
-    /**
2066
-     *        load enhanced xdebug styles for ppl with failing eyesight
2067
-     *
2068
-     * @return        void
2069
-     */
2070
-    public function add_xdebug_style()
2071
-    {
2072
-        echo '<style>.xdebug-error { font-size:1.5em; }</style>';
2073
-    }
2074
-
2075
-
2076
-    /************************/
2077
-    /** LIST TABLE METHODS **/
2078
-    /************************/
2079
-    /**
2080
-     * this sets up the list table if the current view requires it.
2081
-     *
2082
-     * @return void
2083
-     * @throws EE_Error
2084
-     */
2085
-    protected function _set_list_table()
2086
-    {
2087
-        // first is this a list_table view?
2088
-        if (! isset($this->_route_config['list_table'])) {
2089
-            return;
2090
-        } //not a list_table view so get out.
2091
-        // list table functions are per view specific (because some admin pages might have more than one list table!)
2092
-        $list_table_view = '_set_list_table_views_' . $this->_req_action;
2093
-        if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2094
-            // user error msg
2095
-            $error_msg = esc_html__(
2096
-                'An error occurred. The requested list table views could not be found.',
2097
-                'event_espresso'
2098
-            );
2099
-            // developer error msg
2100
-            $error_msg .= '||'
2101
-                          . sprintf(
2102
-                              esc_html__(
2103
-                                  'List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.',
2104
-                                  'event_espresso'
2105
-                              ),
2106
-                              $this->_req_action,
2107
-                              $list_table_view
2108
-                          );
2109
-            throw new EE_Error($error_msg);
2110
-        }
2111
-        // let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2112
-        $this->_views = apply_filters(
2113
-            'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2114
-            $this->_views
2115
-        );
2116
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2117
-        $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2118
-        $this->_set_list_table_view();
2119
-        $this->_set_list_table_object();
2120
-    }
2121
-
2122
-
2123
-    /**
2124
-     * set current view for List Table
2125
-     *
2126
-     * @return void
2127
-     */
2128
-    protected function _set_list_table_view()
2129
-    {
2130
-        $this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
2131
-        $status = $this->request->getRequestParam('status', null, 'key');
2132
-        $this->_view = $status && array_key_exists($status, $this->_views)
2133
-            ? $status
2134
-            : $this->_view;
2135
-    }
2136
-
2137
-
2138
-    /**
2139
-     * _set_list_table_object
2140
-     * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
2141
-     *
2142
-     * @throws InvalidInterfaceException
2143
-     * @throws InvalidArgumentException
2144
-     * @throws InvalidDataTypeException
2145
-     * @throws EE_Error
2146
-     * @throws InvalidInterfaceException
2147
-     */
2148
-    protected function _set_list_table_object()
2149
-    {
2150
-        if (isset($this->_route_config['list_table'])) {
2151
-            if (! class_exists($this->_route_config['list_table'])) {
2152
-                throw new EE_Error(
2153
-                    sprintf(
2154
-                        esc_html__(
2155
-                            'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
2156
-                            'event_espresso'
2157
-                        ),
2158
-                        $this->_route_config['list_table'],
2159
-                        get_class($this)
2160
-                    )
2161
-                );
2162
-            }
2163
-            $this->_list_table_object = $this->loader->getShared(
2164
-                $this->_route_config['list_table'],
2165
-                [$this]
2166
-            );
2167
-        }
2168
-    }
2169
-
2170
-
2171
-    /**
2172
-     * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
2173
-     *
2174
-     * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
2175
-     *                                                    urls.  The array should be indexed by the view it is being
2176
-     *                                                    added to.
2177
-     * @return array
2178
-     */
2179
-    public function get_list_table_view_RLs($extra_query_args = [])
2180
-    {
2181
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2182
-        if (empty($this->_views)) {
2183
-            $this->_views = [];
2184
-        }
2185
-        // cycle thru views
2186
-        foreach ($this->_views as $key => $view) {
2187
-            $query_args = [];
2188
-            // check for current view
2189
-            $this->_views[ $key ]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2190
-            $query_args['action']                        = $this->_req_action;
2191
-            $query_args[ $this->_req_action . '_nonce' ] = wp_create_nonce($query_args['action'] . '_nonce');
2192
-            $query_args['status']                        = $view['slug'];
2193
-            // merge any other arguments sent in.
2194
-            if (isset($extra_query_args[ $view['slug'] ])) {
2195
-                $query_args = array_merge($query_args, $extra_query_args[ $view['slug'] ]);
2196
-            }
2197
-            $this->_views[ $key ]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2198
-        }
2199
-        return $this->_views;
2200
-    }
2201
-
2202
-
2203
-    /**
2204
-     * _entries_per_page_dropdown
2205
-     * generates a drop down box for selecting the number of visible rows in an admin page list table
2206
-     *
2207
-     * @param int $max_entries total number of rows in the table
2208
-     * @return string
2209
-     * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how
2210
-     *         WP does it.
2211
-     */
2212
-    protected function _entries_per_page_dropdown($max_entries = 0)
2213
-    {
2214
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2215
-        $values   = [10, 25, 50, 100];
2216
-        $per_page = $this->request->getRequestParam('per_page', 10, 'int');
2217
-        if ($max_entries) {
2218
-            $values[] = $max_entries;
2219
-            sort($values);
2220
-        }
2221
-        $entries_per_page_dropdown = '
115
+	/**
116
+	 * Used to hold default query args for list table routes to help preserve stickiness of filters for carried out
117
+	 * actions.
118
+	 *
119
+	 * @since 4.6.x
120
+	 * @var array.
121
+	 */
122
+	protected $_default_route_query_args;
123
+
124
+	// set via request page and action args.
125
+	protected $_current_page;
126
+
127
+	protected $_current_view;
128
+
129
+	protected $_current_page_view_url;
130
+
131
+	// sanitized request action (and nonce)
132
+
133
+	/**
134
+	 * @var string $_req_action
135
+	 */
136
+	protected $_req_action;
137
+
138
+	/**
139
+	 * @var string $_req_nonce
140
+	 */
141
+	protected $_req_nonce;
142
+
143
+	// search related
144
+	protected $_search_btn_label;
145
+
146
+	protected $_search_box_callback;
147
+
148
+	/**
149
+	 * WP Current Screen object
150
+	 *
151
+	 * @var WP_Screen
152
+	 */
153
+	protected $_current_screen;
154
+
155
+	// for holding EE_Admin_Hooks object when needed (set via set_hook_object())
156
+	protected $_hook_obj;
157
+
158
+	// for holding incoming request data
159
+	protected $_req_data = [];
160
+
161
+	// yes / no array for admin form fields
162
+	protected $_yes_no_values = [];
163
+
164
+	// some default things shared by all child classes
165
+	protected $_default_espresso_metaboxes;
166
+
167
+	/**
168
+	 *    EE_Registry Object
169
+	 *
170
+	 * @var    EE_Registry
171
+	 */
172
+	protected $EE = null;
173
+
174
+
175
+	/**
176
+	 * This is just a property that flags whether the given route is a caffeinated route or not.
177
+	 *
178
+	 * @var boolean
179
+	 */
180
+	protected $_is_caf = false;
181
+
182
+
183
+	/**
184
+	 * @Constructor
185
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
186
+	 * @throws EE_Error
187
+	 * @throws InvalidArgumentException
188
+	 * @throws ReflectionException
189
+	 * @throws InvalidDataTypeException
190
+	 * @throws InvalidInterfaceException
191
+	 */
192
+	public function __construct($routing = true)
193
+	{
194
+		$this->loader  = LoaderFactory::getLoader();
195
+		$this->request = $this->loader->getShared(RequestInterface::class);
196
+
197
+		if (strpos($this->_get_dir(), 'caffeinated') !== false) {
198
+			$this->_is_caf = true;
199
+		}
200
+		$this->_yes_no_values = [
201
+			['id' => true, 'text' => esc_html__('Yes', 'event_espresso')],
202
+			['id' => false, 'text' => esc_html__('No', 'event_espresso')],
203
+		];
204
+		// set the _req_data property.
205
+		$this->_req_data = $this->request->requestParams();
206
+		// routing enabled?
207
+		$this->_routing = $routing;
208
+		// set initial page props (child method)
209
+		$this->_init_page_props();
210
+		// set global defaults
211
+		$this->_set_defaults();
212
+		// set early because incoming requests could be ajax related and we need to register those hooks.
213
+		$this->_global_ajax_hooks();
214
+		$this->_ajax_hooks();
215
+		// other_page_hooks have to be early too.
216
+		$this->_do_other_page_hooks();
217
+		// This just allows us to have extending classes do something specific
218
+		// before the parent constructor runs _page_setup().
219
+		if (method_exists($this, '_before_page_setup')) {
220
+			$this->_before_page_setup();
221
+		}
222
+		// set up page dependencies
223
+		$this->_page_setup();
224
+	}
225
+
226
+
227
+	/**
228
+	 * _init_page_props
229
+	 * Child classes use to set at least the following properties:
230
+	 * $page_slug.
231
+	 * $page_label.
232
+	 *
233
+	 * @abstract
234
+	 * @return void
235
+	 */
236
+	abstract protected function _init_page_props();
237
+
238
+
239
+	/**
240
+	 * _ajax_hooks
241
+	 * child classes put all their add_action('wp_ajax_{name_of_hook}') hooks in here.
242
+	 * Note: within the ajax callback methods.
243
+	 *
244
+	 * @abstract
245
+	 * @return void
246
+	 */
247
+	abstract protected function _ajax_hooks();
248
+
249
+
250
+	/**
251
+	 * _define_page_props
252
+	 * child classes define page properties in here.  Must include at least:
253
+	 * $_admin_base_url = base_url for all admin pages
254
+	 * $_admin_page_title = default admin_page_title for admin pages
255
+	 * $_labels = array of default labels for various automatically generated elements:
256
+	 *    array(
257
+	 *        'buttons' => array(
258
+	 *            'add' => esc_html__('label for add new button'),
259
+	 *            'edit' => esc_html__('label for edit button'),
260
+	 *            'delete' => esc_html__('label for delete button')
261
+	 *            )
262
+	 *        )
263
+	 *
264
+	 * @abstract
265
+	 * @return void
266
+	 */
267
+	abstract protected function _define_page_props();
268
+
269
+
270
+	/**
271
+	 * _set_page_routes
272
+	 * child classes use this to define the page routes for all subpages handled by the class.  Page routes are
273
+	 * assigned to a action => method pairs in an array and to the $_page_routes property.  Each page route must also
274
+	 * have a 'default' route. Here's the format
275
+	 * $this->_page_routes = array(
276
+	 *        'default' => array(
277
+	 *            'func' => '_default_method_handling_route',
278
+	 *            'args' => array('array','of','args'),
279
+	 *            'noheader' => true, //add this in if this page route is processed before any headers are loaded (i.e.
280
+	 *            ajax request, backend processing)
281
+	 *            'headers_sent_route'=>'headers_route_reference', //add this if noheader=>true, and you want to load a
282
+	 *            headers route after.  The string you enter here should match the defined route reference for a
283
+	 *            headers sent route.
284
+	 *            'capability' => 'route_capability', //indicate a string for minimum capability required to access
285
+	 *            this route.
286
+	 *            'obj_id' => 10 // if this route has an object id, then this can include it (used for capability
287
+	 *            checks).
288
+	 *        ),
289
+	 *        'insert_item' => '_method_for_handling_insert_item' //this can be used if all we need to have is a
290
+	 *        handling method.
291
+	 *        )
292
+	 * )
293
+	 *
294
+	 * @abstract
295
+	 * @return void
296
+	 */
297
+	abstract protected function _set_page_routes();
298
+
299
+
300
+	/**
301
+	 * _set_page_config
302
+	 * child classes use this to define the _page_config array for all subpages handled by the class. Each key in the
303
+	 * array corresponds to the page_route for the loaded page. Format:
304
+	 * $this->_page_config = array(
305
+	 *        'default' => array(
306
+	 *            'labels' => array(
307
+	 *                'buttons' => array(
308
+	 *                    'add' => esc_html__('label for adding item'),
309
+	 *                    'edit' => esc_html__('label for editing item'),
310
+	 *                    'delete' => esc_html__('label for deleting item')
311
+	 *                ),
312
+	 *                'publishbox' => esc_html__('Localized Title for Publish metabox', 'event_espresso')
313
+	 *            ), //optional an array of custom labels for various automatically generated elements to use on the
314
+	 *            page. If this isn't present then the defaults will be used as set for the $this->_labels in
315
+	 *            _define_page_props() method
316
+	 *            'nav' => array(
317
+	 *                'label' => esc_html__('Label for Tab', 'event_espresso').
318
+	 *                'url' => 'http://someurl', //automatically generated UNLESS you define
319
+	 *                'css_class' => 'css-class', //automatically generated UNLESS you define
320
+	 *                'order' => 10, //required to indicate tab position.
321
+	 *                'persistent' => false //if you want the nav tab to ONLY display when the specific route is
322
+	 *                displayed then add this parameter.
323
+	 *            'list_table' => 'name_of_list_table' //string for list table class to be loaded for this admin_page.
324
+	 *            'metaboxes' => array('metabox1', 'metabox2'), //if present this key indicates we want to load
325
+	 *            metaboxes set for eventespresso admin pages.
326
+	 *            'has_metaboxes' => true, //this boolean flag can simply be used to indicate if the route will have
327
+	 *            metaboxes.  Typically this is used if the 'metaboxes' index is not used because metaboxes are added
328
+	 *            later.  We just use this flag to make sure the necessary js gets enqueued on page load.
329
+	 *            'has_help_popups' => false //defaults(true) //this boolean flag can simply be used to indicate if the
330
+	 *            given route has help popups setup and if it does then we need to make sure thickbox is enqueued.
331
+	 *            'columns' => array(4, 2), //this key triggers the setup of a page that uses columns (metaboxes).  The
332
+	 *            array indicates the max number of columns (4) and the default number of columns on page load (2).
333
+	 *            There is an option in the "screen_options" dropdown that is setup so users can pick what columns they
334
+	 *            want to display.
335
+	 *            'help_tabs' => array( //this is used for adding help tabs to a page
336
+	 *                'tab_id' => array(
337
+	 *                    'title' => 'tab_title',
338
+	 *                    'filename' => 'name_of_file_containing_content', //this is the primary method for setting
339
+	 *                    help tab content.  The fallback if it isn't present is to try a the callback.  Filename
340
+	 *                    should match a file in the admin folder's "help_tabs" dir (ie..
341
+	 *                    events/help_tabs/name_of_file_containing_content.help_tab.php)
342
+	 *                    'callback' => 'callback_method_for_content', //if 'filename' isn't present then system will
343
+	 *                    attempt to use the callback which should match the name of a method in the class
344
+	 *                    ),
345
+	 *                'tab2_id' => array(
346
+	 *                    'title' => 'tab2 title',
347
+	 *                    'filename' => 'file_name_2'
348
+	 *                    'callback' => 'callback_method_for_content',
349
+	 *                 ),
350
+	 *            'help_sidebar' => 'callback_for_sidebar_content', //this is used for setting up the sidebar in the
351
+	 *            help tab area on an admin page. @return void
352
+	 *
353
+	 * @link
354
+	 *                http://make.wordpress.org/core/2011/12/06/help-and-screen-api-changes-in-3-3/
355
+	 *                'help_tour' => array(
356
+	 *                'name_of_help_tour_class', //all help tours should be a child class of EE_Help_Tour and located
357
+	 *                in a folder for this admin page named "help_tours", a file name matching the key given here
358
+	 *                (name_of_help_tour_class.class.php), and class matching key given here (name_of_help_tour_class)
359
+	 *                ),
360
+	 *                'require_nonce' => TRUE //this is used if you want to set a route to NOT require a nonce (default
361
+	 *                is true if it isn't present).  To remove the requirement for a nonce check when this route is
362
+	 *                visited just set
363
+	 *                'require_nonce' to FALSE
364
+	 *                )
365
+	 *                )
366
+	 *
367
+	 * @abstract
368
+	 */
369
+	abstract protected function _set_page_config();
370
+
371
+
372
+
373
+
374
+
375
+	/** end sample help_tour methods **/
376
+	/**
377
+	 * _add_screen_options
378
+	 * Child classes can add any extra wp_screen_options within this method using built-in WP functions/methods for
379
+	 * doing so. Note child classes can also define _add_screen_options_($this->_current_view) to limit screen options
380
+	 * to a particular view.
381
+	 *
382
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
383
+	 *         see also WP_Screen object documents...
384
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
385
+	 * @abstract
386
+	 * @return void
387
+	 */
388
+	abstract protected function _add_screen_options();
389
+
390
+
391
+	/**
392
+	 * _add_feature_pointers
393
+	 * Child classes should use this method for implementing any "feature pointers" (using built-in WP styling js).
394
+	 * Note child classes can also define _add_feature_pointers_($this->_current_view) to limit screen options to a
395
+	 * particular view. Note: this is just a placeholder for now.  Implementation will come down the road See:
396
+	 * WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
397
+	 * extended) also see:
398
+	 *
399
+	 * @link   http://eamann.com/tech/wordpress-portland/
400
+	 * @abstract
401
+	 * @return void
402
+	 */
403
+	abstract protected function _add_feature_pointers();
404
+
405
+
406
+	/**
407
+	 * load_scripts_styles
408
+	 * child classes put their wp_enqueue_script and wp_enqueue_style hooks in here for anything they need loaded for
409
+	 * their pages/subpages.  Note this is for all pages/subpages of the system.  You can also load only specific
410
+	 * scripts/styles per view by putting them in a dynamic function in this format
411
+	 * (load_scripts_styles_{$this->_current_view}) which matches your page route (action request arg)
412
+	 *
413
+	 * @abstract
414
+	 * @return void
415
+	 */
416
+	abstract public function load_scripts_styles();
417
+
418
+
419
+	/**
420
+	 * admin_init
421
+	 * Anything that should be set/executed at 'admin_init' WP hook runtime should be put in here.  This will apply to
422
+	 * all pages/views loaded by child class.
423
+	 *
424
+	 * @abstract
425
+	 * @return void
426
+	 */
427
+	abstract public function admin_init();
428
+
429
+
430
+	/**
431
+	 * admin_notices
432
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply to
433
+	 * all pages/views loaded by child class.
434
+	 *
435
+	 * @abstract
436
+	 * @return void
437
+	 */
438
+	abstract public function admin_notices();
439
+
440
+
441
+	/**
442
+	 * admin_footer_scripts
443
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
444
+	 * will apply to all pages/views loaded by child class.
445
+	 *
446
+	 * @return void
447
+	 */
448
+	abstract public function admin_footer_scripts();
449
+
450
+
451
+	/**
452
+	 * admin_footer
453
+	 * anything triggered by the 'admin_footer' WP action hook should be added to here. This particular method will
454
+	 * apply to all pages/views loaded by child class.
455
+	 *
456
+	 * @return void
457
+	 */
458
+	public function admin_footer()
459
+	{
460
+	}
461
+
462
+
463
+	/**
464
+	 * _global_ajax_hooks
465
+	 * all global add_action('wp_ajax_{name_of_hook}') hooks in here.
466
+	 * Note: within the ajax callback methods.
467
+	 *
468
+	 * @abstract
469
+	 * @return void
470
+	 */
471
+	protected function _global_ajax_hooks()
472
+	{
473
+		// for lazy loading of metabox content
474
+		add_action('wp_ajax_espresso-ajax-content', [$this, 'ajax_metabox_content'], 10);
475
+	}
476
+
477
+
478
+	public function ajax_metabox_content()
479
+	{
480
+		$content_id  = $this->request->getRequestParam('contentid', '');
481
+		$content_url = $this->request->getRequestParam('contenturl', '', 'url');
482
+		self::cached_rss_display($content_id, $content_url);
483
+		wp_die();
484
+	}
485
+
486
+
487
+	/**
488
+	 * _page_setup
489
+	 * Makes sure any things that need to be loaded early get handled.  We also escape early here if the page requested
490
+	 * doesn't match the object.
491
+	 *
492
+	 * @final
493
+	 * @return void
494
+	 * @throws EE_Error
495
+	 * @throws InvalidArgumentException
496
+	 * @throws ReflectionException
497
+	 * @throws InvalidDataTypeException
498
+	 * @throws InvalidInterfaceException
499
+	 */
500
+	final protected function _page_setup()
501
+	{
502
+		// requires?
503
+		// admin_init stuff - global - we're setting this REALLY early
504
+		// so if EE_Admin pages have to hook into other WP pages they can.
505
+		// But keep in mind, not everything is available from the EE_Admin Page object at this point.
506
+		add_action('admin_init', [$this, 'admin_init_global'], 5);
507
+		// next verify if we need to load anything...
508
+		$this->_current_page = $this->request->getRequestParam('page', '', 'key');
509
+		$this->page_folder   = strtolower(
510
+			str_replace(['_Admin_Page', 'Extend_'], '', get_class($this))
511
+		);
512
+		global $ee_menu_slugs;
513
+		$ee_menu_slugs = (array) $ee_menu_slugs;
514
+		if (
515
+			! defined('DOING_AJAX')
516
+			&& (! $this->_current_page || ! isset($ee_menu_slugs[ $this->_current_page ]))
517
+		) {
518
+			return;
519
+		}
520
+		// because WP List tables have two duplicate select inputs for choosing bulk actions,
521
+		// we need to copy the action from the second to the first
522
+		$action     = $this->request->getRequestParam('action', '-1', 'key');
523
+		$action2    = $this->request->getRequestParam('action2', '-1', 'key');
524
+		$action     = $action !== '-1' ? $action : $action2;
525
+		$req_action = $action !== '-1' ? $action : 'default';
526
+
527
+		// if a specific 'route' has been set, and the action is 'default' OR we are doing_ajax
528
+		// then let's use the route as the action.
529
+		// This covers cases where we're coming in from a list table that isn't on the default route.
530
+		$route = $this->request->getRequestParam('route');
531
+		$this->_req_action = $route && ($req_action === 'default' || $this->request->isAjax())
532
+			? $route
533
+			: $req_action;
534
+		$this->_current_view = $this->_req_action;
535
+		$this->_req_nonce    = $this->_req_action . '_nonce';
536
+		$this->_define_page_props();
537
+		$this->_current_page_view_url = add_query_arg(
538
+			['page' => $this->_current_page, 'action' => $this->_current_view],
539
+			$this->_admin_base_url
540
+		);
541
+		// default things
542
+		$this->_default_espresso_metaboxes = [
543
+			'_espresso_news_post_box',
544
+			'_espresso_links_post_box',
545
+			'_espresso_ratings_request',
546
+			'_espresso_sponsors_post_box',
547
+		];
548
+		// set page configs
549
+		$this->_set_page_routes();
550
+		$this->_set_page_config();
551
+		// let's include any referrer data in our default_query_args for this route for "stickiness".
552
+		if ($this->request->requestParamIsSet('wp_referer')) {
553
+			$this->_default_route_query_args['wp_referer'] = $this->request->getRequestParam(
554
+				'wp_referer',
555
+				null,
556
+				'url'
557
+			);
558
+		}
559
+		// for caffeinated and other extended functionality.
560
+		//  If there is a _extend_page_config method
561
+		// then let's run that to modify the all the various page configuration arrays
562
+		if (method_exists($this, '_extend_page_config')) {
563
+			$this->_extend_page_config();
564
+		}
565
+		// for CPT and other extended functionality.
566
+		// If there is an _extend_page_config_for_cpt
567
+		// then let's run that to modify all the various page configuration arrays.
568
+		if (method_exists($this, '_extend_page_config_for_cpt')) {
569
+			$this->_extend_page_config_for_cpt();
570
+		}
571
+		// filter routes and page_config so addons can add their stuff. Filtering done per class
572
+		$this->_page_routes = apply_filters(
573
+			'FHEE__' . get_class($this) . '__page_setup__page_routes',
574
+			$this->_page_routes,
575
+			$this
576
+		);
577
+		$this->_page_config = apply_filters(
578
+			'FHEE__' . get_class($this) . '__page_setup__page_config',
579
+			$this->_page_config,
580
+			$this
581
+		);
582
+		// if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
583
+		// then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
584
+		if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
585
+			add_action(
586
+				'AHEE__EE_Admin_Page__route_admin_request',
587
+				[$this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view],
588
+				10,
589
+				2
590
+			);
591
+		}
592
+		// next route only if routing enabled
593
+		if ($this->_routing && ! defined('DOING_AJAX')) {
594
+			$this->_verify_routes();
595
+			// next let's just check user_access and kill if no access
596
+			$this->check_user_access();
597
+			if ($this->_is_UI_request) {
598
+				// admin_init stuff - global, all views for this page class, specific view
599
+				add_action('admin_init', [$this, 'admin_init'], 10);
600
+				if (method_exists($this, 'admin_init_' . $this->_current_view)) {
601
+					add_action('admin_init', [$this, 'admin_init_' . $this->_current_view], 15);
602
+				}
603
+			} else {
604
+				// hijack regular WP loading and route admin request immediately
605
+				@ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT));
606
+				$this->route_admin_request();
607
+			}
608
+		}
609
+	}
610
+
611
+
612
+	/**
613
+	 * Provides a way for related child admin pages to load stuff on the loaded admin page.
614
+	 *
615
+	 * @return void
616
+	 * @throws ReflectionException
617
+	 * @throws EE_Error
618
+	 */
619
+	private function _do_other_page_hooks()
620
+	{
621
+		$registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, []);
622
+		foreach ($registered_pages as $page) {
623
+			// now let's setup the file name and class that should be present
624
+			$classname = str_replace('.class.php', '', $page);
625
+			// autoloaders should take care of loading file
626
+			if (! class_exists($classname)) {
627
+				$error_msg[] = sprintf(
628
+					esc_html__(
629
+						'Something went wrong with loading the %s admin hooks page.',
630
+						'event_espresso'
631
+					),
632
+					$page
633
+				);
634
+				$error_msg[] = $error_msg[0]
635
+							   . "\r\n"
636
+							   . sprintf(
637
+								   esc_html__(
638
+									   'There is no class in place for the %1$s admin hooks page.%2$sMake sure you have %3$s defined. If this is a non-EE-core admin page then you also must have an autoloader in place for your class',
639
+									   'event_espresso'
640
+								   ),
641
+								   $page,
642
+								   '<br />',
643
+								   '<strong>' . $classname . '</strong>'
644
+							   );
645
+				throw new EE_Error(implode('||', $error_msg));
646
+			}
647
+			$a = new ReflectionClass($classname);
648
+			// notice we are passing the instance of this class to the hook object.
649
+			$hookobj[] = $a->newInstance($this);
650
+		}
651
+	}
652
+
653
+
654
+	/**
655
+	 * @throws ReflectionException
656
+	 * @throws EE_Error
657
+	 */
658
+	public function load_page_dependencies()
659
+	{
660
+		try {
661
+			$this->_load_page_dependencies();
662
+		} catch (EE_Error $e) {
663
+			$e->get_error();
664
+		}
665
+	}
666
+
667
+
668
+	/**
669
+	 * load_page_dependencies
670
+	 * loads things specific to this page class when its loaded.  Really helps with efficiency.
671
+	 *
672
+	 * @return void
673
+	 * @throws DomainException
674
+	 * @throws EE_Error
675
+	 * @throws InvalidArgumentException
676
+	 * @throws InvalidDataTypeException
677
+	 * @throws InvalidInterfaceException
678
+	 */
679
+	protected function _load_page_dependencies()
680
+	{
681
+		// let's set the current_screen and screen options to override what WP set
682
+		$this->_current_screen = get_current_screen();
683
+		// load admin_notices - global, page class, and view specific
684
+		add_action('admin_notices', [$this, 'admin_notices_global'], 5);
685
+		add_action('admin_notices', [$this, 'admin_notices'], 10);
686
+		if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
687
+			add_action('admin_notices', [$this, 'admin_notices_' . $this->_current_view], 15);
688
+		}
689
+		// load network admin_notices - global, page class, and view specific
690
+		add_action('network_admin_notices', [$this, 'network_admin_notices_global'], 5);
691
+		if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
692
+			add_action('network_admin_notices', [$this, 'network_admin_notices_' . $this->_current_view]);
693
+		}
694
+		// this will save any per_page screen options if they are present
695
+		$this->_set_per_page_screen_options();
696
+		// setup list table properties
697
+		$this->_set_list_table();
698
+		// child classes can "register" a metabox to be automatically handled via the _page_config array property.
699
+		// However in some cases the metaboxes will need to be added within a route handling callback.
700
+		$this->_add_registered_meta_boxes();
701
+		$this->_add_screen_columns();
702
+		// add screen options - global, page child class, and view specific
703
+		$this->_add_global_screen_options();
704
+		$this->_add_screen_options();
705
+		$add_screen_options = "_add_screen_options_{$this->_current_view}";
706
+		if (method_exists($this, $add_screen_options)) {
707
+			$this->{$add_screen_options}();
708
+		}
709
+		// add help tab(s) and tours- set via page_config and qtips.
710
+		// $this->_add_help_tour();
711
+		$this->_add_help_tabs();
712
+		$this->_add_qtips();
713
+		// add feature_pointers - global, page child class, and view specific
714
+		$this->_add_feature_pointers();
715
+		$this->_add_global_feature_pointers();
716
+		$add_feature_pointer = "_add_feature_pointer_{$this->_current_view}";
717
+		if (method_exists($this, $add_feature_pointer)) {
718
+			$this->{$add_feature_pointer}();
719
+		}
720
+		// enqueue scripts/styles - global, page class, and view specific
721
+		add_action('admin_enqueue_scripts', [$this, 'load_global_scripts_styles'], 5);
722
+		add_action('admin_enqueue_scripts', [$this, 'load_scripts_styles'], 10);
723
+		if (method_exists($this, "load_scripts_styles_{$this->_current_view}")) {
724
+			add_action('admin_enqueue_scripts', [$this, "load_scripts_styles_{$this->_current_view}"], 15);
725
+		}
726
+		add_action('admin_enqueue_scripts', [$this, 'admin_footer_scripts_eei18n_js_strings'], 100);
727
+		// admin_print_footer_scripts - global, page child class, and view specific.
728
+		// NOTE, despite the name, whenever possible, scripts should NOT be loaded using this.
729
+		// In most cases that's doing_it_wrong().  But adding hidden container elements etc.
730
+		// is a good use case. Notice the late priority we're giving these
731
+		add_action('admin_print_footer_scripts', [$this, 'admin_footer_scripts_global'], 99);
732
+		add_action('admin_print_footer_scripts', [$this, 'admin_footer_scripts'], 100);
733
+		if (method_exists($this, "admin_footer_scripts_{$this->_current_view}")) {
734
+			add_action('admin_print_footer_scripts', [$this, "admin_footer_scripts_{$this->_current_view}"], 101);
735
+		}
736
+		// admin footer scripts
737
+		add_action('admin_footer', [$this, 'admin_footer_global'], 99);
738
+		add_action('admin_footer', [$this, 'admin_footer'], 100);
739
+		if (method_exists($this, "admin_footer_{$this->_current_view}")) {
740
+			add_action('admin_footer', [$this, "admin_footer_{$this->_current_view}"], 101);
741
+		}
742
+		do_action('FHEE__EE_Admin_Page___load_page_dependencies__after_load', $this->page_slug);
743
+		// targeted hook
744
+		do_action(
745
+			"FHEE__EE_Admin_Page___load_page_dependencies__after_load__{$this->page_slug}__{$this->_req_action}"
746
+		);
747
+	}
748
+
749
+
750
+	/**
751
+	 * _set_defaults
752
+	 * This sets some global defaults for class properties.
753
+	 */
754
+	private function _set_defaults()
755
+	{
756
+		$this->_current_screen       = $this->_admin_page_title = $this->_req_action = $this->_req_nonce = null;
757
+		$this->_event                = $this->_template_path = $this->_column_template_path = null;
758
+		$this->_nav_tabs             = $this->_views = $this->_page_routes = [];
759
+		$this->_page_config          = $this->_default_route_query_args = [];
760
+		$this->_default_nav_tab_name = 'overview';
761
+		// init template args
762
+		$this->_template_args = [
763
+			'admin_page_header'  => '',
764
+			'admin_page_content' => '',
765
+			'post_body_content'  => '',
766
+			'before_list_table'  => '',
767
+			'after_list_table'   => '',
768
+		];
769
+	}
770
+
771
+
772
+	/**
773
+	 * route_admin_request
774
+	 *
775
+	 * @return void
776
+	 * @throws InvalidArgumentException
777
+	 * @throws InvalidInterfaceException
778
+	 * @throws InvalidDataTypeException
779
+	 * @throws EE_Error
780
+	 * @throws ReflectionException
781
+	 * @see    _route_admin_request()
782
+	 */
783
+	public function route_admin_request()
784
+	{
785
+		try {
786
+			$this->_route_admin_request();
787
+		} catch (EE_Error $e) {
788
+			$e->get_error();
789
+		}
790
+	}
791
+
792
+
793
+	public function set_wp_page_slug($wp_page_slug)
794
+	{
795
+		$this->_wp_page_slug = $wp_page_slug;
796
+		// if in network admin then we need to append "-network" to the page slug. Why? Because that's how WP rolls...
797
+		if (is_network_admin()) {
798
+			$this->_wp_page_slug .= '-network';
799
+		}
800
+	}
801
+
802
+
803
+	/**
804
+	 * _verify_routes
805
+	 * All this method does is verify the incoming request and make sure that routes exist for it.  We do this early so
806
+	 * we know if we need to drop out.
807
+	 *
808
+	 * @return bool
809
+	 * @throws EE_Error
810
+	 */
811
+	protected function _verify_routes()
812
+	{
813
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
814
+		if (! $this->_current_page && ! defined('DOING_AJAX')) {
815
+			return false;
816
+		}
817
+		$this->_route = false;
818
+		// check that the page_routes array is not empty
819
+		if (empty($this->_page_routes)) {
820
+			// user error msg
821
+			$error_msg = sprintf(
822
+				esc_html__('No page routes have been set for the %s admin page.', 'event_espresso'),
823
+				$this->_admin_page_title
824
+			);
825
+			// developer error msg
826
+			$error_msg .= '||' . $error_msg
827
+						  . esc_html__(
828
+							  ' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
829
+							  'event_espresso'
830
+						  );
831
+			throw new EE_Error($error_msg);
832
+		}
833
+		// and that the requested page route exists
834
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
835
+			$this->_route        = $this->_page_routes[ $this->_req_action ];
836
+			$this->_route_config = isset($this->_page_config[ $this->_req_action ])
837
+				? $this->_page_config[ $this->_req_action ] : [];
838
+		} else {
839
+			// user error msg
840
+			$error_msg = sprintf(
841
+				esc_html__(
842
+					'The requested page route does not exist for the %s admin page.',
843
+					'event_espresso'
844
+				),
845
+				$this->_admin_page_title
846
+			);
847
+			// developer error msg
848
+			$error_msg .= '||' . $error_msg
849
+						  . sprintf(
850
+							  esc_html__(
851
+								  ' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
852
+								  'event_espresso'
853
+							  ),
854
+							  $this->_req_action
855
+						  );
856
+			throw new EE_Error($error_msg);
857
+		}
858
+		// and that a default route exists
859
+		if (! array_key_exists('default', $this->_page_routes)) {
860
+			// user error msg
861
+			$error_msg = sprintf(
862
+				esc_html__(
863
+					'A default page route has not been set for the % admin page.',
864
+					'event_espresso'
865
+				),
866
+				$this->_admin_page_title
867
+			);
868
+			// developer error msg
869
+			$error_msg .= '||' . $error_msg
870
+						  . esc_html__(
871
+							  ' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
872
+							  'event_espresso'
873
+						  );
874
+			throw new EE_Error($error_msg);
875
+		}
876
+		// first lets' catch if the UI request has EVER been set.
877
+		if ($this->_is_UI_request === null) {
878
+			// lets set if this is a UI request or not.
879
+			$this->_is_UI_request = ! $this->request->getRequestParam('noheader', false, 'bool');
880
+			// wait a minute... we might have a noheader in the route array
881
+			$this->_is_UI_request = ! (
882
+				is_array($this->_route) && isset($this->_route['noheader']) && $this->_route['noheader']
883
+			)
884
+				? $this->_is_UI_request
885
+				: false;
886
+		}
887
+		$this->_set_current_labels();
888
+		return true;
889
+	}
890
+
891
+
892
+	/**
893
+	 * this method simply verifies a given route and makes sure its an actual route available for the loaded page
894
+	 *
895
+	 * @param string $route the route name we're verifying
896
+	 * @return bool we'll throw an exception if this isn't a valid route.
897
+	 * @throws EE_Error
898
+	 */
899
+	protected function _verify_route($route)
900
+	{
901
+		if (array_key_exists($this->_req_action, $this->_page_routes)) {
902
+			return true;
903
+		}
904
+		// user error msg
905
+		$error_msg = sprintf(
906
+			esc_html__('The given page route does not exist for the %s admin page.', 'event_espresso'),
907
+			$this->_admin_page_title
908
+		);
909
+		// developer error msg
910
+		$error_msg .= '||' . $error_msg
911
+					  . sprintf(
912
+						  esc_html__(
913
+							  ' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
914
+							  'event_espresso'
915
+						  ),
916
+						  $route
917
+					  );
918
+		throw new EE_Error($error_msg);
919
+	}
920
+
921
+
922
+	/**
923
+	 * perform nonce verification
924
+	 * This method has be encapsulated here so that any ajax requests that bypass normal routes can verify their nonces
925
+	 * using this method (and save retyping!)
926
+	 *
927
+	 * @param string $nonce     The nonce sent
928
+	 * @param string $nonce_ref The nonce reference string (name0)
929
+	 * @return void
930
+	 * @throws EE_Error
931
+	 */
932
+	protected function _verify_nonce($nonce, $nonce_ref)
933
+	{
934
+		// verify nonce against expected value
935
+		if (! wp_verify_nonce($nonce, $nonce_ref)) {
936
+			// these are not the droids you are looking for !!!
937
+			$msg = sprintf(
938
+				esc_html__('%sNonce Fail.%s', 'event_espresso'),
939
+				'<a href="https://www.youtube.com/watch?v=56_S0WeTkzs">',
940
+				'</a>'
941
+			);
942
+			if (WP_DEBUG) {
943
+				$msg .= "\n  ";
944
+				$msg .= sprintf(
945
+					esc_html__(
946
+						'In order to dynamically generate nonces for your actions, use the %s::add_query_args_and_nonce() method. May the Nonce be with you!',
947
+						'event_espresso'
948
+					),
949
+					__CLASS__
950
+				);
951
+			}
952
+			if (! defined('DOING_AJAX')) {
953
+				wp_die($msg);
954
+			}
955
+			EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
956
+			$this->_return_json();
957
+		}
958
+	}
959
+
960
+
961
+	/**
962
+	 * _route_admin_request()
963
+	 * Meat and potatoes of the class.  Basically, this dude checks out what's being requested and sees if theres are
964
+	 * some doodads to work the magic and handle the flingjangy. Translation:  Checks if the requested action is listed
965
+	 * in the page routes and then will try to load the corresponding method.
966
+	 *
967
+	 * @return void
968
+	 * @throws EE_Error
969
+	 * @throws InvalidArgumentException
970
+	 * @throws InvalidDataTypeException
971
+	 * @throws InvalidInterfaceException
972
+	 * @throws ReflectionException
973
+	 */
974
+	protected function _route_admin_request()
975
+	{
976
+		if (! $this->_is_UI_request) {
977
+			$this->_verify_routes();
978
+		}
979
+		$nonce_check = ! isset($this->_route_config['require_nonce']) || $this->_route_config['require_nonce'];
980
+		if ($this->_req_action !== 'default' && $nonce_check) {
981
+			// set nonce from post data
982
+			$nonce = $this->request->getRequestParam($this->_req_nonce, '');
983
+			$this->_verify_nonce($nonce, $this->_req_nonce);
984
+		}
985
+		// set the nav_tabs array but ONLY if this is  UI_request
986
+		if ($this->_is_UI_request) {
987
+			$this->_set_nav_tabs();
988
+		}
989
+		// grab callback function
990
+		$func = is_array($this->_route) ? $this->_route['func'] : $this->_route;
991
+		// check if callback has args
992
+		$args      = is_array($this->_route) && isset($this->_route['args']) ? $this->_route['args'] : [];
993
+		$error_msg = '';
994
+		// action right before calling route
995
+		// (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
996
+		if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
997
+			do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
998
+		}
999
+		// right before calling the route, let's remove _wp_http_referer from the
1000
+		// $_SERVER[REQUEST_URI] global (its now in _req_data for route processing).
1001
+		$_SERVER['REQUEST_URI'] = remove_query_arg(
1002
+			'_wp_http_referer',
1003
+			wp_unslash($_SERVER['REQUEST_URI'])
1004
+		);
1005
+		if (! empty($func)) {
1006
+			if (is_array($func)) {
1007
+				list($class, $method) = $func;
1008
+			} elseif (strpos($func, '::') !== false) {
1009
+				list($class, $method) = explode('::', $func);
1010
+			} else {
1011
+				$class  = $this;
1012
+				$method = $func;
1013
+			}
1014
+			if (! (is_object($class) && $class === $this)) {
1015
+				// send along this admin page object for access by addons.
1016
+				$args['admin_page_object'] = $this;
1017
+			}
1018
+			if (// is it a method on a class that doesn't work?
1019
+				(
1020
+					(
1021
+						method_exists($class, $method)
1022
+						&& call_user_func_array([$class, $method], $args) === false
1023
+					)
1024
+					&& (
1025
+						// is it a standalone function that doesn't work?
1026
+						function_exists($method)
1027
+						&& call_user_func_array(
1028
+							   $func,
1029
+							   array_merge(['admin_page_object' => $this], $args)
1030
+						   ) === false
1031
+					)
1032
+				)
1033
+				|| (
1034
+					// is it neither a class method NOR a standalone function?
1035
+					! method_exists($class, $method)
1036
+					&& ! function_exists($method)
1037
+				)
1038
+			) {
1039
+				// user error msg
1040
+				$error_msg = esc_html__(
1041
+					'An error occurred. The  requested page route could not be found.',
1042
+					'event_espresso'
1043
+				);
1044
+				// developer error msg
1045
+				$error_msg .= '||';
1046
+				$error_msg .= sprintf(
1047
+					esc_html__(
1048
+						'Page route "%s" could not be called. Check that the spelling for method names and actions in the "_page_routes" array are all correct.',
1049
+						'event_espresso'
1050
+					),
1051
+					$method
1052
+				);
1053
+			}
1054
+			if (! empty($error_msg)) {
1055
+				throw new EE_Error($error_msg);
1056
+			}
1057
+		}
1058
+		// if we've routed and this route has a no headers route AND a sent_headers_route,
1059
+		// then we need to reset the routing properties to the new route.
1060
+		// now if UI request is FALSE and noheader is true AND we have a headers_sent_route in the route array then let's set UI_request to true because the no header route has a second func after headers have been sent.
1061
+		if ($this->_is_UI_request === false
1062
+			&& is_array($this->_route)
1063
+			&& ! empty($this->_route['headers_sent_route'])
1064
+		) {
1065
+			$this->_reset_routing_properties($this->_route['headers_sent_route']);
1066
+		}
1067
+	}
1068
+
1069
+
1070
+	/**
1071
+	 * This method just allows the resetting of page properties in the case where a no headers
1072
+	 * route redirects to a headers route in its route config.
1073
+	 *
1074
+	 * @param string $new_route New (non header) route to redirect to.
1075
+	 * @return   void
1076
+	 * @throws ReflectionException
1077
+	 * @throws InvalidArgumentException
1078
+	 * @throws InvalidInterfaceException
1079
+	 * @throws InvalidDataTypeException
1080
+	 * @throws EE_Error
1081
+	 * @since   4.3.0
1082
+	 */
1083
+	protected function _reset_routing_properties($new_route)
1084
+	{
1085
+		$this->_is_UI_request = true;
1086
+		// now we set the current route to whatever the headers_sent_route is set at
1087
+		$this->request->setRequestParam('action', $new_route);
1088
+		// rerun page setup
1089
+		$this->_page_setup();
1090
+	}
1091
+
1092
+
1093
+	/**
1094
+	 * _add_query_arg
1095
+	 * adds nonce to array of arguments then calls WP add_query_arg function
1096
+	 *(internally just uses EEH_URL's function with the same name)
1097
+	 *
1098
+	 * @param array  $args
1099
+	 * @param string $url
1100
+	 * @param bool   $sticky                  if true, then the existing Request params will be appended to the
1101
+	 *                                        generated url in an associative array indexed by the key 'wp_referer';
1102
+	 *                                        Example usage: If the current page is:
1103
+	 *                                        http://mydomain.com/wp-admin/admin.php?page=espresso_registrations
1104
+	 *                                        &action=default&event_id=20&month_range=March%202015
1105
+	 *                                        &_wpnonce=5467821
1106
+	 *                                        and you call:
1107
+	 *                                        EE_Admin_Page::add_query_args_and_nonce(
1108
+	 *                                        array(
1109
+	 *                                        'action' => 'resend_something',
1110
+	 *                                        'page=>espresso_registrations'
1111
+	 *                                        ),
1112
+	 *                                        $some_url,
1113
+	 *                                        true
1114
+	 *                                        );
1115
+	 *                                        It will produce a url in this structure:
1116
+	 *                                        http://{$some_url}/?page=espresso_registrations&action=resend_something
1117
+	 *                                        &wp_referer[action]=default&wp_referer[event_id]=20&wpreferer[
1118
+	 *                                        month_range]=March%202015
1119
+	 * @param bool   $exclude_nonce           If true, the the nonce will be excluded from the generated nonce.
1120
+	 * @return string
1121
+	 */
1122
+	public static function add_query_args_and_nonce(
1123
+		$args = [],
1124
+		$url = false,
1125
+		$sticky = false,
1126
+		$exclude_nonce = false
1127
+	) {
1128
+		// if there is a _wp_http_referer include the values from the request but only if sticky = true
1129
+		if ($sticky) {
1130
+			$request = $_REQUEST;
1131
+			unset($request['_wp_http_referer']);
1132
+			unset($request['wp_referer']);
1133
+			foreach ($request as $key => $value) {
1134
+				// do not add nonces
1135
+				if (strpos($key, 'nonce') !== false) {
1136
+					continue;
1137
+				}
1138
+				$args[ 'wp_referer[' . $key . ']' ] = $value;
1139
+			}
1140
+		}
1141
+		return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
1142
+	}
1143
+
1144
+
1145
+	/**
1146
+	 * This returns a generated link that will load the related help tab.
1147
+	 *
1148
+	 * @param string $help_tab_id the id for the connected help tab
1149
+	 * @param string $icon_style  (optional) include css class for the style you want to use for the help icon.
1150
+	 * @param string $help_text   (optional) send help text you want to use for the link if default not to be used
1151
+	 * @return string              generated link
1152
+	 * @uses EEH_Template::get_help_tab_link()
1153
+	 */
1154
+	protected function _get_help_tab_link($help_tab_id, $icon_style = '', $help_text = '')
1155
+	{
1156
+		return EEH_Template::get_help_tab_link(
1157
+			$help_tab_id,
1158
+			$this->page_slug,
1159
+			$this->_req_action,
1160
+			$icon_style,
1161
+			$help_text
1162
+		);
1163
+	}
1164
+
1165
+
1166
+	/**
1167
+	 * _add_help_tabs
1168
+	 * Note child classes define their help tabs within the page_config array.
1169
+	 *
1170
+	 * @link   http://codex.wordpress.org/Function_Reference/add_help_tab
1171
+	 * @return void
1172
+	 * @throws DomainException
1173
+	 * @throws EE_Error
1174
+	 */
1175
+	protected function _add_help_tabs()
1176
+	{
1177
+		$tour_buttons = '';
1178
+		if (isset($this->_page_config[ $this->_req_action ])) {
1179
+			$config = $this->_page_config[ $this->_req_action ];
1180
+			// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1181
+			// is there a help tour for the current route?  if there is let's setup the tour buttons
1182
+			// if (isset($this->_help_tour[ $this->_req_action ])) {
1183
+			//     $tb = array();
1184
+			//     $tour_buttons = '<div class="ee-abs-container"><div class="ee-help-tour-restart-buttons">';
1185
+			//     foreach ($this->_help_tour['tours'] as $tour) {
1186
+			//         // if this is the end tour then we don't need to setup a button
1187
+			//         if ($tour instanceof EE_Help_Tour_final_stop || ! $tour instanceof EE_Help_Tour) {
1188
+			//             continue;
1189
+			//         }
1190
+			//         $tb[] = '<button id="trigger-tour-'
1191
+			//                 . $tour->get_slug()
1192
+			//                 . '" class="button-primary trigger-ee-help-tour">'
1193
+			//                 . $tour->get_label()
1194
+			//                 . '</button>';
1195
+			//     }
1196
+			//     $tour_buttons .= implode('<br />', $tb);
1197
+			//     $tour_buttons .= '</div></div>';
1198
+			// }
1199
+			// let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1200
+			if (is_array($config) && isset($config['help_sidebar'])) {
1201
+				// check that the callback given is valid
1202
+				if (! method_exists($this, $config['help_sidebar'])) {
1203
+					throw new EE_Error(
1204
+						sprintf(
1205
+							esc_html__(
1206
+								'The _page_config array has a callback set for the "help_sidebar" option.  However the callback given (%s) is not a valid callback.  Doublecheck the spelling and make sure this method exists for the class %s',
1207
+								'event_espresso'
1208
+							),
1209
+							$config['help_sidebar'],
1210
+							get_class($this)
1211
+						)
1212
+					);
1213
+				}
1214
+				$content = apply_filters(
1215
+					'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1216
+					$this->{$config['help_sidebar']}()
1217
+				);
1218
+				$content .= $tour_buttons; // add help tour buttons.
1219
+				// do we have any help tours setup?  Cause if we do we want to add the buttons
1220
+				$this->_current_screen->set_help_sidebar($content);
1221
+			}
1222
+			// if we DON'T have config help sidebar and there ARE tour buttons then we'll just add the tour buttons to the sidebar.
1223
+			if (! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1224
+				$this->_current_screen->set_help_sidebar($tour_buttons);
1225
+			}
1226
+			// handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1227
+			if (! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1228
+				$_ht['id']      = $this->page_slug;
1229
+				$_ht['title']   = esc_html__('Help Tours', 'event_espresso');
1230
+				$_ht['content'] = '<p>'
1231
+								  . esc_html__(
1232
+									  'The buttons to the right allow you to start/restart any help tours available for this page',
1233
+									  'event_espresso'
1234
+								  ) . '</p>';
1235
+				$this->_current_screen->add_help_tab($_ht);
1236
+			}
1237
+			if (! isset($config['help_tabs'])) {
1238
+				return;
1239
+			} //no help tabs for this route
1240
+			foreach ((array) $config['help_tabs'] as $tab_id => $cfg) {
1241
+				// we're here so there ARE help tabs!
1242
+				// make sure we've got what we need
1243
+				if (! isset($cfg['title'])) {
1244
+					throw new EE_Error(
1245
+						esc_html__(
1246
+							'The _page_config array is not set up properly for help tabs.  It is missing a title',
1247
+							'event_espresso'
1248
+						)
1249
+					);
1250
+				}
1251
+				if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1252
+					throw new EE_Error(
1253
+						esc_html__(
1254
+							'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
1255
+							'event_espresso'
1256
+						)
1257
+					);
1258
+				}
1259
+				// first priority goes to content.
1260
+				if (! empty($cfg['content'])) {
1261
+					$content = ! empty($cfg['content']) ? $cfg['content'] : null;
1262
+					// second priority goes to filename
1263
+				} elseif (! empty($cfg['filename'])) {
1264
+					$file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1265
+					// it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1266
+					$file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1267
+															 . basename($this->_get_dir())
1268
+															 . '/help_tabs/'
1269
+															 . $cfg['filename']
1270
+															 . '.help_tab.php' : $file_path;
1271
+					// if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1272
+					if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1273
+						EE_Error::add_error(
1274
+							sprintf(
1275
+								esc_html__(
1276
+									'The filename given for the help tab %s is not a valid file and there is no other configuration for the tab content.  Please check that the string you set for the help tab on this route (%s) is the correct spelling.  The file should be in %s',
1277
+									'event_espresso'
1278
+								),
1279
+								$tab_id,
1280
+								key($config),
1281
+								$file_path
1282
+							),
1283
+							__FILE__,
1284
+							__FUNCTION__,
1285
+							__LINE__
1286
+						);
1287
+						return;
1288
+					}
1289
+					$template_args['admin_page_obj'] = $this;
1290
+					$content                         = EEH_Template::display_template(
1291
+						$file_path,
1292
+						$template_args,
1293
+						true
1294
+					);
1295
+				} else {
1296
+					$content = '';
1297
+				}
1298
+				// check if callback is valid
1299
+				if (empty($content)
1300
+					&& (
1301
+						! isset($cfg['callback']) || ! method_exists($this, $cfg['callback'])
1302
+					)
1303
+				) {
1304
+					EE_Error::add_error(
1305
+						sprintf(
1306
+							esc_html__(
1307
+								'The callback given for a %s help tab on this page does not content OR a corresponding method for generating the content.  Check the spelling or make sure the method is present.',
1308
+								'event_espresso'
1309
+							),
1310
+							$cfg['title']
1311
+						),
1312
+						__FILE__,
1313
+						__FUNCTION__,
1314
+						__LINE__
1315
+					);
1316
+					return;
1317
+				}
1318
+				// setup config array for help tab method
1319
+				$id  = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1320
+				$_ht = [
1321
+					'id'       => $id,
1322
+					'title'    => $cfg['title'],
1323
+					'callback' => isset($cfg['callback']) && empty($content) ? [$this, $cfg['callback']] : null,
1324
+					'content'  => $content,
1325
+				];
1326
+				$this->_current_screen->add_help_tab($_ht);
1327
+			}
1328
+		}
1329
+	}
1330
+
1331
+
1332
+	/**
1333
+	 * This basically checks loaded $_page_config property to see if there are any help_tours defined.  "help_tours" is
1334
+	 * an array with properties for setting up usage of the joyride plugin
1335
+	 *
1336
+	 * @link   http://zurb.com/playground/jquery-joyride-feature-tour-plugin
1337
+	 * @see    instructions regarding the format and construction of the "help_tour" array element is found in the
1338
+	 *         _set_page_config() comments
1339
+	 * @return void
1340
+	 * @throws InvalidArgumentException
1341
+	 * @throws InvalidDataTypeException
1342
+	 * @throws InvalidInterfaceException
1343
+	 */
1344
+	protected function _add_help_tour()
1345
+	{
1346
+		// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1347
+		// $tours = array();
1348
+		// $this->_help_tour = array();
1349
+		// // exit early if help tours are turned off globally
1350
+		// if ((defined('EE_DISABLE_HELP_TOURS') && EE_DISABLE_HELP_TOURS)
1351
+		//     || ! EE_Registry::instance()->CFG->admin->help_tour_activation
1352
+		// ) {
1353
+		//     return;
1354
+		// }
1355
+		// // loop through _page_config to find any help_tour defined
1356
+		// foreach ($this->_page_config as $route => $config) {
1357
+		//     // we're only going to set things up for this route
1358
+		//     if ($route !== $this->_req_action) {
1359
+		//         continue;
1360
+		//     }
1361
+		//     if (isset($config['help_tour'])) {
1362
+		//         foreach ($config['help_tour'] as $tour) {
1363
+		//             $file_path = $this->_get_dir() . '/help_tours/' . $tour . '.class.php';
1364
+		//             // let's see if we can get that file...
1365
+		//             // if not its possible this is a decaf route not set in caffeinated
1366
+		//             // so lets try and get the caffeinated equivalent
1367
+		//             $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1368
+		//                                                      . basename($this->_get_dir())
1369
+		//                                                      . '/help_tours/'
1370
+		//                                                      . $tour
1371
+		//                                                      . '.class.php' : $file_path;
1372
+		//             // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1373
+		//             if (! is_readable($file_path)) {
1374
+		//                 EE_Error::add_error(
1375
+		//                     sprintf(
1376
+		//                         esc_html__(
1377
+		//                             'The file path given for the help tour (%s) is not a valid path.  Please check that the string you set for the help tour on this route (%s) is the correct spelling',
1378
+		//                             'event_espresso'
1379
+		//                         ),
1380
+		//                         $file_path,
1381
+		//                         $tour
1382
+		//                     ),
1383
+		//                     __FILE__,
1384
+		//                     __FUNCTION__,
1385
+		//                     __LINE__
1386
+		//                 );
1387
+		//                 return;
1388
+		//             }
1389
+		//             require_once $file_path;
1390
+		//             if (! class_exists($tour)) {
1391
+		//                 $error_msg[] = sprintf(
1392
+		//                     esc_html__('Something went wrong with loading the %s Help Tour Class.', 'event_espresso'),
1393
+		//                     $tour
1394
+		//                 );
1395
+		//                 $error_msg[] = $error_msg[0] . "\r\n"
1396
+		//                                . sprintf(
1397
+		//                                    esc_html__(
1398
+		//                                        'There is no class in place for the %s help tour.%s Make sure you have <strong>%s</strong> defined in the "help_tour" array for the %s route of the % admin page.',
1399
+		//                                        'event_espresso'
1400
+		//                                    ),
1401
+		//                                    $tour,
1402
+		//                                    '<br />',
1403
+		//                                    $tour,
1404
+		//                                    $this->_req_action,
1405
+		//                                    get_class($this)
1406
+		//                                );
1407
+		//                 throw new EE_Error(implode('||', $error_msg));
1408
+		//             }
1409
+		//             $tour_obj = new $tour($this->_is_caf);
1410
+		//             $tours[] = $tour_obj;
1411
+		//             $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($tour_obj);
1412
+		//         }
1413
+		//         // let's inject the end tour stop element common to all pages... this will only get seen once per machine.
1414
+		//         $end_stop_tour = new EE_Help_Tour_final_stop($this->_is_caf);
1415
+		//         $tours[] = $end_stop_tour;
1416
+		//         $this->_help_tour[ $route ][] = EEH_Template::help_tour_stops_generator($end_stop_tour);
1417
+		//     }
1418
+		// }
1419
+		//
1420
+		// if (! empty($tours)) {
1421
+		//     $this->_help_tour['tours'] = $tours;
1422
+		// }
1423
+		// // that's it!  Now that the $_help_tours property is set (or not)
1424
+		// // the scripts and html should be taken care of automatically.
1425
+		//
1426
+		// /**
1427
+		//  * Allow extending the help tours variable.
1428
+		//  *
1429
+		//  * @param Array $_help_tour The array containing all help tour information to be displayed.
1430
+		//  */
1431
+		// $this->_help_tour = apply_filters('FHEE__EE_Admin_Page___add_help_tour___help_tour', $this->_help_tour);
1432
+	}
1433
+
1434
+
1435
+	/**
1436
+	 * This simply sets up any qtips that have been defined in the page config
1437
+	 *
1438
+	 * @return void
1439
+	 */
1440
+	protected function _add_qtips()
1441
+	{
1442
+		if (isset($this->_route_config['qtips'])) {
1443
+			$qtips = (array) $this->_route_config['qtips'];
1444
+			// load qtip loader
1445
+			$path = [
1446
+				$this->_get_dir() . '/qtips/',
1447
+				EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1448
+			];
1449
+			EEH_Qtip_Loader::instance()->register($qtips, $path);
1450
+		}
1451
+	}
1452
+
1453
+
1454
+	/**
1455
+	 * _set_nav_tabs
1456
+	 * This sets up the nav tabs from the page_routes array.  This method can be overwritten by child classes if you
1457
+	 * wish to add additional tabs or modify accordingly.
1458
+	 *
1459
+	 * @return void
1460
+	 * @throws InvalidArgumentException
1461
+	 * @throws InvalidInterfaceException
1462
+	 * @throws InvalidDataTypeException
1463
+	 */
1464
+	protected function _set_nav_tabs()
1465
+	{
1466
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1467
+		$i = 0;
1468
+		foreach ($this->_page_config as $slug => $config) {
1469
+			if (! is_array($config) || empty($config['nav'])) {
1470
+				continue;
1471
+			}
1472
+			// no nav tab for this config
1473
+			// check for persistent flag
1474
+			if ($slug !== $this->_req_action && isset($config['nav']['persistent']) && ! $config['nav']['persistent']) {
1475
+				// nav tab is only to appear when route requested.
1476
+				continue;
1477
+			}
1478
+			if (! $this->check_user_access($slug, true)) {
1479
+				// no nav tab because current user does not have access.
1480
+				continue;
1481
+			}
1482
+			$css_class                = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1483
+			$this->_nav_tabs[ $slug ] = [
1484
+				'url'       => isset($config['nav']['url'])
1485
+					? $config['nav']['url']
1486
+					: self::add_query_args_and_nonce(
1487
+						['action' => $slug],
1488
+						$this->_admin_base_url
1489
+					),
1490
+				'link_text' => isset($config['nav']['label'])
1491
+					? $config['nav']['label']
1492
+					: ucwords(
1493
+						str_replace('_', ' ', $slug)
1494
+					),
1495
+				'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1496
+				'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1497
+			];
1498
+			$i++;
1499
+		}
1500
+		// if $this->_nav_tabs is empty then lets set the default
1501
+		if (empty($this->_nav_tabs)) {
1502
+			$this->_nav_tabs[ $this->_default_nav_tab_name ] = [
1503
+				'url'       => $this->_admin_base_url,
1504
+				'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1505
+				'css_class' => 'nav-tab-active',
1506
+				'order'     => 10,
1507
+			];
1508
+		}
1509
+		// now let's sort the tabs according to order
1510
+		usort($this->_nav_tabs, [$this, '_sort_nav_tabs']);
1511
+	}
1512
+
1513
+
1514
+	/**
1515
+	 * _set_current_labels
1516
+	 * This method modifies the _labels property with any optional specific labels indicated in the _page_routes
1517
+	 * property array
1518
+	 *
1519
+	 * @return void
1520
+	 */
1521
+	private function _set_current_labels()
1522
+	{
1523
+		if (is_array($this->_route_config) && isset($this->_route_config['labels'])) {
1524
+			foreach ($this->_route_config['labels'] as $label => $text) {
1525
+				if (is_array($text)) {
1526
+					foreach ($text as $sublabel => $subtext) {
1527
+						$this->_labels[ $label ][ $sublabel ] = $subtext;
1528
+					}
1529
+				} else {
1530
+					$this->_labels[ $label ] = $text;
1531
+				}
1532
+			}
1533
+		}
1534
+	}
1535
+
1536
+
1537
+	/**
1538
+	 *        verifies user access for this admin page
1539
+	 *
1540
+	 * @param string $route_to_check if present then the capability for the route matching this string is checked.
1541
+	 * @param bool   $verify_only    Default is FALSE which means if user check fails then wp_die().  Otherwise just
1542
+	 *                               return false if verify fail.
1543
+	 * @return bool
1544
+	 * @throws InvalidArgumentException
1545
+	 * @throws InvalidDataTypeException
1546
+	 * @throws InvalidInterfaceException
1547
+	 */
1548
+	public function check_user_access($route_to_check = '', $verify_only = false)
1549
+	{
1550
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1551
+		$route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1552
+		$capability     = ! empty($route_to_check) && isset($this->_page_routes[ $route_to_check ])
1553
+						  && is_array(
1554
+							  $this->_page_routes[ $route_to_check ]
1555
+						  )
1556
+						  && ! empty($this->_page_routes[ $route_to_check ]['capability'])
1557
+			? $this->_page_routes[ $route_to_check ]['capability'] : null;
1558
+		if (empty($capability) && empty($route_to_check)) {
1559
+			$capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1560
+				: $this->_route['capability'];
1561
+		} else {
1562
+			$capability = empty($capability) ? 'manage_options' : $capability;
1563
+		}
1564
+		$id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1565
+		if (! defined('DOING_AJAX')
1566
+			&& (
1567
+				! function_exists('is_admin')
1568
+				|| ! EE_Registry::instance()->CAP->current_user_can(
1569
+					$capability,
1570
+					$this->page_slug
1571
+					. '_'
1572
+					. $route_to_check,
1573
+					$id
1574
+				)
1575
+			)
1576
+		) {
1577
+			if ($verify_only) {
1578
+				return false;
1579
+			}
1580
+			if (is_user_logged_in()) {
1581
+				wp_die(__('You do not have access to this route.', 'event_espresso'));
1582
+			} else {
1583
+				return false;
1584
+			}
1585
+		}
1586
+		return true;
1587
+	}
1588
+
1589
+
1590
+	/**
1591
+	 * admin_init_global
1592
+	 * This runs all the code that we want executed within the WP admin_init hook.
1593
+	 * This method executes for ALL EE Admin pages.
1594
+	 *
1595
+	 * @return void
1596
+	 */
1597
+	public function admin_init_global()
1598
+	{
1599
+	}
1600
+
1601
+
1602
+	/**
1603
+	 * wp_loaded_global
1604
+	 * This runs all the code that we want executed within the WP wp_loaded hook.  This method is optional for an
1605
+	 * EE_Admin page and will execute on every EE Admin Page load
1606
+	 *
1607
+	 * @return void
1608
+	 */
1609
+	public function wp_loaded()
1610
+	{
1611
+	}
1612
+
1613
+
1614
+	/**
1615
+	 * admin_notices
1616
+	 * Anything triggered by the 'admin_notices' WP hook should be put in here.  This particular method will apply on
1617
+	 * ALL EE_Admin pages.
1618
+	 *
1619
+	 * @return void
1620
+	 */
1621
+	public function admin_notices_global()
1622
+	{
1623
+		$this->_display_no_javascript_warning();
1624
+		$this->_display_espresso_notices();
1625
+	}
1626
+
1627
+
1628
+	public function network_admin_notices_global()
1629
+	{
1630
+		$this->_display_no_javascript_warning();
1631
+		$this->_display_espresso_notices();
1632
+	}
1633
+
1634
+
1635
+	/**
1636
+	 * admin_footer_scripts_global
1637
+	 * Anything triggered by the 'admin_print_footer_scripts' WP hook should be put in here. This particular method
1638
+	 * will apply on ALL EE_Admin pages.
1639
+	 *
1640
+	 * @return void
1641
+	 */
1642
+	public function admin_footer_scripts_global()
1643
+	{
1644
+		$this->_add_admin_page_ajax_loading_img();
1645
+		$this->_add_admin_page_overlay();
1646
+		// if metaboxes are present we need to add the nonce field
1647
+		if (isset($this->_route_config['metaboxes'])
1648
+			|| isset($this->_route_config['list_table'])
1649
+			|| (isset($this->_route_config['has_metaboxes']) && $this->_route_config['has_metaboxes'])
1650
+		) {
1651
+			wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
1652
+			wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
1653
+		}
1654
+	}
1655
+
1656
+
1657
+	/**
1658
+	 * admin_footer_global
1659
+	 * Anything triggered by the wp 'admin_footer' wp hook should be put in here. This particular method will apply on
1660
+	 * ALL EE_Admin Pages.
1661
+	 *
1662
+	 * @return void
1663
+	 */
1664
+	public function admin_footer_global()
1665
+	{
1666
+		// dialog container for dialog helper
1667
+		$d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1668
+		$d_cont .= '<div class="ee-notices"></div>';
1669
+		$d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1670
+		$d_cont .= '</div>';
1671
+		echo $d_cont;
1672
+		// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1673
+		// help tour stuff?
1674
+		// if (isset($this->_help_tour[ $this->_req_action ])) {
1675
+		//     echo implode('<br />', $this->_help_tour[ $this->_req_action ]);
1676
+		// }
1677
+		// current set timezone for timezone js
1678
+		echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1679
+	}
1680
+
1681
+
1682
+	/**
1683
+	 * This function sees if there is a method for help popup content existing for the given route.  If there is then
1684
+	 * we'll use the retrieved array to output the content using the template. For child classes: If you want to have
1685
+	 * help popups then in your templates or your content you set "triggers" for the content using the
1686
+	 * "_set_help_trigger('help_trigger_id')" where "help_trigger_id" is what you will use later in your custom method
1687
+	 * for the help popup content on that page. Then in your Child_Admin_Page class you need to define a help popup
1688
+	 * method for the content in the format "_help_popup_content_{route_name}()"  So if you are setting help content
1689
+	 * for the
1690
+	 * 'edit_event' route you should have a method named "_help_popup_content_edit_route". In your defined
1691
+	 * "help_popup_content_..." method.  You must prepare and return an array in the following format array(
1692
+	 *    'help_trigger_id' => array(
1693
+	 *        'title' => esc_html__('localized title for popup', 'event_espresso'),
1694
+	 *        'content' => esc_html__('localized content for popup', 'event_espresso')
1695
+	 *    )
1696
+	 * );
1697
+	 * Then the EE_Admin_Parent will take care of making sure that is setup properly on the correct route.
1698
+	 *
1699
+	 * @param array $help_array
1700
+	 * @param bool  $display
1701
+	 * @return string content
1702
+	 * @throws DomainException
1703
+	 * @throws EE_Error
1704
+	 */
1705
+	protected function _set_help_popup_content($help_array = [], $display = false)
1706
+	{
1707
+		$content    = '';
1708
+		$help_array = empty($help_array) ? $this->_get_help_content() : $help_array;
1709
+		// loop through the array and setup content
1710
+		foreach ($help_array as $trigger => $help) {
1711
+			// make sure the array is setup properly
1712
+			if (! isset($help['title']) || ! isset($help['content'])) {
1713
+				throw new EE_Error(
1714
+					esc_html__(
1715
+						'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
1716
+						'event_espresso'
1717
+					)
1718
+				);
1719
+			}
1720
+			// we're good so let'd setup the template vars and then assign parsed template content to our content.
1721
+			$template_args = [
1722
+				'help_popup_id'      => $trigger,
1723
+				'help_popup_title'   => $help['title'],
1724
+				'help_popup_content' => $help['content'],
1725
+			];
1726
+			$content       .= EEH_Template::display_template(
1727
+				EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1728
+				$template_args,
1729
+				true
1730
+			);
1731
+		}
1732
+		if ($display) {
1733
+			echo $content;
1734
+			return '';
1735
+		}
1736
+		return $content;
1737
+	}
1738
+
1739
+
1740
+	/**
1741
+	 * All this does is retrieve the help content array if set by the EE_Admin_Page child
1742
+	 *
1743
+	 * @return array properly formatted array for help popup content
1744
+	 * @throws EE_Error
1745
+	 */
1746
+	private function _get_help_content()
1747
+	{
1748
+		// what is the method we're looking for?
1749
+		$method_name = '_help_popup_content_' . $this->_req_action;
1750
+		// if method doesn't exist let's get out.
1751
+		if (! method_exists($this, $method_name)) {
1752
+			return [];
1753
+		}
1754
+		// k we're good to go let's retrieve the help array
1755
+		$help_array = call_user_func([$this, $method_name]);
1756
+		// make sure we've got an array!
1757
+		if (! is_array($help_array)) {
1758
+			throw new EE_Error(
1759
+				esc_html__(
1760
+					'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
1761
+					'event_espresso'
1762
+				)
1763
+			);
1764
+		}
1765
+		return $help_array;
1766
+	}
1767
+
1768
+
1769
+	/**
1770
+	 * EE Admin Pages can use this to set a properly formatted trigger for a help popup.
1771
+	 * By default the trigger html is printed.  Otherwise it can be returned if the $display flag is set "false"
1772
+	 * See comments made on the _set_help_content method for understanding other parts to the help popup tool.
1773
+	 *
1774
+	 * @param string  $trigger_id reference for retrieving the trigger content for the popup
1775
+	 * @param boolean $display    if false then we return the trigger string
1776
+	 * @param array   $dimensions an array of dimensions for the box (array(h,w))
1777
+	 * @return string
1778
+	 * @throws DomainException
1779
+	 * @throws EE_Error
1780
+	 */
1781
+	protected function _set_help_trigger($trigger_id, $display = true, $dimensions = ['400', '640'])
1782
+	{
1783
+		if (defined('DOING_AJAX')) {
1784
+			return '';
1785
+		}
1786
+		// let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1787
+		$help_array   = $this->_get_help_content();
1788
+		$help_content = '';
1789
+		if (empty($help_array) || ! isset($help_array[ $trigger_id ])) {
1790
+			$help_array[ $trigger_id ] = [
1791
+				'title'   => esc_html__('Missing Content', 'event_espresso'),
1792
+				'content' => esc_html__(
1793
+					'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1794
+					'event_espresso'
1795
+				),
1796
+			];
1797
+			$help_content              = $this->_set_help_popup_content($help_array, false);
1798
+		}
1799
+		// let's setup the trigger
1800
+		$content = '<a class="ee-dialog" href="?height='
1801
+				   . $dimensions[0]
1802
+				   . '&width='
1803
+				   . $dimensions[1]
1804
+				   . '&inlineId='
1805
+				   . $trigger_id
1806
+				   . '" target="_blank"><span class="question ee-help-popup-question"></span></a>';
1807
+		$content .= $help_content;
1808
+		if ($display) {
1809
+			echo $content;
1810
+			return '';
1811
+		}
1812
+		return $content;
1813
+	}
1814
+
1815
+
1816
+	/**
1817
+	 * _add_global_screen_options
1818
+	 * Add any extra wp_screen_options within this method using built-in WP functions/methods for doing so.
1819
+	 * This particular method will add_screen_options on ALL EE_Admin Pages
1820
+	 *
1821
+	 * @link   http://chrismarslender.com/wp-tutorials/wordpress-screen-options-tutorial/
1822
+	 *         see also WP_Screen object documents...
1823
+	 * @link   http://codex.wordpress.org/Class_Reference/WP_Screen
1824
+	 * @abstract
1825
+	 * @return void
1826
+	 */
1827
+	private function _add_global_screen_options()
1828
+	{
1829
+	}
1830
+
1831
+
1832
+	/**
1833
+	 * _add_global_feature_pointers
1834
+	 * This method is used for implementing any "feature pointers" (using built-in WP styling js).
1835
+	 * This particular method will implement feature pointers for ALL EE_Admin pages.
1836
+	 * Note: this is just a placeholder for now.  Implementation will come down the road
1837
+	 *
1838
+	 * @see    WP_Internal_Pointers class in wp-admin/includes/template.php for example (its a final class so can't be
1839
+	 *         extended) also see:
1840
+	 * @link   http://eamann.com/tech/wordpress-portland/
1841
+	 * @abstract
1842
+	 * @return void
1843
+	 */
1844
+	private function _add_global_feature_pointers()
1845
+	{
1846
+	}
1847
+
1848
+
1849
+	/**
1850
+	 * load_global_scripts_styles
1851
+	 * The scripts and styles enqueued in here will be loaded on every EE Admin page
1852
+	 *
1853
+	 * @return void
1854
+	 */
1855
+	public function load_global_scripts_styles()
1856
+	{
1857
+		/** STYLES **/
1858
+		// add debugging styles
1859
+		if (WP_DEBUG) {
1860
+			add_action('admin_head', [$this, 'add_xdebug_style']);
1861
+		}
1862
+		// register all styles
1863
+		wp_register_style(
1864
+			'espresso-ui-theme',
1865
+			EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1866
+			[],
1867
+			EVENT_ESPRESSO_VERSION
1868
+		);
1869
+		wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', [], EVENT_ESPRESSO_VERSION);
1870
+		// helpers styles
1871
+		wp_register_style(
1872
+			'ee-text-links',
1873
+			EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1874
+			[],
1875
+			EVENT_ESPRESSO_VERSION
1876
+		);
1877
+		/** SCRIPTS **/
1878
+		// register all scripts
1879
+		wp_register_script(
1880
+			'ee-dialog',
1881
+			EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1882
+			['jquery', 'jquery-ui-draggable'],
1883
+			EVENT_ESPRESSO_VERSION,
1884
+			true
1885
+		);
1886
+		wp_register_script(
1887
+			'ee_admin_js',
1888
+			EE_ADMIN_URL . 'assets/ee-admin-page.js',
1889
+			['espresso_core', 'ee-parse-uri', 'ee-dialog'],
1890
+			EVENT_ESPRESSO_VERSION,
1891
+			true
1892
+		);
1893
+		wp_register_script(
1894
+			'jquery-ui-timepicker-addon',
1895
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1896
+			['jquery-ui-datepicker', 'jquery-ui-slider'],
1897
+			EVENT_ESPRESSO_VERSION,
1898
+			true
1899
+		);
1900
+		// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1901
+		// if (EE_Registry::instance()->CFG->admin->help_tour_activation) {
1902
+		//     add_filter('FHEE_load_joyride', '__return_true');
1903
+		// }
1904
+		// script for sorting tables
1905
+		wp_register_script(
1906
+			'espresso_ajax_table_sorting',
1907
+			EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1908
+			['ee_admin_js', 'jquery-ui-sortable'],
1909
+			EVENT_ESPRESSO_VERSION,
1910
+			true
1911
+		);
1912
+		// script for parsing uri's
1913
+		wp_register_script(
1914
+			'ee-parse-uri',
1915
+			EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1916
+			[],
1917
+			EVENT_ESPRESSO_VERSION,
1918
+			true
1919
+		);
1920
+		// and parsing associative serialized form elements
1921
+		wp_register_script(
1922
+			'ee-serialize-full-array',
1923
+			EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1924
+			['jquery'],
1925
+			EVENT_ESPRESSO_VERSION,
1926
+			true
1927
+		);
1928
+		// helpers scripts
1929
+		wp_register_script(
1930
+			'ee-text-links',
1931
+			EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1932
+			['jquery'],
1933
+			EVENT_ESPRESSO_VERSION,
1934
+			true
1935
+		);
1936
+		wp_register_script(
1937
+			'ee-moment-core',
1938
+			EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1939
+			[],
1940
+			EVENT_ESPRESSO_VERSION,
1941
+			true
1942
+		);
1943
+		wp_register_script(
1944
+			'ee-moment',
1945
+			EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1946
+			['ee-moment-core'],
1947
+			EVENT_ESPRESSO_VERSION,
1948
+			true
1949
+		);
1950
+		wp_register_script(
1951
+			'ee-datepicker',
1952
+			EE_ADMIN_URL . 'assets/ee-datepicker.js',
1953
+			['jquery-ui-timepicker-addon', 'ee-moment'],
1954
+			EVENT_ESPRESSO_VERSION,
1955
+			true
1956
+		);
1957
+		// google charts
1958
+		wp_register_script(
1959
+			'google-charts',
1960
+			'https://www.gstatic.com/charts/loader.js',
1961
+			[],
1962
+			EVENT_ESPRESSO_VERSION,
1963
+			false
1964
+		);
1965
+		// ENQUEUE ALL BASICS BY DEFAULT
1966
+		wp_enqueue_style('ee-admin-css');
1967
+		wp_enqueue_script('ee_admin_js');
1968
+		wp_enqueue_script('ee-accounting');
1969
+		wp_enqueue_script('jquery-validate');
1970
+		// taking care of metaboxes
1971
+		if (empty($this->_cpt_route)
1972
+			&& (isset($this->_route_config['metaboxes']) || isset($this->_route_config['has_metaboxes']))
1973
+		) {
1974
+			wp_enqueue_script('dashboard');
1975
+		}
1976
+		// LOCALIZED DATA
1977
+		// localize script for ajax lazy loading
1978
+		$lazy_loader_container_ids = apply_filters(
1979
+			'FHEE__EE_Admin_Page_Core__load_global_scripts_styles__loader_containers',
1980
+			['espresso_news_post_box_content']
1981
+		);
1982
+		wp_localize_script('ee_admin_js', 'eeLazyLoadingContainers', $lazy_loader_container_ids);
1983
+		// disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1984
+		// /**
1985
+		//  * help tour stuff
1986
+		//  */
1987
+		// if (! empty($this->_help_tour)) {
1988
+		//     // register the js for kicking things off
1989
+		//     wp_enqueue_script(
1990
+		//         'ee-help-tour',
1991
+		//         EE_ADMIN_URL . 'assets/ee-help-tour.js',
1992
+		//         array('jquery-joyride'),
1993
+		//         EVENT_ESPRESSO_VERSION,
1994
+		//         true
1995
+		//     );
1996
+		//     $tours = array();
1997
+		//     // setup tours for the js tour object
1998
+		//     foreach ($this->_help_tour['tours'] as $tour) {
1999
+		//         if ($tour instanceof EE_Help_Tour) {
2000
+		//             $tours[] = array(
2001
+		//                 'id'      => $tour->get_slug(),
2002
+		//                 'options' => $tour->get_options(),
2003
+		//             );
2004
+		//         }
2005
+		//     }
2006
+		//     wp_localize_script('ee-help-tour', 'EE_HELP_TOUR', array('tours' => $tours));
2007
+		//     // admin_footer_global will take care of making sure our help_tour skeleton gets printed via the info stored in $this->_help_tour
2008
+		// }
2009
+	}
2010
+
2011
+
2012
+	/**
2013
+	 *        admin_footer_scripts_eei18n_js_strings
2014
+	 *
2015
+	 * @return        void
2016
+	 */
2017
+	public function admin_footer_scripts_eei18n_js_strings()
2018
+	{
2019
+		EE_Registry::$i18n_js_strings['ajax_url']       = WP_AJAX_URL;
2020
+		EE_Registry::$i18n_js_strings['confirm_delete'] = esc_html__(
2021
+			'Are you absolutely sure you want to delete this item?\nThis action will delete ALL DATA associated with this item!!!\nThis can NOT be undone!!!',
2022
+			'event_espresso'
2023
+		);
2024
+		EE_Registry::$i18n_js_strings['January']        = esc_html__('January', 'event_espresso');
2025
+		EE_Registry::$i18n_js_strings['February']       = esc_html__('February', 'event_espresso');
2026
+		EE_Registry::$i18n_js_strings['March']          = esc_html__('March', 'event_espresso');
2027
+		EE_Registry::$i18n_js_strings['April']          = esc_html__('April', 'event_espresso');
2028
+		EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2029
+		EE_Registry::$i18n_js_strings['June']           = esc_html__('June', 'event_espresso');
2030
+		EE_Registry::$i18n_js_strings['July']           = esc_html__('July', 'event_espresso');
2031
+		EE_Registry::$i18n_js_strings['August']         = esc_html__('August', 'event_espresso');
2032
+		EE_Registry::$i18n_js_strings['September']      = esc_html__('September', 'event_espresso');
2033
+		EE_Registry::$i18n_js_strings['October']        = esc_html__('October', 'event_espresso');
2034
+		EE_Registry::$i18n_js_strings['November']       = esc_html__('November', 'event_espresso');
2035
+		EE_Registry::$i18n_js_strings['December']       = esc_html__('December', 'event_espresso');
2036
+		EE_Registry::$i18n_js_strings['Jan']            = esc_html__('Jan', 'event_espresso');
2037
+		EE_Registry::$i18n_js_strings['Feb']            = esc_html__('Feb', 'event_espresso');
2038
+		EE_Registry::$i18n_js_strings['Mar']            = esc_html__('Mar', 'event_espresso');
2039
+		EE_Registry::$i18n_js_strings['Apr']            = esc_html__('Apr', 'event_espresso');
2040
+		EE_Registry::$i18n_js_strings['May']            = esc_html__('May', 'event_espresso');
2041
+		EE_Registry::$i18n_js_strings['Jun']            = esc_html__('Jun', 'event_espresso');
2042
+		EE_Registry::$i18n_js_strings['Jul']            = esc_html__('Jul', 'event_espresso');
2043
+		EE_Registry::$i18n_js_strings['Aug']            = esc_html__('Aug', 'event_espresso');
2044
+		EE_Registry::$i18n_js_strings['Sep']            = esc_html__('Sep', 'event_espresso');
2045
+		EE_Registry::$i18n_js_strings['Oct']            = esc_html__('Oct', 'event_espresso');
2046
+		EE_Registry::$i18n_js_strings['Nov']            = esc_html__('Nov', 'event_espresso');
2047
+		EE_Registry::$i18n_js_strings['Dec']            = esc_html__('Dec', 'event_espresso');
2048
+		EE_Registry::$i18n_js_strings['Sunday']         = esc_html__('Sunday', 'event_espresso');
2049
+		EE_Registry::$i18n_js_strings['Monday']         = esc_html__('Monday', 'event_espresso');
2050
+		EE_Registry::$i18n_js_strings['Tuesday']        = esc_html__('Tuesday', 'event_espresso');
2051
+		EE_Registry::$i18n_js_strings['Wednesday']      = esc_html__('Wednesday', 'event_espresso');
2052
+		EE_Registry::$i18n_js_strings['Thursday']       = esc_html__('Thursday', 'event_espresso');
2053
+		EE_Registry::$i18n_js_strings['Friday']         = esc_html__('Friday', 'event_espresso');
2054
+		EE_Registry::$i18n_js_strings['Saturday']       = esc_html__('Saturday', 'event_espresso');
2055
+		EE_Registry::$i18n_js_strings['Sun']            = esc_html__('Sun', 'event_espresso');
2056
+		EE_Registry::$i18n_js_strings['Mon']            = esc_html__('Mon', 'event_espresso');
2057
+		EE_Registry::$i18n_js_strings['Tue']            = esc_html__('Tue', 'event_espresso');
2058
+		EE_Registry::$i18n_js_strings['Wed']            = esc_html__('Wed', 'event_espresso');
2059
+		EE_Registry::$i18n_js_strings['Thu']            = esc_html__('Thu', 'event_espresso');
2060
+		EE_Registry::$i18n_js_strings['Fri']            = esc_html__('Fri', 'event_espresso');
2061
+		EE_Registry::$i18n_js_strings['Sat']            = esc_html__('Sat', 'event_espresso');
2062
+	}
2063
+
2064
+
2065
+	/**
2066
+	 *        load enhanced xdebug styles for ppl with failing eyesight
2067
+	 *
2068
+	 * @return        void
2069
+	 */
2070
+	public function add_xdebug_style()
2071
+	{
2072
+		echo '<style>.xdebug-error { font-size:1.5em; }</style>';
2073
+	}
2074
+
2075
+
2076
+	/************************/
2077
+	/** LIST TABLE METHODS **/
2078
+	/************************/
2079
+	/**
2080
+	 * this sets up the list table if the current view requires it.
2081
+	 *
2082
+	 * @return void
2083
+	 * @throws EE_Error
2084
+	 */
2085
+	protected function _set_list_table()
2086
+	{
2087
+		// first is this a list_table view?
2088
+		if (! isset($this->_route_config['list_table'])) {
2089
+			return;
2090
+		} //not a list_table view so get out.
2091
+		// list table functions are per view specific (because some admin pages might have more than one list table!)
2092
+		$list_table_view = '_set_list_table_views_' . $this->_req_action;
2093
+		if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2094
+			// user error msg
2095
+			$error_msg = esc_html__(
2096
+				'An error occurred. The requested list table views could not be found.',
2097
+				'event_espresso'
2098
+			);
2099
+			// developer error msg
2100
+			$error_msg .= '||'
2101
+						  . sprintf(
2102
+							  esc_html__(
2103
+								  'List table views for "%s" route could not be setup. Check that you have the corresponding method, "%s" set up for defining list_table_views for this route.',
2104
+								  'event_espresso'
2105
+							  ),
2106
+							  $this->_req_action,
2107
+							  $list_table_view
2108
+						  );
2109
+			throw new EE_Error($error_msg);
2110
+		}
2111
+		// let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2112
+		$this->_views = apply_filters(
2113
+			'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2114
+			$this->_views
2115
+		);
2116
+		$this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2117
+		$this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2118
+		$this->_set_list_table_view();
2119
+		$this->_set_list_table_object();
2120
+	}
2121
+
2122
+
2123
+	/**
2124
+	 * set current view for List Table
2125
+	 *
2126
+	 * @return void
2127
+	 */
2128
+	protected function _set_list_table_view()
2129
+	{
2130
+		$this->_view = isset($this->_views['in_use']) ? 'in_use' : 'all';
2131
+		$status = $this->request->getRequestParam('status', null, 'key');
2132
+		$this->_view = $status && array_key_exists($status, $this->_views)
2133
+			? $status
2134
+			: $this->_view;
2135
+	}
2136
+
2137
+
2138
+	/**
2139
+	 * _set_list_table_object
2140
+	 * WP_List_Table objects need to be loaded fairly early so automatic stuff WP does is taken care of.
2141
+	 *
2142
+	 * @throws InvalidInterfaceException
2143
+	 * @throws InvalidArgumentException
2144
+	 * @throws InvalidDataTypeException
2145
+	 * @throws EE_Error
2146
+	 * @throws InvalidInterfaceException
2147
+	 */
2148
+	protected function _set_list_table_object()
2149
+	{
2150
+		if (isset($this->_route_config['list_table'])) {
2151
+			if (! class_exists($this->_route_config['list_table'])) {
2152
+				throw new EE_Error(
2153
+					sprintf(
2154
+						esc_html__(
2155
+							'The %s class defined for the list table does not exist.  Please check the spelling of the class ref in the $_page_config property on %s.',
2156
+							'event_espresso'
2157
+						),
2158
+						$this->_route_config['list_table'],
2159
+						get_class($this)
2160
+					)
2161
+				);
2162
+			}
2163
+			$this->_list_table_object = $this->loader->getShared(
2164
+				$this->_route_config['list_table'],
2165
+				[$this]
2166
+			);
2167
+		}
2168
+	}
2169
+
2170
+
2171
+	/**
2172
+	 * get_list_table_view_RLs - get it? View RL ?? VU-RL???  URL ??
2173
+	 *
2174
+	 * @param array $extra_query_args                     Optional. An array of extra query args to add to the generated
2175
+	 *                                                    urls.  The array should be indexed by the view it is being
2176
+	 *                                                    added to.
2177
+	 * @return array
2178
+	 */
2179
+	public function get_list_table_view_RLs($extra_query_args = [])
2180
+	{
2181
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2182
+		if (empty($this->_views)) {
2183
+			$this->_views = [];
2184
+		}
2185
+		// cycle thru views
2186
+		foreach ($this->_views as $key => $view) {
2187
+			$query_args = [];
2188
+			// check for current view
2189
+			$this->_views[ $key ]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2190
+			$query_args['action']                        = $this->_req_action;
2191
+			$query_args[ $this->_req_action . '_nonce' ] = wp_create_nonce($query_args['action'] . '_nonce');
2192
+			$query_args['status']                        = $view['slug'];
2193
+			// merge any other arguments sent in.
2194
+			if (isset($extra_query_args[ $view['slug'] ])) {
2195
+				$query_args = array_merge($query_args, $extra_query_args[ $view['slug'] ]);
2196
+			}
2197
+			$this->_views[ $key ]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2198
+		}
2199
+		return $this->_views;
2200
+	}
2201
+
2202
+
2203
+	/**
2204
+	 * _entries_per_page_dropdown
2205
+	 * generates a drop down box for selecting the number of visible rows in an admin page list table
2206
+	 *
2207
+	 * @param int $max_entries total number of rows in the table
2208
+	 * @return string
2209
+	 * @todo   : Note: ideally this should be added to the screen options dropdown as that would be consistent with how
2210
+	 *         WP does it.
2211
+	 */
2212
+	protected function _entries_per_page_dropdown($max_entries = 0)
2213
+	{
2214
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2215
+		$values   = [10, 25, 50, 100];
2216
+		$per_page = $this->request->getRequestParam('per_page', 10, 'int');
2217
+		if ($max_entries) {
2218
+			$values[] = $max_entries;
2219
+			sort($values);
2220
+		}
2221
+		$entries_per_page_dropdown = '
2222 2222
 			<div id="entries-per-page-dv" class="alignleft actions">
2223 2223
 				<label class="hide-if-no-js">
2224 2224
 					Show
2225 2225
 					<select id="entries-per-page-slct" name="entries-per-page-slct">';
2226
-        foreach ($values as $value) {
2227
-            if ($value < $max_entries) {
2228
-                $selected                  = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2229
-                $entries_per_page_dropdown .= '
2226
+		foreach ($values as $value) {
2227
+			if ($value < $max_entries) {
2228
+				$selected                  = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2229
+				$entries_per_page_dropdown .= '
2230 2230
 						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
2231
-            }
2232
-        }
2233
-        $selected                  = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2234
-        $entries_per_page_dropdown .= '
2231
+			}
2232
+		}
2233
+		$selected                  = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2234
+		$entries_per_page_dropdown .= '
2235 2235
 						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
2236
-        $entries_per_page_dropdown .= '
2236
+		$entries_per_page_dropdown .= '
2237 2237
 					</select>
2238 2238
 					entries
2239 2239
 				</label>
2240 2240
 				<input id="entries-per-page-btn" class="button-secondary" type="submit" value="Go" >
2241 2241
 			</div>
2242 2242
 		';
2243
-        return $entries_per_page_dropdown;
2244
-    }
2245
-
2246
-
2247
-    /**
2248
-     *        _set_search_attributes
2249
-     *
2250
-     * @return        void
2251
-     */
2252
-    public function _set_search_attributes()
2253
-    {
2254
-        $this->_template_args['search']['btn_label'] = sprintf(
2255
-            esc_html__('Search %s', 'event_espresso'),
2256
-            empty($this->_search_btn_label) ? $this->page_label
2257
-                : $this->_search_btn_label
2258
-        );
2259
-        $this->_template_args['search']['callback']  = 'search_' . $this->page_slug;
2260
-    }
2261
-
2262
-
2263
-
2264
-    /*** END LIST TABLE METHODS **/
2265
-
2266
-
2267
-    /**
2268
-     * _add_registered_metaboxes
2269
-     *  this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
2270
-     *
2271
-     * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
2272
-     * @return void
2273
-     * @throws EE_Error
2274
-     */
2275
-    private function _add_registered_meta_boxes()
2276
-    {
2277
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2278
-        // we only add meta boxes if the page_route calls for it
2279
-        if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
2280
-            && is_array(
2281
-                $this->_route_config['metaboxes']
2282
-            )
2283
-        ) {
2284
-            // this simply loops through the callbacks provided
2285
-            // and checks if there is a corresponding callback registered by the child
2286
-            // if there is then we go ahead and process the metabox loader.
2287
-            foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
2288
-                // first check for Closures
2289
-                if ($metabox_callback instanceof Closure) {
2290
-                    $result = $metabox_callback();
2291
-                } elseif (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
2292
-                    $result = call_user_func([$metabox_callback[0], $metabox_callback[1]]);
2293
-                } else {
2294
-                    $result = call_user_func([$this, &$metabox_callback]);
2295
-                }
2296
-                if ($result === false) {
2297
-                    // user error msg
2298
-                    $error_msg = esc_html__(
2299
-                        'An error occurred. The  requested metabox could not be found.',
2300
-                        'event_espresso'
2301
-                    );
2302
-                    // developer error msg
2303
-                    $error_msg .= '||'
2304
-                                  . sprintf(
2305
-                                      esc_html__(
2306
-                                          'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
2307
-                                          'event_espresso'
2308
-                                      ),
2309
-                                      $metabox_callback
2310
-                                  );
2311
-                    throw new EE_Error($error_msg);
2312
-                }
2313
-            }
2314
-        }
2315
-    }
2316
-
2317
-
2318
-    /**
2319
-     * _add_screen_columns
2320
-     * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as
2321
-     * the dynamic column template and we'll setup the column options for the page.
2322
-     *
2323
-     * @return void
2324
-     */
2325
-    private function _add_screen_columns()
2326
-    {
2327
-        if (is_array($this->_route_config)
2328
-            && isset($this->_route_config['columns'])
2329
-            && is_array($this->_route_config['columns'])
2330
-            && count($this->_route_config['columns']) === 2
2331
-        ) {
2332
-            add_screen_option(
2333
-                'layout_columns',
2334
-                [
2335
-                    'max'     => (int) $this->_route_config['columns'][0],
2336
-                    'default' => (int) $this->_route_config['columns'][1],
2337
-                ]
2338
-            );
2339
-            $this->_template_args['num_columns']                 = $this->_route_config['columns'][0];
2340
-            $screen_id                                           = $this->_current_screen->id;
2341
-            $screen_columns                                      = (int) get_user_option("screen_layout_{$screen_id}");
2342
-            $total_columns                                       = ! empty($screen_columns)
2343
-                ? $screen_columns
2344
-                : $this->_route_config['columns'][1];
2345
-            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2346
-            $this->_template_args['current_page']                = $this->_wp_page_slug;
2347
-            $this->_template_args['screen']                      = $this->_current_screen;
2348
-            $this->_column_template_path                         = EE_ADMIN_TEMPLATE
2349
-                                                                   . 'admin_details_metabox_column_wrapper.template.php';
2350
-            // finally if we don't have has_metaboxes set in the route config
2351
-            // let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
2352
-            $this->_route_config['has_metaboxes'] = true;
2353
-        }
2354
-    }
2355
-
2356
-
2357
-
2358
-    /** GLOBALLY AVAILABLE METABOXES **/
2359
-
2360
-
2361
-    /**
2362
-     * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply
2363
-     * referencing the callback in the _page_config array property.  This way you can be very specific about what pages
2364
-     * these get loaded on.
2365
-     */
2366
-    private function _espresso_news_post_box()
2367
-    {
2368
-        $news_box_title = apply_filters(
2369
-            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2370
-            esc_html__('New @ Event Espresso', 'event_espresso')
2371
-        );
2372
-        add_meta_box(
2373
-            'espresso_news_post_box',
2374
-            $news_box_title,
2375
-            [
2376
-                $this,
2377
-                'espresso_news_post_box',
2378
-            ],
2379
-            $this->_wp_page_slug,
2380
-            'side'
2381
-        );
2382
-    }
2383
-
2384
-
2385
-    /**
2386
-     * Code for setting up espresso ratings request metabox.
2387
-     */
2388
-    protected function _espresso_ratings_request()
2389
-    {
2390
-        if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2391
-            return;
2392
-        }
2393
-        $ratings_box_title = apply_filters(
2394
-            'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2395
-            esc_html__('Keep Event Espresso Decaf Free', 'event_espresso')
2396
-        );
2397
-        add_meta_box(
2398
-            'espresso_ratings_request',
2399
-            $ratings_box_title,
2400
-            [
2401
-                $this,
2402
-                'espresso_ratings_request',
2403
-            ],
2404
-            $this->_wp_page_slug,
2405
-            'side'
2406
-        );
2407
-    }
2408
-
2409
-
2410
-    /**
2411
-     * Code for setting up espresso ratings request metabox content.
2412
-     *
2413
-     * @throws DomainException
2414
-     */
2415
-    public function espresso_ratings_request()
2416
-    {
2417
-        EEH_Template::display_template(
2418
-            EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php',
2419
-            []
2420
-        );
2421
-    }
2422
-
2423
-
2424
-    public static function cached_rss_display($rss_id, $url)
2425
-    {
2426
-        $loading   = '<p class="widget-loading hide-if-no-js">'
2427
-                     . __('Loading&#8230;', 'event_espresso')
2428
-                     . '</p><p class="hide-if-js">'
2429
-                     . esc_html__('This widget requires JavaScript.', 'event_espresso')
2430
-                     . '</p>';
2431
-        $pre       = '<div class="espresso-rss-display">' . "\n\t";
2432
-        $pre       .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2433
-        $post      = '</div>' . "\n";
2434
-        $cache_key = 'ee_rss_' . md5($rss_id);
2435
-        $output    = get_transient($cache_key);
2436
-        if ($output !== false) {
2437
-            echo $pre . $output . $post;
2438
-            return true;
2439
-        }
2440
-        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2441
-            echo $pre . $loading . $post;
2442
-            return false;
2443
-        }
2444
-        ob_start();
2445
-        wp_widget_rss_output($url, ['show_date' => 0, 'items' => 5]);
2446
-        set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
2447
-        return true;
2448
-    }
2449
-
2450
-
2451
-    public function espresso_news_post_box()
2452
-    {
2453
-        ?>
2243
+		return $entries_per_page_dropdown;
2244
+	}
2245
+
2246
+
2247
+	/**
2248
+	 *        _set_search_attributes
2249
+	 *
2250
+	 * @return        void
2251
+	 */
2252
+	public function _set_search_attributes()
2253
+	{
2254
+		$this->_template_args['search']['btn_label'] = sprintf(
2255
+			esc_html__('Search %s', 'event_espresso'),
2256
+			empty($this->_search_btn_label) ? $this->page_label
2257
+				: $this->_search_btn_label
2258
+		);
2259
+		$this->_template_args['search']['callback']  = 'search_' . $this->page_slug;
2260
+	}
2261
+
2262
+
2263
+
2264
+	/*** END LIST TABLE METHODS **/
2265
+
2266
+
2267
+	/**
2268
+	 * _add_registered_metaboxes
2269
+	 *  this loads any registered metaboxes via the 'metaboxes' index in the _page_config property array.
2270
+	 *
2271
+	 * @link   http://codex.wordpress.org/Function_Reference/add_meta_box
2272
+	 * @return void
2273
+	 * @throws EE_Error
2274
+	 */
2275
+	private function _add_registered_meta_boxes()
2276
+	{
2277
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2278
+		// we only add meta boxes if the page_route calls for it
2279
+		if (is_array($this->_route_config) && isset($this->_route_config['metaboxes'])
2280
+			&& is_array(
2281
+				$this->_route_config['metaboxes']
2282
+			)
2283
+		) {
2284
+			// this simply loops through the callbacks provided
2285
+			// and checks if there is a corresponding callback registered by the child
2286
+			// if there is then we go ahead and process the metabox loader.
2287
+			foreach ($this->_route_config['metaboxes'] as $metabox_callback) {
2288
+				// first check for Closures
2289
+				if ($metabox_callback instanceof Closure) {
2290
+					$result = $metabox_callback();
2291
+				} elseif (is_array($metabox_callback) && isset($metabox_callback[0], $metabox_callback[1])) {
2292
+					$result = call_user_func([$metabox_callback[0], $metabox_callback[1]]);
2293
+				} else {
2294
+					$result = call_user_func([$this, &$metabox_callback]);
2295
+				}
2296
+				if ($result === false) {
2297
+					// user error msg
2298
+					$error_msg = esc_html__(
2299
+						'An error occurred. The  requested metabox could not be found.',
2300
+						'event_espresso'
2301
+					);
2302
+					// developer error msg
2303
+					$error_msg .= '||'
2304
+								  . sprintf(
2305
+									  esc_html__(
2306
+										  'The metabox with the string "%s" could not be called. Check that the spelling for method names and actions in the "_page_config[\'metaboxes\']" array are all correct.',
2307
+										  'event_espresso'
2308
+									  ),
2309
+									  $metabox_callback
2310
+								  );
2311
+					throw new EE_Error($error_msg);
2312
+				}
2313
+			}
2314
+		}
2315
+	}
2316
+
2317
+
2318
+	/**
2319
+	 * _add_screen_columns
2320
+	 * This will check the _page_config array and if there is "columns" key index indicated, we'll set the template as
2321
+	 * the dynamic column template and we'll setup the column options for the page.
2322
+	 *
2323
+	 * @return void
2324
+	 */
2325
+	private function _add_screen_columns()
2326
+	{
2327
+		if (is_array($this->_route_config)
2328
+			&& isset($this->_route_config['columns'])
2329
+			&& is_array($this->_route_config['columns'])
2330
+			&& count($this->_route_config['columns']) === 2
2331
+		) {
2332
+			add_screen_option(
2333
+				'layout_columns',
2334
+				[
2335
+					'max'     => (int) $this->_route_config['columns'][0],
2336
+					'default' => (int) $this->_route_config['columns'][1],
2337
+				]
2338
+			);
2339
+			$this->_template_args['num_columns']                 = $this->_route_config['columns'][0];
2340
+			$screen_id                                           = $this->_current_screen->id;
2341
+			$screen_columns                                      = (int) get_user_option("screen_layout_{$screen_id}");
2342
+			$total_columns                                       = ! empty($screen_columns)
2343
+				? $screen_columns
2344
+				: $this->_route_config['columns'][1];
2345
+			$this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2346
+			$this->_template_args['current_page']                = $this->_wp_page_slug;
2347
+			$this->_template_args['screen']                      = $this->_current_screen;
2348
+			$this->_column_template_path                         = EE_ADMIN_TEMPLATE
2349
+																   . 'admin_details_metabox_column_wrapper.template.php';
2350
+			// finally if we don't have has_metaboxes set in the route config
2351
+			// let's make sure it IS set other wise the necessary hidden fields for this won't be loaded.
2352
+			$this->_route_config['has_metaboxes'] = true;
2353
+		}
2354
+	}
2355
+
2356
+
2357
+
2358
+	/** GLOBALLY AVAILABLE METABOXES **/
2359
+
2360
+
2361
+	/**
2362
+	 * In this section we put any globally available EE metaboxes for all EE Admin pages.  They are called by simply
2363
+	 * referencing the callback in the _page_config array property.  This way you can be very specific about what pages
2364
+	 * these get loaded on.
2365
+	 */
2366
+	private function _espresso_news_post_box()
2367
+	{
2368
+		$news_box_title = apply_filters(
2369
+			'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2370
+			esc_html__('New @ Event Espresso', 'event_espresso')
2371
+		);
2372
+		add_meta_box(
2373
+			'espresso_news_post_box',
2374
+			$news_box_title,
2375
+			[
2376
+				$this,
2377
+				'espresso_news_post_box',
2378
+			],
2379
+			$this->_wp_page_slug,
2380
+			'side'
2381
+		);
2382
+	}
2383
+
2384
+
2385
+	/**
2386
+	 * Code for setting up espresso ratings request metabox.
2387
+	 */
2388
+	protected function _espresso_ratings_request()
2389
+	{
2390
+		if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2391
+			return;
2392
+		}
2393
+		$ratings_box_title = apply_filters(
2394
+			'FHEE__EE_Admin_Page___espresso_news_post_box__news_box_title',
2395
+			esc_html__('Keep Event Espresso Decaf Free', 'event_espresso')
2396
+		);
2397
+		add_meta_box(
2398
+			'espresso_ratings_request',
2399
+			$ratings_box_title,
2400
+			[
2401
+				$this,
2402
+				'espresso_ratings_request',
2403
+			],
2404
+			$this->_wp_page_slug,
2405
+			'side'
2406
+		);
2407
+	}
2408
+
2409
+
2410
+	/**
2411
+	 * Code for setting up espresso ratings request metabox content.
2412
+	 *
2413
+	 * @throws DomainException
2414
+	 */
2415
+	public function espresso_ratings_request()
2416
+	{
2417
+		EEH_Template::display_template(
2418
+			EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php',
2419
+			[]
2420
+		);
2421
+	}
2422
+
2423
+
2424
+	public static function cached_rss_display($rss_id, $url)
2425
+	{
2426
+		$loading   = '<p class="widget-loading hide-if-no-js">'
2427
+					 . __('Loading&#8230;', 'event_espresso')
2428
+					 . '</p><p class="hide-if-js">'
2429
+					 . esc_html__('This widget requires JavaScript.', 'event_espresso')
2430
+					 . '</p>';
2431
+		$pre       = '<div class="espresso-rss-display">' . "\n\t";
2432
+		$pre       .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2433
+		$post      = '</div>' . "\n";
2434
+		$cache_key = 'ee_rss_' . md5($rss_id);
2435
+		$output    = get_transient($cache_key);
2436
+		if ($output !== false) {
2437
+			echo $pre . $output . $post;
2438
+			return true;
2439
+		}
2440
+		if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2441
+			echo $pre . $loading . $post;
2442
+			return false;
2443
+		}
2444
+		ob_start();
2445
+		wp_widget_rss_output($url, ['show_date' => 0, 'items' => 5]);
2446
+		set_transient($cache_key, ob_get_flush(), 12 * HOUR_IN_SECONDS);
2447
+		return true;
2448
+	}
2449
+
2450
+
2451
+	public function espresso_news_post_box()
2452
+	{
2453
+		?>
2454 2454
         <div class="padding">
2455 2455
             <div id="espresso_news_post_box_content" class="infolinks">
2456 2456
                 <?php
2457
-                // Get RSS Feed(s)
2458
-                self::cached_rss_display(
2459
-                    'espresso_news_post_box_content',
2460
-                    urlencode(
2461
-                        apply_filters(
2462
-                            'FHEE__EE_Admin_Page__espresso_news_post_box__feed_url',
2463
-                            'http://eventespresso.com/feed/'
2464
-                        )
2465
-                    )
2466
-                );
2467
-                ?>
2457
+				// Get RSS Feed(s)
2458
+				self::cached_rss_display(
2459
+					'espresso_news_post_box_content',
2460
+					urlencode(
2461
+						apply_filters(
2462
+							'FHEE__EE_Admin_Page__espresso_news_post_box__feed_url',
2463
+							'http://eventespresso.com/feed/'
2464
+						)
2465
+					)
2466
+				);
2467
+				?>
2468 2468
             </div>
2469 2469
             <?php do_action('AHEE__EE_Admin_Page__espresso_news_post_box__after_content'); ?>
2470 2470
         </div>
2471 2471
         <?php
2472
-    }
2473
-
2474
-
2475
-    private function _espresso_links_post_box()
2476
-    {
2477
-        // Hiding until we actually have content to put in here...
2478
-        // add_meta_box('espresso_links_post_box', esc_html__('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2479
-    }
2480
-
2481
-
2482
-    public function espresso_links_post_box()
2483
-    {
2484
-        // Hiding until we actually have content to put in here...
2485
-        // EEH_Template::display_template(
2486
-        //     EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php'
2487
-        // );
2488
-    }
2489
-
2490
-
2491
-    protected function _espresso_sponsors_post_box()
2492
-    {
2493
-        if (apply_filters('FHEE_show_sponsors_meta_box', true)) {
2494
-            add_meta_box(
2495
-                'espresso_sponsors_post_box',
2496
-                esc_html__('Event Espresso Highlights', 'event_espresso'),
2497
-                [$this, 'espresso_sponsors_post_box'],
2498
-                $this->_wp_page_slug,
2499
-                'side'
2500
-            );
2501
-        }
2502
-    }
2503
-
2504
-
2505
-    public function espresso_sponsors_post_box()
2506
-    {
2507
-        EEH_Template::display_template(
2508
-            EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2509
-        );
2510
-    }
2511
-
2512
-
2513
-    private function _publish_post_box()
2514
-    {
2515
-        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2516
-        // if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2517
-        // then we'll use that for the metabox label.
2518
-        // Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2519
-        if (! empty($this->_labels['publishbox'])) {
2520
-            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][ $this->_req_action ]
2521
-                : $this->_labels['publishbox'];
2522
-        } else {
2523
-            $box_label = esc_html__('Publish', 'event_espresso');
2524
-        }
2525
-        $box_label = apply_filters(
2526
-            'FHEE__EE_Admin_Page___publish_post_box__box_label',
2527
-            $box_label,
2528
-            $this->_req_action,
2529
-            $this
2530
-        );
2531
-        add_meta_box(
2532
-            $meta_box_ref,
2533
-            $box_label,
2534
-            [$this, 'editor_overview'],
2535
-            $this->_current_screen->id,
2536
-            'side',
2537
-            'high'
2538
-        );
2539
-    }
2540
-
2541
-
2542
-    public function editor_overview()
2543
-    {
2544
-        // if we have extra content set let's add it in if not make sure its empty
2545
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2546
-            ? $this->_template_args['publish_box_extra_content']
2547
-            : '';
2548
-        echo EEH_Template::display_template(
2549
-            EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2550
-            $this->_template_args,
2551
-            true
2552
-        );
2553
-    }
2554
-
2555
-
2556
-    /** end of globally available metaboxes section **/
2557
-
2558
-
2559
-    /**
2560
-     * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2561
-     * protected method.
2562
-     *
2563
-     * @param string $name
2564
-     * @param int    $id
2565
-     * @param bool   $delete
2566
-     * @param string $save_close_redirect_URL
2567
-     * @param bool   $both_btns
2568
-     * @throws EE_Error
2569
-     * @throws InvalidArgumentException
2570
-     * @throws InvalidDataTypeException
2571
-     * @throws InvalidInterfaceException
2572
-     * @see   $this->_set_publish_post_box_vars for param details
2573
-     * @since 4.6.0
2574
-     */
2575
-    public function set_publish_post_box_vars(
2576
-        $name = '',
2577
-        $id = 0,
2578
-        $delete = false,
2579
-        $save_close_redirect_URL = '',
2580
-        $both_btns = true
2581
-    ) {
2582
-        $this->_set_publish_post_box_vars(
2583
-            $name,
2584
-            $id,
2585
-            $delete,
2586
-            $save_close_redirect_URL,
2587
-            $both_btns
2588
-        );
2589
-    }
2590
-
2591
-
2592
-    /**
2593
-     * Sets the _template_args arguments used by the _publish_post_box shortcut
2594
-     * Note: currently there is no validation for this.  However if you want the delete button, the
2595
-     * save, and save and close buttons to work properly, then you will want to include a
2596
-     * values for the name and id arguments.
2597
-     *
2598
-     * @param string  $name                       key used for the action ID (i.e. event_id)
2599
-     * @param int     $id                         id attached to the item published
2600
-     * @param string  $delete                     page route callback for the delete action
2601
-     * @param string  $save_close_redirect_URL    custom URL to redirect to after Save & Close has been completed
2602
-     * @param boolean $both_btns                  whether to display BOTH the "Save & Close" and "Save" buttons or just
2603
-     *                                            the Save button
2604
-     * @throws EE_Error
2605
-     * @throws InvalidArgumentException
2606
-     * @throws InvalidDataTypeException
2607
-     * @throws InvalidInterfaceException
2608
-     * @todo  Add in validation for name/id arguments.
2609
-     */
2610
-    protected function _set_publish_post_box_vars(
2611
-        $name = '',
2612
-        $id = 0,
2613
-        $delete = '',
2614
-        $save_close_redirect_URL = '',
2615
-        $both_btns = true
2616
-    ) {
2617
-        // if Save & Close, use a custom redirect URL or default to the main page?
2618
-        $save_close_redirect_URL = ! empty($save_close_redirect_URL)
2619
-            ? $save_close_redirect_URL
2620
-            : $this->_admin_base_url;
2621
-        // create the Save & Close and Save buttons
2622
-        $this->_set_save_buttons($both_btns, [], [], $save_close_redirect_URL);
2623
-        // if we have extra content set let's add it in if not make sure its empty
2624
-        $this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2625
-            ? $this->_template_args['publish_box_extra_content']
2626
-            : '';
2627
-        if ($delete && ! empty($id)) {
2628
-            // make sure we have a default if just true is sent.
2629
-            $delete           = ! empty($delete) ? $delete : 'delete';
2630
-            $delete_link_args = [$name => $id];
2631
-            $delete           = $this->get_action_link_or_button(
2632
-                $delete,
2633
-                $delete,
2634
-                $delete_link_args,
2635
-                'submitdelete deletion',
2636
-                '',
2637
-                false
2638
-            );
2639
-        }
2640
-        $this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2641
-        if (! empty($name) && ! empty($id)) {
2642
-            $hidden_field_arr[ $name ] = [
2643
-                'type'  => 'hidden',
2644
-                'value' => $id,
2645
-            ];
2646
-            $hf                        = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2647
-        } else {
2648
-            $hf = '';
2649
-        }
2650
-        // add hidden field
2651
-        $this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2652
-            ? $hf[ $name ]['field']
2653
-            : $hf;
2654
-    }
2655
-
2656
-
2657
-    /**
2658
-     * displays an error message to ppl who have javascript disabled
2659
-     *
2660
-     * @return void
2661
-     */
2662
-    private function _display_no_javascript_warning()
2663
-    {
2664
-        ?>
2472
+	}
2473
+
2474
+
2475
+	private function _espresso_links_post_box()
2476
+	{
2477
+		// Hiding until we actually have content to put in here...
2478
+		// add_meta_box('espresso_links_post_box', esc_html__('Helpful Plugin Links', 'event_espresso'), array( $this, 'espresso_links_post_box'), $this->_wp_page_slug, 'side');
2479
+	}
2480
+
2481
+
2482
+	public function espresso_links_post_box()
2483
+	{
2484
+		// Hiding until we actually have content to put in here...
2485
+		// EEH_Template::display_template(
2486
+		//     EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_links.template.php'
2487
+		// );
2488
+	}
2489
+
2490
+
2491
+	protected function _espresso_sponsors_post_box()
2492
+	{
2493
+		if (apply_filters('FHEE_show_sponsors_meta_box', true)) {
2494
+			add_meta_box(
2495
+				'espresso_sponsors_post_box',
2496
+				esc_html__('Event Espresso Highlights', 'event_espresso'),
2497
+				[$this, 'espresso_sponsors_post_box'],
2498
+				$this->_wp_page_slug,
2499
+				'side'
2500
+			);
2501
+		}
2502
+	}
2503
+
2504
+
2505
+	public function espresso_sponsors_post_box()
2506
+	{
2507
+		EEH_Template::display_template(
2508
+			EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2509
+		);
2510
+	}
2511
+
2512
+
2513
+	private function _publish_post_box()
2514
+	{
2515
+		$meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2516
+		// if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2517
+		// then we'll use that for the metabox label.
2518
+		// Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2519
+		if (! empty($this->_labels['publishbox'])) {
2520
+			$box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][ $this->_req_action ]
2521
+				: $this->_labels['publishbox'];
2522
+		} else {
2523
+			$box_label = esc_html__('Publish', 'event_espresso');
2524
+		}
2525
+		$box_label = apply_filters(
2526
+			'FHEE__EE_Admin_Page___publish_post_box__box_label',
2527
+			$box_label,
2528
+			$this->_req_action,
2529
+			$this
2530
+		);
2531
+		add_meta_box(
2532
+			$meta_box_ref,
2533
+			$box_label,
2534
+			[$this, 'editor_overview'],
2535
+			$this->_current_screen->id,
2536
+			'side',
2537
+			'high'
2538
+		);
2539
+	}
2540
+
2541
+
2542
+	public function editor_overview()
2543
+	{
2544
+		// if we have extra content set let's add it in if not make sure its empty
2545
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2546
+			? $this->_template_args['publish_box_extra_content']
2547
+			: '';
2548
+		echo EEH_Template::display_template(
2549
+			EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2550
+			$this->_template_args,
2551
+			true
2552
+		);
2553
+	}
2554
+
2555
+
2556
+	/** end of globally available metaboxes section **/
2557
+
2558
+
2559
+	/**
2560
+	 * Public wrapper for the protected method.  Allows plugins/addons to externally call the
2561
+	 * protected method.
2562
+	 *
2563
+	 * @param string $name
2564
+	 * @param int    $id
2565
+	 * @param bool   $delete
2566
+	 * @param string $save_close_redirect_URL
2567
+	 * @param bool   $both_btns
2568
+	 * @throws EE_Error
2569
+	 * @throws InvalidArgumentException
2570
+	 * @throws InvalidDataTypeException
2571
+	 * @throws InvalidInterfaceException
2572
+	 * @see   $this->_set_publish_post_box_vars for param details
2573
+	 * @since 4.6.0
2574
+	 */
2575
+	public function set_publish_post_box_vars(
2576
+		$name = '',
2577
+		$id = 0,
2578
+		$delete = false,
2579
+		$save_close_redirect_URL = '',
2580
+		$both_btns = true
2581
+	) {
2582
+		$this->_set_publish_post_box_vars(
2583
+			$name,
2584
+			$id,
2585
+			$delete,
2586
+			$save_close_redirect_URL,
2587
+			$both_btns
2588
+		);
2589
+	}
2590
+
2591
+
2592
+	/**
2593
+	 * Sets the _template_args arguments used by the _publish_post_box shortcut
2594
+	 * Note: currently there is no validation for this.  However if you want the delete button, the
2595
+	 * save, and save and close buttons to work properly, then you will want to include a
2596
+	 * values for the name and id arguments.
2597
+	 *
2598
+	 * @param string  $name                       key used for the action ID (i.e. event_id)
2599
+	 * @param int     $id                         id attached to the item published
2600
+	 * @param string  $delete                     page route callback for the delete action
2601
+	 * @param string  $save_close_redirect_URL    custom URL to redirect to after Save & Close has been completed
2602
+	 * @param boolean $both_btns                  whether to display BOTH the "Save & Close" and "Save" buttons or just
2603
+	 *                                            the Save button
2604
+	 * @throws EE_Error
2605
+	 * @throws InvalidArgumentException
2606
+	 * @throws InvalidDataTypeException
2607
+	 * @throws InvalidInterfaceException
2608
+	 * @todo  Add in validation for name/id arguments.
2609
+	 */
2610
+	protected function _set_publish_post_box_vars(
2611
+		$name = '',
2612
+		$id = 0,
2613
+		$delete = '',
2614
+		$save_close_redirect_URL = '',
2615
+		$both_btns = true
2616
+	) {
2617
+		// if Save & Close, use a custom redirect URL or default to the main page?
2618
+		$save_close_redirect_URL = ! empty($save_close_redirect_URL)
2619
+			? $save_close_redirect_URL
2620
+			: $this->_admin_base_url;
2621
+		// create the Save & Close and Save buttons
2622
+		$this->_set_save_buttons($both_btns, [], [], $save_close_redirect_URL);
2623
+		// if we have extra content set let's add it in if not make sure its empty
2624
+		$this->_template_args['publish_box_extra_content'] = isset($this->_template_args['publish_box_extra_content'])
2625
+			? $this->_template_args['publish_box_extra_content']
2626
+			: '';
2627
+		if ($delete && ! empty($id)) {
2628
+			// make sure we have a default if just true is sent.
2629
+			$delete           = ! empty($delete) ? $delete : 'delete';
2630
+			$delete_link_args = [$name => $id];
2631
+			$delete           = $this->get_action_link_or_button(
2632
+				$delete,
2633
+				$delete,
2634
+				$delete_link_args,
2635
+				'submitdelete deletion',
2636
+				'',
2637
+				false
2638
+			);
2639
+		}
2640
+		$this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2641
+		if (! empty($name) && ! empty($id)) {
2642
+			$hidden_field_arr[ $name ] = [
2643
+				'type'  => 'hidden',
2644
+				'value' => $id,
2645
+			];
2646
+			$hf                        = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2647
+		} else {
2648
+			$hf = '';
2649
+		}
2650
+		// add hidden field
2651
+		$this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2652
+			? $hf[ $name ]['field']
2653
+			: $hf;
2654
+	}
2655
+
2656
+
2657
+	/**
2658
+	 * displays an error message to ppl who have javascript disabled
2659
+	 *
2660
+	 * @return void
2661
+	 */
2662
+	private function _display_no_javascript_warning()
2663
+	{
2664
+		?>
2665 2665
         <noscript>
2666 2666
             <div id="no-js-message" class="error">
2667 2667
                 <p style="font-size:1.3em;">
2668 2668
                     <span style="color:red;"><?php esc_html_e('Warning!', 'event_espresso'); ?></span>
2669 2669
                     <?php esc_html_e(
2670
-                        'Javascript is currently turned off for your browser. Javascript must be enabled in order for all of the features on this page to function properly. Please turn your javascript back on.',
2671
-                        'event_espresso'
2672
-                    ); ?>
2670
+						'Javascript is currently turned off for your browser. Javascript must be enabled in order for all of the features on this page to function properly. Please turn your javascript back on.',
2671
+						'event_espresso'
2672
+					); ?>
2673 2673
                 </p>
2674 2674
             </div>
2675 2675
         </noscript>
2676 2676
         <?php
2677
-    }
2678
-
2679
-
2680
-    /**
2681
-     * displays espresso success and/or error notices
2682
-     *
2683
-     * @return void
2684
-     */
2685
-    private function _display_espresso_notices()
2686
-    {
2687
-        $notices = $this->_get_transient(true);
2688
-        echo stripslashes($notices);
2689
-    }
2690
-
2691
-
2692
-    /**
2693
-     * spinny things pacify the masses
2694
-     *
2695
-     * @return void
2696
-     */
2697
-    protected function _add_admin_page_ajax_loading_img()
2698
-    {
2699
-        ?>
2677
+	}
2678
+
2679
+
2680
+	/**
2681
+	 * displays espresso success and/or error notices
2682
+	 *
2683
+	 * @return void
2684
+	 */
2685
+	private function _display_espresso_notices()
2686
+	{
2687
+		$notices = $this->_get_transient(true);
2688
+		echo stripslashes($notices);
2689
+	}
2690
+
2691
+
2692
+	/**
2693
+	 * spinny things pacify the masses
2694
+	 *
2695
+	 * @return void
2696
+	 */
2697
+	protected function _add_admin_page_ajax_loading_img()
2698
+	{
2699
+		?>
2700 2700
         <div id="espresso-ajax-loading" class="ajax-loading-grey">
2701 2701
             <span class="ee-spinner ee-spin"></span><span class="hidden"><?php
2702
-                esc_html_e('loading...', 'event_espresso'); ?></span>
2702
+				esc_html_e('loading...', 'event_espresso'); ?></span>
2703 2703
         </div>
2704 2704
         <?php
2705
-    }
2705
+	}
2706 2706
 
2707 2707
 
2708
-    /**
2709
-     * add admin page overlay for modal boxes
2710
-     *
2711
-     * @return void
2712
-     */
2713
-    protected function _add_admin_page_overlay()
2714
-    {
2715
-        ?>
2708
+	/**
2709
+	 * add admin page overlay for modal boxes
2710
+	 *
2711
+	 * @return void
2712
+	 */
2713
+	protected function _add_admin_page_overlay()
2714
+	{
2715
+		?>
2716 2716
         <div id="espresso-admin-page-overlay-dv" class=""></div>
2717 2717
         <?php
2718
-    }
2719
-
2720
-
2721
-    /**
2722
-     * facade for add_meta_box
2723
-     *
2724
-     * @param string  $action        where the metabox get's displayed
2725
-     * @param string  $title         Title of Metabox (output in metabox header)
2726
-     * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback
2727
-     *                               instead of the one created in here.
2728
-     * @param array   $callback_args an array of args supplied for the metabox
2729
-     * @param string  $column        what metabox column
2730
-     * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2731
-     * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function
2732
-     *                               created but just set our own callback for wp's add_meta_box.
2733
-     * @throws DomainException
2734
-     */
2735
-    public function _add_admin_page_meta_box(
2736
-        $action,
2737
-        $title,
2738
-        $callback,
2739
-        $callback_args,
2740
-        $column = 'normal',
2741
-        $priority = 'high',
2742
-        $create_func = true
2743
-    ) {
2744
-        do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2745
-        // if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2746
-        if (empty($callback_args) && $create_func) {
2747
-            $callback_args = [
2748
-                'template_path' => $this->_template_path,
2749
-                'template_args' => $this->_template_args,
2750
-            ];
2751
-        }
2752
-        // if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2753
-        $call_back_func = $create_func
2754
-            ? function ($post, $metabox) {
2755
-                do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2756
-                echo EEH_Template::display_template(
2757
-                    $metabox['args']['template_path'],
2758
-                    $metabox['args']['template_args'],
2759
-                    true
2760
-                );
2761
-            }
2762
-            : $callback;
2763
-        add_meta_box(
2764
-            str_replace('_', '-', $action) . '-mbox',
2765
-            $title,
2766
-            $call_back_func,
2767
-            $this->_wp_page_slug,
2768
-            $column,
2769
-            $priority,
2770
-            $callback_args
2771
-        );
2772
-    }
2773
-
2774
-
2775
-    /**
2776
-     * generates HTML wrapper for and admin details page that contains metaboxes in columns
2777
-     *
2778
-     * @throws DomainException
2779
-     * @throws EE_Error
2780
-     */
2781
-    public function display_admin_page_with_metabox_columns()
2782
-    {
2783
-        $this->_template_args['post_body_content']  = $this->_template_args['admin_page_content'];
2784
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2785
-            $this->_column_template_path,
2786
-            $this->_template_args,
2787
-            true
2788
-        );
2789
-        // the final wrapper
2790
-        $this->admin_page_wrapper();
2791
-    }
2792
-
2793
-
2794
-    /**
2795
-     * generates  HTML wrapper for an admin details page
2796
-     *
2797
-     * @return void
2798
-     * @throws EE_Error
2799
-     * @throws DomainException
2800
-     */
2801
-    public function display_admin_page_with_sidebar()
2802
-    {
2803
-        $this->_display_admin_page(true);
2804
-    }
2805
-
2806
-
2807
-    /**
2808
-     * generates  HTML wrapper for an admin details page (except no sidebar)
2809
-     *
2810
-     * @return void
2811
-     * @throws EE_Error
2812
-     * @throws DomainException
2813
-     */
2814
-    public function display_admin_page_with_no_sidebar()
2815
-    {
2816
-        $this->_display_admin_page();
2817
-    }
2818
-
2819
-
2820
-    /**
2821
-     * generates HTML wrapper for an EE about admin page (no sidebar)
2822
-     *
2823
-     * @return void
2824
-     * @throws EE_Error
2825
-     * @throws DomainException
2826
-     */
2827
-    public function display_about_admin_page()
2828
-    {
2829
-        $this->_display_admin_page(false, true);
2830
-    }
2831
-
2832
-
2833
-    /**
2834
-     * display_admin_page
2835
-     * contains the code for actually displaying an admin page
2836
-     *
2837
-     * @param boolean $sidebar true with sidebar, false without
2838
-     * @param boolean $about   use the about admin wrapper instead of the default.
2839
-     * @return void
2840
-     * @throws DomainException
2841
-     * @throws EE_Error
2842
-     */
2843
-    private function _display_admin_page($sidebar = false, $about = false)
2844
-    {
2845
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2846
-        // custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2847
-        do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2848
-        // set current wp page slug - looks like: event-espresso_page_event_categories
2849
-        // keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2850
-        $this->_template_args['current_page']              = $this->_wp_page_slug;
2851
-        $this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2852
-            ? 'poststuff'
2853
-            : 'espresso-default-admin';
2854
-        $template_path                                     = $sidebar
2855
-            ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2856
-            : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2857
-        if (defined('DOING_AJAX') && DOING_AJAX) {
2858
-            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2859
-        }
2860
-        $template_path                                     = ! empty($this->_column_template_path)
2861
-            ? $this->_column_template_path : $template_path;
2862
-        $this->_template_args['post_body_content']         = isset($this->_template_args['admin_page_content'])
2863
-            ? $this->_template_args['admin_page_content']
2864
-            : '';
2865
-        $this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content'])
2866
-            ? $this->_template_args['before_admin_page_content']
2867
-            : '';
2868
-        $this->_template_args['after_admin_page_content']  = isset($this->_template_args['after_admin_page_content'])
2869
-            ? $this->_template_args['after_admin_page_content']
2870
-            : '';
2871
-        $this->_template_args['admin_page_content']        = EEH_Template::display_template(
2872
-            $template_path,
2873
-            $this->_template_args,
2874
-            true
2875
-        );
2876
-        // the final template wrapper
2877
-        $this->admin_page_wrapper($about);
2878
-    }
2879
-
2880
-
2881
-    /**
2882
-     * This is used to display caf preview pages.
2883
-     *
2884
-     * @param string $utm_campaign_source what is the key used for google analytics link
2885
-     * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE
2886
-     *                                    = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2887
-     * @return void
2888
-     * @throws DomainException
2889
-     * @throws EE_Error
2890
-     * @throws InvalidArgumentException
2891
-     * @throws InvalidDataTypeException
2892
-     * @throws InvalidInterfaceException
2893
-     * @since 4.3.2
2894
-     */
2895
-    public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2896
-    {
2897
-        // let's generate a default preview action button if there isn't one already present.
2898
-        $this->_labels['buttons']['buy_now']           = esc_html__(
2899
-            'Upgrade to Event Espresso 4 Right Now',
2900
-            'event_espresso'
2901
-        );
2902
-        $buy_now_url                                   = add_query_arg(
2903
-            [
2904
-                'ee_ver'       => 'ee4',
2905
-                'utm_source'   => 'ee4_plugin_admin',
2906
-                'utm_medium'   => 'link',
2907
-                'utm_campaign' => $utm_campaign_source,
2908
-                'utm_content'  => 'buy_now_button',
2909
-            ],
2910
-            'http://eventespresso.com/pricing/'
2911
-        );
2912
-        $this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2913
-            ? $this->get_action_link_or_button(
2914
-                '',
2915
-                'buy_now',
2916
-                [],
2917
-                'button-primary button-large',
2918
-                $buy_now_url,
2919
-                true
2920
-            )
2921
-            : $this->_template_args['preview_action_button'];
2922
-        $this->_template_args['admin_page_content']    = EEH_Template::display_template(
2923
-            EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2924
-            $this->_template_args,
2925
-            true
2926
-        );
2927
-        $this->_display_admin_page($display_sidebar);
2928
-    }
2929
-
2930
-
2931
-    /**
2932
-     * display_admin_list_table_page_with_sidebar
2933
-     * generates HTML wrapper for an admin_page with list_table
2934
-     *
2935
-     * @return void
2936
-     * @throws EE_Error
2937
-     * @throws DomainException
2938
-     */
2939
-    public function display_admin_list_table_page_with_sidebar()
2940
-    {
2941
-        $this->_display_admin_list_table_page(true);
2942
-    }
2943
-
2944
-
2945
-    /**
2946
-     * display_admin_list_table_page_with_no_sidebar
2947
-     * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
2948
-     *
2949
-     * @return void
2950
-     * @throws EE_Error
2951
-     * @throws DomainException
2952
-     */
2953
-    public function display_admin_list_table_page_with_no_sidebar()
2954
-    {
2955
-        $this->_display_admin_list_table_page();
2956
-    }
2957
-
2958
-
2959
-    /**
2960
-     * generates html wrapper for an admin_list_table page
2961
-     *
2962
-     * @param boolean $sidebar whether to display with sidebar or not.
2963
-     * @return void
2964
-     * @throws DomainException
2965
-     * @throws EE_Error
2966
-     */
2967
-    private function _display_admin_list_table_page($sidebar = false)
2968
-    {
2969
-        // setup search attributes
2970
-        $this->_set_search_attributes();
2971
-        $this->_template_args['current_page']     = $this->_wp_page_slug;
2972
-        $template_path                            = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2973
-        $this->_template_args['table_url']        = defined('DOING_AJAX')
2974
-            ? add_query_arg(['noheader' => 'true', 'route' => $this->_req_action], $this->_admin_base_url)
2975
-            : add_query_arg(['route' => $this->_req_action], $this->_admin_base_url);
2976
-        $this->_template_args['list_table']       = $this->_list_table_object;
2977
-        $this->_template_args['current_route']    = $this->_req_action;
2978
-        $this->_template_args['list_table_class'] = get_class($this->_list_table_object);
2979
-        $ajax_sorting_callback                    = $this->_list_table_object->get_ajax_sorting_callback();
2980
-        if (! empty($ajax_sorting_callback)) {
2981
-            $sortable_list_table_form_fields = wp_nonce_field(
2982
-                $ajax_sorting_callback . '_nonce',
2983
-                $ajax_sorting_callback . '_nonce',
2984
-                false,
2985
-                false
2986
-            );
2987
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'
2988
-                                                . $this->page_slug
2989
-                                                . '" />';
2990
-            $sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'
2991
-                                                . $ajax_sorting_callback
2992
-                                                . '" />';
2993
-        } else {
2994
-            $sortable_list_table_form_fields = '';
2995
-        }
2996
-        $this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
2997
-        $hidden_form_fields                                      =
2998
-            isset($this->_template_args['list_table_hidden_fields'])
2999
-                ? $this->_template_args['list_table_hidden_fields']
3000
-                : '';
3001
-        $nonce_ref                                               = $this->_req_action . '_nonce';
3002
-        $hidden_form_fields                                      .= '<input type="hidden" name="'
3003
-                                                                    . $nonce_ref
3004
-                                                                    . '" value="'
3005
-                                                                    . wp_create_nonce($nonce_ref)
3006
-                                                                    . '">';
3007
-        $this->_template_args['list_table_hidden_fields']        = $hidden_form_fields;
3008
-        // display message about search results?
3009
-        $search = $this->request->getRequestParam('s');
3010
-        $this->_template_args['before_list_table'] .= ! empty($search)
3011
-            ? '<p class="ee-search-results">' . sprintf(
3012
-                esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3013
-                trim($search, '%')
3014
-            ) . '</p>'
3015
-            : '';
3016
-        // filter before_list_table template arg
3017
-        $this->_template_args['before_list_table'] = apply_filters(
3018
-            'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
3019
-            $this->_template_args['before_list_table'],
3020
-            $this->page_slug,
3021
-            $this->request->requestParams(),
3022
-            $this->_req_action
3023
-        );
3024
-        // convert to array and filter again
3025
-        // arrays are easier to inject new items in a specific location,
3026
-        // but would not be backwards compatible, so we have to add a new filter
3027
-        $this->_template_args['before_list_table'] = implode(
3028
-            " \n",
3029
-            (array) apply_filters(
3030
-                'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_args_array',
3031
-                (array) $this->_template_args['before_list_table'],
3032
-                $this->page_slug,
3033
-                $this->request->requestParams(),
3034
-                $this->_req_action
3035
-            )
3036
-        );
3037
-        // filter after_list_table template arg
3038
-        $this->_template_args['after_list_table'] = apply_filters(
3039
-            'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
3040
-            $this->_template_args['after_list_table'],
3041
-            $this->page_slug,
3042
-            $this->request->requestParams(),
3043
-            $this->_req_action
3044
-        );
3045
-        // convert to array and filter again
3046
-        // arrays are easier to inject new items in a specific location,
3047
-        // but would not be backwards compatible, so we have to add a new filter
3048
-        $this->_template_args['after_list_table']   = implode(
3049
-            " \n",
3050
-            (array) apply_filters(
3051
-                'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
3052
-                (array) $this->_template_args['after_list_table'],
3053
-                $this->page_slug,
3054
-                $this->request->requestParams(),
3055
-                $this->_req_action
3056
-            )
3057
-        );
3058
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3059
-            $template_path,
3060
-            $this->_template_args,
3061
-            true
3062
-        );
3063
-        // the final template wrapper
3064
-        if ($sidebar) {
3065
-            $this->display_admin_page_with_sidebar();
3066
-        } else {
3067
-            $this->display_admin_page_with_no_sidebar();
3068
-        }
3069
-    }
3070
-
3071
-
3072
-    /**
3073
-     * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the
3074
-     * html string for the legend.
3075
-     * $items are expected in an array in the following format:
3076
-     * $legend_items = array(
3077
-     *        'item_id' => array(
3078
-     *            'icon' => 'http://url_to_icon_being_described.png',
3079
-     *            'desc' => esc_html__('localized description of item');
3080
-     *        )
3081
-     * );
3082
-     *
3083
-     * @param array $items see above for format of array
3084
-     * @return string html string of legend
3085
-     * @throws DomainException
3086
-     */
3087
-    protected function _display_legend($items)
3088
-    {
3089
-        $this->_template_args['items'] = apply_filters(
3090
-            'FHEE__EE_Admin_Page___display_legend__items',
3091
-            (array) $items,
3092
-            $this
3093
-        );
3094
-        return EEH_Template::display_template(
3095
-            EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3096
-            $this->_template_args,
3097
-            true
3098
-        );
3099
-    }
3100
-
3101
-
3102
-    /**
3103
-     * This is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
3104
-     * The returned json object is created from an array in the following format:
3105
-     * array(
3106
-     *  'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
3107
-     *  'success' => FALSE, //(default FALSE) - contains any special success message.
3108
-     *  'notices' => '', // - contains any EE_Error formatted notices
3109
-     *  'content' => 'string can be html', //this is a string of formatted content (can be html)
3110
-     *  'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
3111
-     *  We're also going to include the template args with every package (so js can pick out any specific template args
3112
-     *  that might be included in here)
3113
-     * )
3114
-     * The json object is populated by whatever is set in the $_template_args property.
3115
-     *
3116
-     * @param bool  $sticky_notices    Used to indicate whether you want to ensure notices are added to a transient
3117
-     *                                 instead of displayed.
3118
-     * @param array $notices_arguments Use this to pass any additional args on to the _process_notices.
3119
-     * @return void
3120
-     * @throws EE_Error
3121
-     */
3122
-    protected function _return_json($sticky_notices = false, $notices_arguments = [])
3123
-    {
3124
-        // make sure any EE_Error notices have been handled.
3125
-        $this->_process_notices($notices_arguments, true, $sticky_notices);
3126
-        $data = isset($this->_template_args['data']) ? $this->_template_args['data'] : [];
3127
-        unset($this->_template_args['data']);
3128
-        $json = [
3129
-            'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
3130
-            'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
3131
-            'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
3132
-            'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
3133
-            'notices'   => EE_Error::get_notices(),
3134
-            'content'   => isset($this->_template_args['admin_page_content'])
3135
-                ? $this->_template_args['admin_page_content'] : '',
3136
-            'data'      => array_merge($data, ['template_args' => $this->_template_args]),
3137
-            'isEEajax'  => true
3138
-            // special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
3139
-        ];
3140
-        // make sure there are no php errors or headers_sent.  Then we can set correct json header.
3141
-        if (null === error_get_last() || ! headers_sent()) {
3142
-            header('Content-Type: application/json; charset=UTF-8');
3143
-        }
3144
-        echo wp_json_encode($json);
3145
-        exit();
3146
-    }
3147
-
3148
-
3149
-    /**
3150
-     * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
3151
-     *
3152
-     * @return void
3153
-     * @throws EE_Error
3154
-     */
3155
-    public function return_json()
3156
-    {
3157
-        if (defined('DOING_AJAX') && DOING_AJAX) {
3158
-            $this->_return_json();
3159
-        } else {
3160
-            throw new EE_Error(
3161
-                sprintf(
3162
-                    esc_html__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'),
3163
-                    __FUNCTION__
3164
-                )
3165
-            );
3166
-        }
3167
-    }
3168
-
3169
-
3170
-    /**
3171
-     * This provides a way for child hook classes to send along themselves by reference so methods/properties within
3172
-     * them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
3173
-     *
3174
-     * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
3175
-     */
3176
-    public function set_hook_object(EE_Admin_Hooks $hook_obj)
3177
-    {
3178
-        $this->_hook_obj = $hook_obj;
3179
-    }
3180
-
3181
-
3182
-    /**
3183
-     *        generates  HTML wrapper with Tabbed nav for an admin page
3184
-     *
3185
-     * @param boolean $about whether to use the special about page wrapper or default.
3186
-     * @return void
3187
-     * @throws DomainException
3188
-     * @throws EE_Error
3189
-     */
3190
-    public function admin_page_wrapper($about = false)
3191
-    {
3192
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3193
-        $this->_nav_tabs                                   = $this->_get_main_nav_tabs();
3194
-        $this->_template_args['nav_tabs']                  = $this->_nav_tabs;
3195
-        $this->_template_args['admin_page_title']          = $this->_admin_page_title;
3196
-        $this->_template_args['before_admin_page_content'] = apply_filters(
3197
-            "FHEE_before_admin_page_content{$this->_current_page}{$this->_current_view}",
3198
-            isset($this->_template_args['before_admin_page_content'])
3199
-                ? $this->_template_args['before_admin_page_content']
3200
-                : ''
3201
-        );
3202
-        $this->_template_args['after_admin_page_content']  = apply_filters(
3203
-            "FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3204
-            isset($this->_template_args['after_admin_page_content'])
3205
-                ? $this->_template_args['after_admin_page_content']
3206
-                : ''
3207
-        );
3208
-        $this->_template_args['after_admin_page_content']  .= $this->_set_help_popup_content();
3209
-        // load settings page wrapper template
3210
-        $template_path = ! defined('DOING_AJAX')
3211
-            ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
3212
-            : EE_ADMIN_TEMPLATE
3213
-              . 'admin_wrapper_ajax.template.php';
3214
-        // about page?
3215
-        $template_path = $about
3216
-            ? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php'
3217
-            : $template_path;
3218
-        if (defined('DOING_AJAX')) {
3219
-            $this->_template_args['admin_page_content'] = EEH_Template::display_template(
3220
-                $template_path,
3221
-                $this->_template_args,
3222
-                true
3223
-            );
3224
-            $this->_return_json();
3225
-        } else {
3226
-            EEH_Template::display_template($template_path, $this->_template_args);
3227
-        }
3228
-    }
3229
-
3230
-
3231
-    /**
3232
-     * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
3233
-     *
3234
-     * @return string html
3235
-     * @throws EE_Error
3236
-     */
3237
-    protected function _get_main_nav_tabs()
3238
-    {
3239
-        // let's generate the html using the EEH_Tabbed_Content helper.
3240
-        // We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute
3241
-        // (rather than setting in the page_routes array)
3242
-        return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
3243
-    }
3244
-
3245
-
3246
-    /**
3247
-     *        sort nav tabs
3248
-     *
3249
-     * @param $a
3250
-     * @param $b
3251
-     * @return int
3252
-     */
3253
-    private function _sort_nav_tabs($a, $b)
3254
-    {
3255
-        if ($a['order'] === $b['order']) {
3256
-            return 0;
3257
-        }
3258
-        return ($a['order'] < $b['order']) ? -1 : 1;
3259
-    }
3260
-
3261
-
3262
-    /**
3263
-     *    generates HTML for the forms used on admin pages
3264
-     *
3265
-     * @param array  $input_vars   - array of input field details
3266
-     * @param string $generator    (options are 'string' or 'array', basically use this to indicate which generator to
3267
-     *                             use)
3268
-     * @param bool   $id
3269
-     * @return string
3270
-     * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
3271
-     * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
3272
-     */
3273
-    protected function _generate_admin_form_fields($input_vars = [], $generator = 'string', $id = false)
3274
-    {
3275
-        $content = $generator === 'string'
3276
-            ? EEH_Form_Fields::get_form_fields($input_vars, $id)
3277
-            : EEH_Form_Fields::get_form_fields_array($input_vars);
3278
-        return $content;
3279
-    }
3280
-
3281
-
3282
-    /**
3283
-     * generates the "Save" and "Save & Close" buttons for edit forms
3284
-     *
3285
-     * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save &
3286
-     *                                   Close" button.
3287
-     * @param array            $text     if included, generator will use the given text for the buttons ( array([0] =>
3288
-     *                                   'Save', [1] => 'save & close')
3289
-     * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e.
3290
-     *                                   via the "name" value in the button).  We can also use this to just dump
3291
-     *                                   default actions by submitting some other value.
3292
-     * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it
3293
-     *                                   will use the $referrer string. IF null, then we don't do ANYTHING on save and
3294
-     *                                   close (normal form handling).
3295
-     */
3296
-    protected function _set_save_buttons($both = true, $text = [], $actions = [], $referrer = null)
3297
-    {
3298
-        // make sure $text and $actions are in an array
3299
-        $text          = (array) $text;
3300
-        $actions       = (array) $actions;
3301
-        $referrer_url  = empty($referrer)
3302
-            ? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3303
-              . $_SERVER['REQUEST_URI']
3304
-              . '" />'
3305
-            : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3306
-              . $referrer
3307
-              . '" />';
3308
-        $button_text   = ! empty($text)
3309
-            ? $text
3310
-            : [
3311
-                esc_html__('Save', 'event_espresso'),
3312
-                esc_html__('Save and Close', 'event_espresso'),
3313
-            ];
3314
-        $default_names = ['save', 'save_and_close'];
3315
-        // add in a hidden index for the current page (so save and close redirects properly)
3316
-        $this->_template_args['save_buttons'] = $referrer_url;
3317
-        foreach ($button_text as $key => $button) {
3318
-            $ref                                  = $default_names[ $key ];
3319
-            $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3320
-                                                     . $ref
3321
-                                                     . '" value="'
3322
-                                                     . $button
3323
-                                                     . '" name="'
3324
-                                                     . (! empty($actions) ? $actions[ $key ] : $ref)
3325
-                                                     . '" id="'
3326
-                                                     . $this->_current_view . '_' . $ref
3327
-                                                     . '" />';
3328
-            if (! $both) {
3329
-                break;
3330
-            }
3331
-        }
3332
-    }
3333
-
3334
-
3335
-    /**
3336
-     * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
3337
-     *
3338
-     * @param string $route
3339
-     * @param array  $additional_hidden_fields
3340
-     * @see   $this->_set_add_edit_form_tags() for details on params
3341
-     * @since 4.6.0
3342
-     */
3343
-    public function set_add_edit_form_tags($route = '', $additional_hidden_fields = [])
3344
-    {
3345
-        $this->_set_add_edit_form_tags($route, $additional_hidden_fields);
3346
-    }
3347
-
3348
-
3349
-    /**
3350
-     * set form open and close tags on add/edit pages.
3351
-     *
3352
-     * @param string $route                    the route you want the form to direct to
3353
-     * @param array  $additional_hidden_fields any additional hidden fields required in the form header
3354
-     * @return void
3355
-     */
3356
-    protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = [])
3357
-    {
3358
-        if (empty($route)) {
3359
-            $user_msg = esc_html__(
3360
-                'An error occurred. No action was set for this page\'s form.',
3361
-                'event_espresso'
3362
-            );
3363
-            $dev_msg  = $user_msg . "\n"
3364
-                        . sprintf(
3365
-                            esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3366
-                            __FUNCTION__,
3367
-                            __CLASS__
3368
-                        );
3369
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3370
-        }
3371
-        // open form
3372
-        $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
3373
-                                                             . $this->_admin_base_url
3374
-                                                             . '" id="'
3375
-                                                             . $route
3376
-                                                             . '_event_form" >';
3377
-        // add nonce
3378
-        $nonce                                             =
3379
-            wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3380
-        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3381
-        // add REQUIRED form action
3382
-        $hidden_fields = [
3383
-            'action' => ['type' => 'hidden', 'value' => $route],
3384
-        ];
3385
-        // merge arrays
3386
-        $hidden_fields = is_array($additional_hidden_fields)
3387
-            ? array_merge($hidden_fields, $additional_hidden_fields)
3388
-            : $hidden_fields;
3389
-        // generate form fields
3390
-        $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3391
-        // add fields to form
3392
-        foreach ((array) $form_fields as $field_name => $form_field) {
3393
-            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3394
-        }
3395
-        // close form
3396
-        $this->_template_args['after_admin_page_content'] = '</form>';
3397
-    }
3398
-
3399
-
3400
-    /**
3401
-     * Public Wrapper for _redirect_after_action() method since its
3402
-     * discovered it would be useful for external code to have access.
3403
-     *
3404
-     * @param bool   $success
3405
-     * @param string $what
3406
-     * @param string $action_desc
3407
-     * @param array  $query_args
3408
-     * @param bool   $override_overwrite
3409
-     * @throws EE_Error
3410
-     * @see   EE_Admin_Page::_redirect_after_action() for params.
3411
-     * @since 4.5.0
3412
-     */
3413
-    public function redirect_after_action(
3414
-        $success = false,
3415
-        $what = 'item',
3416
-        $action_desc = 'processed',
3417
-        $query_args = [],
3418
-        $override_overwrite = false
3419
-    ) {
3420
-        $this->_redirect_after_action(
3421
-            $success,
3422
-            $what,
3423
-            $action_desc,
3424
-            $query_args,
3425
-            $override_overwrite
3426
-        );
3427
-    }
3428
-
3429
-
3430
-    /**
3431
-     * Helper method for merging existing request data with the returned redirect url.
3432
-     *
3433
-     * This is typically used for redirects after an action so that if the original view was a filtered view those
3434
-     * filters are still applied.
3435
-     *
3436
-     * @param array $new_route_data
3437
-     * @return array
3438
-     */
3439
-    protected function mergeExistingRequestParamsWithRedirectArgs(array $new_route_data)
3440
-    {
3441
-        foreach ($this->request->requestParams() as $ref => $value) {
3442
-            // unset nonces
3443
-            if (strpos($ref, 'nonce') !== false) {
3444
-                $this->request->unSetRequestParam($ref);
3445
-                continue;
3446
-            }
3447
-            // urlencode values.
3448
-            $value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
3449
-            $this->request->setRequestParam($ref, $value);
3450
-        }
3451
-        return array_merge($this->request->requestParams(), $new_route_data);
3452
-    }
3453
-
3454
-
3455
-    /**
3456
-     *    _redirect_after_action
3457
-     *
3458
-     * @param int    $success            - whether success was for two or more records, or just one, or none
3459
-     * @param string $what               - what the action was performed on
3460
-     * @param string $action_desc        - what was done ie: updated, deleted, etc
3461
-     * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin
3462
-     *                                   action is completed
3463
-     * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to
3464
-     *                                   override this so that they show.
3465
-     * @return void
3466
-     * @throws EE_Error
3467
-     */
3468
-    protected function _redirect_after_action(
3469
-        $success = 0,
3470
-        $what = 'item',
3471
-        $action_desc = 'processed',
3472
-        $query_args = [],
3473
-        $override_overwrite = false
3474
-    ) {
3475
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3476
-        // class name for actions/filters.
3477
-        $classname = get_class($this);
3478
-        // set redirect url.
3479
-        // Note if there is a "page" index in the $query_args then we go with vanilla admin.php route,
3480
-        // otherwise we go with whatever is set as the _admin_base_url
3481
-        $redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3482
-        $notices      = EE_Error::get_notices(false);
3483
-        // overwrite default success messages //BUT ONLY if overwrite not overridden
3484
-        if (! $override_overwrite || ! empty($notices['errors'])) {
3485
-            EE_Error::overwrite_success();
3486
-        }
3487
-        if (! empty($what) && ! empty($action_desc) && empty($notices['errors'])) {
3488
-            // how many records affected ? more than one record ? or just one ?
3489
-            if ($success > 1) {
3490
-                // set plural msg
3491
-                EE_Error::add_success(
3492
-                    sprintf(
3493
-                        esc_html__('The "%s" have been successfully %s.', 'event_espresso'),
3494
-                        $what,
3495
-                        $action_desc
3496
-                    ),
3497
-                    __FILE__,
3498
-                    __FUNCTION__,
3499
-                    __LINE__
3500
-                );
3501
-            } elseif ($success === 1) {
3502
-                // set singular msg
3503
-                EE_Error::add_success(
3504
-                    sprintf(
3505
-                        esc_html__('The "%s" has been successfully %s.', 'event_espresso'),
3506
-                        $what,
3507
-                        $action_desc
3508
-                    ),
3509
-                    __FILE__,
3510
-                    __FUNCTION__,
3511
-                    __LINE__
3512
-                );
3513
-            }
3514
-        }
3515
-        // check that $query_args isn't something crazy
3516
-        if (! is_array($query_args)) {
3517
-            $query_args = [];
3518
-        }
3519
-        /**
3520
-         * Allow injecting actions before the query_args are modified for possible different
3521
-         * redirections on save and close actions
3522
-         *
3523
-         * @param array $query_args       The original query_args array coming into the
3524
-         *                                method.
3525
-         * @since 4.2.0
3526
-         */
3527
-        do_action(
3528
-            "AHEE__{$classname}___redirect_after_action__before_redirect_modification_{$this->_req_action}",
3529
-            $query_args
3530
-        );
3531
-        // calculate where we're going (if we have a "save and close" button pushed)
3532
-
3533
-        if (
3534
-            $this->request->requestParamIsSet('save_and_close')
3535
-            && $this->request->requestParamIsSet('save_and_close_referrer')
3536
-        ) {
3537
-            // even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
3538
-            $parsed_url = parse_url($this->request->getRequestParam('save_and_close_referrer', '', 'url'));
3539
-            // regenerate query args array from referrer URL
3540
-            parse_str($parsed_url['query'], $query_args);
3541
-            // correct page and action will be in the query args now
3542
-            $redirect_url = admin_url('admin.php');
3543
-        }
3544
-        // merge any default query_args set in _default_route_query_args property
3545
-        if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3546
-            $args_to_merge = [];
3547
-            foreach ($this->_default_route_query_args as $query_param => $query_value) {
3548
-                // is there a wp_referer array in our _default_route_query_args property?
3549
-                if ($query_param === 'wp_referer') {
3550
-                    $query_value = (array) $query_value;
3551
-                    foreach ($query_value as $reference => $value) {
3552
-                        if (strpos($reference, 'nonce') !== false) {
3553
-                            continue;
3554
-                        }
3555
-                        // finally we will override any arguments in the referer with
3556
-                        // what might be set on the _default_route_query_args array.
3557
-                        if (isset($this->_default_route_query_args[ $reference ])) {
3558
-                            $args_to_merge[ $reference ] = urlencode($this->_default_route_query_args[ $reference ]);
3559
-                        } else {
3560
-                            $args_to_merge[ $reference ] = urlencode($value);
3561
-                        }
3562
-                    }
3563
-                    continue;
3564
-                }
3565
-                $args_to_merge[ $query_param ] = $query_value;
3566
-            }
3567
-            // now let's merge these arguments but override with what was specifically sent in to the
3568
-            // redirect.
3569
-            $query_args = array_merge($args_to_merge, $query_args);
3570
-        }
3571
-        $this->_process_notices($query_args);
3572
-        // generate redirect url
3573
-        // if redirecting to anything other than the main page, add a nonce
3574
-        if (isset($query_args['action'])) {
3575
-            // manually generate wp_nonce and merge that with the query vars
3576
-            // becuz the wp_nonce_url function wrecks havoc on some vars
3577
-            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3578
-        }
3579
-        // we're adding some hooks and filters in here for processing any things just before redirects
3580
-        // (example: an admin page has done an insert or update and we want to run something after that).
3581
-        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3582
-        $redirect_url = apply_filters(
3583
-            'FHEE_redirect_' . $classname . $this->_req_action,
3584
-            self::add_query_args_and_nonce($query_args, $redirect_url),
3585
-            $query_args
3586
-        );
3587
-        // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3588
-        if (defined('DOING_AJAX')) {
3589
-            $default_data                    = [
3590
-                'close'        => true,
3591
-                'redirect_url' => $redirect_url,
3592
-                'where'        => 'main',
3593
-                'what'         => 'append',
3594
-            ];
3595
-            $this->_template_args['success'] = $success;
3596
-            $this->_template_args['data']    = ! empty($this->_template_args['data']) ? array_merge(
3597
-                $default_data,
3598
-                $this->_template_args['data']
3599
-            ) : $default_data;
3600
-            $this->_return_json();
3601
-        }
3602
-        wp_safe_redirect($redirect_url);
3603
-        exit();
3604
-    }
3605
-
3606
-
3607
-    /**
3608
-     * process any notices before redirecting (or returning ajax request)
3609
-     * This method sets the $this->_template_args['notices'] attribute;
3610
-     *
3611
-     * @param array $query_args         any query args that need to be used for notice transient ('action')
3612
-     * @param bool  $skip_route_verify  This is typically used when we are processing notices REALLY early and
3613
-     *                                  page_routes haven't been defined yet.
3614
-     * @param bool  $sticky_notices     This is used to flag that regardless of whether this is doing_ajax or not, we
3615
-     *                                  still save a transient for the notice.
3616
-     * @return void
3617
-     * @throws EE_Error
3618
-     */
3619
-    protected function _process_notices($query_args = [], $skip_route_verify = false, $sticky_notices = true)
3620
-    {
3621
-        // first let's set individual error properties if doing_ajax and the properties aren't already set.
3622
-        if (defined('DOING_AJAX') && DOING_AJAX) {
3623
-            $notices = EE_Error::get_notices(false);
3624
-            if (empty($this->_template_args['success'])) {
3625
-                $this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
3626
-            }
3627
-            if (empty($this->_template_args['errors'])) {
3628
-                $this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
3629
-            }
3630
-            if (empty($this->_template_args['attention'])) {
3631
-                $this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
3632
-            }
3633
-        }
3634
-        $this->_template_args['notices'] = EE_Error::get_notices();
3635
-        // IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3636
-        if (! defined('DOING_AJAX') || $sticky_notices) {
3637
-            $route = isset($query_args['action']) ? $query_args['action'] : 'default';
3638
-            $this->_add_transient(
3639
-                $route,
3640
-                $this->_template_args['notices'],
3641
-                true,
3642
-                $skip_route_verify
3643
-            );
3644
-        }
3645
-    }
3646
-
3647
-
3648
-    /**
3649
-     * get_action_link_or_button
3650
-     * returns the button html for adding, editing, or deleting an item (depending on given type)
3651
-     *
3652
-     * @param string $action        use this to indicate which action the url is generated with.
3653
-     * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key)
3654
-     *                              property.
3655
-     * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
3656
-     * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
3657
-     * @param string $base_url      If this is not provided
3658
-     *                              the _admin_base_url will be used as the default for the button base_url.
3659
-     *                              Otherwise this value will be used.
3660
-     * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
3661
-     * @return string
3662
-     * @throws InvalidArgumentException
3663
-     * @throws InvalidInterfaceException
3664
-     * @throws InvalidDataTypeException
3665
-     * @throws EE_Error
3666
-     */
3667
-    public function get_action_link_or_button(
3668
-        $action,
3669
-        $type = 'add',
3670
-        $extra_request = [],
3671
-        $class = 'button-primary',
3672
-        $base_url = '',
3673
-        $exclude_nonce = false
3674
-    ) {
3675
-        // first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3676
-        if (empty($base_url) && ! isset($this->_page_routes[ $action ])) {
3677
-            throw new EE_Error(
3678
-                sprintf(
3679
-                    esc_html__(
3680
-                        'There is no page route for given action for the button.  This action was given: %s',
3681
-                        'event_espresso'
3682
-                    ),
3683
-                    $action
3684
-                )
3685
-            );
3686
-        }
3687
-        if (! isset($this->_labels['buttons'][ $type ])) {
3688
-            throw new EE_Error(
3689
-                sprintf(
3690
-                    __(
3691
-                        'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
3692
-                        'event_espresso'
3693
-                    ),
3694
-                    $type
3695
-                )
3696
-            );
3697
-        }
3698
-        // finally check user access for this button.
3699
-        $has_access = $this->check_user_access($action, true);
3700
-        if (! $has_access) {
3701
-            return '';
3702
-        }
3703
-        $_base_url  = ! $base_url ? $this->_admin_base_url : $base_url;
3704
-        $query_args = [
3705
-            'action' => $action,
3706
-        ];
3707
-        // merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3708
-        if (! empty($extra_request)) {
3709
-            $query_args = array_merge($extra_request, $query_args);
3710
-        }
3711
-        $url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3712
-        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][ $type ], $class);
3713
-    }
3714
-
3715
-
3716
-    /**
3717
-     * _per_page_screen_option
3718
-     * Utility function for adding in a per_page_option in the screen_options_dropdown.
3719
-     *
3720
-     * @return void
3721
-     * @throws InvalidArgumentException
3722
-     * @throws InvalidInterfaceException
3723
-     * @throws InvalidDataTypeException
3724
-     */
3725
-    protected function _per_page_screen_option()
3726
-    {
3727
-        $option = 'per_page';
3728
-        $args   = [
3729
-            'label'   => apply_filters(
3730
-                'FHEE__EE_Admin_Page___per_page_screen_options___label',
3731
-                $this->_admin_page_title,
3732
-                $this
3733
-            ),
3734
-            'default' => (int) apply_filters(
3735
-                'FHEE__EE_Admin_Page___per_page_screen_options__default',
3736
-                20
3737
-            ),
3738
-            'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3739
-        ];
3740
-        // ONLY add the screen option if the user has access to it.
3741
-        if ($this->check_user_access($this->_current_view, true)) {
3742
-            add_screen_option($option, $args);
3743
-        }
3744
-    }
3745
-
3746
-
3747
-    /**
3748
-     * set_per_page_screen_option
3749
-     * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3750
-     * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than
3751
-     * admin_menu.
3752
-     *
3753
-     * @return void
3754
-     */
3755
-    private function _set_per_page_screen_options()
3756
-    {
3757
-        if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3758
-            check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3759
-            if (! $user = wp_get_current_user()) {
3760
-                return;
3761
-            }
3762
-            $option = $_POST['wp_screen_options']['option'];
3763
-            $value  = $_POST['wp_screen_options']['value'];
3764
-            if ($option != sanitize_key($option)) {
3765
-                return;
3766
-            }
3767
-            $map_option = $option;
3768
-            $option     = str_replace('-', '_', $option);
3769
-            switch ($map_option) {
3770
-                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3771
-                    $value     = (int) $value;
3772
-                    $max_value = apply_filters(
3773
-                        'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
3774
-                        999,
3775
-                        $this->_current_page,
3776
-                        $this->_current_view
3777
-                    );
3778
-                    if ($value < 1) {
3779
-                        return;
3780
-                    }
3781
-                    $value = min($value, $max_value);
3782
-                    break;
3783
-                default:
3784
-                    $value = apply_filters(
3785
-                        'FHEE__EE_Admin_Page___set_per_page_screen_options__value',
3786
-                        false,
3787
-                        $option,
3788
-                        $value
3789
-                    );
3790
-                    if (false === $value) {
3791
-                        return;
3792
-                    }
3793
-                    break;
3794
-            }
3795
-            update_user_meta($user->ID, $option, $value);
3796
-            wp_safe_redirect(remove_query_arg(['pagenum', 'apage', 'paged'], wp_get_referer()));
3797
-            exit;
3798
-        }
3799
-    }
3800
-
3801
-
3802
-    /**
3803
-     * This just allows for setting the $_template_args property if it needs to be set outside the object
3804
-     *
3805
-     * @param array $data array that will be assigned to template args.
3806
-     */
3807
-    public function set_template_args($data)
3808
-    {
3809
-        $this->_template_args = array_merge($this->_template_args, (array) $data);
3810
-    }
3811
-
3812
-
3813
-    /**
3814
-     * This makes available the WP transient system for temporarily moving data between routes
3815
-     *
3816
-     * @param string $route             the route that should receive the transient
3817
-     * @param array  $data              the data that gets sent
3818
-     * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a
3819
-     *                                  normal route transient.
3820
-     * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used
3821
-     *                                  when we are adding a transient before page_routes have been defined.
3822
-     * @return void
3823
-     * @throws EE_Error
3824
-     */
3825
-    protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3826
-    {
3827
-        $user_id = get_current_user_id();
3828
-        if (! $skip_route_verify) {
3829
-            $this->_verify_route($route);
3830
-        }
3831
-        // now let's set the string for what kind of transient we're setting
3832
-        $transient = $notices
3833
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3834
-            : 'rte_tx_' . $route . '_' . $user_id;
3835
-        $data      = $notices ? ['notices' => $data] : $data;
3836
-        // is there already a transient for this route?  If there is then let's ADD to that transient
3837
-        $existing = is_multisite() && is_network_admin()
3838
-            ? get_site_transient($transient)
3839
-            : get_transient($transient);
3840
-        if ($existing) {
3841
-            $data = array_merge((array) $data, (array) $existing);
3842
-        }
3843
-        if (is_multisite() && is_network_admin()) {
3844
-            set_site_transient($transient, $data, 8);
3845
-        } else {
3846
-            set_transient($transient, $data, 8);
3847
-        }
3848
-    }
3849
-
3850
-
3851
-    /**
3852
-     * this retrieves the temporary transient that has been set for moving data between routes.
3853
-     *
3854
-     * @param bool   $notices true we get notices transient. False we just return normal route transient
3855
-     * @param string $route
3856
-     * @return mixed data
3857
-     */
3858
-    protected function _get_transient($notices = false, $route = '')
3859
-    {
3860
-        $user_id   = get_current_user_id();
3861
-        $route     = ! $route ? $this->_req_action : $route;
3862
-        $transient = $notices
3863
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3864
-            : 'rte_tx_' . $route . '_' . $user_id;
3865
-        $data      = is_multisite() && is_network_admin()
3866
-            ? get_site_transient($transient)
3867
-            : get_transient($transient);
3868
-        // delete transient after retrieval (just in case it hasn't expired);
3869
-        if (is_multisite() && is_network_admin()) {
3870
-            delete_site_transient($transient);
3871
-        } else {
3872
-            delete_transient($transient);
3873
-        }
3874
-        return $notices && isset($data['notices']) ? $data['notices'] : $data;
3875
-    }
3876
-
3877
-
3878
-    /**
3879
-     * The purpose of this method is just to run garbage collection on any EE transients that might have expired but
3880
-     * would not be called later. This will be assigned to run on a specific EE Admin page. (place the method in the
3881
-     * default route callback on the EE_Admin page you want it run.)
3882
-     *
3883
-     * @return void
3884
-     */
3885
-    protected function _transient_garbage_collection()
3886
-    {
3887
-        global $wpdb;
3888
-        // retrieve all existing transients
3889
-        $query =
3890
-            "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3891
-        if ($results = $wpdb->get_results($query)) {
3892
-            foreach ($results as $result) {
3893
-                $transient = str_replace('_transient_', '', $result->option_name);
3894
-                get_transient($transient);
3895
-                if (is_multisite() && is_network_admin()) {
3896
-                    get_site_transient($transient);
3897
-                }
3898
-            }
3899
-        }
3900
-    }
3901
-
3902
-
3903
-    /**
3904
-     * get_view
3905
-     *
3906
-     * @return string content of _view property
3907
-     */
3908
-    public function get_view()
3909
-    {
3910
-        return $this->_view;
3911
-    }
3912
-
3913
-
3914
-    /**
3915
-     * getter for the protected $_views property
3916
-     *
3917
-     * @return array
3918
-     */
3919
-    public function get_views()
3920
-    {
3921
-        return $this->_views;
3922
-    }
3923
-
3924
-
3925
-    /**
3926
-     * get_current_page
3927
-     *
3928
-     * @return string _current_page property value
3929
-     */
3930
-    public function get_current_page()
3931
-    {
3932
-        return $this->_current_page;
3933
-    }
3934
-
3935
-
3936
-    /**
3937
-     * get_current_view
3938
-     *
3939
-     * @return string _current_view property value
3940
-     */
3941
-    public function get_current_view()
3942
-    {
3943
-        return $this->_current_view;
3944
-    }
3945
-
3946
-
3947
-    /**
3948
-     * get_current_screen
3949
-     *
3950
-     * @return object The current WP_Screen object
3951
-     */
3952
-    public function get_current_screen()
3953
-    {
3954
-        return $this->_current_screen;
3955
-    }
3956
-
3957
-
3958
-    /**
3959
-     * get_current_page_view_url
3960
-     *
3961
-     * @return string This returns the url for the current_page_view.
3962
-     */
3963
-    public function get_current_page_view_url()
3964
-    {
3965
-        return $this->_current_page_view_url;
3966
-    }
3967
-
3968
-
3969
-    /**
3970
-     * just returns the _req_data property
3971
-     *
3972
-     * @return array
3973
-     */
3974
-    public function get_request_data()
3975
-    {
3976
-        return $this->request->requestParams();
3977
-    }
3978
-
3979
-
3980
-    /**
3981
-     * returns the _req_data protected property
3982
-     *
3983
-     * @return string
3984
-     */
3985
-    public function get_req_action()
3986
-    {
3987
-        return $this->_req_action;
3988
-    }
3989
-
3990
-
3991
-    /**
3992
-     * @return bool  value of $_is_caf property
3993
-     */
3994
-    public function is_caf()
3995
-    {
3996
-        return $this->_is_caf;
3997
-    }
3998
-
3999
-
4000
-    /**
4001
-     * @return mixed
4002
-     */
4003
-    public function default_espresso_metaboxes()
4004
-    {
4005
-        return $this->_default_espresso_metaboxes;
4006
-    }
4007
-
4008
-
4009
-    /**
4010
-     * @return mixed
4011
-     */
4012
-    public function admin_base_url()
4013
-    {
4014
-        return $this->_admin_base_url;
4015
-    }
4016
-
4017
-
4018
-    /**
4019
-     * @return mixed
4020
-     */
4021
-    public function wp_page_slug()
4022
-    {
4023
-        return $this->_wp_page_slug;
4024
-    }
4025
-
4026
-
4027
-    /**
4028
-     * updates  espresso configuration settings
4029
-     *
4030
-     * @param string                   $tab
4031
-     * @param EE_Config_Base|EE_Config $config
4032
-     * @param string                   $file file where error occurred
4033
-     * @param string                   $func function  where error occurred
4034
-     * @param string                   $line line no where error occurred
4035
-     * @return boolean
4036
-     */
4037
-    protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
4038
-    {
4039
-        // remove any options that are NOT going to be saved with the config settings.
4040
-        if (isset($config->core->ee_ueip_optin)) {
4041
-            // TODO: remove the following two lines and make sure values are migrated from 3.1
4042
-            update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
4043
-            update_option('ee_ueip_has_notified', true);
4044
-        }
4045
-        // and save it (note we're also doing the network save here)
4046
-        $net_saved    = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
4047
-        $config_saved = EE_Config::instance()->update_espresso_config(false, false);
4048
-        if ($config_saved && $net_saved) {
4049
-            EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
4050
-            return true;
4051
-        }
4052
-        EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
4053
-        return false;
4054
-    }
4055
-
4056
-
4057
-    /**
4058
-     * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
4059
-     *
4060
-     * @return array
4061
-     */
4062
-    public function get_yes_no_values()
4063
-    {
4064
-        return $this->_yes_no_values;
4065
-    }
4066
-
4067
-
4068
-    protected function _get_dir()
4069
-    {
4070
-        $reflector = new ReflectionClass(get_class($this));
4071
-        return dirname($reflector->getFileName());
4072
-    }
4073
-
4074
-
4075
-    /**
4076
-     * A helper for getting a "next link".
4077
-     *
4078
-     * @param string $url   The url to link to
4079
-     * @param string $class The class to use.
4080
-     * @return string
4081
-     */
4082
-    protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4083
-    {
4084
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4085
-    }
4086
-
4087
-
4088
-    /**
4089
-     * A helper for getting a "previous link".
4090
-     *
4091
-     * @param string $url   The url to link to
4092
-     * @param string $class The class to use.
4093
-     * @return string
4094
-     */
4095
-    protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4096
-    {
4097
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4098
-    }
4099
-
4100
-
4101
-
4102
-
4103
-
4104
-
4105
-
4106
-    // below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
4107
-
4108
-
4109
-    /**
4110
-     * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller
4111
-     * knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the
4112
-     * _req_data array.
4113
-     *
4114
-     * @return bool success/fail
4115
-     * @throws EE_Error
4116
-     * @throws InvalidArgumentException
4117
-     * @throws ReflectionException
4118
-     * @throws InvalidDataTypeException
4119
-     * @throws InvalidInterfaceException
4120
-     */
4121
-    protected function _process_resend_registration()
4122
-    {
4123
-        $this->_template_args['success'] = EED_Messages::process_resend($this->request->requestParams());
4124
-        do_action(
4125
-            'AHEE__EE_Admin_Page___process_resend_registration',
4126
-            $this->_template_args['success'],
4127
-            $this->request->requestParams()
4128
-        );
4129
-        return $this->_template_args['success'];
4130
-    }
4131
-
4132
-
4133
-    /**
4134
-     * This automatically processes any payment message notifications when manual payment has been applied.
4135
-     *
4136
-     * @param EE_Payment $payment
4137
-     * @return bool success/fail
4138
-     */
4139
-    protected function _process_payment_notification(EE_Payment $payment)
4140
-    {
4141
-        add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
4142
-        do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
4143
-        $this->_template_args['success'] = apply_filters(
4144
-            'FHEE__EE_Admin_Page___process_admin_payment_notification__success',
4145
-            false,
4146
-            $payment
4147
-        );
4148
-        return $this->_template_args['success'];
4149
-    }
2718
+	}
2719
+
2720
+
2721
+	/**
2722
+	 * facade for add_meta_box
2723
+	 *
2724
+	 * @param string  $action        where the metabox get's displayed
2725
+	 * @param string  $title         Title of Metabox (output in metabox header)
2726
+	 * @param string  $callback      If not empty and $create_fun is set to false then we'll use a custom callback
2727
+	 *                               instead of the one created in here.
2728
+	 * @param array   $callback_args an array of args supplied for the metabox
2729
+	 * @param string  $column        what metabox column
2730
+	 * @param string  $priority      give this metabox a priority (using accepted priorities for wp meta boxes)
2731
+	 * @param boolean $create_func   default is true.  Basically we can say we don't WANT to have the runtime function
2732
+	 *                               created but just set our own callback for wp's add_meta_box.
2733
+	 * @throws DomainException
2734
+	 */
2735
+	public function _add_admin_page_meta_box(
2736
+		$action,
2737
+		$title,
2738
+		$callback,
2739
+		$callback_args,
2740
+		$column = 'normal',
2741
+		$priority = 'high',
2742
+		$create_func = true
2743
+	) {
2744
+		do_action('AHEE_log', __FILE__, __FUNCTION__, $callback);
2745
+		// if we have empty callback args and we want to automatically create the metabox callback then we need to make sure the callback args are generated.
2746
+		if (empty($callback_args) && $create_func) {
2747
+			$callback_args = [
2748
+				'template_path' => $this->_template_path,
2749
+				'template_args' => $this->_template_args,
2750
+			];
2751
+		}
2752
+		// if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2753
+		$call_back_func = $create_func
2754
+			? function ($post, $metabox) {
2755
+				do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2756
+				echo EEH_Template::display_template(
2757
+					$metabox['args']['template_path'],
2758
+					$metabox['args']['template_args'],
2759
+					true
2760
+				);
2761
+			}
2762
+			: $callback;
2763
+		add_meta_box(
2764
+			str_replace('_', '-', $action) . '-mbox',
2765
+			$title,
2766
+			$call_back_func,
2767
+			$this->_wp_page_slug,
2768
+			$column,
2769
+			$priority,
2770
+			$callback_args
2771
+		);
2772
+	}
2773
+
2774
+
2775
+	/**
2776
+	 * generates HTML wrapper for and admin details page that contains metaboxes in columns
2777
+	 *
2778
+	 * @throws DomainException
2779
+	 * @throws EE_Error
2780
+	 */
2781
+	public function display_admin_page_with_metabox_columns()
2782
+	{
2783
+		$this->_template_args['post_body_content']  = $this->_template_args['admin_page_content'];
2784
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
2785
+			$this->_column_template_path,
2786
+			$this->_template_args,
2787
+			true
2788
+		);
2789
+		// the final wrapper
2790
+		$this->admin_page_wrapper();
2791
+	}
2792
+
2793
+
2794
+	/**
2795
+	 * generates  HTML wrapper for an admin details page
2796
+	 *
2797
+	 * @return void
2798
+	 * @throws EE_Error
2799
+	 * @throws DomainException
2800
+	 */
2801
+	public function display_admin_page_with_sidebar()
2802
+	{
2803
+		$this->_display_admin_page(true);
2804
+	}
2805
+
2806
+
2807
+	/**
2808
+	 * generates  HTML wrapper for an admin details page (except no sidebar)
2809
+	 *
2810
+	 * @return void
2811
+	 * @throws EE_Error
2812
+	 * @throws DomainException
2813
+	 */
2814
+	public function display_admin_page_with_no_sidebar()
2815
+	{
2816
+		$this->_display_admin_page();
2817
+	}
2818
+
2819
+
2820
+	/**
2821
+	 * generates HTML wrapper for an EE about admin page (no sidebar)
2822
+	 *
2823
+	 * @return void
2824
+	 * @throws EE_Error
2825
+	 * @throws DomainException
2826
+	 */
2827
+	public function display_about_admin_page()
2828
+	{
2829
+		$this->_display_admin_page(false, true);
2830
+	}
2831
+
2832
+
2833
+	/**
2834
+	 * display_admin_page
2835
+	 * contains the code for actually displaying an admin page
2836
+	 *
2837
+	 * @param boolean $sidebar true with sidebar, false without
2838
+	 * @param boolean $about   use the about admin wrapper instead of the default.
2839
+	 * @return void
2840
+	 * @throws DomainException
2841
+	 * @throws EE_Error
2842
+	 */
2843
+	private function _display_admin_page($sidebar = false, $about = false)
2844
+	{
2845
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2846
+		// custom remove metaboxes hook to add or remove any metaboxes to/from Admin pages.
2847
+		do_action('AHEE__EE_Admin_Page___display_admin_page__modify_metaboxes');
2848
+		// set current wp page slug - looks like: event-espresso_page_event_categories
2849
+		// keep in mind "event-espresso" COULD be something else if the top level menu label has been translated.
2850
+		$this->_template_args['current_page']              = $this->_wp_page_slug;
2851
+		$this->_template_args['admin_page_wrapper_div_id'] = $this->_cpt_route
2852
+			? 'poststuff'
2853
+			: 'espresso-default-admin';
2854
+		$template_path                                     = $sidebar
2855
+			? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2856
+			: EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2857
+		if (defined('DOING_AJAX') && DOING_AJAX) {
2858
+			$template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2859
+		}
2860
+		$template_path                                     = ! empty($this->_column_template_path)
2861
+			? $this->_column_template_path : $template_path;
2862
+		$this->_template_args['post_body_content']         = isset($this->_template_args['admin_page_content'])
2863
+			? $this->_template_args['admin_page_content']
2864
+			: '';
2865
+		$this->_template_args['before_admin_page_content'] = isset($this->_template_args['before_admin_page_content'])
2866
+			? $this->_template_args['before_admin_page_content']
2867
+			: '';
2868
+		$this->_template_args['after_admin_page_content']  = isset($this->_template_args['after_admin_page_content'])
2869
+			? $this->_template_args['after_admin_page_content']
2870
+			: '';
2871
+		$this->_template_args['admin_page_content']        = EEH_Template::display_template(
2872
+			$template_path,
2873
+			$this->_template_args,
2874
+			true
2875
+		);
2876
+		// the final template wrapper
2877
+		$this->admin_page_wrapper($about);
2878
+	}
2879
+
2880
+
2881
+	/**
2882
+	 * This is used to display caf preview pages.
2883
+	 *
2884
+	 * @param string $utm_campaign_source what is the key used for google analytics link
2885
+	 * @param bool   $display_sidebar     whether to use the sidebar template or the full template for the page.  TRUE
2886
+	 *                                    = SHOW sidebar, FALSE = no sidebar. Default no sidebar.
2887
+	 * @return void
2888
+	 * @throws DomainException
2889
+	 * @throws EE_Error
2890
+	 * @throws InvalidArgumentException
2891
+	 * @throws InvalidDataTypeException
2892
+	 * @throws InvalidInterfaceException
2893
+	 * @since 4.3.2
2894
+	 */
2895
+	public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2896
+	{
2897
+		// let's generate a default preview action button if there isn't one already present.
2898
+		$this->_labels['buttons']['buy_now']           = esc_html__(
2899
+			'Upgrade to Event Espresso 4 Right Now',
2900
+			'event_espresso'
2901
+		);
2902
+		$buy_now_url                                   = add_query_arg(
2903
+			[
2904
+				'ee_ver'       => 'ee4',
2905
+				'utm_source'   => 'ee4_plugin_admin',
2906
+				'utm_medium'   => 'link',
2907
+				'utm_campaign' => $utm_campaign_source,
2908
+				'utm_content'  => 'buy_now_button',
2909
+			],
2910
+			'http://eventespresso.com/pricing/'
2911
+		);
2912
+		$this->_template_args['preview_action_button'] = ! isset($this->_template_args['preview_action_button'])
2913
+			? $this->get_action_link_or_button(
2914
+				'',
2915
+				'buy_now',
2916
+				[],
2917
+				'button-primary button-large',
2918
+				$buy_now_url,
2919
+				true
2920
+			)
2921
+			: $this->_template_args['preview_action_button'];
2922
+		$this->_template_args['admin_page_content']    = EEH_Template::display_template(
2923
+			EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2924
+			$this->_template_args,
2925
+			true
2926
+		);
2927
+		$this->_display_admin_page($display_sidebar);
2928
+	}
2929
+
2930
+
2931
+	/**
2932
+	 * display_admin_list_table_page_with_sidebar
2933
+	 * generates HTML wrapper for an admin_page with list_table
2934
+	 *
2935
+	 * @return void
2936
+	 * @throws EE_Error
2937
+	 * @throws DomainException
2938
+	 */
2939
+	public function display_admin_list_table_page_with_sidebar()
2940
+	{
2941
+		$this->_display_admin_list_table_page(true);
2942
+	}
2943
+
2944
+
2945
+	/**
2946
+	 * display_admin_list_table_page_with_no_sidebar
2947
+	 * generates HTML wrapper for an admin_page with list_table (but with no sidebar)
2948
+	 *
2949
+	 * @return void
2950
+	 * @throws EE_Error
2951
+	 * @throws DomainException
2952
+	 */
2953
+	public function display_admin_list_table_page_with_no_sidebar()
2954
+	{
2955
+		$this->_display_admin_list_table_page();
2956
+	}
2957
+
2958
+
2959
+	/**
2960
+	 * generates html wrapper for an admin_list_table page
2961
+	 *
2962
+	 * @param boolean $sidebar whether to display with sidebar or not.
2963
+	 * @return void
2964
+	 * @throws DomainException
2965
+	 * @throws EE_Error
2966
+	 */
2967
+	private function _display_admin_list_table_page($sidebar = false)
2968
+	{
2969
+		// setup search attributes
2970
+		$this->_set_search_attributes();
2971
+		$this->_template_args['current_page']     = $this->_wp_page_slug;
2972
+		$template_path                            = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2973
+		$this->_template_args['table_url']        = defined('DOING_AJAX')
2974
+			? add_query_arg(['noheader' => 'true', 'route' => $this->_req_action], $this->_admin_base_url)
2975
+			: add_query_arg(['route' => $this->_req_action], $this->_admin_base_url);
2976
+		$this->_template_args['list_table']       = $this->_list_table_object;
2977
+		$this->_template_args['current_route']    = $this->_req_action;
2978
+		$this->_template_args['list_table_class'] = get_class($this->_list_table_object);
2979
+		$ajax_sorting_callback                    = $this->_list_table_object->get_ajax_sorting_callback();
2980
+		if (! empty($ajax_sorting_callback)) {
2981
+			$sortable_list_table_form_fields = wp_nonce_field(
2982
+				$ajax_sorting_callback . '_nonce',
2983
+				$ajax_sorting_callback . '_nonce',
2984
+				false,
2985
+				false
2986
+			);
2987
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_page" name="ajax_table_sort_page" value="'
2988
+												. $this->page_slug
2989
+												. '" />';
2990
+			$sortable_list_table_form_fields .= '<input type="hidden" id="ajax_table_sort_action" name="ajax_table_sort_action" value="'
2991
+												. $ajax_sorting_callback
2992
+												. '" />';
2993
+		} else {
2994
+			$sortable_list_table_form_fields = '';
2995
+		}
2996
+		$this->_template_args['sortable_list_table_form_fields'] = $sortable_list_table_form_fields;
2997
+		$hidden_form_fields                                      =
2998
+			isset($this->_template_args['list_table_hidden_fields'])
2999
+				? $this->_template_args['list_table_hidden_fields']
3000
+				: '';
3001
+		$nonce_ref                                               = $this->_req_action . '_nonce';
3002
+		$hidden_form_fields                                      .= '<input type="hidden" name="'
3003
+																	. $nonce_ref
3004
+																	. '" value="'
3005
+																	. wp_create_nonce($nonce_ref)
3006
+																	. '">';
3007
+		$this->_template_args['list_table_hidden_fields']        = $hidden_form_fields;
3008
+		// display message about search results?
3009
+		$search = $this->request->getRequestParam('s');
3010
+		$this->_template_args['before_list_table'] .= ! empty($search)
3011
+			? '<p class="ee-search-results">' . sprintf(
3012
+				esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3013
+				trim($search, '%')
3014
+			) . '</p>'
3015
+			: '';
3016
+		// filter before_list_table template arg
3017
+		$this->_template_args['before_list_table'] = apply_filters(
3018
+			'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_arg',
3019
+			$this->_template_args['before_list_table'],
3020
+			$this->page_slug,
3021
+			$this->request->requestParams(),
3022
+			$this->_req_action
3023
+		);
3024
+		// convert to array and filter again
3025
+		// arrays are easier to inject new items in a specific location,
3026
+		// but would not be backwards compatible, so we have to add a new filter
3027
+		$this->_template_args['before_list_table'] = implode(
3028
+			" \n",
3029
+			(array) apply_filters(
3030
+				'FHEE__EE_Admin_Page___display_admin_list_table_page__before_list_table__template_args_array',
3031
+				(array) $this->_template_args['before_list_table'],
3032
+				$this->page_slug,
3033
+				$this->request->requestParams(),
3034
+				$this->_req_action
3035
+			)
3036
+		);
3037
+		// filter after_list_table template arg
3038
+		$this->_template_args['after_list_table'] = apply_filters(
3039
+			'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_arg',
3040
+			$this->_template_args['after_list_table'],
3041
+			$this->page_slug,
3042
+			$this->request->requestParams(),
3043
+			$this->_req_action
3044
+		);
3045
+		// convert to array and filter again
3046
+		// arrays are easier to inject new items in a specific location,
3047
+		// but would not be backwards compatible, so we have to add a new filter
3048
+		$this->_template_args['after_list_table']   = implode(
3049
+			" \n",
3050
+			(array) apply_filters(
3051
+				'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
3052
+				(array) $this->_template_args['after_list_table'],
3053
+				$this->page_slug,
3054
+				$this->request->requestParams(),
3055
+				$this->_req_action
3056
+			)
3057
+		);
3058
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
3059
+			$template_path,
3060
+			$this->_template_args,
3061
+			true
3062
+		);
3063
+		// the final template wrapper
3064
+		if ($sidebar) {
3065
+			$this->display_admin_page_with_sidebar();
3066
+		} else {
3067
+			$this->display_admin_page_with_no_sidebar();
3068
+		}
3069
+	}
3070
+
3071
+
3072
+	/**
3073
+	 * This just prepares a legend using the given items and the admin_details_legend.template.php file and returns the
3074
+	 * html string for the legend.
3075
+	 * $items are expected in an array in the following format:
3076
+	 * $legend_items = array(
3077
+	 *        'item_id' => array(
3078
+	 *            'icon' => 'http://url_to_icon_being_described.png',
3079
+	 *            'desc' => esc_html__('localized description of item');
3080
+	 *        )
3081
+	 * );
3082
+	 *
3083
+	 * @param array $items see above for format of array
3084
+	 * @return string html string of legend
3085
+	 * @throws DomainException
3086
+	 */
3087
+	protected function _display_legend($items)
3088
+	{
3089
+		$this->_template_args['items'] = apply_filters(
3090
+			'FHEE__EE_Admin_Page___display_legend__items',
3091
+			(array) $items,
3092
+			$this
3093
+		);
3094
+		return EEH_Template::display_template(
3095
+			EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3096
+			$this->_template_args,
3097
+			true
3098
+		);
3099
+	}
3100
+
3101
+
3102
+	/**
3103
+	 * This is used whenever we're DOING_AJAX to return a formatted json array that our calling javascript can expect
3104
+	 * The returned json object is created from an array in the following format:
3105
+	 * array(
3106
+	 *  'error' => FALSE, //(default FALSE), contains any errors and/or exceptions (exceptions return json early),
3107
+	 *  'success' => FALSE, //(default FALSE) - contains any special success message.
3108
+	 *  'notices' => '', // - contains any EE_Error formatted notices
3109
+	 *  'content' => 'string can be html', //this is a string of formatted content (can be html)
3110
+	 *  'data' => array() //this can be any key/value pairs that a method returns for later json parsing by the js.
3111
+	 *  We're also going to include the template args with every package (so js can pick out any specific template args
3112
+	 *  that might be included in here)
3113
+	 * )
3114
+	 * The json object is populated by whatever is set in the $_template_args property.
3115
+	 *
3116
+	 * @param bool  $sticky_notices    Used to indicate whether you want to ensure notices are added to a transient
3117
+	 *                                 instead of displayed.
3118
+	 * @param array $notices_arguments Use this to pass any additional args on to the _process_notices.
3119
+	 * @return void
3120
+	 * @throws EE_Error
3121
+	 */
3122
+	protected function _return_json($sticky_notices = false, $notices_arguments = [])
3123
+	{
3124
+		// make sure any EE_Error notices have been handled.
3125
+		$this->_process_notices($notices_arguments, true, $sticky_notices);
3126
+		$data = isset($this->_template_args['data']) ? $this->_template_args['data'] : [];
3127
+		unset($this->_template_args['data']);
3128
+		$json = [
3129
+			'error'     => isset($this->_template_args['error']) ? $this->_template_args['error'] : false,
3130
+			'success'   => isset($this->_template_args['success']) ? $this->_template_args['success'] : false,
3131
+			'errors'    => isset($this->_template_args['errors']) ? $this->_template_args['errors'] : false,
3132
+			'attention' => isset($this->_template_args['attention']) ? $this->_template_args['attention'] : false,
3133
+			'notices'   => EE_Error::get_notices(),
3134
+			'content'   => isset($this->_template_args['admin_page_content'])
3135
+				? $this->_template_args['admin_page_content'] : '',
3136
+			'data'      => array_merge($data, ['template_args' => $this->_template_args]),
3137
+			'isEEajax'  => true
3138
+			// special flag so any ajax.Success methods in js can identify this return package as a EEajax package.
3139
+		];
3140
+		// make sure there are no php errors or headers_sent.  Then we can set correct json header.
3141
+		if (null === error_get_last() || ! headers_sent()) {
3142
+			header('Content-Type: application/json; charset=UTF-8');
3143
+		}
3144
+		echo wp_json_encode($json);
3145
+		exit();
3146
+	}
3147
+
3148
+
3149
+	/**
3150
+	 * Simply a wrapper for the protected method so we can call this outside the class (ONLY when doing ajax)
3151
+	 *
3152
+	 * @return void
3153
+	 * @throws EE_Error
3154
+	 */
3155
+	public function return_json()
3156
+	{
3157
+		if (defined('DOING_AJAX') && DOING_AJAX) {
3158
+			$this->_return_json();
3159
+		} else {
3160
+			throw new EE_Error(
3161
+				sprintf(
3162
+					esc_html__('The public %s method can only be called when DOING_AJAX = TRUE', 'event_espresso'),
3163
+					__FUNCTION__
3164
+				)
3165
+			);
3166
+		}
3167
+	}
3168
+
3169
+
3170
+	/**
3171
+	 * This provides a way for child hook classes to send along themselves by reference so methods/properties within
3172
+	 * them can be accessed by EE_Admin_child pages. This is assigned to the $_hook_obj property.
3173
+	 *
3174
+	 * @param EE_Admin_Hooks $hook_obj This will be the object for the EE_Admin_Hooks child
3175
+	 */
3176
+	public function set_hook_object(EE_Admin_Hooks $hook_obj)
3177
+	{
3178
+		$this->_hook_obj = $hook_obj;
3179
+	}
3180
+
3181
+
3182
+	/**
3183
+	 *        generates  HTML wrapper with Tabbed nav for an admin page
3184
+	 *
3185
+	 * @param boolean $about whether to use the special about page wrapper or default.
3186
+	 * @return void
3187
+	 * @throws DomainException
3188
+	 * @throws EE_Error
3189
+	 */
3190
+	public function admin_page_wrapper($about = false)
3191
+	{
3192
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3193
+		$this->_nav_tabs                                   = $this->_get_main_nav_tabs();
3194
+		$this->_template_args['nav_tabs']                  = $this->_nav_tabs;
3195
+		$this->_template_args['admin_page_title']          = $this->_admin_page_title;
3196
+		$this->_template_args['before_admin_page_content'] = apply_filters(
3197
+			"FHEE_before_admin_page_content{$this->_current_page}{$this->_current_view}",
3198
+			isset($this->_template_args['before_admin_page_content'])
3199
+				? $this->_template_args['before_admin_page_content']
3200
+				: ''
3201
+		);
3202
+		$this->_template_args['after_admin_page_content']  = apply_filters(
3203
+			"FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3204
+			isset($this->_template_args['after_admin_page_content'])
3205
+				? $this->_template_args['after_admin_page_content']
3206
+				: ''
3207
+		);
3208
+		$this->_template_args['after_admin_page_content']  .= $this->_set_help_popup_content();
3209
+		// load settings page wrapper template
3210
+		$template_path = ! defined('DOING_AJAX')
3211
+			? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
3212
+			: EE_ADMIN_TEMPLATE
3213
+			  . 'admin_wrapper_ajax.template.php';
3214
+		// about page?
3215
+		$template_path = $about
3216
+			? EE_ADMIN_TEMPLATE . 'about_admin_wrapper.template.php'
3217
+			: $template_path;
3218
+		if (defined('DOING_AJAX')) {
3219
+			$this->_template_args['admin_page_content'] = EEH_Template::display_template(
3220
+				$template_path,
3221
+				$this->_template_args,
3222
+				true
3223
+			);
3224
+			$this->_return_json();
3225
+		} else {
3226
+			EEH_Template::display_template($template_path, $this->_template_args);
3227
+		}
3228
+	}
3229
+
3230
+
3231
+	/**
3232
+	 * This returns the admin_nav tabs html using the configuration in the _nav_tabs property
3233
+	 *
3234
+	 * @return string html
3235
+	 * @throws EE_Error
3236
+	 */
3237
+	protected function _get_main_nav_tabs()
3238
+	{
3239
+		// let's generate the html using the EEH_Tabbed_Content helper.
3240
+		// We do this here so that it's possible for child classes to add in nav tabs dynamically at the last minute
3241
+		// (rather than setting in the page_routes array)
3242
+		return EEH_Tabbed_Content::display_admin_nav_tabs($this->_nav_tabs);
3243
+	}
3244
+
3245
+
3246
+	/**
3247
+	 *        sort nav tabs
3248
+	 *
3249
+	 * @param $a
3250
+	 * @param $b
3251
+	 * @return int
3252
+	 */
3253
+	private function _sort_nav_tabs($a, $b)
3254
+	{
3255
+		if ($a['order'] === $b['order']) {
3256
+			return 0;
3257
+		}
3258
+		return ($a['order'] < $b['order']) ? -1 : 1;
3259
+	}
3260
+
3261
+
3262
+	/**
3263
+	 *    generates HTML for the forms used on admin pages
3264
+	 *
3265
+	 * @param array  $input_vars   - array of input field details
3266
+	 * @param string $generator    (options are 'string' or 'array', basically use this to indicate which generator to
3267
+	 *                             use)
3268
+	 * @param bool   $id
3269
+	 * @return string
3270
+	 * @uses   EEH_Form_Fields::get_form_fields (/helper/EEH_Form_Fields.helper.php)
3271
+	 * @uses   EEH_Form_Fields::get_form_fields_array (/helper/EEH_Form_Fields.helper.php)
3272
+	 */
3273
+	protected function _generate_admin_form_fields($input_vars = [], $generator = 'string', $id = false)
3274
+	{
3275
+		$content = $generator === 'string'
3276
+			? EEH_Form_Fields::get_form_fields($input_vars, $id)
3277
+			: EEH_Form_Fields::get_form_fields_array($input_vars);
3278
+		return $content;
3279
+	}
3280
+
3281
+
3282
+	/**
3283
+	 * generates the "Save" and "Save & Close" buttons for edit forms
3284
+	 *
3285
+	 * @param bool             $both     if true then both buttons will be generated.  If false then just the "Save &
3286
+	 *                                   Close" button.
3287
+	 * @param array            $text     if included, generator will use the given text for the buttons ( array([0] =>
3288
+	 *                                   'Save', [1] => 'save & close')
3289
+	 * @param array            $actions  if included allows us to set the actions that each button will carry out (i.e.
3290
+	 *                                   via the "name" value in the button).  We can also use this to just dump
3291
+	 *                                   default actions by submitting some other value.
3292
+	 * @param bool|string|null $referrer if false then we just do the default action on save and close.  Other wise it
3293
+	 *                                   will use the $referrer string. IF null, then we don't do ANYTHING on save and
3294
+	 *                                   close (normal form handling).
3295
+	 */
3296
+	protected function _set_save_buttons($both = true, $text = [], $actions = [], $referrer = null)
3297
+	{
3298
+		// make sure $text and $actions are in an array
3299
+		$text          = (array) $text;
3300
+		$actions       = (array) $actions;
3301
+		$referrer_url  = empty($referrer)
3302
+			? '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3303
+			  . $_SERVER['REQUEST_URI']
3304
+			  . '" />'
3305
+			: '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3306
+			  . $referrer
3307
+			  . '" />';
3308
+		$button_text   = ! empty($text)
3309
+			? $text
3310
+			: [
3311
+				esc_html__('Save', 'event_espresso'),
3312
+				esc_html__('Save and Close', 'event_espresso'),
3313
+			];
3314
+		$default_names = ['save', 'save_and_close'];
3315
+		// add in a hidden index for the current page (so save and close redirects properly)
3316
+		$this->_template_args['save_buttons'] = $referrer_url;
3317
+		foreach ($button_text as $key => $button) {
3318
+			$ref                                  = $default_names[ $key ];
3319
+			$this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3320
+													 . $ref
3321
+													 . '" value="'
3322
+													 . $button
3323
+													 . '" name="'
3324
+													 . (! empty($actions) ? $actions[ $key ] : $ref)
3325
+													 . '" id="'
3326
+													 . $this->_current_view . '_' . $ref
3327
+													 . '" />';
3328
+			if (! $both) {
3329
+				break;
3330
+			}
3331
+		}
3332
+	}
3333
+
3334
+
3335
+	/**
3336
+	 * Wrapper for the protected function.  Allows plugins/addons to call this to set the form tags.
3337
+	 *
3338
+	 * @param string $route
3339
+	 * @param array  $additional_hidden_fields
3340
+	 * @see   $this->_set_add_edit_form_tags() for details on params
3341
+	 * @since 4.6.0
3342
+	 */
3343
+	public function set_add_edit_form_tags($route = '', $additional_hidden_fields = [])
3344
+	{
3345
+		$this->_set_add_edit_form_tags($route, $additional_hidden_fields);
3346
+	}
3347
+
3348
+
3349
+	/**
3350
+	 * set form open and close tags on add/edit pages.
3351
+	 *
3352
+	 * @param string $route                    the route you want the form to direct to
3353
+	 * @param array  $additional_hidden_fields any additional hidden fields required in the form header
3354
+	 * @return void
3355
+	 */
3356
+	protected function _set_add_edit_form_tags($route = '', $additional_hidden_fields = [])
3357
+	{
3358
+		if (empty($route)) {
3359
+			$user_msg = esc_html__(
3360
+				'An error occurred. No action was set for this page\'s form.',
3361
+				'event_espresso'
3362
+			);
3363
+			$dev_msg  = $user_msg . "\n"
3364
+						. sprintf(
3365
+							esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3366
+							__FUNCTION__,
3367
+							__CLASS__
3368
+						);
3369
+			EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3370
+		}
3371
+		// open form
3372
+		$this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
3373
+															 . $this->_admin_base_url
3374
+															 . '" id="'
3375
+															 . $route
3376
+															 . '_event_form" >';
3377
+		// add nonce
3378
+		$nonce                                             =
3379
+			wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3380
+		$this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3381
+		// add REQUIRED form action
3382
+		$hidden_fields = [
3383
+			'action' => ['type' => 'hidden', 'value' => $route],
3384
+		];
3385
+		// merge arrays
3386
+		$hidden_fields = is_array($additional_hidden_fields)
3387
+			? array_merge($hidden_fields, $additional_hidden_fields)
3388
+			: $hidden_fields;
3389
+		// generate form fields
3390
+		$form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3391
+		// add fields to form
3392
+		foreach ((array) $form_fields as $field_name => $form_field) {
3393
+			$this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3394
+		}
3395
+		// close form
3396
+		$this->_template_args['after_admin_page_content'] = '</form>';
3397
+	}
3398
+
3399
+
3400
+	/**
3401
+	 * Public Wrapper for _redirect_after_action() method since its
3402
+	 * discovered it would be useful for external code to have access.
3403
+	 *
3404
+	 * @param bool   $success
3405
+	 * @param string $what
3406
+	 * @param string $action_desc
3407
+	 * @param array  $query_args
3408
+	 * @param bool   $override_overwrite
3409
+	 * @throws EE_Error
3410
+	 * @see   EE_Admin_Page::_redirect_after_action() for params.
3411
+	 * @since 4.5.0
3412
+	 */
3413
+	public function redirect_after_action(
3414
+		$success = false,
3415
+		$what = 'item',
3416
+		$action_desc = 'processed',
3417
+		$query_args = [],
3418
+		$override_overwrite = false
3419
+	) {
3420
+		$this->_redirect_after_action(
3421
+			$success,
3422
+			$what,
3423
+			$action_desc,
3424
+			$query_args,
3425
+			$override_overwrite
3426
+		);
3427
+	}
3428
+
3429
+
3430
+	/**
3431
+	 * Helper method for merging existing request data with the returned redirect url.
3432
+	 *
3433
+	 * This is typically used for redirects after an action so that if the original view was a filtered view those
3434
+	 * filters are still applied.
3435
+	 *
3436
+	 * @param array $new_route_data
3437
+	 * @return array
3438
+	 */
3439
+	protected function mergeExistingRequestParamsWithRedirectArgs(array $new_route_data)
3440
+	{
3441
+		foreach ($this->request->requestParams() as $ref => $value) {
3442
+			// unset nonces
3443
+			if (strpos($ref, 'nonce') !== false) {
3444
+				$this->request->unSetRequestParam($ref);
3445
+				continue;
3446
+			}
3447
+			// urlencode values.
3448
+			$value = is_array($value) ? array_map('urlencode', $value) : urlencode($value);
3449
+			$this->request->setRequestParam($ref, $value);
3450
+		}
3451
+		return array_merge($this->request->requestParams(), $new_route_data);
3452
+	}
3453
+
3454
+
3455
+	/**
3456
+	 *    _redirect_after_action
3457
+	 *
3458
+	 * @param int    $success            - whether success was for two or more records, or just one, or none
3459
+	 * @param string $what               - what the action was performed on
3460
+	 * @param string $action_desc        - what was done ie: updated, deleted, etc
3461
+	 * @param array  $query_args         - an array of query_args to be added to the URL to redirect to after the admin
3462
+	 *                                   action is completed
3463
+	 * @param BOOL   $override_overwrite by default all EE_Error::success messages are overwritten, this allows you to
3464
+	 *                                   override this so that they show.
3465
+	 * @return void
3466
+	 * @throws EE_Error
3467
+	 */
3468
+	protected function _redirect_after_action(
3469
+		$success = 0,
3470
+		$what = 'item',
3471
+		$action_desc = 'processed',
3472
+		$query_args = [],
3473
+		$override_overwrite = false
3474
+	) {
3475
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
3476
+		// class name for actions/filters.
3477
+		$classname = get_class($this);
3478
+		// set redirect url.
3479
+		// Note if there is a "page" index in the $query_args then we go with vanilla admin.php route,
3480
+		// otherwise we go with whatever is set as the _admin_base_url
3481
+		$redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3482
+		$notices      = EE_Error::get_notices(false);
3483
+		// overwrite default success messages //BUT ONLY if overwrite not overridden
3484
+		if (! $override_overwrite || ! empty($notices['errors'])) {
3485
+			EE_Error::overwrite_success();
3486
+		}
3487
+		if (! empty($what) && ! empty($action_desc) && empty($notices['errors'])) {
3488
+			// how many records affected ? more than one record ? or just one ?
3489
+			if ($success > 1) {
3490
+				// set plural msg
3491
+				EE_Error::add_success(
3492
+					sprintf(
3493
+						esc_html__('The "%s" have been successfully %s.', 'event_espresso'),
3494
+						$what,
3495
+						$action_desc
3496
+					),
3497
+					__FILE__,
3498
+					__FUNCTION__,
3499
+					__LINE__
3500
+				);
3501
+			} elseif ($success === 1) {
3502
+				// set singular msg
3503
+				EE_Error::add_success(
3504
+					sprintf(
3505
+						esc_html__('The "%s" has been successfully %s.', 'event_espresso'),
3506
+						$what,
3507
+						$action_desc
3508
+					),
3509
+					__FILE__,
3510
+					__FUNCTION__,
3511
+					__LINE__
3512
+				);
3513
+			}
3514
+		}
3515
+		// check that $query_args isn't something crazy
3516
+		if (! is_array($query_args)) {
3517
+			$query_args = [];
3518
+		}
3519
+		/**
3520
+		 * Allow injecting actions before the query_args are modified for possible different
3521
+		 * redirections on save and close actions
3522
+		 *
3523
+		 * @param array $query_args       The original query_args array coming into the
3524
+		 *                                method.
3525
+		 * @since 4.2.0
3526
+		 */
3527
+		do_action(
3528
+			"AHEE__{$classname}___redirect_after_action__before_redirect_modification_{$this->_req_action}",
3529
+			$query_args
3530
+		);
3531
+		// calculate where we're going (if we have a "save and close" button pushed)
3532
+
3533
+		if (
3534
+			$this->request->requestParamIsSet('save_and_close')
3535
+			&& $this->request->requestParamIsSet('save_and_close_referrer')
3536
+		) {
3537
+			// even though we have the save_and_close referrer, we need to parse the url for the action in order to generate a nonce
3538
+			$parsed_url = parse_url($this->request->getRequestParam('save_and_close_referrer', '', 'url'));
3539
+			// regenerate query args array from referrer URL
3540
+			parse_str($parsed_url['query'], $query_args);
3541
+			// correct page and action will be in the query args now
3542
+			$redirect_url = admin_url('admin.php');
3543
+		}
3544
+		// merge any default query_args set in _default_route_query_args property
3545
+		if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3546
+			$args_to_merge = [];
3547
+			foreach ($this->_default_route_query_args as $query_param => $query_value) {
3548
+				// is there a wp_referer array in our _default_route_query_args property?
3549
+				if ($query_param === 'wp_referer') {
3550
+					$query_value = (array) $query_value;
3551
+					foreach ($query_value as $reference => $value) {
3552
+						if (strpos($reference, 'nonce') !== false) {
3553
+							continue;
3554
+						}
3555
+						// finally we will override any arguments in the referer with
3556
+						// what might be set on the _default_route_query_args array.
3557
+						if (isset($this->_default_route_query_args[ $reference ])) {
3558
+							$args_to_merge[ $reference ] = urlencode($this->_default_route_query_args[ $reference ]);
3559
+						} else {
3560
+							$args_to_merge[ $reference ] = urlencode($value);
3561
+						}
3562
+					}
3563
+					continue;
3564
+				}
3565
+				$args_to_merge[ $query_param ] = $query_value;
3566
+			}
3567
+			// now let's merge these arguments but override with what was specifically sent in to the
3568
+			// redirect.
3569
+			$query_args = array_merge($args_to_merge, $query_args);
3570
+		}
3571
+		$this->_process_notices($query_args);
3572
+		// generate redirect url
3573
+		// if redirecting to anything other than the main page, add a nonce
3574
+		if (isset($query_args['action'])) {
3575
+			// manually generate wp_nonce and merge that with the query vars
3576
+			// becuz the wp_nonce_url function wrecks havoc on some vars
3577
+			$query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3578
+		}
3579
+		// we're adding some hooks and filters in here for processing any things just before redirects
3580
+		// (example: an admin page has done an insert or update and we want to run something after that).
3581
+		do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3582
+		$redirect_url = apply_filters(
3583
+			'FHEE_redirect_' . $classname . $this->_req_action,
3584
+			self::add_query_args_and_nonce($query_args, $redirect_url),
3585
+			$query_args
3586
+		);
3587
+		// check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3588
+		if (defined('DOING_AJAX')) {
3589
+			$default_data                    = [
3590
+				'close'        => true,
3591
+				'redirect_url' => $redirect_url,
3592
+				'where'        => 'main',
3593
+				'what'         => 'append',
3594
+			];
3595
+			$this->_template_args['success'] = $success;
3596
+			$this->_template_args['data']    = ! empty($this->_template_args['data']) ? array_merge(
3597
+				$default_data,
3598
+				$this->_template_args['data']
3599
+			) : $default_data;
3600
+			$this->_return_json();
3601
+		}
3602
+		wp_safe_redirect($redirect_url);
3603
+		exit();
3604
+	}
3605
+
3606
+
3607
+	/**
3608
+	 * process any notices before redirecting (or returning ajax request)
3609
+	 * This method sets the $this->_template_args['notices'] attribute;
3610
+	 *
3611
+	 * @param array $query_args         any query args that need to be used for notice transient ('action')
3612
+	 * @param bool  $skip_route_verify  This is typically used when we are processing notices REALLY early and
3613
+	 *                                  page_routes haven't been defined yet.
3614
+	 * @param bool  $sticky_notices     This is used to flag that regardless of whether this is doing_ajax or not, we
3615
+	 *                                  still save a transient for the notice.
3616
+	 * @return void
3617
+	 * @throws EE_Error
3618
+	 */
3619
+	protected function _process_notices($query_args = [], $skip_route_verify = false, $sticky_notices = true)
3620
+	{
3621
+		// first let's set individual error properties if doing_ajax and the properties aren't already set.
3622
+		if (defined('DOING_AJAX') && DOING_AJAX) {
3623
+			$notices = EE_Error::get_notices(false);
3624
+			if (empty($this->_template_args['success'])) {
3625
+				$this->_template_args['success'] = isset($notices['success']) ? $notices['success'] : false;
3626
+			}
3627
+			if (empty($this->_template_args['errors'])) {
3628
+				$this->_template_args['errors'] = isset($notices['errors']) ? $notices['errors'] : false;
3629
+			}
3630
+			if (empty($this->_template_args['attention'])) {
3631
+				$this->_template_args['attention'] = isset($notices['attention']) ? $notices['attention'] : false;
3632
+			}
3633
+		}
3634
+		$this->_template_args['notices'] = EE_Error::get_notices();
3635
+		// IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3636
+		if (! defined('DOING_AJAX') || $sticky_notices) {
3637
+			$route = isset($query_args['action']) ? $query_args['action'] : 'default';
3638
+			$this->_add_transient(
3639
+				$route,
3640
+				$this->_template_args['notices'],
3641
+				true,
3642
+				$skip_route_verify
3643
+			);
3644
+		}
3645
+	}
3646
+
3647
+
3648
+	/**
3649
+	 * get_action_link_or_button
3650
+	 * returns the button html for adding, editing, or deleting an item (depending on given type)
3651
+	 *
3652
+	 * @param string $action        use this to indicate which action the url is generated with.
3653
+	 * @param string $type          accepted strings must be defined in the $_labels['button'] array(as the key)
3654
+	 *                              property.
3655
+	 * @param array  $extra_request if the button requires extra params you can include them in $key=>$value pairs.
3656
+	 * @param string $class         Use this to give the class for the button. Defaults to 'button-primary'
3657
+	 * @param string $base_url      If this is not provided
3658
+	 *                              the _admin_base_url will be used as the default for the button base_url.
3659
+	 *                              Otherwise this value will be used.
3660
+	 * @param bool   $exclude_nonce If true then no nonce will be in the generated button link.
3661
+	 * @return string
3662
+	 * @throws InvalidArgumentException
3663
+	 * @throws InvalidInterfaceException
3664
+	 * @throws InvalidDataTypeException
3665
+	 * @throws EE_Error
3666
+	 */
3667
+	public function get_action_link_or_button(
3668
+		$action,
3669
+		$type = 'add',
3670
+		$extra_request = [],
3671
+		$class = 'button-primary',
3672
+		$base_url = '',
3673
+		$exclude_nonce = false
3674
+	) {
3675
+		// first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3676
+		if (empty($base_url) && ! isset($this->_page_routes[ $action ])) {
3677
+			throw new EE_Error(
3678
+				sprintf(
3679
+					esc_html__(
3680
+						'There is no page route for given action for the button.  This action was given: %s',
3681
+						'event_espresso'
3682
+					),
3683
+					$action
3684
+				)
3685
+			);
3686
+		}
3687
+		if (! isset($this->_labels['buttons'][ $type ])) {
3688
+			throw new EE_Error(
3689
+				sprintf(
3690
+					__(
3691
+						'There is no label for the given button type (%s). Labels are set in the <code>_page_config</code> property.',
3692
+						'event_espresso'
3693
+					),
3694
+					$type
3695
+				)
3696
+			);
3697
+		}
3698
+		// finally check user access for this button.
3699
+		$has_access = $this->check_user_access($action, true);
3700
+		if (! $has_access) {
3701
+			return '';
3702
+		}
3703
+		$_base_url  = ! $base_url ? $this->_admin_base_url : $base_url;
3704
+		$query_args = [
3705
+			'action' => $action,
3706
+		];
3707
+		// merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3708
+		if (! empty($extra_request)) {
3709
+			$query_args = array_merge($extra_request, $query_args);
3710
+		}
3711
+		$url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3712
+		return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][ $type ], $class);
3713
+	}
3714
+
3715
+
3716
+	/**
3717
+	 * _per_page_screen_option
3718
+	 * Utility function for adding in a per_page_option in the screen_options_dropdown.
3719
+	 *
3720
+	 * @return void
3721
+	 * @throws InvalidArgumentException
3722
+	 * @throws InvalidInterfaceException
3723
+	 * @throws InvalidDataTypeException
3724
+	 */
3725
+	protected function _per_page_screen_option()
3726
+	{
3727
+		$option = 'per_page';
3728
+		$args   = [
3729
+			'label'   => apply_filters(
3730
+				'FHEE__EE_Admin_Page___per_page_screen_options___label',
3731
+				$this->_admin_page_title,
3732
+				$this
3733
+			),
3734
+			'default' => (int) apply_filters(
3735
+				'FHEE__EE_Admin_Page___per_page_screen_options__default',
3736
+				20
3737
+			),
3738
+			'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3739
+		];
3740
+		// ONLY add the screen option if the user has access to it.
3741
+		if ($this->check_user_access($this->_current_view, true)) {
3742
+			add_screen_option($option, $args);
3743
+		}
3744
+	}
3745
+
3746
+
3747
+	/**
3748
+	 * set_per_page_screen_option
3749
+	 * All this does is make sure that WordPress saves any per_page screen options (if set) for the current page.
3750
+	 * we have to do this rather than running inside the 'set-screen-options' hook because it runs earlier than
3751
+	 * admin_menu.
3752
+	 *
3753
+	 * @return void
3754
+	 */
3755
+	private function _set_per_page_screen_options()
3756
+	{
3757
+		if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3758
+			check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3759
+			if (! $user = wp_get_current_user()) {
3760
+				return;
3761
+			}
3762
+			$option = $_POST['wp_screen_options']['option'];
3763
+			$value  = $_POST['wp_screen_options']['value'];
3764
+			if ($option != sanitize_key($option)) {
3765
+				return;
3766
+			}
3767
+			$map_option = $option;
3768
+			$option     = str_replace('-', '_', $option);
3769
+			switch ($map_option) {
3770
+				case $this->_current_page . '_' . $this->_current_view . '_per_page':
3771
+					$value     = (int) $value;
3772
+					$max_value = apply_filters(
3773
+						'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
3774
+						999,
3775
+						$this->_current_page,
3776
+						$this->_current_view
3777
+					);
3778
+					if ($value < 1) {
3779
+						return;
3780
+					}
3781
+					$value = min($value, $max_value);
3782
+					break;
3783
+				default:
3784
+					$value = apply_filters(
3785
+						'FHEE__EE_Admin_Page___set_per_page_screen_options__value',
3786
+						false,
3787
+						$option,
3788
+						$value
3789
+					);
3790
+					if (false === $value) {
3791
+						return;
3792
+					}
3793
+					break;
3794
+			}
3795
+			update_user_meta($user->ID, $option, $value);
3796
+			wp_safe_redirect(remove_query_arg(['pagenum', 'apage', 'paged'], wp_get_referer()));
3797
+			exit;
3798
+		}
3799
+	}
3800
+
3801
+
3802
+	/**
3803
+	 * This just allows for setting the $_template_args property if it needs to be set outside the object
3804
+	 *
3805
+	 * @param array $data array that will be assigned to template args.
3806
+	 */
3807
+	public function set_template_args($data)
3808
+	{
3809
+		$this->_template_args = array_merge($this->_template_args, (array) $data);
3810
+	}
3811
+
3812
+
3813
+	/**
3814
+	 * This makes available the WP transient system for temporarily moving data between routes
3815
+	 *
3816
+	 * @param string $route             the route that should receive the transient
3817
+	 * @param array  $data              the data that gets sent
3818
+	 * @param bool   $notices           If this is for notices then we use this to indicate so, otherwise its just a
3819
+	 *                                  normal route transient.
3820
+	 * @param bool   $skip_route_verify Used to indicate we want to skip route verification.  This is usually ONLY used
3821
+	 *                                  when we are adding a transient before page_routes have been defined.
3822
+	 * @return void
3823
+	 * @throws EE_Error
3824
+	 */
3825
+	protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3826
+	{
3827
+		$user_id = get_current_user_id();
3828
+		if (! $skip_route_verify) {
3829
+			$this->_verify_route($route);
3830
+		}
3831
+		// now let's set the string for what kind of transient we're setting
3832
+		$transient = $notices
3833
+			? 'ee_rte_n_tx_' . $route . '_' . $user_id
3834
+			: 'rte_tx_' . $route . '_' . $user_id;
3835
+		$data      = $notices ? ['notices' => $data] : $data;
3836
+		// is there already a transient for this route?  If there is then let's ADD to that transient
3837
+		$existing = is_multisite() && is_network_admin()
3838
+			? get_site_transient($transient)
3839
+			: get_transient($transient);
3840
+		if ($existing) {
3841
+			$data = array_merge((array) $data, (array) $existing);
3842
+		}
3843
+		if (is_multisite() && is_network_admin()) {
3844
+			set_site_transient($transient, $data, 8);
3845
+		} else {
3846
+			set_transient($transient, $data, 8);
3847
+		}
3848
+	}
3849
+
3850
+
3851
+	/**
3852
+	 * this retrieves the temporary transient that has been set for moving data between routes.
3853
+	 *
3854
+	 * @param bool   $notices true we get notices transient. False we just return normal route transient
3855
+	 * @param string $route
3856
+	 * @return mixed data
3857
+	 */
3858
+	protected function _get_transient($notices = false, $route = '')
3859
+	{
3860
+		$user_id   = get_current_user_id();
3861
+		$route     = ! $route ? $this->_req_action : $route;
3862
+		$transient = $notices
3863
+			? 'ee_rte_n_tx_' . $route . '_' . $user_id
3864
+			: 'rte_tx_' . $route . '_' . $user_id;
3865
+		$data      = is_multisite() && is_network_admin()
3866
+			? get_site_transient($transient)
3867
+			: get_transient($transient);
3868
+		// delete transient after retrieval (just in case it hasn't expired);
3869
+		if (is_multisite() && is_network_admin()) {
3870
+			delete_site_transient($transient);
3871
+		} else {
3872
+			delete_transient($transient);
3873
+		}
3874
+		return $notices && isset($data['notices']) ? $data['notices'] : $data;
3875
+	}
3876
+
3877
+
3878
+	/**
3879
+	 * The purpose of this method is just to run garbage collection on any EE transients that might have expired but
3880
+	 * would not be called later. This will be assigned to run on a specific EE Admin page. (place the method in the
3881
+	 * default route callback on the EE_Admin page you want it run.)
3882
+	 *
3883
+	 * @return void
3884
+	 */
3885
+	protected function _transient_garbage_collection()
3886
+	{
3887
+		global $wpdb;
3888
+		// retrieve all existing transients
3889
+		$query =
3890
+			"SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '%rte_tx_%' OR option_name LIKE '%rte_n_tx_%'";
3891
+		if ($results = $wpdb->get_results($query)) {
3892
+			foreach ($results as $result) {
3893
+				$transient = str_replace('_transient_', '', $result->option_name);
3894
+				get_transient($transient);
3895
+				if (is_multisite() && is_network_admin()) {
3896
+					get_site_transient($transient);
3897
+				}
3898
+			}
3899
+		}
3900
+	}
3901
+
3902
+
3903
+	/**
3904
+	 * get_view
3905
+	 *
3906
+	 * @return string content of _view property
3907
+	 */
3908
+	public function get_view()
3909
+	{
3910
+		return $this->_view;
3911
+	}
3912
+
3913
+
3914
+	/**
3915
+	 * getter for the protected $_views property
3916
+	 *
3917
+	 * @return array
3918
+	 */
3919
+	public function get_views()
3920
+	{
3921
+		return $this->_views;
3922
+	}
3923
+
3924
+
3925
+	/**
3926
+	 * get_current_page
3927
+	 *
3928
+	 * @return string _current_page property value
3929
+	 */
3930
+	public function get_current_page()
3931
+	{
3932
+		return $this->_current_page;
3933
+	}
3934
+
3935
+
3936
+	/**
3937
+	 * get_current_view
3938
+	 *
3939
+	 * @return string _current_view property value
3940
+	 */
3941
+	public function get_current_view()
3942
+	{
3943
+		return $this->_current_view;
3944
+	}
3945
+
3946
+
3947
+	/**
3948
+	 * get_current_screen
3949
+	 *
3950
+	 * @return object The current WP_Screen object
3951
+	 */
3952
+	public function get_current_screen()
3953
+	{
3954
+		return $this->_current_screen;
3955
+	}
3956
+
3957
+
3958
+	/**
3959
+	 * get_current_page_view_url
3960
+	 *
3961
+	 * @return string This returns the url for the current_page_view.
3962
+	 */
3963
+	public function get_current_page_view_url()
3964
+	{
3965
+		return $this->_current_page_view_url;
3966
+	}
3967
+
3968
+
3969
+	/**
3970
+	 * just returns the _req_data property
3971
+	 *
3972
+	 * @return array
3973
+	 */
3974
+	public function get_request_data()
3975
+	{
3976
+		return $this->request->requestParams();
3977
+	}
3978
+
3979
+
3980
+	/**
3981
+	 * returns the _req_data protected property
3982
+	 *
3983
+	 * @return string
3984
+	 */
3985
+	public function get_req_action()
3986
+	{
3987
+		return $this->_req_action;
3988
+	}
3989
+
3990
+
3991
+	/**
3992
+	 * @return bool  value of $_is_caf property
3993
+	 */
3994
+	public function is_caf()
3995
+	{
3996
+		return $this->_is_caf;
3997
+	}
3998
+
3999
+
4000
+	/**
4001
+	 * @return mixed
4002
+	 */
4003
+	public function default_espresso_metaboxes()
4004
+	{
4005
+		return $this->_default_espresso_metaboxes;
4006
+	}
4007
+
4008
+
4009
+	/**
4010
+	 * @return mixed
4011
+	 */
4012
+	public function admin_base_url()
4013
+	{
4014
+		return $this->_admin_base_url;
4015
+	}
4016
+
4017
+
4018
+	/**
4019
+	 * @return mixed
4020
+	 */
4021
+	public function wp_page_slug()
4022
+	{
4023
+		return $this->_wp_page_slug;
4024
+	}
4025
+
4026
+
4027
+	/**
4028
+	 * updates  espresso configuration settings
4029
+	 *
4030
+	 * @param string                   $tab
4031
+	 * @param EE_Config_Base|EE_Config $config
4032
+	 * @param string                   $file file where error occurred
4033
+	 * @param string                   $func function  where error occurred
4034
+	 * @param string                   $line line no where error occurred
4035
+	 * @return boolean
4036
+	 */
4037
+	protected function _update_espresso_configuration($tab, $config, $file = '', $func = '', $line = '')
4038
+	{
4039
+		// remove any options that are NOT going to be saved with the config settings.
4040
+		if (isset($config->core->ee_ueip_optin)) {
4041
+			// TODO: remove the following two lines and make sure values are migrated from 3.1
4042
+			update_option('ee_ueip_optin', $config->core->ee_ueip_optin);
4043
+			update_option('ee_ueip_has_notified', true);
4044
+		}
4045
+		// and save it (note we're also doing the network save here)
4046
+		$net_saved    = is_main_site() ? EE_Network_Config::instance()->update_config(false, false) : true;
4047
+		$config_saved = EE_Config::instance()->update_espresso_config(false, false);
4048
+		if ($config_saved && $net_saved) {
4049
+			EE_Error::add_success(sprintf(__('"%s" have been successfully updated.', 'event_espresso'), $tab));
4050
+			return true;
4051
+		}
4052
+		EE_Error::add_error(sprintf(__('The "%s" were not updated.', 'event_espresso'), $tab), $file, $func, $line);
4053
+		return false;
4054
+	}
4055
+
4056
+
4057
+	/**
4058
+	 * Returns an array to be used for EE_FOrm_Fields.helper.php's select_input as the $values argument.
4059
+	 *
4060
+	 * @return array
4061
+	 */
4062
+	public function get_yes_no_values()
4063
+	{
4064
+		return $this->_yes_no_values;
4065
+	}
4066
+
4067
+
4068
+	protected function _get_dir()
4069
+	{
4070
+		$reflector = new ReflectionClass(get_class($this));
4071
+		return dirname($reflector->getFileName());
4072
+	}
4073
+
4074
+
4075
+	/**
4076
+	 * A helper for getting a "next link".
4077
+	 *
4078
+	 * @param string $url   The url to link to
4079
+	 * @param string $class The class to use.
4080
+	 * @return string
4081
+	 */
4082
+	protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4083
+	{
4084
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
4085
+	}
4086
+
4087
+
4088
+	/**
4089
+	 * A helper for getting a "previous link".
4090
+	 *
4091
+	 * @param string $url   The url to link to
4092
+	 * @param string $class The class to use.
4093
+	 * @return string
4094
+	 */
4095
+	protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4096
+	{
4097
+		return '<a class="' . $class . '" href="' . $url . '"></a>';
4098
+	}
4099
+
4100
+
4101
+
4102
+
4103
+
4104
+
4105
+
4106
+	// below are some messages related methods that should be available across the EE_Admin system.  Note, these methods are NOT page specific
4107
+
4108
+
4109
+	/**
4110
+	 * This processes an request to resend a registration and assumes we have a _REG_ID for doing so. So if the caller
4111
+	 * knows that the _REG_ID isn't in the req_data array but CAN obtain it, the caller should ADD the _REG_ID to the
4112
+	 * _req_data array.
4113
+	 *
4114
+	 * @return bool success/fail
4115
+	 * @throws EE_Error
4116
+	 * @throws InvalidArgumentException
4117
+	 * @throws ReflectionException
4118
+	 * @throws InvalidDataTypeException
4119
+	 * @throws InvalidInterfaceException
4120
+	 */
4121
+	protected function _process_resend_registration()
4122
+	{
4123
+		$this->_template_args['success'] = EED_Messages::process_resend($this->request->requestParams());
4124
+		do_action(
4125
+			'AHEE__EE_Admin_Page___process_resend_registration',
4126
+			$this->_template_args['success'],
4127
+			$this->request->requestParams()
4128
+		);
4129
+		return $this->_template_args['success'];
4130
+	}
4131
+
4132
+
4133
+	/**
4134
+	 * This automatically processes any payment message notifications when manual payment has been applied.
4135
+	 *
4136
+	 * @param EE_Payment $payment
4137
+	 * @return bool success/fail
4138
+	 */
4139
+	protected function _process_payment_notification(EE_Payment $payment)
4140
+	{
4141
+		add_filter('FHEE__EE_Payment_Processor__process_registration_payments__display_notifications', '__return_true');
4142
+		do_action('AHEE__EE_Admin_Page___process_admin_payment_notification', $payment);
4143
+		$this->_template_args['success'] = apply_filters(
4144
+			'FHEE__EE_Admin_Page___process_admin_payment_notification__success',
4145
+			false,
4146
+			$payment
4147
+		);
4148
+		return $this->_template_args['success'];
4149
+	}
4150 4150
 }
Please login to merge, or discard this patch.
Spacing   +182 added lines, -182 removed lines patch added patch discarded remove patch
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
         $ee_menu_slugs = (array) $ee_menu_slugs;
514 514
         if (
515 515
             ! defined('DOING_AJAX')
516
-            && (! $this->_current_page || ! isset($ee_menu_slugs[ $this->_current_page ]))
516
+            && ( ! $this->_current_page || ! isset($ee_menu_slugs[$this->_current_page]))
517 517
         ) {
518 518
             return;
519 519
         }
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
             ? $route
533 533
             : $req_action;
534 534
         $this->_current_view = $this->_req_action;
535
-        $this->_req_nonce    = $this->_req_action . '_nonce';
535
+        $this->_req_nonce    = $this->_req_action.'_nonce';
536 536
         $this->_define_page_props();
537 537
         $this->_current_page_view_url = add_query_arg(
538 538
             ['page' => $this->_current_page, 'action' => $this->_current_view],
@@ -570,21 +570,21 @@  discard block
 block discarded – undo
570 570
         }
571 571
         // filter routes and page_config so addons can add their stuff. Filtering done per class
572 572
         $this->_page_routes = apply_filters(
573
-            'FHEE__' . get_class($this) . '__page_setup__page_routes',
573
+            'FHEE__'.get_class($this).'__page_setup__page_routes',
574 574
             $this->_page_routes,
575 575
             $this
576 576
         );
577 577
         $this->_page_config = apply_filters(
578
-            'FHEE__' . get_class($this) . '__page_setup__page_config',
578
+            'FHEE__'.get_class($this).'__page_setup__page_config',
579 579
             $this->_page_config,
580 580
             $this
581 581
         );
582 582
         // if AHEE__EE_Admin_Page__route_admin_request_$this->_current_view method is present
583 583
         // then we call it hooked into the AHEE__EE_Admin_Page__route_admin_request action
584
-        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view)) {
584
+        if (method_exists($this, 'AHEE__EE_Admin_Page__route_admin_request_'.$this->_current_view)) {
585 585
             add_action(
586 586
                 'AHEE__EE_Admin_Page__route_admin_request',
587
-                [$this, 'AHEE__EE_Admin_Page__route_admin_request_' . $this->_current_view],
587
+                [$this, 'AHEE__EE_Admin_Page__route_admin_request_'.$this->_current_view],
588 588
                 10,
589 589
                 2
590 590
             );
@@ -597,8 +597,8 @@  discard block
 block discarded – undo
597 597
             if ($this->_is_UI_request) {
598 598
                 // admin_init stuff - global, all views for this page class, specific view
599 599
                 add_action('admin_init', [$this, 'admin_init'], 10);
600
-                if (method_exists($this, 'admin_init_' . $this->_current_view)) {
601
-                    add_action('admin_init', [$this, 'admin_init_' . $this->_current_view], 15);
600
+                if (method_exists($this, 'admin_init_'.$this->_current_view)) {
601
+                    add_action('admin_init', [$this, 'admin_init_'.$this->_current_view], 15);
602 602
                 }
603 603
             } else {
604 604
                 // hijack regular WP loading and route admin request immediately
@@ -618,12 +618,12 @@  discard block
 block discarded – undo
618 618
      */
619 619
     private function _do_other_page_hooks()
620 620
     {
621
-        $registered_pages = apply_filters('FHEE_do_other_page_hooks_' . $this->page_slug, []);
621
+        $registered_pages = apply_filters('FHEE_do_other_page_hooks_'.$this->page_slug, []);
622 622
         foreach ($registered_pages as $page) {
623 623
             // now let's setup the file name and class that should be present
624 624
             $classname = str_replace('.class.php', '', $page);
625 625
             // autoloaders should take care of loading file
626
-            if (! class_exists($classname)) {
626
+            if ( ! class_exists($classname)) {
627 627
                 $error_msg[] = sprintf(
628 628
                     esc_html__(
629 629
                         'Something went wrong with loading the %s admin hooks page.',
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
                                    ),
641 641
                                    $page,
642 642
                                    '<br />',
643
-                                   '<strong>' . $classname . '</strong>'
643
+                                   '<strong>'.$classname.'</strong>'
644 644
                                );
645 645
                 throw new EE_Error(implode('||', $error_msg));
646 646
             }
@@ -683,13 +683,13 @@  discard block
 block discarded – undo
683 683
         // load admin_notices - global, page class, and view specific
684 684
         add_action('admin_notices', [$this, 'admin_notices_global'], 5);
685 685
         add_action('admin_notices', [$this, 'admin_notices'], 10);
686
-        if (method_exists($this, 'admin_notices_' . $this->_current_view)) {
687
-            add_action('admin_notices', [$this, 'admin_notices_' . $this->_current_view], 15);
686
+        if (method_exists($this, 'admin_notices_'.$this->_current_view)) {
687
+            add_action('admin_notices', [$this, 'admin_notices_'.$this->_current_view], 15);
688 688
         }
689 689
         // load network admin_notices - global, page class, and view specific
690 690
         add_action('network_admin_notices', [$this, 'network_admin_notices_global'], 5);
691
-        if (method_exists($this, 'network_admin_notices_' . $this->_current_view)) {
692
-            add_action('network_admin_notices', [$this, 'network_admin_notices_' . $this->_current_view]);
691
+        if (method_exists($this, 'network_admin_notices_'.$this->_current_view)) {
692
+            add_action('network_admin_notices', [$this, 'network_admin_notices_'.$this->_current_view]);
693 693
         }
694 694
         // this will save any per_page screen options if they are present
695 695
         $this->_set_per_page_screen_options();
@@ -811,7 +811,7 @@  discard block
 block discarded – undo
811 811
     protected function _verify_routes()
812 812
     {
813 813
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
814
-        if (! $this->_current_page && ! defined('DOING_AJAX')) {
814
+        if ( ! $this->_current_page && ! defined('DOING_AJAX')) {
815 815
             return false;
816 816
         }
817 817
         $this->_route = false;
@@ -823,7 +823,7 @@  discard block
 block discarded – undo
823 823
                 $this->_admin_page_title
824 824
             );
825 825
             // developer error msg
826
-            $error_msg .= '||' . $error_msg
826
+            $error_msg .= '||'.$error_msg
827 827
                           . esc_html__(
828 828
                               ' Make sure the "set_page_routes()" method exists, and is setting the "_page_routes" array properly.',
829 829
                               'event_espresso'
@@ -832,9 +832,9 @@  discard block
 block discarded – undo
832 832
         }
833 833
         // and that the requested page route exists
834 834
         if (array_key_exists($this->_req_action, $this->_page_routes)) {
835
-            $this->_route        = $this->_page_routes[ $this->_req_action ];
836
-            $this->_route_config = isset($this->_page_config[ $this->_req_action ])
837
-                ? $this->_page_config[ $this->_req_action ] : [];
835
+            $this->_route        = $this->_page_routes[$this->_req_action];
836
+            $this->_route_config = isset($this->_page_config[$this->_req_action])
837
+                ? $this->_page_config[$this->_req_action] : [];
838 838
         } else {
839 839
             // user error msg
840 840
             $error_msg = sprintf(
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
                 $this->_admin_page_title
846 846
             );
847 847
             // developer error msg
848
-            $error_msg .= '||' . $error_msg
848
+            $error_msg .= '||'.$error_msg
849 849
                           . sprintf(
850 850
                               esc_html__(
851 851
                                   ' Create a key in the "_page_routes" array named "%s" and set its value to the appropriate method.',
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
             throw new EE_Error($error_msg);
857 857
         }
858 858
         // and that a default route exists
859
-        if (! array_key_exists('default', $this->_page_routes)) {
859
+        if ( ! array_key_exists('default', $this->_page_routes)) {
860 860
             // user error msg
861 861
             $error_msg = sprintf(
862 862
                 esc_html__(
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
                 $this->_admin_page_title
867 867
             );
868 868
             // developer error msg
869
-            $error_msg .= '||' . $error_msg
869
+            $error_msg .= '||'.$error_msg
870 870
                           . esc_html__(
871 871
                               ' Create a key in the "_page_routes" array named "default" and set its value to your default page method.',
872 872
                               'event_espresso'
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
             $this->_admin_page_title
908 908
         );
909 909
         // developer error msg
910
-        $error_msg .= '||' . $error_msg
910
+        $error_msg .= '||'.$error_msg
911 911
                       . sprintf(
912 912
                           esc_html__(
913 913
                               ' Check the route you are using in your method (%s) and make sure it matches a route set in your "_page_routes" array property',
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
     protected function _verify_nonce($nonce, $nonce_ref)
933 933
     {
934 934
         // verify nonce against expected value
935
-        if (! wp_verify_nonce($nonce, $nonce_ref)) {
935
+        if ( ! wp_verify_nonce($nonce, $nonce_ref)) {
936 936
             // these are not the droids you are looking for !!!
937 937
             $msg = sprintf(
938 938
                 esc_html__('%sNonce Fail.%s', 'event_espresso'),
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
                     __CLASS__
950 950
                 );
951 951
             }
952
-            if (! defined('DOING_AJAX')) {
952
+            if ( ! defined('DOING_AJAX')) {
953 953
                 wp_die($msg);
954 954
             }
955 955
             EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
      */
974 974
     protected function _route_admin_request()
975 975
     {
976
-        if (! $this->_is_UI_request) {
976
+        if ( ! $this->_is_UI_request) {
977 977
             $this->_verify_routes();
978 978
         }
979 979
         $nonce_check = ! isset($this->_route_config['require_nonce']) || $this->_route_config['require_nonce'];
@@ -993,7 +993,7 @@  discard block
 block discarded – undo
993 993
         $error_msg = '';
994 994
         // action right before calling route
995 995
         // (hook is something like 'AHEE__Registrations_Admin_Page__route_admin_request')
996
-        if (! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
996
+        if ( ! did_action('AHEE__EE_Admin_Page__route_admin_request')) {
997 997
             do_action('AHEE__EE_Admin_Page__route_admin_request', $this->_current_view, $this);
998 998
         }
999 999
         // right before calling the route, let's remove _wp_http_referer from the
@@ -1002,7 +1002,7 @@  discard block
 block discarded – undo
1002 1002
             '_wp_http_referer',
1003 1003
             wp_unslash($_SERVER['REQUEST_URI'])
1004 1004
         );
1005
-        if (! empty($func)) {
1005
+        if ( ! empty($func)) {
1006 1006
             if (is_array($func)) {
1007 1007
                 list($class, $method) = $func;
1008 1008
             } elseif (strpos($func, '::') !== false) {
@@ -1011,7 +1011,7 @@  discard block
 block discarded – undo
1011 1011
                 $class  = $this;
1012 1012
                 $method = $func;
1013 1013
             }
1014
-            if (! (is_object($class) && $class === $this)) {
1014
+            if ( ! (is_object($class) && $class === $this)) {
1015 1015
                 // send along this admin page object for access by addons.
1016 1016
                 $args['admin_page_object'] = $this;
1017 1017
             }
@@ -1051,7 +1051,7 @@  discard block
 block discarded – undo
1051 1051
                     $method
1052 1052
                 );
1053 1053
             }
1054
-            if (! empty($error_msg)) {
1054
+            if ( ! empty($error_msg)) {
1055 1055
                 throw new EE_Error($error_msg);
1056 1056
             }
1057 1057
         }
@@ -1135,7 +1135,7 @@  discard block
 block discarded – undo
1135 1135
                 if (strpos($key, 'nonce') !== false) {
1136 1136
                     continue;
1137 1137
                 }
1138
-                $args[ 'wp_referer[' . $key . ']' ] = $value;
1138
+                $args['wp_referer['.$key.']'] = $value;
1139 1139
             }
1140 1140
         }
1141 1141
         return EEH_URL::add_query_args_and_nonce($args, $url, $exclude_nonce);
@@ -1175,8 +1175,8 @@  discard block
 block discarded – undo
1175 1175
     protected function _add_help_tabs()
1176 1176
     {
1177 1177
         $tour_buttons = '';
1178
-        if (isset($this->_page_config[ $this->_req_action ])) {
1179
-            $config = $this->_page_config[ $this->_req_action ];
1178
+        if (isset($this->_page_config[$this->_req_action])) {
1179
+            $config = $this->_page_config[$this->_req_action];
1180 1180
             // disabled temporarily. see: https://github.com/eventespresso/eventsmart.com-website/issues/836
1181 1181
             // is there a help tour for the current route?  if there is let's setup the tour buttons
1182 1182
             // if (isset($this->_help_tour[ $this->_req_action ])) {
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
             // let's see if there is a help_sidebar set for the current route and we'll set that up for usage as well.
1200 1200
             if (is_array($config) && isset($config['help_sidebar'])) {
1201 1201
                 // check that the callback given is valid
1202
-                if (! method_exists($this, $config['help_sidebar'])) {
1202
+                if ( ! method_exists($this, $config['help_sidebar'])) {
1203 1203
                     throw new EE_Error(
1204 1204
                         sprintf(
1205 1205
                             esc_html__(
@@ -1212,7 +1212,7 @@  discard block
 block discarded – undo
1212 1212
                     );
1213 1213
                 }
1214 1214
                 $content = apply_filters(
1215
-                    'FHEE__' . get_class($this) . '__add_help_tabs__help_sidebar',
1215
+                    'FHEE__'.get_class($this).'__add_help_tabs__help_sidebar',
1216 1216
                     $this->{$config['help_sidebar']}()
1217 1217
                 );
1218 1218
                 $content .= $tour_buttons; // add help tour buttons.
@@ -1220,27 +1220,27 @@  discard block
 block discarded – undo
1220 1220
                 $this->_current_screen->set_help_sidebar($content);
1221 1221
             }
1222 1222
             // if we DON'T have config help sidebar and there ARE tour buttons then we'll just add the tour buttons to the sidebar.
1223
-            if (! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1223
+            if ( ! isset($config['help_sidebar']) && ! empty($tour_buttons)) {
1224 1224
                 $this->_current_screen->set_help_sidebar($tour_buttons);
1225 1225
             }
1226 1226
             // handle if no help_tabs are set so the sidebar will still show for the help tour buttons
1227
-            if (! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1227
+            if ( ! isset($config['help_tabs']) && ! empty($tour_buttons)) {
1228 1228
                 $_ht['id']      = $this->page_slug;
1229 1229
                 $_ht['title']   = esc_html__('Help Tours', 'event_espresso');
1230 1230
                 $_ht['content'] = '<p>'
1231 1231
                                   . esc_html__(
1232 1232
                                       'The buttons to the right allow you to start/restart any help tours available for this page',
1233 1233
                                       'event_espresso'
1234
-                                  ) . '</p>';
1234
+                                  ).'</p>';
1235 1235
                 $this->_current_screen->add_help_tab($_ht);
1236 1236
             }
1237
-            if (! isset($config['help_tabs'])) {
1237
+            if ( ! isset($config['help_tabs'])) {
1238 1238
                 return;
1239 1239
             } //no help tabs for this route
1240 1240
             foreach ((array) $config['help_tabs'] as $tab_id => $cfg) {
1241 1241
                 // we're here so there ARE help tabs!
1242 1242
                 // make sure we've got what we need
1243
-                if (! isset($cfg['title'])) {
1243
+                if ( ! isset($cfg['title'])) {
1244 1244
                     throw new EE_Error(
1245 1245
                         esc_html__(
1246 1246
                             'The _page_config array is not set up properly for help tabs.  It is missing a title',
@@ -1248,7 +1248,7 @@  discard block
 block discarded – undo
1248 1248
                         )
1249 1249
                     );
1250 1250
                 }
1251
-                if (! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1251
+                if ( ! isset($cfg['filename']) && ! isset($cfg['callback']) && ! isset($cfg['content'])) {
1252 1252
                     throw new EE_Error(
1253 1253
                         esc_html__(
1254 1254
                             'The _page_config array is not setup properly for help tabs. It is missing a either a filename reference, or a callback reference or a content reference so there is no way to know the content for the help tab',
@@ -1257,11 +1257,11 @@  discard block
 block discarded – undo
1257 1257
                     );
1258 1258
                 }
1259 1259
                 // first priority goes to content.
1260
-                if (! empty($cfg['content'])) {
1260
+                if ( ! empty($cfg['content'])) {
1261 1261
                     $content = ! empty($cfg['content']) ? $cfg['content'] : null;
1262 1262
                     // second priority goes to filename
1263
-                } elseif (! empty($cfg['filename'])) {
1264
-                    $file_path = $this->_get_dir() . '/help_tabs/' . $cfg['filename'] . '.help_tab.php';
1263
+                } elseif ( ! empty($cfg['filename'])) {
1264
+                    $file_path = $this->_get_dir().'/help_tabs/'.$cfg['filename'].'.help_tab.php';
1265 1265
                     // it's possible that the file is located on decaf route (and above sets up for caf route, if this is the case then lets check decaf route too)
1266 1266
                     $file_path = ! is_readable($file_path) ? EE_ADMIN_PAGES
1267 1267
                                                              . basename($this->_get_dir())
@@ -1269,7 +1269,7 @@  discard block
 block discarded – undo
1269 1269
                                                              . $cfg['filename']
1270 1270
                                                              . '.help_tab.php' : $file_path;
1271 1271
                     // if file is STILL not readable then let's do a EE_Error so its more graceful than a fatal error.
1272
-                    if (! isset($cfg['callback']) && ! is_readable($file_path)) {
1272
+                    if ( ! isset($cfg['callback']) && ! is_readable($file_path)) {
1273 1273
                         EE_Error::add_error(
1274 1274
                             sprintf(
1275 1275
                                 esc_html__(
@@ -1316,7 +1316,7 @@  discard block
 block discarded – undo
1316 1316
                     return;
1317 1317
                 }
1318 1318
                 // setup config array for help tab method
1319
-                $id  = $this->page_slug . '-' . $this->_req_action . '-' . $tab_id;
1319
+                $id  = $this->page_slug.'-'.$this->_req_action.'-'.$tab_id;
1320 1320
                 $_ht = [
1321 1321
                     'id'       => $id,
1322 1322
                     'title'    => $cfg['title'],
@@ -1443,8 +1443,8 @@  discard block
 block discarded – undo
1443 1443
             $qtips = (array) $this->_route_config['qtips'];
1444 1444
             // load qtip loader
1445 1445
             $path = [
1446
-                $this->_get_dir() . '/qtips/',
1447
-                EE_ADMIN_PAGES . basename($this->_get_dir()) . '/qtips/',
1446
+                $this->_get_dir().'/qtips/',
1447
+                EE_ADMIN_PAGES.basename($this->_get_dir()).'/qtips/',
1448 1448
             ];
1449 1449
             EEH_Qtip_Loader::instance()->register($qtips, $path);
1450 1450
         }
@@ -1466,7 +1466,7 @@  discard block
 block discarded – undo
1466 1466
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1467 1467
         $i = 0;
1468 1468
         foreach ($this->_page_config as $slug => $config) {
1469
-            if (! is_array($config) || empty($config['nav'])) {
1469
+            if ( ! is_array($config) || empty($config['nav'])) {
1470 1470
                 continue;
1471 1471
             }
1472 1472
             // no nav tab for this config
@@ -1475,12 +1475,12 @@  discard block
 block discarded – undo
1475 1475
                 // nav tab is only to appear when route requested.
1476 1476
                 continue;
1477 1477
             }
1478
-            if (! $this->check_user_access($slug, true)) {
1478
+            if ( ! $this->check_user_access($slug, true)) {
1479 1479
                 // no nav tab because current user does not have access.
1480 1480
                 continue;
1481 1481
             }
1482
-            $css_class                = isset($config['css_class']) ? $config['css_class'] . ' ' : '';
1483
-            $this->_nav_tabs[ $slug ] = [
1482
+            $css_class                = isset($config['css_class']) ? $config['css_class'].' ' : '';
1483
+            $this->_nav_tabs[$slug] = [
1484 1484
                 'url'       => isset($config['nav']['url'])
1485 1485
                     ? $config['nav']['url']
1486 1486
                     : self::add_query_args_and_nonce(
@@ -1492,14 +1492,14 @@  discard block
 block discarded – undo
1492 1492
                     : ucwords(
1493 1493
                         str_replace('_', ' ', $slug)
1494 1494
                     ),
1495
-                'css_class' => $this->_req_action === $slug ? $css_class . 'nav-tab-active' : $css_class,
1495
+                'css_class' => $this->_req_action === $slug ? $css_class.'nav-tab-active' : $css_class,
1496 1496
                 'order'     => isset($config['nav']['order']) ? $config['nav']['order'] : $i,
1497 1497
             ];
1498 1498
             $i++;
1499 1499
         }
1500 1500
         // if $this->_nav_tabs is empty then lets set the default
1501 1501
         if (empty($this->_nav_tabs)) {
1502
-            $this->_nav_tabs[ $this->_default_nav_tab_name ] = [
1502
+            $this->_nav_tabs[$this->_default_nav_tab_name] = [
1503 1503
                 'url'       => $this->_admin_base_url,
1504 1504
                 'link_text' => ucwords(str_replace('_', ' ', $this->_default_nav_tab_name)),
1505 1505
                 'css_class' => 'nav-tab-active',
@@ -1524,10 +1524,10 @@  discard block
 block discarded – undo
1524 1524
             foreach ($this->_route_config['labels'] as $label => $text) {
1525 1525
                 if (is_array($text)) {
1526 1526
                     foreach ($text as $sublabel => $subtext) {
1527
-                        $this->_labels[ $label ][ $sublabel ] = $subtext;
1527
+                        $this->_labels[$label][$sublabel] = $subtext;
1528 1528
                     }
1529 1529
                 } else {
1530
-                    $this->_labels[ $label ] = $text;
1530
+                    $this->_labels[$label] = $text;
1531 1531
                 }
1532 1532
             }
1533 1533
         }
@@ -1549,12 +1549,12 @@  discard block
 block discarded – undo
1549 1549
     {
1550 1550
         do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1551 1551
         $route_to_check = empty($route_to_check) ? $this->_req_action : $route_to_check;
1552
-        $capability     = ! empty($route_to_check) && isset($this->_page_routes[ $route_to_check ])
1552
+        $capability     = ! empty($route_to_check) && isset($this->_page_routes[$route_to_check])
1553 1553
                           && is_array(
1554
-                              $this->_page_routes[ $route_to_check ]
1554
+                              $this->_page_routes[$route_to_check]
1555 1555
                           )
1556
-                          && ! empty($this->_page_routes[ $route_to_check ]['capability'])
1557
-            ? $this->_page_routes[ $route_to_check ]['capability'] : null;
1556
+                          && ! empty($this->_page_routes[$route_to_check]['capability'])
1557
+            ? $this->_page_routes[$route_to_check]['capability'] : null;
1558 1558
         if (empty($capability) && empty($route_to_check)) {
1559 1559
             $capability = is_array($this->_route) && empty($this->_route['capability']) ? 'manage_options'
1560 1560
                 : $this->_route['capability'];
@@ -1562,7 +1562,7 @@  discard block
 block discarded – undo
1562 1562
             $capability = empty($capability) ? 'manage_options' : $capability;
1563 1563
         }
1564 1564
         $id = is_array($this->_route) && ! empty($this->_route['obj_id']) ? $this->_route['obj_id'] : 0;
1565
-        if (! defined('DOING_AJAX')
1565
+        if ( ! defined('DOING_AJAX')
1566 1566
             && (
1567 1567
                 ! function_exists('is_admin')
1568 1568
                 || ! EE_Registry::instance()->CAP->current_user_can(
@@ -1664,7 +1664,7 @@  discard block
 block discarded – undo
1664 1664
     public function admin_footer_global()
1665 1665
     {
1666 1666
         // dialog container for dialog helper
1667
-        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">' . "\n";
1667
+        $d_cont = '<div class="ee-admin-dialog-container auto-hide hidden">'."\n";
1668 1668
         $d_cont .= '<div class="ee-notices"></div>';
1669 1669
         $d_cont .= '<div class="ee-admin-dialog-container-inner-content"></div>';
1670 1670
         $d_cont .= '</div>';
@@ -1675,7 +1675,7 @@  discard block
 block discarded – undo
1675 1675
         //     echo implode('<br />', $this->_help_tour[ $this->_req_action ]);
1676 1676
         // }
1677 1677
         // current set timezone for timezone js
1678
-        echo '<span id="current_timezone" class="hidden">' . EEH_DTT_Helper::get_timezone() . '</span>';
1678
+        echo '<span id="current_timezone" class="hidden">'.EEH_DTT_Helper::get_timezone().'</span>';
1679 1679
     }
1680 1680
 
1681 1681
 
@@ -1709,7 +1709,7 @@  discard block
 block discarded – undo
1709 1709
         // loop through the array and setup content
1710 1710
         foreach ($help_array as $trigger => $help) {
1711 1711
             // make sure the array is setup properly
1712
-            if (! isset($help['title']) || ! isset($help['content'])) {
1712
+            if ( ! isset($help['title']) || ! isset($help['content'])) {
1713 1713
                 throw new EE_Error(
1714 1714
                     esc_html__(
1715 1715
                         'Does not look like the popup content array has been setup correctly.  Might want to double check that.  Read the comments for the _get_help_popup_content method found in "EE_Admin_Page" class',
@@ -1723,8 +1723,8 @@  discard block
 block discarded – undo
1723 1723
                 'help_popup_title'   => $help['title'],
1724 1724
                 'help_popup_content' => $help['content'],
1725 1725
             ];
1726
-            $content       .= EEH_Template::display_template(
1727
-                EE_ADMIN_TEMPLATE . 'admin_help_popup.template.php',
1726
+            $content .= EEH_Template::display_template(
1727
+                EE_ADMIN_TEMPLATE.'admin_help_popup.template.php',
1728 1728
                 $template_args,
1729 1729
                 true
1730 1730
             );
@@ -1746,15 +1746,15 @@  discard block
 block discarded – undo
1746 1746
     private function _get_help_content()
1747 1747
     {
1748 1748
         // what is the method we're looking for?
1749
-        $method_name = '_help_popup_content_' . $this->_req_action;
1749
+        $method_name = '_help_popup_content_'.$this->_req_action;
1750 1750
         // if method doesn't exist let's get out.
1751
-        if (! method_exists($this, $method_name)) {
1751
+        if ( ! method_exists($this, $method_name)) {
1752 1752
             return [];
1753 1753
         }
1754 1754
         // k we're good to go let's retrieve the help array
1755 1755
         $help_array = call_user_func([$this, $method_name]);
1756 1756
         // make sure we've got an array!
1757
-        if (! is_array($help_array)) {
1757
+        if ( ! is_array($help_array)) {
1758 1758
             throw new EE_Error(
1759 1759
                 esc_html__(
1760 1760
                     'Something went wrong with help popup content generation. Expecting an array and well, this ain\'t no array bub.',
@@ -1786,15 +1786,15 @@  discard block
 block discarded – undo
1786 1786
         // let's check and see if there is any content set for this popup.  If there isn't then we'll include a default title and content so that developers know something needs to be corrected
1787 1787
         $help_array   = $this->_get_help_content();
1788 1788
         $help_content = '';
1789
-        if (empty($help_array) || ! isset($help_array[ $trigger_id ])) {
1790
-            $help_array[ $trigger_id ] = [
1789
+        if (empty($help_array) || ! isset($help_array[$trigger_id])) {
1790
+            $help_array[$trigger_id] = [
1791 1791
                 'title'   => esc_html__('Missing Content', 'event_espresso'),
1792 1792
                 'content' => esc_html__(
1793 1793
                     'A trigger has been set that doesn\'t have any corresponding content. Make sure you have set the help content. (see the "_set_help_popup_content" method in the EE_Admin_Page for instructions.)',
1794 1794
                     'event_espresso'
1795 1795
                 ),
1796 1796
             ];
1797
-            $help_content              = $this->_set_help_popup_content($help_array, false);
1797
+            $help_content = $this->_set_help_popup_content($help_array, false);
1798 1798
         }
1799 1799
         // let's setup the trigger
1800 1800
         $content = '<a class="ee-dialog" href="?height='
@@ -1862,15 +1862,15 @@  discard block
 block discarded – undo
1862 1862
         // register all styles
1863 1863
         wp_register_style(
1864 1864
             'espresso-ui-theme',
1865
-            EE_GLOBAL_ASSETS_URL . 'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1865
+            EE_GLOBAL_ASSETS_URL.'css/espresso-ui-theme/jquery-ui-1.10.3.custom.min.css',
1866 1866
             [],
1867 1867
             EVENT_ESPRESSO_VERSION
1868 1868
         );
1869
-        wp_register_style('ee-admin-css', EE_ADMIN_URL . 'assets/ee-admin-page.css', [], EVENT_ESPRESSO_VERSION);
1869
+        wp_register_style('ee-admin-css', EE_ADMIN_URL.'assets/ee-admin-page.css', [], EVENT_ESPRESSO_VERSION);
1870 1870
         // helpers styles
1871 1871
         wp_register_style(
1872 1872
             'ee-text-links',
1873
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.css',
1873
+            EE_PLUGIN_DIR_URL.'core/helpers/assets/ee_text_list_helper.css',
1874 1874
             [],
1875 1875
             EVENT_ESPRESSO_VERSION
1876 1876
         );
@@ -1878,21 +1878,21 @@  discard block
 block discarded – undo
1878 1878
         // register all scripts
1879 1879
         wp_register_script(
1880 1880
             'ee-dialog',
1881
-            EE_ADMIN_URL . 'assets/ee-dialog-helper.js',
1881
+            EE_ADMIN_URL.'assets/ee-dialog-helper.js',
1882 1882
             ['jquery', 'jquery-ui-draggable'],
1883 1883
             EVENT_ESPRESSO_VERSION,
1884 1884
             true
1885 1885
         );
1886 1886
         wp_register_script(
1887 1887
             'ee_admin_js',
1888
-            EE_ADMIN_URL . 'assets/ee-admin-page.js',
1888
+            EE_ADMIN_URL.'assets/ee-admin-page.js',
1889 1889
             ['espresso_core', 'ee-parse-uri', 'ee-dialog'],
1890 1890
             EVENT_ESPRESSO_VERSION,
1891 1891
             true
1892 1892
         );
1893 1893
         wp_register_script(
1894 1894
             'jquery-ui-timepicker-addon',
1895
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery-ui-timepicker-addon.js',
1895
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery-ui-timepicker-addon.js',
1896 1896
             ['jquery-ui-datepicker', 'jquery-ui-slider'],
1897 1897
             EVENT_ESPRESSO_VERSION,
1898 1898
             true
@@ -1904,7 +1904,7 @@  discard block
 block discarded – undo
1904 1904
         // script for sorting tables
1905 1905
         wp_register_script(
1906 1906
             'espresso_ajax_table_sorting',
1907
-            EE_ADMIN_URL . 'assets/espresso_ajax_table_sorting.js',
1907
+            EE_ADMIN_URL.'assets/espresso_ajax_table_sorting.js',
1908 1908
             ['ee_admin_js', 'jquery-ui-sortable'],
1909 1909
             EVENT_ESPRESSO_VERSION,
1910 1910
             true
@@ -1912,7 +1912,7 @@  discard block
 block discarded – undo
1912 1912
         // script for parsing uri's
1913 1913
         wp_register_script(
1914 1914
             'ee-parse-uri',
1915
-            EE_GLOBAL_ASSETS_URL . 'scripts/parseuri.js',
1915
+            EE_GLOBAL_ASSETS_URL.'scripts/parseuri.js',
1916 1916
             [],
1917 1917
             EVENT_ESPRESSO_VERSION,
1918 1918
             true
@@ -1920,7 +1920,7 @@  discard block
 block discarded – undo
1920 1920
         // and parsing associative serialized form elements
1921 1921
         wp_register_script(
1922 1922
             'ee-serialize-full-array',
1923
-            EE_GLOBAL_ASSETS_URL . 'scripts/jquery.serializefullarray.js',
1923
+            EE_GLOBAL_ASSETS_URL.'scripts/jquery.serializefullarray.js',
1924 1924
             ['jquery'],
1925 1925
             EVENT_ESPRESSO_VERSION,
1926 1926
             true
@@ -1928,28 +1928,28 @@  discard block
 block discarded – undo
1928 1928
         // helpers scripts
1929 1929
         wp_register_script(
1930 1930
             'ee-text-links',
1931
-            EE_PLUGIN_DIR_URL . 'core/helpers/assets/ee_text_list_helper.js',
1931
+            EE_PLUGIN_DIR_URL.'core/helpers/assets/ee_text_list_helper.js',
1932 1932
             ['jquery'],
1933 1933
             EVENT_ESPRESSO_VERSION,
1934 1934
             true
1935 1935
         );
1936 1936
         wp_register_script(
1937 1937
             'ee-moment-core',
1938
-            EE_THIRD_PARTY_URL . 'moment/moment-with-locales.min.js',
1938
+            EE_THIRD_PARTY_URL.'moment/moment-with-locales.min.js',
1939 1939
             [],
1940 1940
             EVENT_ESPRESSO_VERSION,
1941 1941
             true
1942 1942
         );
1943 1943
         wp_register_script(
1944 1944
             'ee-moment',
1945
-            EE_THIRD_PARTY_URL . 'moment/moment-timezone-with-data.min.js',
1945
+            EE_THIRD_PARTY_URL.'moment/moment-timezone-with-data.min.js',
1946 1946
             ['ee-moment-core'],
1947 1947
             EVENT_ESPRESSO_VERSION,
1948 1948
             true
1949 1949
         );
1950 1950
         wp_register_script(
1951 1951
             'ee-datepicker',
1952
-            EE_ADMIN_URL . 'assets/ee-datepicker.js',
1952
+            EE_ADMIN_URL.'assets/ee-datepicker.js',
1953 1953
             ['jquery-ui-timepicker-addon', 'ee-moment'],
1954 1954
             EVENT_ESPRESSO_VERSION,
1955 1955
             true
@@ -2085,12 +2085,12 @@  discard block
 block discarded – undo
2085 2085
     protected function _set_list_table()
2086 2086
     {
2087 2087
         // first is this a list_table view?
2088
-        if (! isset($this->_route_config['list_table'])) {
2088
+        if ( ! isset($this->_route_config['list_table'])) {
2089 2089
             return;
2090 2090
         } //not a list_table view so get out.
2091 2091
         // list table functions are per view specific (because some admin pages might have more than one list table!)
2092
-        $list_table_view = '_set_list_table_views_' . $this->_req_action;
2093
-        if (! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2092
+        $list_table_view = '_set_list_table_views_'.$this->_req_action;
2093
+        if ( ! method_exists($this, $list_table_view) || $this->{$list_table_view}() === false) {
2094 2094
             // user error msg
2095 2095
             $error_msg = esc_html__(
2096 2096
                 'An error occurred. The requested list table views could not be found.',
@@ -2110,10 +2110,10 @@  discard block
 block discarded – undo
2110 2110
         }
2111 2111
         // let's provide the ability to filter the views per PAGE AND ROUTE, per PAGE, and globally
2112 2112
         $this->_views = apply_filters(
2113
-            'FHEE_list_table_views_' . $this->page_slug . '_' . $this->_req_action,
2113
+            'FHEE_list_table_views_'.$this->page_slug.'_'.$this->_req_action,
2114 2114
             $this->_views
2115 2115
         );
2116
-        $this->_views = apply_filters('FHEE_list_table_views_' . $this->page_slug, $this->_views);
2116
+        $this->_views = apply_filters('FHEE_list_table_views_'.$this->page_slug, $this->_views);
2117 2117
         $this->_views = apply_filters('FHEE_list_table_views', $this->_views);
2118 2118
         $this->_set_list_table_view();
2119 2119
         $this->_set_list_table_object();
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
     protected function _set_list_table_object()
2149 2149
     {
2150 2150
         if (isset($this->_route_config['list_table'])) {
2151
-            if (! class_exists($this->_route_config['list_table'])) {
2151
+            if ( ! class_exists($this->_route_config['list_table'])) {
2152 2152
                 throw new EE_Error(
2153 2153
                     sprintf(
2154 2154
                         esc_html__(
@@ -2186,15 +2186,15 @@  discard block
 block discarded – undo
2186 2186
         foreach ($this->_views as $key => $view) {
2187 2187
             $query_args = [];
2188 2188
             // check for current view
2189
-            $this->_views[ $key ]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2189
+            $this->_views[$key]['class']               = $this->_view === $view['slug'] ? 'current' : '';
2190 2190
             $query_args['action']                        = $this->_req_action;
2191
-            $query_args[ $this->_req_action . '_nonce' ] = wp_create_nonce($query_args['action'] . '_nonce');
2191
+            $query_args[$this->_req_action.'_nonce'] = wp_create_nonce($query_args['action'].'_nonce');
2192 2192
             $query_args['status']                        = $view['slug'];
2193 2193
             // merge any other arguments sent in.
2194
-            if (isset($extra_query_args[ $view['slug'] ])) {
2195
-                $query_args = array_merge($query_args, $extra_query_args[ $view['slug'] ]);
2194
+            if (isset($extra_query_args[$view['slug']])) {
2195
+                $query_args = array_merge($query_args, $extra_query_args[$view['slug']]);
2196 2196
             }
2197
-            $this->_views[ $key ]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2197
+            $this->_views[$key]['url'] = EE_Admin_Page::add_query_args_and_nonce($query_args, $this->_admin_base_url);
2198 2198
         }
2199 2199
         return $this->_views;
2200 2200
     }
@@ -2225,14 +2225,14 @@  discard block
 block discarded – undo
2225 2225
 					<select id="entries-per-page-slct" name="entries-per-page-slct">';
2226 2226
         foreach ($values as $value) {
2227 2227
             if ($value < $max_entries) {
2228
-                $selected                  = $value === $per_page ? ' selected="' . $per_page . '"' : '';
2228
+                $selected = $value === $per_page ? ' selected="'.$per_page.'"' : '';
2229 2229
                 $entries_per_page_dropdown .= '
2230
-						<option value="' . $value . '"' . $selected . '>' . $value . '&nbsp;&nbsp;</option>';
2230
+						<option value="' . $value.'"'.$selected.'>'.$value.'&nbsp;&nbsp;</option>';
2231 2231
             }
2232 2232
         }
2233
-        $selected                  = $max_entries === $per_page ? ' selected="' . $per_page . '"' : '';
2233
+        $selected = $max_entries === $per_page ? ' selected="'.$per_page.'"' : '';
2234 2234
         $entries_per_page_dropdown .= '
2235
-						<option value="' . $max_entries . '"' . $selected . '>All&nbsp;&nbsp;</option>';
2235
+						<option value="' . $max_entries.'"'.$selected.'>All&nbsp;&nbsp;</option>';
2236 2236
         $entries_per_page_dropdown .= '
2237 2237
 					</select>
2238 2238
 					entries
@@ -2256,7 +2256,7 @@  discard block
 block discarded – undo
2256 2256
             empty($this->_search_btn_label) ? $this->page_label
2257 2257
                 : $this->_search_btn_label
2258 2258
         );
2259
-        $this->_template_args['search']['callback']  = 'search_' . $this->page_slug;
2259
+        $this->_template_args['search']['callback'] = 'search_'.$this->page_slug;
2260 2260
     }
2261 2261
 
2262 2262
 
@@ -2342,7 +2342,7 @@  discard block
 block discarded – undo
2342 2342
             $total_columns                                       = ! empty($screen_columns)
2343 2343
                 ? $screen_columns
2344 2344
                 : $this->_route_config['columns'][1];
2345
-            $this->_template_args['current_screen_widget_class'] = 'columns-' . $total_columns;
2345
+            $this->_template_args['current_screen_widget_class'] = 'columns-'.$total_columns;
2346 2346
             $this->_template_args['current_page']                = $this->_wp_page_slug;
2347 2347
             $this->_template_args['screen']                      = $this->_current_screen;
2348 2348
             $this->_column_template_path                         = EE_ADMIN_TEMPLATE
@@ -2387,7 +2387,7 @@  discard block
 block discarded – undo
2387 2387
      */
2388 2388
     protected function _espresso_ratings_request()
2389 2389
     {
2390
-        if (! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2390
+        if ( ! apply_filters('FHEE_show_ratings_request_meta_box', true)) {
2391 2391
             return;
2392 2392
         }
2393 2393
         $ratings_box_title = apply_filters(
@@ -2415,7 +2415,7 @@  discard block
 block discarded – undo
2415 2415
     public function espresso_ratings_request()
2416 2416
     {
2417 2417
         EEH_Template::display_template(
2418
-            EE_ADMIN_TEMPLATE . 'espresso_ratings_request_content.template.php',
2418
+            EE_ADMIN_TEMPLATE.'espresso_ratings_request_content.template.php',
2419 2419
             []
2420 2420
         );
2421 2421
     }
@@ -2423,22 +2423,22 @@  discard block
 block discarded – undo
2423 2423
 
2424 2424
     public static function cached_rss_display($rss_id, $url)
2425 2425
     {
2426
-        $loading   = '<p class="widget-loading hide-if-no-js">'
2426
+        $loading = '<p class="widget-loading hide-if-no-js">'
2427 2427
                      . __('Loading&#8230;', 'event_espresso')
2428 2428
                      . '</p><p class="hide-if-js">'
2429 2429
                      . esc_html__('This widget requires JavaScript.', 'event_espresso')
2430 2430
                      . '</p>';
2431
-        $pre       = '<div class="espresso-rss-display">' . "\n\t";
2432
-        $pre       .= '<span id="' . $rss_id . '_url" class="hidden">' . $url . '</span>';
2433
-        $post      = '</div>' . "\n";
2434
-        $cache_key = 'ee_rss_' . md5($rss_id);
2431
+        $pre       = '<div class="espresso-rss-display">'."\n\t";
2432
+        $pre .= '<span id="'.$rss_id.'_url" class="hidden">'.$url.'</span>';
2433
+        $post      = '</div>'."\n";
2434
+        $cache_key = 'ee_rss_'.md5($rss_id);
2435 2435
         $output    = get_transient($cache_key);
2436 2436
         if ($output !== false) {
2437
-            echo $pre . $output . $post;
2437
+            echo $pre.$output.$post;
2438 2438
             return true;
2439 2439
         }
2440
-        if (! (defined('DOING_AJAX') && DOING_AJAX)) {
2441
-            echo $pre . $loading . $post;
2440
+        if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
2441
+            echo $pre.$loading.$post;
2442 2442
             return false;
2443 2443
         }
2444 2444
         ob_start();
@@ -2505,19 +2505,19 @@  discard block
 block discarded – undo
2505 2505
     public function espresso_sponsors_post_box()
2506 2506
     {
2507 2507
         EEH_Template::display_template(
2508
-            EE_ADMIN_TEMPLATE . 'admin_general_metabox_contents_espresso_sponsors.template.php'
2508
+            EE_ADMIN_TEMPLATE.'admin_general_metabox_contents_espresso_sponsors.template.php'
2509 2509
         );
2510 2510
     }
2511 2511
 
2512 2512
 
2513 2513
     private function _publish_post_box()
2514 2514
     {
2515
-        $meta_box_ref = 'espresso_' . $this->page_slug . '_editor_overview';
2515
+        $meta_box_ref = 'espresso_'.$this->page_slug.'_editor_overview';
2516 2516
         // if there is a array('label' => array('publishbox' => 'some title') ) present in the _page_config array
2517 2517
         // then we'll use that for the metabox label.
2518 2518
         // Otherwise we'll just use publish (publishbox itself could be an array of labels indexed by routes)
2519
-        if (! empty($this->_labels['publishbox'])) {
2520
-            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][ $this->_req_action ]
2519
+        if ( ! empty($this->_labels['publishbox'])) {
2520
+            $box_label = is_array($this->_labels['publishbox']) ? $this->_labels['publishbox'][$this->_req_action]
2521 2521
                 : $this->_labels['publishbox'];
2522 2522
         } else {
2523 2523
             $box_label = esc_html__('Publish', 'event_espresso');
@@ -2546,7 +2546,7 @@  discard block
 block discarded – undo
2546 2546
             ? $this->_template_args['publish_box_extra_content']
2547 2547
             : '';
2548 2548
         echo EEH_Template::display_template(
2549
-            EE_ADMIN_TEMPLATE . 'admin_details_publish_metabox.template.php',
2549
+            EE_ADMIN_TEMPLATE.'admin_details_publish_metabox.template.php',
2550 2550
             $this->_template_args,
2551 2551
             true
2552 2552
         );
@@ -2638,18 +2638,18 @@  discard block
 block discarded – undo
2638 2638
             );
2639 2639
         }
2640 2640
         $this->_template_args['publish_delete_link'] = ! empty($id) ? $delete : '';
2641
-        if (! empty($name) && ! empty($id)) {
2642
-            $hidden_field_arr[ $name ] = [
2641
+        if ( ! empty($name) && ! empty($id)) {
2642
+            $hidden_field_arr[$name] = [
2643 2643
                 'type'  => 'hidden',
2644 2644
                 'value' => $id,
2645 2645
             ];
2646
-            $hf                        = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2646
+            $hf = $this->_generate_admin_form_fields($hidden_field_arr, 'array');
2647 2647
         } else {
2648 2648
             $hf = '';
2649 2649
         }
2650 2650
         // add hidden field
2651 2651
         $this->_template_args['publish_hidden_fields'] = is_array($hf) && ! empty($name)
2652
-            ? $hf[ $name ]['field']
2652
+            ? $hf[$name]['field']
2653 2653
             : $hf;
2654 2654
     }
2655 2655
 
@@ -2751,7 +2751,7 @@  discard block
 block discarded – undo
2751 2751
         }
2752 2752
         // if $create_func is true (default) then we automatically create the function for displaying the actual meta box.  If false then we take the $callback reference passed through and use it instead (so callers can define their own callback function/method if they wish)
2753 2753
         $call_back_func = $create_func
2754
-            ? function ($post, $metabox) {
2754
+            ? function($post, $metabox) {
2755 2755
                 do_action('AHEE_log', __FILE__, __FUNCTION__, '');
2756 2756
                 echo EEH_Template::display_template(
2757 2757
                     $metabox['args']['template_path'],
@@ -2761,7 +2761,7 @@  discard block
 block discarded – undo
2761 2761
             }
2762 2762
             : $callback;
2763 2763
         add_meta_box(
2764
-            str_replace('_', '-', $action) . '-mbox',
2764
+            str_replace('_', '-', $action).'-mbox',
2765 2765
             $title,
2766 2766
             $call_back_func,
2767 2767
             $this->_wp_page_slug,
@@ -2853,9 +2853,9 @@  discard block
 block discarded – undo
2853 2853
             : 'espresso-default-admin';
2854 2854
         $template_path                                     = $sidebar
2855 2855
             ? EE_ADMIN_TEMPLATE . 'admin_details_wrapper.template.php'
2856
-            : EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar.template.php';
2856
+            : EE_ADMIN_TEMPLATE.'admin_details_wrapper_no_sidebar.template.php';
2857 2857
         if (defined('DOING_AJAX') && DOING_AJAX) {
2858
-            $template_path = EE_ADMIN_TEMPLATE . 'admin_details_wrapper_no_sidebar_ajax.template.php';
2858
+            $template_path = EE_ADMIN_TEMPLATE.'admin_details_wrapper_no_sidebar_ajax.template.php';
2859 2859
         }
2860 2860
         $template_path                                     = ! empty($this->_column_template_path)
2861 2861
             ? $this->_column_template_path : $template_path;
@@ -2895,11 +2895,11 @@  discard block
 block discarded – undo
2895 2895
     public function display_admin_caf_preview_page($utm_campaign_source = '', $display_sidebar = true)
2896 2896
     {
2897 2897
         // let's generate a default preview action button if there isn't one already present.
2898
-        $this->_labels['buttons']['buy_now']           = esc_html__(
2898
+        $this->_labels['buttons']['buy_now'] = esc_html__(
2899 2899
             'Upgrade to Event Espresso 4 Right Now',
2900 2900
             'event_espresso'
2901 2901
         );
2902
-        $buy_now_url                                   = add_query_arg(
2902
+        $buy_now_url = add_query_arg(
2903 2903
             [
2904 2904
                 'ee_ver'       => 'ee4',
2905 2905
                 'utm_source'   => 'ee4_plugin_admin',
@@ -2919,8 +2919,8 @@  discard block
 block discarded – undo
2919 2919
                 true
2920 2920
             )
2921 2921
             : $this->_template_args['preview_action_button'];
2922
-        $this->_template_args['admin_page_content']    = EEH_Template::display_template(
2923
-            EE_ADMIN_TEMPLATE . 'admin_caf_full_page_preview.template.php',
2922
+        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
2923
+            EE_ADMIN_TEMPLATE.'admin_caf_full_page_preview.template.php',
2924 2924
             $this->_template_args,
2925 2925
             true
2926 2926
         );
@@ -2969,7 +2969,7 @@  discard block
 block discarded – undo
2969 2969
         // setup search attributes
2970 2970
         $this->_set_search_attributes();
2971 2971
         $this->_template_args['current_page']     = $this->_wp_page_slug;
2972
-        $template_path                            = EE_ADMIN_TEMPLATE . 'admin_list_wrapper.template.php';
2972
+        $template_path                            = EE_ADMIN_TEMPLATE.'admin_list_wrapper.template.php';
2973 2973
         $this->_template_args['table_url']        = defined('DOING_AJAX')
2974 2974
             ? add_query_arg(['noheader' => 'true', 'route' => $this->_req_action], $this->_admin_base_url)
2975 2975
             : add_query_arg(['route' => $this->_req_action], $this->_admin_base_url);
@@ -2977,10 +2977,10 @@  discard block
 block discarded – undo
2977 2977
         $this->_template_args['current_route']    = $this->_req_action;
2978 2978
         $this->_template_args['list_table_class'] = get_class($this->_list_table_object);
2979 2979
         $ajax_sorting_callback                    = $this->_list_table_object->get_ajax_sorting_callback();
2980
-        if (! empty($ajax_sorting_callback)) {
2980
+        if ( ! empty($ajax_sorting_callback)) {
2981 2981
             $sortable_list_table_form_fields = wp_nonce_field(
2982
-                $ajax_sorting_callback . '_nonce',
2983
-                $ajax_sorting_callback . '_nonce',
2982
+                $ajax_sorting_callback.'_nonce',
2983
+                $ajax_sorting_callback.'_nonce',
2984 2984
                 false,
2985 2985
                 false
2986 2986
             );
@@ -2998,20 +2998,20 @@  discard block
 block discarded – undo
2998 2998
             isset($this->_template_args['list_table_hidden_fields'])
2999 2999
                 ? $this->_template_args['list_table_hidden_fields']
3000 3000
                 : '';
3001
-        $nonce_ref                                               = $this->_req_action . '_nonce';
3002
-        $hidden_form_fields                                      .= '<input type="hidden" name="'
3001
+        $nonce_ref = $this->_req_action.'_nonce';
3002
+        $hidden_form_fields .= '<input type="hidden" name="'
3003 3003
                                                                     . $nonce_ref
3004 3004
                                                                     . '" value="'
3005 3005
                                                                     . wp_create_nonce($nonce_ref)
3006 3006
                                                                     . '">';
3007
-        $this->_template_args['list_table_hidden_fields']        = $hidden_form_fields;
3007
+        $this->_template_args['list_table_hidden_fields'] = $hidden_form_fields;
3008 3008
         // display message about search results?
3009 3009
         $search = $this->request->getRequestParam('s');
3010 3010
         $this->_template_args['before_list_table'] .= ! empty($search)
3011
-            ? '<p class="ee-search-results">' . sprintf(
3011
+            ? '<p class="ee-search-results">'.sprintf(
3012 3012
                 esc_html__('Displaying search results for the search string: %1$s', 'event_espresso'),
3013 3013
                 trim($search, '%')
3014
-            ) . '</p>'
3014
+            ).'</p>'
3015 3015
             : '';
3016 3016
         // filter before_list_table template arg
3017 3017
         $this->_template_args['before_list_table'] = apply_filters(
@@ -3045,7 +3045,7 @@  discard block
 block discarded – undo
3045 3045
         // convert to array and filter again
3046 3046
         // arrays are easier to inject new items in a specific location,
3047 3047
         // but would not be backwards compatible, so we have to add a new filter
3048
-        $this->_template_args['after_list_table']   = implode(
3048
+        $this->_template_args['after_list_table'] = implode(
3049 3049
             " \n",
3050 3050
             (array) apply_filters(
3051 3051
                 'FHEE__EE_Admin_Page___display_admin_list_table_page__after_list_table__template_args_array',
@@ -3092,7 +3092,7 @@  discard block
 block discarded – undo
3092 3092
             $this
3093 3093
         );
3094 3094
         return EEH_Template::display_template(
3095
-            EE_ADMIN_TEMPLATE . 'admin_details_legend.template.php',
3095
+            EE_ADMIN_TEMPLATE.'admin_details_legend.template.php',
3096 3096
             $this->_template_args,
3097 3097
             true
3098 3098
         );
@@ -3199,13 +3199,13 @@  discard block
 block discarded – undo
3199 3199
                 ? $this->_template_args['before_admin_page_content']
3200 3200
                 : ''
3201 3201
         );
3202
-        $this->_template_args['after_admin_page_content']  = apply_filters(
3202
+        $this->_template_args['after_admin_page_content'] = apply_filters(
3203 3203
             "FHEE_after_admin_page_content{$this->_current_page}{$this->_current_view}",
3204 3204
             isset($this->_template_args['after_admin_page_content'])
3205 3205
                 ? $this->_template_args['after_admin_page_content']
3206 3206
                 : ''
3207 3207
         );
3208
-        $this->_template_args['after_admin_page_content']  .= $this->_set_help_popup_content();
3208
+        $this->_template_args['after_admin_page_content'] .= $this->_set_help_popup_content();
3209 3209
         // load settings page wrapper template
3210 3210
         $template_path = ! defined('DOING_AJAX')
3211 3211
             ? EE_ADMIN_TEMPLATE . 'admin_wrapper.template.php'
@@ -3305,7 +3305,7 @@  discard block
 block discarded – undo
3305 3305
             : '<input type="hidden" id="save_and_close_referrer" name="save_and_close_referrer" value="'
3306 3306
               . $referrer
3307 3307
               . '" />';
3308
-        $button_text   = ! empty($text)
3308
+        $button_text = ! empty($text)
3309 3309
             ? $text
3310 3310
             : [
3311 3311
                 esc_html__('Save', 'event_espresso'),
@@ -3315,17 +3315,17 @@  discard block
 block discarded – undo
3315 3315
         // add in a hidden index for the current page (so save and close redirects properly)
3316 3316
         $this->_template_args['save_buttons'] = $referrer_url;
3317 3317
         foreach ($button_text as $key => $button) {
3318
-            $ref                                  = $default_names[ $key ];
3318
+            $ref = $default_names[$key];
3319 3319
             $this->_template_args['save_buttons'] .= '<input type="submit" class="button-primary '
3320 3320
                                                      . $ref
3321 3321
                                                      . '" value="'
3322 3322
                                                      . $button
3323 3323
                                                      . '" name="'
3324
-                                                     . (! empty($actions) ? $actions[ $key ] : $ref)
3324
+                                                     . ( ! empty($actions) ? $actions[$key] : $ref)
3325 3325
                                                      . '" id="'
3326
-                                                     . $this->_current_view . '_' . $ref
3326
+                                                     . $this->_current_view.'_'.$ref
3327 3327
                                                      . '" />';
3328
-            if (! $both) {
3328
+            if ( ! $both) {
3329 3329
                 break;
3330 3330
             }
3331 3331
         }
@@ -3360,13 +3360,13 @@  discard block
 block discarded – undo
3360 3360
                 'An error occurred. No action was set for this page\'s form.',
3361 3361
                 'event_espresso'
3362 3362
             );
3363
-            $dev_msg  = $user_msg . "\n"
3363
+            $dev_msg = $user_msg."\n"
3364 3364
                         . sprintf(
3365 3365
                             esc_html__('The $route argument is required for the %s->%s method.', 'event_espresso'),
3366 3366
                             __FUNCTION__,
3367 3367
                             __CLASS__
3368 3368
                         );
3369
-            EE_Error::add_error($user_msg . '||' . $dev_msg, __FILE__, __FUNCTION__, __LINE__);
3369
+            EE_Error::add_error($user_msg.'||'.$dev_msg, __FILE__, __FUNCTION__, __LINE__);
3370 3370
         }
3371 3371
         // open form
3372 3372
         $this->_template_args['before_admin_page_content'] = '<form name="form" method="post" action="'
@@ -3375,9 +3375,9 @@  discard block
 block discarded – undo
3375 3375
                                                              . $route
3376 3376
                                                              . '_event_form" >';
3377 3377
         // add nonce
3378
-        $nonce                                             =
3379
-            wp_nonce_field($route . '_nonce', $route . '_nonce', false, false);
3380
-        $this->_template_args['before_admin_page_content'] .= "\n\t" . $nonce;
3378
+        $nonce =
3379
+            wp_nonce_field($route.'_nonce', $route.'_nonce', false, false);
3380
+        $this->_template_args['before_admin_page_content'] .= "\n\t".$nonce;
3381 3381
         // add REQUIRED form action
3382 3382
         $hidden_fields = [
3383 3383
             'action' => ['type' => 'hidden', 'value' => $route],
@@ -3390,7 +3390,7 @@  discard block
 block discarded – undo
3390 3390
         $form_fields = $this->_generate_admin_form_fields($hidden_fields, 'array');
3391 3391
         // add fields to form
3392 3392
         foreach ((array) $form_fields as $field_name => $form_field) {
3393
-            $this->_template_args['before_admin_page_content'] .= "\n\t" . $form_field['field'];
3393
+            $this->_template_args['before_admin_page_content'] .= "\n\t".$form_field['field'];
3394 3394
         }
3395 3395
         // close form
3396 3396
         $this->_template_args['after_admin_page_content'] = '</form>';
@@ -3481,10 +3481,10 @@  discard block
 block discarded – undo
3481 3481
         $redirect_url = isset($query_args['page']) ? admin_url('admin.php') : $this->_admin_base_url;
3482 3482
         $notices      = EE_Error::get_notices(false);
3483 3483
         // overwrite default success messages //BUT ONLY if overwrite not overridden
3484
-        if (! $override_overwrite || ! empty($notices['errors'])) {
3484
+        if ( ! $override_overwrite || ! empty($notices['errors'])) {
3485 3485
             EE_Error::overwrite_success();
3486 3486
         }
3487
-        if (! empty($what) && ! empty($action_desc) && empty($notices['errors'])) {
3487
+        if ( ! empty($what) && ! empty($action_desc) && empty($notices['errors'])) {
3488 3488
             // how many records affected ? more than one record ? or just one ?
3489 3489
             if ($success > 1) {
3490 3490
                 // set plural msg
@@ -3513,7 +3513,7 @@  discard block
 block discarded – undo
3513 3513
             }
3514 3514
         }
3515 3515
         // check that $query_args isn't something crazy
3516
-        if (! is_array($query_args)) {
3516
+        if ( ! is_array($query_args)) {
3517 3517
             $query_args = [];
3518 3518
         }
3519 3519
         /**
@@ -3542,7 +3542,7 @@  discard block
 block discarded – undo
3542 3542
             $redirect_url = admin_url('admin.php');
3543 3543
         }
3544 3544
         // merge any default query_args set in _default_route_query_args property
3545
-        if (! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3545
+        if ( ! empty($this->_default_route_query_args) && ! $this->_is_UI_request) {
3546 3546
             $args_to_merge = [];
3547 3547
             foreach ($this->_default_route_query_args as $query_param => $query_value) {
3548 3548
                 // is there a wp_referer array in our _default_route_query_args property?
@@ -3554,15 +3554,15 @@  discard block
 block discarded – undo
3554 3554
                         }
3555 3555
                         // finally we will override any arguments in the referer with
3556 3556
                         // what might be set on the _default_route_query_args array.
3557
-                        if (isset($this->_default_route_query_args[ $reference ])) {
3558
-                            $args_to_merge[ $reference ] = urlencode($this->_default_route_query_args[ $reference ]);
3557
+                        if (isset($this->_default_route_query_args[$reference])) {
3558
+                            $args_to_merge[$reference] = urlencode($this->_default_route_query_args[$reference]);
3559 3559
                         } else {
3560
-                            $args_to_merge[ $reference ] = urlencode($value);
3560
+                            $args_to_merge[$reference] = urlencode($value);
3561 3561
                         }
3562 3562
                     }
3563 3563
                     continue;
3564 3564
                 }
3565
-                $args_to_merge[ $query_param ] = $query_value;
3565
+                $args_to_merge[$query_param] = $query_value;
3566 3566
             }
3567 3567
             // now let's merge these arguments but override with what was specifically sent in to the
3568 3568
             // redirect.
@@ -3574,19 +3574,19 @@  discard block
 block discarded – undo
3574 3574
         if (isset($query_args['action'])) {
3575 3575
             // manually generate wp_nonce and merge that with the query vars
3576 3576
             // becuz the wp_nonce_url function wrecks havoc on some vars
3577
-            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'] . '_nonce');
3577
+            $query_args['_wpnonce'] = wp_create_nonce($query_args['action'].'_nonce');
3578 3578
         }
3579 3579
         // we're adding some hooks and filters in here for processing any things just before redirects
3580 3580
         // (example: an admin page has done an insert or update and we want to run something after that).
3581
-        do_action('AHEE_redirect_' . $classname . $this->_req_action, $query_args);
3581
+        do_action('AHEE_redirect_'.$classname.$this->_req_action, $query_args);
3582 3582
         $redirect_url = apply_filters(
3583
-            'FHEE_redirect_' . $classname . $this->_req_action,
3583
+            'FHEE_redirect_'.$classname.$this->_req_action,
3584 3584
             self::add_query_args_and_nonce($query_args, $redirect_url),
3585 3585
             $query_args
3586 3586
         );
3587 3587
         // check if we're doing ajax.  If we are then lets just return the results and js can handle how it wants.
3588 3588
         if (defined('DOING_AJAX')) {
3589
-            $default_data                    = [
3589
+            $default_data = [
3590 3590
                 'close'        => true,
3591 3591
                 'redirect_url' => $redirect_url,
3592 3592
                 'where'        => 'main',
@@ -3633,7 +3633,7 @@  discard block
 block discarded – undo
3633 3633
         }
3634 3634
         $this->_template_args['notices'] = EE_Error::get_notices();
3635 3635
         // IF this isn't ajax we need to create a transient for the notices using the route (however, overridden if $sticky_notices == true)
3636
-        if (! defined('DOING_AJAX') || $sticky_notices) {
3636
+        if ( ! defined('DOING_AJAX') || $sticky_notices) {
3637 3637
             $route = isset($query_args['action']) ? $query_args['action'] : 'default';
3638 3638
             $this->_add_transient(
3639 3639
                 $route,
@@ -3673,7 +3673,7 @@  discard block
 block discarded – undo
3673 3673
         $exclude_nonce = false
3674 3674
     ) {
3675 3675
         // first let's validate the action (if $base_url is FALSE otherwise validation will happen further along)
3676
-        if (empty($base_url) && ! isset($this->_page_routes[ $action ])) {
3676
+        if (empty($base_url) && ! isset($this->_page_routes[$action])) {
3677 3677
             throw new EE_Error(
3678 3678
                 sprintf(
3679 3679
                     esc_html__(
@@ -3684,7 +3684,7 @@  discard block
 block discarded – undo
3684 3684
                 )
3685 3685
             );
3686 3686
         }
3687
-        if (! isset($this->_labels['buttons'][ $type ])) {
3687
+        if ( ! isset($this->_labels['buttons'][$type])) {
3688 3688
             throw new EE_Error(
3689 3689
                 sprintf(
3690 3690
                     __(
@@ -3697,7 +3697,7 @@  discard block
 block discarded – undo
3697 3697
         }
3698 3698
         // finally check user access for this button.
3699 3699
         $has_access = $this->check_user_access($action, true);
3700
-        if (! $has_access) {
3700
+        if ( ! $has_access) {
3701 3701
             return '';
3702 3702
         }
3703 3703
         $_base_url  = ! $base_url ? $this->_admin_base_url : $base_url;
@@ -3705,11 +3705,11 @@  discard block
 block discarded – undo
3705 3705
             'action' => $action,
3706 3706
         ];
3707 3707
         // merge extra_request args but make sure our original action takes precedence and doesn't get overwritten.
3708
-        if (! empty($extra_request)) {
3708
+        if ( ! empty($extra_request)) {
3709 3709
             $query_args = array_merge($extra_request, $query_args);
3710 3710
         }
3711 3711
         $url = self::add_query_args_and_nonce($query_args, $_base_url, false, $exclude_nonce);
3712
-        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][ $type ], $class);
3712
+        return EEH_Template::get_button_or_link($url, $this->_labels['buttons'][$type], $class);
3713 3713
     }
3714 3714
 
3715 3715
 
@@ -3735,7 +3735,7 @@  discard block
 block discarded – undo
3735 3735
                 'FHEE__EE_Admin_Page___per_page_screen_options__default',
3736 3736
                 20
3737 3737
             ),
3738
-            'option'  => $this->_current_page . '_' . $this->_current_view . '_per_page',
3738
+            'option'  => $this->_current_page.'_'.$this->_current_view.'_per_page',
3739 3739
         ];
3740 3740
         // ONLY add the screen option if the user has access to it.
3741 3741
         if ($this->check_user_access($this->_current_view, true)) {
@@ -3756,7 +3756,7 @@  discard block
 block discarded – undo
3756 3756
     {
3757 3757
         if (isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options'])) {
3758 3758
             check_admin_referer('screen-options-nonce', 'screenoptionnonce');
3759
-            if (! $user = wp_get_current_user()) {
3759
+            if ( ! $user = wp_get_current_user()) {
3760 3760
                 return;
3761 3761
             }
3762 3762
             $option = $_POST['wp_screen_options']['option'];
@@ -3767,7 +3767,7 @@  discard block
 block discarded – undo
3767 3767
             $map_option = $option;
3768 3768
             $option     = str_replace('-', '_', $option);
3769 3769
             switch ($map_option) {
3770
-                case $this->_current_page . '_' . $this->_current_view . '_per_page':
3770
+                case $this->_current_page.'_'.$this->_current_view.'_per_page':
3771 3771
                     $value     = (int) $value;
3772 3772
                     $max_value = apply_filters(
3773 3773
                         'FHEE__EE_Admin_Page___set_per_page_screen_options__max_value',
@@ -3825,13 +3825,13 @@  discard block
 block discarded – undo
3825 3825
     protected function _add_transient($route, $data, $notices = false, $skip_route_verify = false)
3826 3826
     {
3827 3827
         $user_id = get_current_user_id();
3828
-        if (! $skip_route_verify) {
3828
+        if ( ! $skip_route_verify) {
3829 3829
             $this->_verify_route($route);
3830 3830
         }
3831 3831
         // now let's set the string for what kind of transient we're setting
3832 3832
         $transient = $notices
3833
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3834
-            : 'rte_tx_' . $route . '_' . $user_id;
3833
+            ? 'ee_rte_n_tx_'.$route.'_'.$user_id
3834
+            : 'rte_tx_'.$route.'_'.$user_id;
3835 3835
         $data      = $notices ? ['notices' => $data] : $data;
3836 3836
         // is there already a transient for this route?  If there is then let's ADD to that transient
3837 3837
         $existing = is_multisite() && is_network_admin()
@@ -3860,8 +3860,8 @@  discard block
 block discarded – undo
3860 3860
         $user_id   = get_current_user_id();
3861 3861
         $route     = ! $route ? $this->_req_action : $route;
3862 3862
         $transient = $notices
3863
-            ? 'ee_rte_n_tx_' . $route . '_' . $user_id
3864
-            : 'rte_tx_' . $route . '_' . $user_id;
3863
+            ? 'ee_rte_n_tx_'.$route.'_'.$user_id
3864
+            : 'rte_tx_'.$route.'_'.$user_id;
3865 3865
         $data      = is_multisite() && is_network_admin()
3866 3866
             ? get_site_transient($transient)
3867 3867
             : get_transient($transient);
@@ -4081,7 +4081,7 @@  discard block
 block discarded – undo
4081 4081
      */
4082 4082
     protected function _next_link($url, $class = 'dashicons dashicons-arrow-right')
4083 4083
     {
4084
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4084
+        return '<a class="'.$class.'" href="'.$url.'"></a>';
4085 4085
     }
4086 4086
 
4087 4087
 
@@ -4094,7 +4094,7 @@  discard block
 block discarded – undo
4094 4094
      */
4095 4095
     protected function _previous_link($url, $class = 'dashicons dashicons-arrow-left')
4096 4096
     {
4097
-        return '<a class="' . $class . '" href="' . $url . '"></a>';
4097
+        return '<a class="'.$class.'" href="'.$url.'"></a>';
4098 4098
     }
4099 4099
 
4100 4100
 
Please login to merge, or discard this patch.
core/EE_System.core.php 2 patches
Indentation   +1300 added lines, -1300 removed lines patch added patch discarded remove patch
@@ -27,1304 +27,1304 @@
 block discarded – undo
27 27
 final class EE_System implements ResettableInterface
28 28
 {
29 29
 
30
-    /**
31
-     * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
32
-     * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
33
-     */
34
-    const req_type_normal = 0;
35
-
36
-    /**
37
-     * Indicates this is a brand new installation of EE so we should install
38
-     * tables and default data etc
39
-     */
40
-    const req_type_new_activation = 1;
41
-
42
-    /**
43
-     * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
44
-     * and we just exited maintenance mode). We MUST check the database is setup properly
45
-     * and that default data is setup too
46
-     */
47
-    const req_type_reactivation = 2;
48
-
49
-    /**
50
-     * indicates that EE has been upgraded since its previous request.
51
-     * We may have data migration scripts to call and will want to trigger maintenance mode
52
-     */
53
-    const req_type_upgrade = 3;
54
-
55
-    /**
56
-     * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
57
-     */
58
-    const req_type_downgrade = 4;
59
-
60
-    /**
61
-     * @deprecated since version 4.6.0.dev.006
62
-     * Now whenever a new_activation is detected the request type is still just
63
-     * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
64
-     * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
65
-     * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
66
-     * (Specifically, when the migration manager indicates migrations are finished
67
-     * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
68
-     */
69
-    const req_type_activation_but_not_installed = 5;
70
-
71
-    /**
72
-     * option prefix for recording the activation history (like core's "espresso_db_update") of addons
73
-     */
74
-    const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
75
-
76
-    /**
77
-     * @var EE_System $_instance
78
-     */
79
-    private static $_instance;
80
-
81
-    /**
82
-     * @var EE_Registry $registry
83
-     */
84
-    private $registry;
85
-
86
-    /**
87
-     * @var LoaderInterface $loader
88
-     */
89
-    private $loader;
90
-
91
-    /**
92
-     * @var EE_Capabilities $capabilities
93
-     */
94
-    private $capabilities;
95
-
96
-    /**
97
-     * @var RequestInterface $request
98
-     */
99
-    private $request;
100
-
101
-    /**
102
-     * @var EE_Maintenance_Mode $maintenance_mode
103
-     */
104
-    private $maintenance_mode;
105
-
106
-    /**
107
-     * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
108
-     * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
109
-     *
110
-     * @var int $_req_type
111
-     */
112
-    private $_req_type;
113
-
114
-    /**
115
-     * Whether or not there was a non-micro version change in EE core version during this request
116
-     *
117
-     * @var boolean $_major_version_change
118
-     */
119
-    private $_major_version_change = false;
120
-
121
-    /**
122
-     * A Context DTO dedicated solely to identifying the current request type.
123
-     *
124
-     * @var RequestTypeContextCheckerInterface $request_type
125
-     */
126
-    private $request_type;
127
-
128
-
129
-    /**
130
-     * @singleton method used to instantiate class object
131
-     * @param EE_Registry|null         $registry
132
-     * @param LoaderInterface|null     $loader
133
-     * @param RequestInterface|null    $request
134
-     * @param EE_Maintenance_Mode|null $maintenance_mode
135
-     * @return EE_System
136
-     */
137
-    public static function instance(
138
-        EE_Registry $registry = null,
139
-        LoaderInterface $loader = null,
140
-        RequestInterface $request = null,
141
-        EE_Maintenance_Mode $maintenance_mode = null
142
-    ) {
143
-        // check if class object is instantiated
144
-        if (! self::$_instance instanceof EE_System) {
145
-            self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
146
-        }
147
-        return self::$_instance;
148
-    }
149
-
150
-
151
-    /**
152
-     * resets the instance and returns it
153
-     *
154
-     * @return EE_System
155
-     */
156
-    public static function reset()
157
-    {
158
-        self::$_instance->_req_type = null;
159
-        // make sure none of the old hooks are left hanging around
160
-        remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
-        // we need to reset the migration manager in order for it to detect DMSs properly
162
-        EE_Data_Migration_Manager::reset();
163
-        self::instance()->detect_activations_or_upgrades();
164
-        self::instance()->perform_activations_upgrades_and_migrations();
165
-        return self::instance();
166
-    }
167
-
168
-
169
-    /**
170
-     * sets hooks for running rest of system
171
-     * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
172
-     * starting EE Addons from any other point may lead to problems
173
-     *
174
-     * @param EE_Registry         $registry
175
-     * @param LoaderInterface     $loader
176
-     * @param RequestInterface    $request
177
-     * @param EE_Maintenance_Mode $maintenance_mode
178
-     */
179
-    private function __construct(
180
-        EE_Registry $registry,
181
-        LoaderInterface $loader,
182
-        RequestInterface $request,
183
-        EE_Maintenance_Mode $maintenance_mode
184
-    ) {
185
-        $this->registry = $registry;
186
-        $this->loader = $loader;
187
-        $this->request = $request;
188
-        $this->maintenance_mode = $maintenance_mode;
189
-        do_action('AHEE__EE_System__construct__begin', $this);
190
-        add_action(
191
-            'AHEE__EE_Bootstrap__load_espresso_addons',
192
-            array($this, 'loadCapabilities'),
193
-            5
194
-        );
195
-        add_action(
196
-            'AHEE__EE_Bootstrap__load_espresso_addons',
197
-            array($this, 'loadCommandBus'),
198
-            7
199
-        );
200
-        add_action(
201
-            'AHEE__EE_Bootstrap__load_espresso_addons',
202
-            array($this, 'loadPluginApi'),
203
-            9
204
-        );
205
-        // allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
206
-        add_action(
207
-            'AHEE__EE_Bootstrap__load_espresso_addons',
208
-            array($this, 'load_espresso_addons')
209
-        );
210
-        // when an ee addon is activated, we want to call the core hook(s) again
211
-        // because the newly-activated addon didn't get a chance to run at all
212
-        add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
213
-        // detect whether install or upgrade
214
-        add_action(
215
-            'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
216
-            array($this, 'detect_activations_or_upgrades'),
217
-            3
218
-        );
219
-        // load EE_Config, EE_Textdomain, etc
220
-        add_action(
221
-            'AHEE__EE_Bootstrap__load_core_configuration',
222
-            array($this, 'load_core_configuration'),
223
-            5
224
-        );
225
-        // load specifications for matching routes to current request
226
-        add_action(
227
-            'AHEE__EE_Bootstrap__load_core_configuration',
228
-            array($this, 'loadRouteMatchSpecifications')
229
-        );
230
-        // load EE_Config, EE_Textdomain, etc
231
-        add_action(
232
-            'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
233
-            array($this, 'register_shortcodes_modules_and_widgets'),
234
-            7
235
-        );
236
-        // you wanna get going? I wanna get going... let's get going!
237
-        add_action(
238
-            'AHEE__EE_Bootstrap__brew_espresso',
239
-            array($this, 'brew_espresso'),
240
-            9
241
-        );
242
-        // other housekeeping
243
-        // exclude EE critical pages from wp_list_pages
244
-        add_filter(
245
-            'wp_list_pages_excludes',
246
-            array($this, 'remove_pages_from_wp_list_pages'),
247
-            10
248
-        );
249
-        // ALL EE Addons should use the following hook point to attach their initial setup too
250
-        // it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
251
-        do_action('AHEE__EE_System__construct__complete', $this);
252
-    }
253
-
254
-
255
-    /**
256
-     * load and setup EE_Capabilities
257
-     *
258
-     * @return void
259
-     * @throws EE_Error
260
-     */
261
-    public function loadCapabilities()
262
-    {
263
-        $this->capabilities = $this->loader->getShared('EE_Capabilities');
264
-        add_action(
265
-            'AHEE__EE_Capabilities__init_caps__before_initialization',
266
-            function () {
267
-                LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
268
-            }
269
-        );
270
-    }
271
-
272
-
273
-    /**
274
-     * create and cache the CommandBus, and also add middleware
275
-     * The CapChecker middleware requires the use of EE_Capabilities
276
-     * which is why we need to load the CommandBus after Caps are set up
277
-     *
278
-     * @return void
279
-     * @throws EE_Error
280
-     */
281
-    public function loadCommandBus()
282
-    {
283
-        $this->loader->getShared(
284
-            'CommandBusInterface',
285
-            array(
286
-                null,
287
-                apply_filters(
288
-                    'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
289
-                    array(
290
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
291
-                        $this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
292
-                    )
293
-                ),
294
-            )
295
-        );
296
-    }
297
-
298
-
299
-    /**
300
-     * @return void
301
-     * @throws EE_Error
302
-     */
303
-    public function loadPluginApi()
304
-    {
305
-        // set autoloaders for all of the classes implementing EEI_Plugin_API
306
-        // which provide helpers for EE plugin authors to more easily register certain components with EE.
307
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
308
-        // load legacy EE_Request_Handler in case add-ons still need it
309
-        $this->loader->getShared('EE_Request_Handler');
310
-    }
311
-
312
-
313
-    /**
314
-     * @param string $addon_name
315
-     * @param string $version_constant
316
-     * @param string $min_version_required
317
-     * @param string $load_callback
318
-     * @param string $plugin_file_constant
319
-     * @return void
320
-     */
321
-    private function deactivateIncompatibleAddon(
322
-        $addon_name,
323
-        $version_constant,
324
-        $min_version_required,
325
-        $load_callback,
326
-        $plugin_file_constant
327
-    ) {
328
-        if (! defined($version_constant)) {
329
-            return;
330
-        }
331
-        $addon_version = constant($version_constant);
332
-        if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
333
-            remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
334
-            if (! function_exists('deactivate_plugins')) {
335
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
336
-            }
337
-            deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
338
-            unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
339
-            EE_Error::add_error(
340
-                sprintf(
341
-                    esc_html__(
342
-                        'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
343
-                        'event_espresso'
344
-                    ),
345
-                    $addon_name,
346
-                    $min_version_required
347
-                ),
348
-                __FILE__,
349
-                __FUNCTION__ . "({$addon_name})",
350
-                __LINE__
351
-            );
352
-            EE_Error::get_notices(false, true);
353
-        }
354
-    }
355
-
356
-
357
-    /**
358
-     * load_espresso_addons
359
-     * allow addons to load first so that they can set hooks for running DMS's, etc
360
-     * this is hooked into both:
361
-     *    'AHEE__EE_Bootstrap__load_core_configuration'
362
-     *        which runs during the WP 'plugins_loaded' action at priority 5
363
-     *    and the WP 'activate_plugin' hook point
364
-     *
365
-     * @access public
366
-     * @return void
367
-     */
368
-    public function load_espresso_addons()
369
-    {
370
-        $this->deactivateIncompatibleAddon(
371
-            'Wait Lists',
372
-            'EE_WAIT_LISTS_VERSION',
373
-            '1.0.0.beta.074',
374
-            'load_espresso_wait_lists',
375
-            'EE_WAIT_LISTS_PLUGIN_FILE'
376
-        );
377
-        $this->deactivateIncompatibleAddon(
378
-            'Automated Upcoming Event Notifications',
379
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
380
-            '1.0.0.beta.091',
381
-            'load_espresso_automated_upcoming_event_notification',
382
-            'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
383
-        );
384
-        do_action('AHEE__EE_System__load_espresso_addons');
385
-        // if the WP API basic auth plugin isn't already loaded, load it now.
386
-        // We want it for mobile apps. Just include the entire plugin
387
-        // also, don't load the basic auth when a plugin is getting activated, because
388
-        // it could be the basic auth plugin, and it doesn't check if its methods are already defined
389
-        // and causes a fatal error
390
-        if (($this->request->isWordPressApi() || $this->request->isApi())
391
-            && $this->request->getRequestParam('activate') !== 'true'
392
-            && ! function_exists('json_basic_auth_handler')
393
-            && ! function_exists('json_basic_auth_error')
394
-            && ! in_array(
395
-                $this->request->getRequestParam('action'),
396
-                array('activate', 'activate-selected'),
397
-                true
398
-            )
399
-        ) {
400
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth/basic-auth.php';
401
-        }
402
-        do_action('AHEE__EE_System__load_espresso_addons__complete');
403
-    }
404
-
405
-
406
-    /**
407
-     * detect_activations_or_upgrades
408
-     * Checks for activation or upgrade of core first;
409
-     * then also checks if any registered addons have been activated or upgraded
410
-     * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
411
-     * which runs during the WP 'plugins_loaded' action at priority 3
412
-     *
413
-     * @access public
414
-     * @return void
415
-     */
416
-    public function detect_activations_or_upgrades()
417
-    {
418
-        // first off: let's make sure to handle core
419
-        $this->detect_if_activation_or_upgrade();
420
-        foreach ($this->registry->addons as $addon) {
421
-            if ($addon instanceof EE_Addon) {
422
-                // detect teh request type for that addon
423
-                $addon->detect_req_type();
424
-            }
425
-        }
426
-    }
427
-
428
-
429
-    /**
430
-     * detect_if_activation_or_upgrade
431
-     * Takes care of detecting whether this is a brand new install or code upgrade,
432
-     * and either setting up the DB or setting up maintenance mode etc.
433
-     *
434
-     * @access public
435
-     * @return void
436
-     */
437
-    public function detect_if_activation_or_upgrade()
438
-    {
439
-        do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
440
-        // check if db has been updated, or if its a brand-new installation
441
-        $espresso_db_update = $this->fix_espresso_db_upgrade_option();
442
-        $request_type = $this->detect_req_type($espresso_db_update);
443
-        // EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
444
-        switch ($request_type) {
445
-            case EE_System::req_type_new_activation:
446
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
447
-                $this->_handle_core_version_change($espresso_db_update);
448
-                break;
449
-            case EE_System::req_type_reactivation:
450
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
451
-                $this->_handle_core_version_change($espresso_db_update);
452
-                break;
453
-            case EE_System::req_type_upgrade:
454
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
455
-                // migrations may be required now that we've upgraded
456
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
457
-                $this->_handle_core_version_change($espresso_db_update);
458
-                break;
459
-            case EE_System::req_type_downgrade:
460
-                do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
461
-                // its possible migrations are no longer required
462
-                $this->maintenance_mode->set_maintenance_mode_if_db_old();
463
-                $this->_handle_core_version_change($espresso_db_update);
464
-                break;
465
-            case EE_System::req_type_normal:
466
-            default:
467
-                break;
468
-        }
469
-        do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
470
-    }
471
-
472
-
473
-    /**
474
-     * Updates the list of installed versions and sets hooks for
475
-     * initializing the database later during the request
476
-     *
477
-     * @param array $espresso_db_update
478
-     */
479
-    private function _handle_core_version_change($espresso_db_update)
480
-    {
481
-        $this->update_list_of_installed_versions($espresso_db_update);
482
-        // get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
-        add_action(
484
-            'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
-            array($this, 'initialize_db_if_no_migrations_required')
486
-        );
487
-    }
488
-
489
-
490
-    /**
491
-     * standardizes the wp option 'espresso_db_upgrade' which actually stores
492
-     * information about what versions of EE have been installed and activated,
493
-     * NOT necessarily the state of the database
494
-     *
495
-     * @param mixed $espresso_db_update           the value of the WordPress option.
496
-     *                                            If not supplied, fetches it from the options table
497
-     * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
498
-     */
499
-    private function fix_espresso_db_upgrade_option($espresso_db_update = null)
500
-    {
501
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
502
-        if (! $espresso_db_update) {
503
-            $espresso_db_update = get_option('espresso_db_update');
504
-        }
505
-        // check that option is an array
506
-        if (! is_array($espresso_db_update)) {
507
-            // if option is FALSE, then it never existed
508
-            if ($espresso_db_update === false) {
509
-                // make $espresso_db_update an array and save option with autoload OFF
510
-                $espresso_db_update = array();
511
-                add_option('espresso_db_update', $espresso_db_update, '', 'no');
512
-            } else {
513
-                // option is NOT FALSE but also is NOT an array, so make it an array and save it
514
-                $espresso_db_update = array($espresso_db_update => array());
515
-                update_option('espresso_db_update', $espresso_db_update);
516
-            }
517
-        } else {
518
-            $corrected_db_update = array();
519
-            // if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
520
-            foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
521
-                if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
522
-                    // the key is an int, and the value IS NOT an array
523
-                    // so it must be numerically-indexed, where values are versions installed...
524
-                    // fix it!
525
-                    $version_string = $should_be_array;
526
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
527
-                } else {
528
-                    // ok it checks out
529
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
530
-                }
531
-            }
532
-            $espresso_db_update = $corrected_db_update;
533
-            update_option('espresso_db_update', $espresso_db_update);
534
-        }
535
-        do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
536
-        return $espresso_db_update;
537
-    }
538
-
539
-
540
-    /**
541
-     * Does the traditional work of setting up the plugin's database and adding default data.
542
-     * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
543
-     * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
544
-     * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
545
-     * so that it will be done when migrations are finished
546
-     *
547
-     * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
548
-     * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
549
-     *                                       This is a resource-intensive job
550
-     *                                       so we prefer to only do it when necessary
551
-     * @return void
552
-     * @throws EE_Error
553
-     */
554
-    public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
555
-    {
556
-        $request_type = $this->detect_req_type();
557
-        // only initialize system if we're not in maintenance mode.
558
-        if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
559
-            /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
560
-            $rewrite_rules = $this->loader->getShared(
561
-                'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
562
-            );
563
-            $rewrite_rules->flush();
564
-            if ($verify_schema) {
565
-                EEH_Activation::initialize_db_and_folders();
566
-            }
567
-            EEH_Activation::initialize_db_content();
568
-            EEH_Activation::system_initialization();
569
-            if ($initialize_addons_too) {
570
-                $this->initialize_addons();
571
-            }
572
-        } else {
573
-            EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
574
-        }
575
-        if ($request_type === EE_System::req_type_new_activation
576
-            || $request_type === EE_System::req_type_reactivation
577
-            || (
578
-                $request_type === EE_System::req_type_upgrade
579
-                && $this->is_major_version_change()
580
-            )
581
-        ) {
582
-            add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
583
-        }
584
-    }
585
-
586
-
587
-    /**
588
-     * Initializes the db for all registered addons
589
-     *
590
-     * @throws EE_Error
591
-     */
592
-    public function initialize_addons()
593
-    {
594
-        // foreach registered addon, make sure its db is up-to-date too
595
-        foreach ($this->registry->addons as $addon) {
596
-            if ($addon instanceof EE_Addon) {
597
-                $addon->initialize_db_if_no_migrations_required();
598
-            }
599
-        }
600
-    }
601
-
602
-
603
-    /**
604
-     * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
-     *
606
-     * @param    array  $version_history
607
-     * @param    string $current_version_to_add version to be added to the version history
608
-     * @return    boolean success as to whether or not this option was changed
609
-     */
610
-    public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
-    {
612
-        if (! $version_history) {
613
-            $version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
-        }
615
-        if ($current_version_to_add === null) {
616
-            $current_version_to_add = espresso_version();
617
-        }
618
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
-        // re-save
620
-        return update_option('espresso_db_update', $version_history);
621
-    }
622
-
623
-
624
-    /**
625
-     * Detects if the current version indicated in the has existed in the list of
626
-     * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
627
-     *
628
-     * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
629
-     *                                  If not supplied, fetches it from the options table.
630
-     *                                  Also, caches its result so later parts of the code can also know whether
631
-     *                                  there's been an update or not. This way we can add the current version to
632
-     *                                  espresso_db_update, but still know if this is a new install or not
633
-     * @return int one of the constants on EE_System::req_type_
634
-     */
635
-    public function detect_req_type($espresso_db_update = null)
636
-    {
637
-        if ($this->_req_type === null) {
638
-            $espresso_db_update = ! empty($espresso_db_update)
639
-                ? $espresso_db_update
640
-                : $this->fix_espresso_db_upgrade_option();
641
-            $this->_req_type = EE_System::detect_req_type_given_activation_history(
642
-                $espresso_db_update,
643
-                'ee_espresso_activation',
644
-                espresso_version()
645
-            );
646
-            $this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
-            $this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
-        }
649
-        return $this->_req_type;
650
-    }
651
-
652
-
653
-    /**
654
-     * Returns whether or not there was a non-micro version change (ie, change in either
655
-     * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
656
-     * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
657
-     *
658
-     * @param $activation_history
659
-     * @return bool
660
-     */
661
-    private function _detect_major_version_change($activation_history)
662
-    {
663
-        $previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
664
-        $previous_version_parts = explode('.', $previous_version);
665
-        $current_version_parts = explode('.', espresso_version());
666
-        return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
667
-               && ($previous_version_parts[0] !== $current_version_parts[0]
668
-                   || $previous_version_parts[1] !== $current_version_parts[1]
669
-               );
670
-    }
671
-
672
-
673
-    /**
674
-     * Returns true if either the major or minor version of EE changed during this request.
675
-     * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
676
-     *
677
-     * @return bool
678
-     */
679
-    public function is_major_version_change()
680
-    {
681
-        return $this->_major_version_change;
682
-    }
683
-
684
-
685
-    /**
686
-     * Determines the request type for any ee addon, given three piece of info: the current array of activation
687
-     * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
688
-     * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
689
-     * just activated to (for core that will always be espresso_version())
690
-     *
691
-     * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
692
-     *                                                 ee plugin. for core that's 'espresso_db_update'
693
-     * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
694
-     *                                                 indicate that this plugin was just activated
695
-     * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
696
-     *                                                 espresso_version())
697
-     * @return int one of the constants on EE_System::req_type_*
698
-     */
699
-    public static function detect_req_type_given_activation_history(
700
-        $activation_history_for_addon,
701
-        $activation_indicator_option_name,
702
-        $version_to_upgrade_to
703
-    ) {
704
-        $version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
705
-        if ($activation_history_for_addon) {
706
-            // it exists, so this isn't a completely new install
707
-            // check if this version already in that list of previously installed versions
708
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
709
-                // it a version we haven't seen before
710
-                if ($version_is_higher === 1) {
711
-                    $req_type = EE_System::req_type_upgrade;
712
-                } else {
713
-                    $req_type = EE_System::req_type_downgrade;
714
-                }
715
-                delete_option($activation_indicator_option_name);
716
-            } else {
717
-                // its not an update. maybe a reactivation?
718
-                if (get_option($activation_indicator_option_name, false)) {
719
-                    if ($version_is_higher === -1) {
720
-                        $req_type = EE_System::req_type_downgrade;
721
-                    } elseif ($version_is_higher === 0) {
722
-                        // we've seen this version before, but it's an activation. must be a reactivation
723
-                        $req_type = EE_System::req_type_reactivation;
724
-                    } else {// $version_is_higher === 1
725
-                        $req_type = EE_System::req_type_upgrade;
726
-                    }
727
-                    delete_option($activation_indicator_option_name);
728
-                } else {
729
-                    // we've seen this version before and the activation indicate doesn't show it was just activated
730
-                    if ($version_is_higher === -1) {
731
-                        $req_type = EE_System::req_type_downgrade;
732
-                    } elseif ($version_is_higher === 0) {
733
-                        // we've seen this version before and it's not an activation. its normal request
734
-                        $req_type = EE_System::req_type_normal;
735
-                    } else {// $version_is_higher === 1
736
-                        $req_type = EE_System::req_type_upgrade;
737
-                    }
738
-                }
739
-            }
740
-        } else {
741
-            // brand new install
742
-            $req_type = EE_System::req_type_new_activation;
743
-            delete_option($activation_indicator_option_name);
744
-        }
745
-        return $req_type;
746
-    }
747
-
748
-
749
-    /**
750
-     * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
-     * the $activation_history_for_addon
752
-     *
753
-     * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
-     *                                             sometimes containing 'unknown-date'
755
-     * @param string $version_to_upgrade_to        (current version)
756
-     * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
-     *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
-     *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
-     *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
-     */
761
-    private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
-    {
763
-        // find the most recently-activated version
764
-        $most_recently_active_version =
765
-            EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
-        return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
-    }
768
-
769
-
770
-    /**
771
-     * Gets the most recently active version listed in the activation history,
772
-     * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
773
-     *
774
-     * @param array $activation_history  (keys are versions, values are arrays of times activated,
775
-     *                                   sometimes containing 'unknown-date'
776
-     * @return string
777
-     */
778
-    private static function _get_most_recently_active_version_from_activation_history($activation_history)
779
-    {
780
-        $most_recently_active_version_activation = '1970-01-01 00:00:00';
781
-        $most_recently_active_version = '0.0.0.dev.000';
782
-        if (is_array($activation_history)) {
783
-            foreach ($activation_history as $version => $times_activated) {
784
-                // check there is a record of when this version was activated. Otherwise,
785
-                // mark it as unknown
786
-                if (! $times_activated) {
787
-                    $times_activated = array('unknown-date');
788
-                }
789
-                if (is_string($times_activated)) {
790
-                    $times_activated = array($times_activated);
791
-                }
792
-                foreach ($times_activated as $an_activation) {
793
-                    if ($an_activation !== 'unknown-date'
794
-                        && $an_activation
795
-                           > $most_recently_active_version_activation) {
796
-                        $most_recently_active_version = $version;
797
-                        $most_recently_active_version_activation = $an_activation === 'unknown-date'
798
-                            ? '1970-01-01 00:00:00'
799
-                            : $an_activation;
800
-                    }
801
-                }
802
-            }
803
-        }
804
-        return $most_recently_active_version;
805
-    }
806
-
807
-
808
-    /**
809
-     * This redirects to the about EE page after activation
810
-     *
811
-     * @return void
812
-     */
813
-    public function redirect_to_about_ee()
814
-    {
815
-        $notices = EE_Error::get_notices(false);
816
-        // if current user is an admin and it's not an ajax or rest request
817
-        if (! isset($notices['errors'])
818
-            && $this->request->isAdmin()
819
-            && apply_filters(
820
-                'FHEE__EE_System__redirect_to_about_ee__do_redirect',
821
-                $this->capabilities->current_user_can('manage_options', 'espresso_about_default')
822
-            )
823
-        ) {
824
-            $query_params = array('page' => 'espresso_about');
825
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
826
-                $query_params['new_activation'] = true;
827
-            }
828
-            if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
829
-                $query_params['reactivation'] = true;
830
-            }
831
-            $url = add_query_arg($query_params, admin_url('admin.php'));
832
-            wp_safe_redirect($url);
833
-            exit();
834
-        }
835
-    }
836
-
837
-
838
-    /**
839
-     * load_core_configuration
840
-     * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
841
-     * which runs during the WP 'plugins_loaded' action at priority 5
842
-     *
843
-     * @return void
844
-     * @throws ReflectionException
845
-     * @throws Exception
846
-     */
847
-    public function load_core_configuration()
848
-    {
849
-        do_action('AHEE__EE_System__load_core_configuration__begin', $this);
850
-        $this->loader->getShared('EE_Load_Textdomain');
851
-        // load textdomain
852
-        EE_Load_Textdomain::load_textdomain();
853
-        // load caf stuff a chance to play during the activation process too.
854
-        $this->_maybe_brew_regular();
855
-        // load and setup EE_Config and EE_Network_Config
856
-        $config = $this->loader->getShared('EE_Config');
857
-        $this->loader->getShared('EE_Network_Config');
858
-        // setup autoloaders
859
-        // enable logging?
860
-        if ($config->admin->use_remote_logging) {
861
-            $this->loader->getShared('EE_Log');
862
-        }
863
-        // check for activation errors
864
-        $activation_errors = get_option('ee_plugin_activation_errors', false);
865
-        if ($activation_errors) {
866
-            EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
-            update_option('ee_plugin_activation_errors', false);
868
-        }
869
-        // get model names
870
-        $this->_parse_model_names();
871
-        // configure custom post type definitions
872
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
873
-        $this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
874
-        do_action('AHEE__EE_System__load_core_configuration__complete', $this);
875
-    }
876
-
877
-
878
-    /**
879
-     * cycles through all of the models/*.model.php files, and assembles an array of model names
880
-     *
881
-     * @return void
882
-     * @throws ReflectionException
883
-     */
884
-    private function _parse_model_names()
885
-    {
886
-        // get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
888
-        $model_names = array();
889
-        $non_abstract_db_models = array();
890
-        foreach ($models as $model) {
891
-            // get model classname
892
-            $classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
-            $short_name = str_replace('EEM_', '', $classname);
894
-            $reflectionClass = new ReflectionClass($classname);
895
-            if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
-                $non_abstract_db_models[ $short_name ] = $classname;
897
-            }
898
-            $model_names[ $short_name ] = $classname;
899
-        }
900
-        $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
-        $this->registry->non_abstract_db_models = apply_filters(
902
-            'FHEE__EE_System__parse_implemented_model_names',
903
-            $non_abstract_db_models
904
-        );
905
-    }
906
-
907
-
908
-    /**
909
-     * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
910
-     * that need to be setup before our EE_System launches.
911
-     *
912
-     * @return void
913
-     * @throws DomainException
914
-     * @throws InvalidArgumentException
915
-     * @throws InvalidDataTypeException
916
-     * @throws InvalidInterfaceException
917
-     * @throws InvalidClassException
918
-     * @throws InvalidFilePathException
919
-     */
920
-    private function _maybe_brew_regular()
921
-    {
922
-        /** @var Domain $domain */
923
-        $domain = DomainFactory::getShared(
924
-            new FullyQualifiedName(
925
-                'EventEspresso\core\domain\Domain'
926
-            ),
927
-            array(
928
-                new FilePath(EVENT_ESPRESSO_MAIN_FILE),
929
-                Version::fromString(espresso_version()),
930
-            )
931
-        );
932
-        if ($domain->isCaffeinated()) {
933
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
934
-        }
935
-    }
936
-
937
-
938
-    /**
939
-     * @since 4.9.71.p
940
-     * @throws Exception
941
-     */
942
-    public function loadRouteMatchSpecifications()
943
-    {
944
-        try {
945
-            $this->loader->getShared(
946
-                'EventEspresso\core\services\route_match\RouteMatchSpecificationManager'
947
-            );
948
-        } catch (Exception $exception) {
949
-            new ExceptionStackTraceDisplay($exception);
950
-        }
951
-        do_action('AHEE__EE_System__loadRouteMatchSpecifications');
952
-    }
953
-
954
-
955
-    /**
956
-     * register_shortcodes_modules_and_widgets
957
-     * generate lists of shortcodes and modules, then verify paths and classes
958
-     * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
959
-     * which runs during the WP 'plugins_loaded' action at priority 7
960
-     *
961
-     * @access public
962
-     * @return void
963
-     * @throws Exception
964
-     */
965
-    public function register_shortcodes_modules_and_widgets()
966
-    {
967
-        if ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isAjax()) {
968
-            // load, register, and add shortcodes the new way
969
-            $this->loader->getShared('EventEspresso\core\services\shortcodes\ShortcodesManager');
970
-        }
971
-        do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
972
-        // check for addons using old hook point
973
-        if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
974
-            $this->_incompatible_addon_error();
975
-        }
976
-    }
977
-
978
-
979
-    /**
980
-     * _incompatible_addon_error
981
-     *
982
-     * @access public
983
-     * @return void
984
-     */
985
-    private function _incompatible_addon_error()
986
-    {
987
-        // get array of classes hooking into here
988
-        $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
989
-            'AHEE__EE_System__register_shortcodes_modules_and_addons'
990
-        );
991
-        if (! empty($class_names)) {
992
-            $msg = __(
993
-                'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
994
-                'event_espresso'
995
-            );
996
-            $msg .= '<ul>';
997
-            foreach ($class_names as $class_name) {
998
-                $msg .= '<li><b>Event Espresso - '
999
-                        . str_replace(
1000
-                            array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'),
1001
-                            '',
1002
-                            $class_name
1003
-                        ) . '</b></li>';
1004
-            }
1005
-            $msg .= '</ul>';
1006
-            $msg .= __(
1007
-                'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
1008
-                'event_espresso'
1009
-            );
1010
-            // save list of incompatible addons to wp-options for later use
1011
-            add_option('ee_incompatible_addons', $class_names, '', 'no');
1012
-            if (is_admin()) {
1013
-                EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1014
-            }
1015
-        }
1016
-    }
1017
-
1018
-
1019
-    /**
1020
-     * brew_espresso
1021
-     * begins the process of setting hooks for initializing EE in the correct order
1022
-     * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1023
-     * which runs during the WP 'plugins_loaded' action at priority 9
1024
-     *
1025
-     * @return void
1026
-     */
1027
-    public function brew_espresso()
1028
-    {
1029
-        do_action('AHEE__EE_System__brew_espresso__begin', $this);
1030
-        // load some final core systems
1031
-        add_action('init', array($this, 'set_hooks_for_core'), 1);
1032
-        add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1033
-        add_action('init', array($this, 'load_CPTs_and_session'), 5);
1034
-        add_action('init', array($this, 'load_controllers'), 7);
1035
-        add_action('init', array($this, 'core_loaded_and_ready'), 9);
1036
-        add_action('init', array($this, 'initialize'), 10);
1037
-        add_action('init', array($this, 'initialize_last'), 100);
1038
-        if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1039
-            // pew pew pew
1040
-            $this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1041
-            do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1042
-        }
1043
-        do_action('AHEE__EE_System__brew_espresso__complete', $this);
1044
-    }
1045
-
1046
-
1047
-    /**
1048
-     *    set_hooks_for_core
1049
-     *
1050
-     * @access public
1051
-     * @return    void
1052
-     * @throws EE_Error
1053
-     */
1054
-    public function set_hooks_for_core()
1055
-    {
1056
-        $this->_deactivate_incompatible_addons();
1057
-        do_action('AHEE__EE_System__set_hooks_for_core');
1058
-        $this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1059
-        // caps need to be initialized on every request so that capability maps are set.
1060
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1061
-        $this->registry->CAP->init_caps();
1062
-    }
1063
-
1064
-
1065
-    /**
1066
-     * Using the information gathered in EE_System::_incompatible_addon_error,
1067
-     * deactivates any addons considered incompatible with the current version of EE
1068
-     */
1069
-    private function _deactivate_incompatible_addons()
1070
-    {
1071
-        $incompatible_addons = get_option('ee_incompatible_addons', array());
1072
-        if (! empty($incompatible_addons)) {
1073
-            $active_plugins = get_option('active_plugins', array());
1074
-            foreach ($active_plugins as $active_plugin) {
1075
-                foreach ($incompatible_addons as $incompatible_addon) {
1076
-                    if (strpos($active_plugin, $incompatible_addon) !== false) {
1077
-                        unset($_GET['activate']);
1078
-                        espresso_deactivate_plugin($active_plugin);
1079
-                    }
1080
-                }
1081
-            }
1082
-        }
1083
-    }
1084
-
1085
-
1086
-    /**
1087
-     *    perform_activations_upgrades_and_migrations
1088
-     *
1089
-     * @access public
1090
-     * @return    void
1091
-     */
1092
-    public function perform_activations_upgrades_and_migrations()
1093
-    {
1094
-        do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1095
-    }
1096
-
1097
-
1098
-    /**
1099
-     * @return void
1100
-     * @throws DomainException
1101
-     */
1102
-    public function load_CPTs_and_session()
1103
-    {
1104
-        do_action('AHEE__EE_System__load_CPTs_and_session__start');
1105
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies $register_custom_taxonomies */
1106
-        $register_custom_taxonomies = $this->loader->getShared(
1107
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
1108
-        );
1109
-        $register_custom_taxonomies->registerCustomTaxonomies();
1110
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
1111
-        $register_custom_post_types = $this->loader->getShared(
1112
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
1113
-        );
1114
-        $register_custom_post_types->registerCustomPostTypes();
1115
-        /** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms $register_custom_taxonomy_terms */
1116
-        $register_custom_taxonomy_terms = $this->loader->getShared(
1117
-            'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
1118
-        );
1119
-        $register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1120
-        // load legacy Custom Post Types and Taxonomies
1121
-        $this->loader->getShared('EE_Register_CPTs');
1122
-        do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1123
-    }
1124
-
1125
-
1126
-    /**
1127
-     * load_controllers
1128
-     * this is the best place to load any additional controllers that needs access to EE core.
1129
-     * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1130
-     * time
1131
-     *
1132
-     * @access public
1133
-     * @return void
1134
-     */
1135
-    public function load_controllers()
1136
-    {
1137
-        do_action('AHEE__EE_System__load_controllers__start');
1138
-        // let's get it started
1139
-        if (! $this->maintenance_mode->level()
1140
-            && ($this->request->isFrontend() || $this->request->isFrontAjax())
1141
-        ) {
1142
-            do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1143
-            $this->loader->getShared('EE_Front_Controller');
1144
-        } elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1145
-            do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1146
-            $this->loader->getShared('EE_Admin');
1147
-        } elseif ($this->request->isWordPressHeartbeat()) {
1148
-            $this->loader->getShared('EventEspresso\core\domain\services\admin\ajax\WordpressHeartbeat');
1149
-        }
1150
-        do_action('AHEE__EE_System__load_controllers__complete');
1151
-    }
1152
-
1153
-
1154
-    /**
1155
-     * core_loaded_and_ready
1156
-     * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1157
-     *
1158
-     * @access public
1159
-     * @return void
1160
-     * @throws Exception
1161
-     */
1162
-    public function core_loaded_and_ready()
1163
-    {
1164
-        if ($this->request->isAdmin()
1165
-            || $this->request->isFrontend()
1166
-            || $this->request->isIframe()
1167
-            || $this->request->isWordPressApi()
1168
-        ) {
1169
-            try {
1170
-                $this->loader->getShared('EventEspresso\core\services\assets\Registry');
1171
-                $this->loader->getShared('EventEspresso\core\domain\services\assets\CoreAssetManager');
1172
-                if ($this->canLoadBlocks()) {
1173
-                    $this->loader->getShared(
1174
-                        'EventEspresso\core\services\editor\BlockRegistrationManager'
1175
-                    );
1176
-                }
1177
-            } catch (Exception $exception) {
1178
-                new ExceptionStackTraceDisplay($exception);
1179
-            }
1180
-        }
1181
-        if ($this->request->isAdmin()
1182
-            || $this->request->isEeAjax()
1183
-            || $this->request->isFrontend()
1184
-        ) {
1185
-            $this->loader->getShared('EE_Session');
1186
-        }
1187
-        // integrate WP_Query with the EE models
1188
-        $this->loader->getShared('EE_CPT_Strategy');
1189
-        do_action('AHEE__EE_System__core_loaded_and_ready');
1190
-        // always load template tags, because it's faster than checking if it's a front-end request, and many page
1191
-        // builders require these even on the front-end
1192
-        require_once EE_PUBLIC . 'template_tags.php';
1193
-        do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1194
-    }
1195
-
1196
-
1197
-    /**
1198
-     * initialize
1199
-     * this is the best place to begin initializing client code
1200
-     *
1201
-     * @access public
1202
-     * @return void
1203
-     */
1204
-    public function initialize()
1205
-    {
1206
-        do_action('AHEE__EE_System__initialize');
1207
-    }
1208
-
1209
-
1210
-    /**
1211
-     * initialize_last
1212
-     * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1213
-     * initialize has done so
1214
-     *
1215
-     * @access public
1216
-     * @return void
1217
-     */
1218
-    public function initialize_last()
1219
-    {
1220
-        do_action('AHEE__EE_System__initialize_last');
1221
-        /** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1222
-        $rewrite_rules = $this->loader->getShared(
1223
-            'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1224
-        );
1225
-        $rewrite_rules->flushRewriteRules();
1226
-        add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1227
-        if (($this->request->isAjax() || $this->request->isAdmin())
1228
-            && $this->maintenance_mode->models_can_query()) {
1229
-            $this->loader->getShared('EventEspresso\core\services\privacy\export\PersonalDataExporterManager');
1230
-            $this->loader->getShared('EventEspresso\core\services\privacy\erasure\PersonalDataEraserManager');
1231
-        }
1232
-    }
1233
-
1234
-
1235
-    /**
1236
-     * @return void
1237
-     * @throws EE_Error
1238
-     */
1239
-    public function addEspressoToolbar()
1240
-    {
1241
-        $this->loader->getShared(
1242
-            'EventEspresso\core\domain\services\admin\AdminToolBar',
1243
-            array($this->registry->CAP)
1244
-        );
1245
-    }
1246
-
1247
-
1248
-    /**
1249
-     * do_not_cache
1250
-     * sets no cache headers and defines no cache constants for WP plugins
1251
-     *
1252
-     * @access public
1253
-     * @return void
1254
-     */
1255
-    public static function do_not_cache()
1256
-    {
1257
-        // set no cache constants
1258
-        if (! defined('DONOTCACHEPAGE')) {
1259
-            define('DONOTCACHEPAGE', true);
1260
-        }
1261
-        if (! defined('DONOTCACHCEOBJECT')) {
1262
-            define('DONOTCACHCEOBJECT', true);
1263
-        }
1264
-        if (! defined('DONOTCACHEDB')) {
1265
-            define('DONOTCACHEDB', true);
1266
-        }
1267
-        // add no cache headers
1268
-        add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1269
-        // plus a little extra for nginx and Google Chrome
1270
-        add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1271
-        // prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1272
-        remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1273
-    }
1274
-
1275
-
1276
-    /**
1277
-     *    extra_nocache_headers
1278
-     *
1279
-     * @access    public
1280
-     * @param $headers
1281
-     * @return    array
1282
-     */
1283
-    public static function extra_nocache_headers($headers)
1284
-    {
1285
-        // for NGINX
1286
-        $headers['X-Accel-Expires'] = 0;
1287
-        // plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1288
-        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1289
-        return $headers;
1290
-    }
1291
-
1292
-
1293
-    /**
1294
-     *    nocache_headers
1295
-     *
1296
-     * @access    public
1297
-     * @return    void
1298
-     */
1299
-    public static function nocache_headers()
1300
-    {
1301
-        nocache_headers();
1302
-    }
1303
-
1304
-
1305
-    /**
1306
-     * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1307
-     * never returned with the function.
1308
-     *
1309
-     * @param  array $exclude_array any existing pages being excluded are in this array.
1310
-     * @return array
1311
-     */
1312
-    public function remove_pages_from_wp_list_pages($exclude_array)
1313
-    {
1314
-        return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1315
-    }
1316
-
1317
-
1318
-    /**
1319
-     * Return whether blocks can be registered/loaded or not.
1320
-     * @return bool
1321
-     */
1322
-    private function canLoadBlocks()
1323
-    {
1324
-        return apply_filters('FHEE__EE_System__canLoadBlocks', true)
1325
-               && function_exists('register_block_type')
1326
-               // don't load blocks if in the Divi page builder editor context
1327
-               // @see https://github.com/eventespresso/event-espresso-core/issues/814
1328
-               && ! $this->request->getRequestParam('et_fb', false);
1329
-    }
30
+	/**
31
+	 * indicates this is a 'normal' request. Ie, not activation, nor upgrade, nor activation.
32
+	 * So examples of this would be a normal GET request on the frontend or backend, or a POST, etc
33
+	 */
34
+	const req_type_normal = 0;
35
+
36
+	/**
37
+	 * Indicates this is a brand new installation of EE so we should install
38
+	 * tables and default data etc
39
+	 */
40
+	const req_type_new_activation = 1;
41
+
42
+	/**
43
+	 * we've detected that EE has been reactivated (or EE was activated during maintenance mode,
44
+	 * and we just exited maintenance mode). We MUST check the database is setup properly
45
+	 * and that default data is setup too
46
+	 */
47
+	const req_type_reactivation = 2;
48
+
49
+	/**
50
+	 * indicates that EE has been upgraded since its previous request.
51
+	 * We may have data migration scripts to call and will want to trigger maintenance mode
52
+	 */
53
+	const req_type_upgrade = 3;
54
+
55
+	/**
56
+	 * TODO  will detect that EE has been DOWNGRADED. We probably don't want to run in this case...
57
+	 */
58
+	const req_type_downgrade = 4;
59
+
60
+	/**
61
+	 * @deprecated since version 4.6.0.dev.006
62
+	 * Now whenever a new_activation is detected the request type is still just
63
+	 * new_activation (same for reactivation, upgrade, downgrade etc), but if we'r ein maintenance mode
64
+	 * EE_System::initialize_db_if_no_migrations_required and EE_Addon::initialize_db_if_no_migrations_required
65
+	 * will instead enqueue that EE plugin's db initialization for when we're taken out of maintenance mode.
66
+	 * (Specifically, when the migration manager indicates migrations are finished
67
+	 * EE_Data_Migration_Manager::initialize_db_for_enqueued_ee_plugins() will be called)
68
+	 */
69
+	const req_type_activation_but_not_installed = 5;
70
+
71
+	/**
72
+	 * option prefix for recording the activation history (like core's "espresso_db_update") of addons
73
+	 */
74
+	const addon_activation_history_option_prefix = 'ee_addon_activation_history_';
75
+
76
+	/**
77
+	 * @var EE_System $_instance
78
+	 */
79
+	private static $_instance;
80
+
81
+	/**
82
+	 * @var EE_Registry $registry
83
+	 */
84
+	private $registry;
85
+
86
+	/**
87
+	 * @var LoaderInterface $loader
88
+	 */
89
+	private $loader;
90
+
91
+	/**
92
+	 * @var EE_Capabilities $capabilities
93
+	 */
94
+	private $capabilities;
95
+
96
+	/**
97
+	 * @var RequestInterface $request
98
+	 */
99
+	private $request;
100
+
101
+	/**
102
+	 * @var EE_Maintenance_Mode $maintenance_mode
103
+	 */
104
+	private $maintenance_mode;
105
+
106
+	/**
107
+	 * Stores which type of request this is, options being one of the constants on EE_System starting with req_type_*.
108
+	 * It can be a brand-new activation, a reactivation, an upgrade, a downgrade, or a normal request.
109
+	 *
110
+	 * @var int $_req_type
111
+	 */
112
+	private $_req_type;
113
+
114
+	/**
115
+	 * Whether or not there was a non-micro version change in EE core version during this request
116
+	 *
117
+	 * @var boolean $_major_version_change
118
+	 */
119
+	private $_major_version_change = false;
120
+
121
+	/**
122
+	 * A Context DTO dedicated solely to identifying the current request type.
123
+	 *
124
+	 * @var RequestTypeContextCheckerInterface $request_type
125
+	 */
126
+	private $request_type;
127
+
128
+
129
+	/**
130
+	 * @singleton method used to instantiate class object
131
+	 * @param EE_Registry|null         $registry
132
+	 * @param LoaderInterface|null     $loader
133
+	 * @param RequestInterface|null    $request
134
+	 * @param EE_Maintenance_Mode|null $maintenance_mode
135
+	 * @return EE_System
136
+	 */
137
+	public static function instance(
138
+		EE_Registry $registry = null,
139
+		LoaderInterface $loader = null,
140
+		RequestInterface $request = null,
141
+		EE_Maintenance_Mode $maintenance_mode = null
142
+	) {
143
+		// check if class object is instantiated
144
+		if (! self::$_instance instanceof EE_System) {
145
+			self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
146
+		}
147
+		return self::$_instance;
148
+	}
149
+
150
+
151
+	/**
152
+	 * resets the instance and returns it
153
+	 *
154
+	 * @return EE_System
155
+	 */
156
+	public static function reset()
157
+	{
158
+		self::$_instance->_req_type = null;
159
+		// make sure none of the old hooks are left hanging around
160
+		remove_all_actions('AHEE__EE_System__perform_activations_upgrades_and_migrations');
161
+		// we need to reset the migration manager in order for it to detect DMSs properly
162
+		EE_Data_Migration_Manager::reset();
163
+		self::instance()->detect_activations_or_upgrades();
164
+		self::instance()->perform_activations_upgrades_and_migrations();
165
+		return self::instance();
166
+	}
167
+
168
+
169
+	/**
170
+	 * sets hooks for running rest of system
171
+	 * provides "AHEE__EE_System__construct__complete" hook for EE Addons to use as their starting point
172
+	 * starting EE Addons from any other point may lead to problems
173
+	 *
174
+	 * @param EE_Registry         $registry
175
+	 * @param LoaderInterface     $loader
176
+	 * @param RequestInterface    $request
177
+	 * @param EE_Maintenance_Mode $maintenance_mode
178
+	 */
179
+	private function __construct(
180
+		EE_Registry $registry,
181
+		LoaderInterface $loader,
182
+		RequestInterface $request,
183
+		EE_Maintenance_Mode $maintenance_mode
184
+	) {
185
+		$this->registry = $registry;
186
+		$this->loader = $loader;
187
+		$this->request = $request;
188
+		$this->maintenance_mode = $maintenance_mode;
189
+		do_action('AHEE__EE_System__construct__begin', $this);
190
+		add_action(
191
+			'AHEE__EE_Bootstrap__load_espresso_addons',
192
+			array($this, 'loadCapabilities'),
193
+			5
194
+		);
195
+		add_action(
196
+			'AHEE__EE_Bootstrap__load_espresso_addons',
197
+			array($this, 'loadCommandBus'),
198
+			7
199
+		);
200
+		add_action(
201
+			'AHEE__EE_Bootstrap__load_espresso_addons',
202
+			array($this, 'loadPluginApi'),
203
+			9
204
+		);
205
+		// allow addons to load first so that they can register autoloaders, set hooks for running DMS's, etc
206
+		add_action(
207
+			'AHEE__EE_Bootstrap__load_espresso_addons',
208
+			array($this, 'load_espresso_addons')
209
+		);
210
+		// when an ee addon is activated, we want to call the core hook(s) again
211
+		// because the newly-activated addon didn't get a chance to run at all
212
+		add_action('activate_plugin', array($this, 'load_espresso_addons'), 1);
213
+		// detect whether install or upgrade
214
+		add_action(
215
+			'AHEE__EE_Bootstrap__detect_activations_or_upgrades',
216
+			array($this, 'detect_activations_or_upgrades'),
217
+			3
218
+		);
219
+		// load EE_Config, EE_Textdomain, etc
220
+		add_action(
221
+			'AHEE__EE_Bootstrap__load_core_configuration',
222
+			array($this, 'load_core_configuration'),
223
+			5
224
+		);
225
+		// load specifications for matching routes to current request
226
+		add_action(
227
+			'AHEE__EE_Bootstrap__load_core_configuration',
228
+			array($this, 'loadRouteMatchSpecifications')
229
+		);
230
+		// load EE_Config, EE_Textdomain, etc
231
+		add_action(
232
+			'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets',
233
+			array($this, 'register_shortcodes_modules_and_widgets'),
234
+			7
235
+		);
236
+		// you wanna get going? I wanna get going... let's get going!
237
+		add_action(
238
+			'AHEE__EE_Bootstrap__brew_espresso',
239
+			array($this, 'brew_espresso'),
240
+			9
241
+		);
242
+		// other housekeeping
243
+		// exclude EE critical pages from wp_list_pages
244
+		add_filter(
245
+			'wp_list_pages_excludes',
246
+			array($this, 'remove_pages_from_wp_list_pages'),
247
+			10
248
+		);
249
+		// ALL EE Addons should use the following hook point to attach their initial setup too
250
+		// it's extremely important for EE Addons to register any class autoloaders so that they can be available when the EE_Config loads
251
+		do_action('AHEE__EE_System__construct__complete', $this);
252
+	}
253
+
254
+
255
+	/**
256
+	 * load and setup EE_Capabilities
257
+	 *
258
+	 * @return void
259
+	 * @throws EE_Error
260
+	 */
261
+	public function loadCapabilities()
262
+	{
263
+		$this->capabilities = $this->loader->getShared('EE_Capabilities');
264
+		add_action(
265
+			'AHEE__EE_Capabilities__init_caps__before_initialization',
266
+			function () {
267
+				LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
268
+			}
269
+		);
270
+	}
271
+
272
+
273
+	/**
274
+	 * create and cache the CommandBus, and also add middleware
275
+	 * The CapChecker middleware requires the use of EE_Capabilities
276
+	 * which is why we need to load the CommandBus after Caps are set up
277
+	 *
278
+	 * @return void
279
+	 * @throws EE_Error
280
+	 */
281
+	public function loadCommandBus()
282
+	{
283
+		$this->loader->getShared(
284
+			'CommandBusInterface',
285
+			array(
286
+				null,
287
+				apply_filters(
288
+					'FHEE__EE_Load_Espresso_Core__handle_request__CommandBus_middleware',
289
+					array(
290
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\CapChecker'),
291
+						$this->loader->getShared('EventEspresso\core\services\commands\middleware\AddActionHook'),
292
+					)
293
+				),
294
+			)
295
+		);
296
+	}
297
+
298
+
299
+	/**
300
+	 * @return void
301
+	 * @throws EE_Error
302
+	 */
303
+	public function loadPluginApi()
304
+	{
305
+		// set autoloaders for all of the classes implementing EEI_Plugin_API
306
+		// which provide helpers for EE plugin authors to more easily register certain components with EE.
307
+		EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
308
+		// load legacy EE_Request_Handler in case add-ons still need it
309
+		$this->loader->getShared('EE_Request_Handler');
310
+	}
311
+
312
+
313
+	/**
314
+	 * @param string $addon_name
315
+	 * @param string $version_constant
316
+	 * @param string $min_version_required
317
+	 * @param string $load_callback
318
+	 * @param string $plugin_file_constant
319
+	 * @return void
320
+	 */
321
+	private function deactivateIncompatibleAddon(
322
+		$addon_name,
323
+		$version_constant,
324
+		$min_version_required,
325
+		$load_callback,
326
+		$plugin_file_constant
327
+	) {
328
+		if (! defined($version_constant)) {
329
+			return;
330
+		}
331
+		$addon_version = constant($version_constant);
332
+		if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
333
+			remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
334
+			if (! function_exists('deactivate_plugins')) {
335
+				require_once ABSPATH . 'wp-admin/includes/plugin.php';
336
+			}
337
+			deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
338
+			unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
339
+			EE_Error::add_error(
340
+				sprintf(
341
+					esc_html__(
342
+						'We\'re sorry, but the Event Espresso %1$s addon was deactivated because version %2$s or higher is required with this version of Event Espresso core.',
343
+						'event_espresso'
344
+					),
345
+					$addon_name,
346
+					$min_version_required
347
+				),
348
+				__FILE__,
349
+				__FUNCTION__ . "({$addon_name})",
350
+				__LINE__
351
+			);
352
+			EE_Error::get_notices(false, true);
353
+		}
354
+	}
355
+
356
+
357
+	/**
358
+	 * load_espresso_addons
359
+	 * allow addons to load first so that they can set hooks for running DMS's, etc
360
+	 * this is hooked into both:
361
+	 *    'AHEE__EE_Bootstrap__load_core_configuration'
362
+	 *        which runs during the WP 'plugins_loaded' action at priority 5
363
+	 *    and the WP 'activate_plugin' hook point
364
+	 *
365
+	 * @access public
366
+	 * @return void
367
+	 */
368
+	public function load_espresso_addons()
369
+	{
370
+		$this->deactivateIncompatibleAddon(
371
+			'Wait Lists',
372
+			'EE_WAIT_LISTS_VERSION',
373
+			'1.0.0.beta.074',
374
+			'load_espresso_wait_lists',
375
+			'EE_WAIT_LISTS_PLUGIN_FILE'
376
+		);
377
+		$this->deactivateIncompatibleAddon(
378
+			'Automated Upcoming Event Notifications',
379
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_VERSION',
380
+			'1.0.0.beta.091',
381
+			'load_espresso_automated_upcoming_event_notification',
382
+			'EE_AUTOMATED_UPCOMING_EVENT_NOTIFICATION_PLUGIN_FILE'
383
+		);
384
+		do_action('AHEE__EE_System__load_espresso_addons');
385
+		// if the WP API basic auth plugin isn't already loaded, load it now.
386
+		// We want it for mobile apps. Just include the entire plugin
387
+		// also, don't load the basic auth when a plugin is getting activated, because
388
+		// it could be the basic auth plugin, and it doesn't check if its methods are already defined
389
+		// and causes a fatal error
390
+		if (($this->request->isWordPressApi() || $this->request->isApi())
391
+			&& $this->request->getRequestParam('activate') !== 'true'
392
+			&& ! function_exists('json_basic_auth_handler')
393
+			&& ! function_exists('json_basic_auth_error')
394
+			&& ! in_array(
395
+				$this->request->getRequestParam('action'),
396
+				array('activate', 'activate-selected'),
397
+				true
398
+			)
399
+		) {
400
+			include_once EE_THIRD_PARTY . 'wp-api-basic-auth/basic-auth.php';
401
+		}
402
+		do_action('AHEE__EE_System__load_espresso_addons__complete');
403
+	}
404
+
405
+
406
+	/**
407
+	 * detect_activations_or_upgrades
408
+	 * Checks for activation or upgrade of core first;
409
+	 * then also checks if any registered addons have been activated or upgraded
410
+	 * This is hooked into 'AHEE__EE_Bootstrap__detect_activations_or_upgrades'
411
+	 * which runs during the WP 'plugins_loaded' action at priority 3
412
+	 *
413
+	 * @access public
414
+	 * @return void
415
+	 */
416
+	public function detect_activations_or_upgrades()
417
+	{
418
+		// first off: let's make sure to handle core
419
+		$this->detect_if_activation_or_upgrade();
420
+		foreach ($this->registry->addons as $addon) {
421
+			if ($addon instanceof EE_Addon) {
422
+				// detect teh request type for that addon
423
+				$addon->detect_req_type();
424
+			}
425
+		}
426
+	}
427
+
428
+
429
+	/**
430
+	 * detect_if_activation_or_upgrade
431
+	 * Takes care of detecting whether this is a brand new install or code upgrade,
432
+	 * and either setting up the DB or setting up maintenance mode etc.
433
+	 *
434
+	 * @access public
435
+	 * @return void
436
+	 */
437
+	public function detect_if_activation_or_upgrade()
438
+	{
439
+		do_action('AHEE__EE_System___detect_if_activation_or_upgrade__begin');
440
+		// check if db has been updated, or if its a brand-new installation
441
+		$espresso_db_update = $this->fix_espresso_db_upgrade_option();
442
+		$request_type = $this->detect_req_type($espresso_db_update);
443
+		// EEH_Debug_Tools::printr( $request_type, '$request_type', __FILE__, __LINE__ );
444
+		switch ($request_type) {
445
+			case EE_System::req_type_new_activation:
446
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__new_activation');
447
+				$this->_handle_core_version_change($espresso_db_update);
448
+				break;
449
+			case EE_System::req_type_reactivation:
450
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__reactivation');
451
+				$this->_handle_core_version_change($espresso_db_update);
452
+				break;
453
+			case EE_System::req_type_upgrade:
454
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__upgrade');
455
+				// migrations may be required now that we've upgraded
456
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
457
+				$this->_handle_core_version_change($espresso_db_update);
458
+				break;
459
+			case EE_System::req_type_downgrade:
460
+				do_action('AHEE__EE_System__detect_if_activation_or_upgrade__downgrade');
461
+				// its possible migrations are no longer required
462
+				$this->maintenance_mode->set_maintenance_mode_if_db_old();
463
+				$this->_handle_core_version_change($espresso_db_update);
464
+				break;
465
+			case EE_System::req_type_normal:
466
+			default:
467
+				break;
468
+		}
469
+		do_action('AHEE__EE_System__detect_if_activation_or_upgrade__complete');
470
+	}
471
+
472
+
473
+	/**
474
+	 * Updates the list of installed versions and sets hooks for
475
+	 * initializing the database later during the request
476
+	 *
477
+	 * @param array $espresso_db_update
478
+	 */
479
+	private function _handle_core_version_change($espresso_db_update)
480
+	{
481
+		$this->update_list_of_installed_versions($espresso_db_update);
482
+		// get ready to verify the DB is ok (provided we aren't in maintenance mode, of course)
483
+		add_action(
484
+			'AHEE__EE_System__perform_activations_upgrades_and_migrations',
485
+			array($this, 'initialize_db_if_no_migrations_required')
486
+		);
487
+	}
488
+
489
+
490
+	/**
491
+	 * standardizes the wp option 'espresso_db_upgrade' which actually stores
492
+	 * information about what versions of EE have been installed and activated,
493
+	 * NOT necessarily the state of the database
494
+	 *
495
+	 * @param mixed $espresso_db_update           the value of the WordPress option.
496
+	 *                                            If not supplied, fetches it from the options table
497
+	 * @return array the correct value of 'espresso_db_upgrade', after saving it, if it needed correction
498
+	 */
499
+	private function fix_espresso_db_upgrade_option($espresso_db_update = null)
500
+	{
501
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
502
+		if (! $espresso_db_update) {
503
+			$espresso_db_update = get_option('espresso_db_update');
504
+		}
505
+		// check that option is an array
506
+		if (! is_array($espresso_db_update)) {
507
+			// if option is FALSE, then it never existed
508
+			if ($espresso_db_update === false) {
509
+				// make $espresso_db_update an array and save option with autoload OFF
510
+				$espresso_db_update = array();
511
+				add_option('espresso_db_update', $espresso_db_update, '', 'no');
512
+			} else {
513
+				// option is NOT FALSE but also is NOT an array, so make it an array and save it
514
+				$espresso_db_update = array($espresso_db_update => array());
515
+				update_option('espresso_db_update', $espresso_db_update);
516
+			}
517
+		} else {
518
+			$corrected_db_update = array();
519
+			// if IS an array, but is it an array where KEYS are version numbers, and values are arrays?
520
+			foreach ($espresso_db_update as $should_be_version_string => $should_be_array) {
521
+				if (is_int($should_be_version_string) && ! is_array($should_be_array)) {
522
+					// the key is an int, and the value IS NOT an array
523
+					// so it must be numerically-indexed, where values are versions installed...
524
+					// fix it!
525
+					$version_string = $should_be_array;
526
+					$corrected_db_update[ $version_string ] = array('unknown-date');
527
+				} else {
528
+					// ok it checks out
529
+					$corrected_db_update[ $should_be_version_string ] = $should_be_array;
530
+				}
531
+			}
532
+			$espresso_db_update = $corrected_db_update;
533
+			update_option('espresso_db_update', $espresso_db_update);
534
+		}
535
+		do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__complete', $espresso_db_update);
536
+		return $espresso_db_update;
537
+	}
538
+
539
+
540
+	/**
541
+	 * Does the traditional work of setting up the plugin's database and adding default data.
542
+	 * If migration script/process did not exist, this is what would happen on every activation/reactivation/upgrade.
543
+	 * NOTE: if we're in maintenance mode (which would be the case if we detect there are data
544
+	 * migration scripts that need to be run and a version change happens), enqueues core for database initialization,
545
+	 * so that it will be done when migrations are finished
546
+	 *
547
+	 * @param boolean $initialize_addons_too if true, we double-check addons' database tables etc too;
548
+	 * @param boolean $verify_schema         if true will re-check the database tables have the correct schema.
549
+	 *                                       This is a resource-intensive job
550
+	 *                                       so we prefer to only do it when necessary
551
+	 * @return void
552
+	 * @throws EE_Error
553
+	 */
554
+	public function initialize_db_if_no_migrations_required($initialize_addons_too = false, $verify_schema = true)
555
+	{
556
+		$request_type = $this->detect_req_type();
557
+		// only initialize system if we're not in maintenance mode.
558
+		if ($this->maintenance_mode->level() !== EE_Maintenance_Mode::level_2_complete_maintenance) {
559
+			/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
560
+			$rewrite_rules = $this->loader->getShared(
561
+				'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
562
+			);
563
+			$rewrite_rules->flush();
564
+			if ($verify_schema) {
565
+				EEH_Activation::initialize_db_and_folders();
566
+			}
567
+			EEH_Activation::initialize_db_content();
568
+			EEH_Activation::system_initialization();
569
+			if ($initialize_addons_too) {
570
+				$this->initialize_addons();
571
+			}
572
+		} else {
573
+			EE_Data_Migration_Manager::instance()->enqueue_db_initialization_for('Core');
574
+		}
575
+		if ($request_type === EE_System::req_type_new_activation
576
+			|| $request_type === EE_System::req_type_reactivation
577
+			|| (
578
+				$request_type === EE_System::req_type_upgrade
579
+				&& $this->is_major_version_change()
580
+			)
581
+		) {
582
+			add_action('AHEE__EE_System__initialize_last', array($this, 'redirect_to_about_ee'), 9);
583
+		}
584
+	}
585
+
586
+
587
+	/**
588
+	 * Initializes the db for all registered addons
589
+	 *
590
+	 * @throws EE_Error
591
+	 */
592
+	public function initialize_addons()
593
+	{
594
+		// foreach registered addon, make sure its db is up-to-date too
595
+		foreach ($this->registry->addons as $addon) {
596
+			if ($addon instanceof EE_Addon) {
597
+				$addon->initialize_db_if_no_migrations_required();
598
+			}
599
+		}
600
+	}
601
+
602
+
603
+	/**
604
+	 * Adds the current code version to the saved wp option which stores a list of all ee versions ever installed.
605
+	 *
606
+	 * @param    array  $version_history
607
+	 * @param    string $current_version_to_add version to be added to the version history
608
+	 * @return    boolean success as to whether or not this option was changed
609
+	 */
610
+	public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611
+	{
612
+		if (! $version_history) {
613
+			$version_history = $this->fix_espresso_db_upgrade_option($version_history);
614
+		}
615
+		if ($current_version_to_add === null) {
616
+			$current_version_to_add = espresso_version();
617
+		}
618
+		$version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
619
+		// re-save
620
+		return update_option('espresso_db_update', $version_history);
621
+	}
622
+
623
+
624
+	/**
625
+	 * Detects if the current version indicated in the has existed in the list of
626
+	 * previously-installed versions of EE (espresso_db_update). Does NOT modify it (ie, no side-effect)
627
+	 *
628
+	 * @param array $espresso_db_update array from the wp option stored under the name 'espresso_db_update'.
629
+	 *                                  If not supplied, fetches it from the options table.
630
+	 *                                  Also, caches its result so later parts of the code can also know whether
631
+	 *                                  there's been an update or not. This way we can add the current version to
632
+	 *                                  espresso_db_update, but still know if this is a new install or not
633
+	 * @return int one of the constants on EE_System::req_type_
634
+	 */
635
+	public function detect_req_type($espresso_db_update = null)
636
+	{
637
+		if ($this->_req_type === null) {
638
+			$espresso_db_update = ! empty($espresso_db_update)
639
+				? $espresso_db_update
640
+				: $this->fix_espresso_db_upgrade_option();
641
+			$this->_req_type = EE_System::detect_req_type_given_activation_history(
642
+				$espresso_db_update,
643
+				'ee_espresso_activation',
644
+				espresso_version()
645
+			);
646
+			$this->_major_version_change = $this->_detect_major_version_change($espresso_db_update);
647
+			$this->request->setIsActivation($this->_req_type !== EE_System::req_type_normal);
648
+		}
649
+		return $this->_req_type;
650
+	}
651
+
652
+
653
+	/**
654
+	 * Returns whether or not there was a non-micro version change (ie, change in either
655
+	 * the first or second number in the version. Eg 4.9.0.rc.001 to 4.10.0.rc.000,
656
+	 * but not 4.9.0.rc.0001 to 4.9.1.rc.0001
657
+	 *
658
+	 * @param $activation_history
659
+	 * @return bool
660
+	 */
661
+	private function _detect_major_version_change($activation_history)
662
+	{
663
+		$previous_version = EE_System::_get_most_recently_active_version_from_activation_history($activation_history);
664
+		$previous_version_parts = explode('.', $previous_version);
665
+		$current_version_parts = explode('.', espresso_version());
666
+		return isset($previous_version_parts[0], $previous_version_parts[1], $current_version_parts[0], $current_version_parts[1])
667
+			   && ($previous_version_parts[0] !== $current_version_parts[0]
668
+				   || $previous_version_parts[1] !== $current_version_parts[1]
669
+			   );
670
+	}
671
+
672
+
673
+	/**
674
+	 * Returns true if either the major or minor version of EE changed during this request.
675
+	 * Eg 4.9.0.rc.001 to 4.10.0.rc.000, but not 4.9.0.rc.0001 to 4.9.1.rc.0001
676
+	 *
677
+	 * @return bool
678
+	 */
679
+	public function is_major_version_change()
680
+	{
681
+		return $this->_major_version_change;
682
+	}
683
+
684
+
685
+	/**
686
+	 * Determines the request type for any ee addon, given three piece of info: the current array of activation
687
+	 * histories (for core that' 'espresso_db_update' wp option); the name of the WordPress option which is temporarily
688
+	 * set upon activation of the plugin (for core it's 'ee_espresso_activation'); and the version that this plugin was
689
+	 * just activated to (for core that will always be espresso_version())
690
+	 *
691
+	 * @param array  $activation_history_for_addon     the option's value which stores the activation history for this
692
+	 *                                                 ee plugin. for core that's 'espresso_db_update'
693
+	 * @param string $activation_indicator_option_name the name of the WordPress option that is temporarily set to
694
+	 *                                                 indicate that this plugin was just activated
695
+	 * @param string $version_to_upgrade_to            the version that was just upgraded to (for core that will be
696
+	 *                                                 espresso_version())
697
+	 * @return int one of the constants on EE_System::req_type_*
698
+	 */
699
+	public static function detect_req_type_given_activation_history(
700
+		$activation_history_for_addon,
701
+		$activation_indicator_option_name,
702
+		$version_to_upgrade_to
703
+	) {
704
+		$version_is_higher = self::_new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to);
705
+		if ($activation_history_for_addon) {
706
+			// it exists, so this isn't a completely new install
707
+			// check if this version already in that list of previously installed versions
708
+			if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
709
+				// it a version we haven't seen before
710
+				if ($version_is_higher === 1) {
711
+					$req_type = EE_System::req_type_upgrade;
712
+				} else {
713
+					$req_type = EE_System::req_type_downgrade;
714
+				}
715
+				delete_option($activation_indicator_option_name);
716
+			} else {
717
+				// its not an update. maybe a reactivation?
718
+				if (get_option($activation_indicator_option_name, false)) {
719
+					if ($version_is_higher === -1) {
720
+						$req_type = EE_System::req_type_downgrade;
721
+					} elseif ($version_is_higher === 0) {
722
+						// we've seen this version before, but it's an activation. must be a reactivation
723
+						$req_type = EE_System::req_type_reactivation;
724
+					} else {// $version_is_higher === 1
725
+						$req_type = EE_System::req_type_upgrade;
726
+					}
727
+					delete_option($activation_indicator_option_name);
728
+				} else {
729
+					// we've seen this version before and the activation indicate doesn't show it was just activated
730
+					if ($version_is_higher === -1) {
731
+						$req_type = EE_System::req_type_downgrade;
732
+					} elseif ($version_is_higher === 0) {
733
+						// we've seen this version before and it's not an activation. its normal request
734
+						$req_type = EE_System::req_type_normal;
735
+					} else {// $version_is_higher === 1
736
+						$req_type = EE_System::req_type_upgrade;
737
+					}
738
+				}
739
+			}
740
+		} else {
741
+			// brand new install
742
+			$req_type = EE_System::req_type_new_activation;
743
+			delete_option($activation_indicator_option_name);
744
+		}
745
+		return $req_type;
746
+	}
747
+
748
+
749
+	/**
750
+	 * Detects if the $version_to_upgrade_to is higher than the most recent version in
751
+	 * the $activation_history_for_addon
752
+	 *
753
+	 * @param array  $activation_history_for_addon (keys are versions, values are arrays of times activated,
754
+	 *                                             sometimes containing 'unknown-date'
755
+	 * @param string $version_to_upgrade_to        (current version)
756
+	 * @return int results of version_compare( $version_to_upgrade_to, $most_recently_active_version ).
757
+	 *                                             ie, -1 if $version_to_upgrade_to is LOWER (downgrade);
758
+	 *                                             0 if $version_to_upgrade_to MATCHES (reactivation or normal request);
759
+	 *                                             1 if $version_to_upgrade_to is HIGHER (upgrade) ;
760
+	 */
761
+	private static function _new_version_is_higher($activation_history_for_addon, $version_to_upgrade_to)
762
+	{
763
+		// find the most recently-activated version
764
+		$most_recently_active_version =
765
+			EE_System::_get_most_recently_active_version_from_activation_history($activation_history_for_addon);
766
+		return version_compare($version_to_upgrade_to, $most_recently_active_version);
767
+	}
768
+
769
+
770
+	/**
771
+	 * Gets the most recently active version listed in the activation history,
772
+	 * and if none are found (ie, it's a brand new install) returns '0.0.0.dev.000'.
773
+	 *
774
+	 * @param array $activation_history  (keys are versions, values are arrays of times activated,
775
+	 *                                   sometimes containing 'unknown-date'
776
+	 * @return string
777
+	 */
778
+	private static function _get_most_recently_active_version_from_activation_history($activation_history)
779
+	{
780
+		$most_recently_active_version_activation = '1970-01-01 00:00:00';
781
+		$most_recently_active_version = '0.0.0.dev.000';
782
+		if (is_array($activation_history)) {
783
+			foreach ($activation_history as $version => $times_activated) {
784
+				// check there is a record of when this version was activated. Otherwise,
785
+				// mark it as unknown
786
+				if (! $times_activated) {
787
+					$times_activated = array('unknown-date');
788
+				}
789
+				if (is_string($times_activated)) {
790
+					$times_activated = array($times_activated);
791
+				}
792
+				foreach ($times_activated as $an_activation) {
793
+					if ($an_activation !== 'unknown-date'
794
+						&& $an_activation
795
+						   > $most_recently_active_version_activation) {
796
+						$most_recently_active_version = $version;
797
+						$most_recently_active_version_activation = $an_activation === 'unknown-date'
798
+							? '1970-01-01 00:00:00'
799
+							: $an_activation;
800
+					}
801
+				}
802
+			}
803
+		}
804
+		return $most_recently_active_version;
805
+	}
806
+
807
+
808
+	/**
809
+	 * This redirects to the about EE page after activation
810
+	 *
811
+	 * @return void
812
+	 */
813
+	public function redirect_to_about_ee()
814
+	{
815
+		$notices = EE_Error::get_notices(false);
816
+		// if current user is an admin and it's not an ajax or rest request
817
+		if (! isset($notices['errors'])
818
+			&& $this->request->isAdmin()
819
+			&& apply_filters(
820
+				'FHEE__EE_System__redirect_to_about_ee__do_redirect',
821
+				$this->capabilities->current_user_can('manage_options', 'espresso_about_default')
822
+			)
823
+		) {
824
+			$query_params = array('page' => 'espresso_about');
825
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_new_activation) {
826
+				$query_params['new_activation'] = true;
827
+			}
828
+			if (EE_System::instance()->detect_req_type() === EE_System::req_type_reactivation) {
829
+				$query_params['reactivation'] = true;
830
+			}
831
+			$url = add_query_arg($query_params, admin_url('admin.php'));
832
+			wp_safe_redirect($url);
833
+			exit();
834
+		}
835
+	}
836
+
837
+
838
+	/**
839
+	 * load_core_configuration
840
+	 * this is hooked into 'AHEE__EE_Bootstrap__load_core_configuration'
841
+	 * which runs during the WP 'plugins_loaded' action at priority 5
842
+	 *
843
+	 * @return void
844
+	 * @throws ReflectionException
845
+	 * @throws Exception
846
+	 */
847
+	public function load_core_configuration()
848
+	{
849
+		do_action('AHEE__EE_System__load_core_configuration__begin', $this);
850
+		$this->loader->getShared('EE_Load_Textdomain');
851
+		// load textdomain
852
+		EE_Load_Textdomain::load_textdomain();
853
+		// load caf stuff a chance to play during the activation process too.
854
+		$this->_maybe_brew_regular();
855
+		// load and setup EE_Config and EE_Network_Config
856
+		$config = $this->loader->getShared('EE_Config');
857
+		$this->loader->getShared('EE_Network_Config');
858
+		// setup autoloaders
859
+		// enable logging?
860
+		if ($config->admin->use_remote_logging) {
861
+			$this->loader->getShared('EE_Log');
862
+		}
863
+		// check for activation errors
864
+		$activation_errors = get_option('ee_plugin_activation_errors', false);
865
+		if ($activation_errors) {
866
+			EE_Error::add_error($activation_errors, __FILE__, __FUNCTION__, __LINE__);
867
+			update_option('ee_plugin_activation_errors', false);
868
+		}
869
+		// get model names
870
+		$this->_parse_model_names();
871
+		// configure custom post type definitions
872
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomTaxonomyDefinitions');
873
+		$this->loader->getShared('EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions');
874
+		do_action('AHEE__EE_System__load_core_configuration__complete', $this);
875
+	}
876
+
877
+
878
+	/**
879
+	 * cycles through all of the models/*.model.php files, and assembles an array of model names
880
+	 *
881
+	 * @return void
882
+	 * @throws ReflectionException
883
+	 */
884
+	private function _parse_model_names()
885
+	{
886
+		// get all the files in the EE_MODELS folder that end in .model.php
887
+		$models = glob(EE_MODELS . '*.model.php');
888
+		$model_names = array();
889
+		$non_abstract_db_models = array();
890
+		foreach ($models as $model) {
891
+			// get model classname
892
+			$classname = EEH_File::get_classname_from_filepath_with_standard_filename($model);
893
+			$short_name = str_replace('EEM_', '', $classname);
894
+			$reflectionClass = new ReflectionClass($classname);
895
+			if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
+				$non_abstract_db_models[ $short_name ] = $classname;
897
+			}
898
+			$model_names[ $short_name ] = $classname;
899
+		}
900
+		$this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901
+		$this->registry->non_abstract_db_models = apply_filters(
902
+			'FHEE__EE_System__parse_implemented_model_names',
903
+			$non_abstract_db_models
904
+		);
905
+	}
906
+
907
+
908
+	/**
909
+	 * The purpose of this method is to simply check for a file named "caffeinated/brewing_regular.php" for any hooks
910
+	 * that need to be setup before our EE_System launches.
911
+	 *
912
+	 * @return void
913
+	 * @throws DomainException
914
+	 * @throws InvalidArgumentException
915
+	 * @throws InvalidDataTypeException
916
+	 * @throws InvalidInterfaceException
917
+	 * @throws InvalidClassException
918
+	 * @throws InvalidFilePathException
919
+	 */
920
+	private function _maybe_brew_regular()
921
+	{
922
+		/** @var Domain $domain */
923
+		$domain = DomainFactory::getShared(
924
+			new FullyQualifiedName(
925
+				'EventEspresso\core\domain\Domain'
926
+			),
927
+			array(
928
+				new FilePath(EVENT_ESPRESSO_MAIN_FILE),
929
+				Version::fromString(espresso_version()),
930
+			)
931
+		);
932
+		if ($domain->isCaffeinated()) {
933
+			require_once EE_CAFF_PATH . 'brewing_regular.php';
934
+		}
935
+	}
936
+
937
+
938
+	/**
939
+	 * @since 4.9.71.p
940
+	 * @throws Exception
941
+	 */
942
+	public function loadRouteMatchSpecifications()
943
+	{
944
+		try {
945
+			$this->loader->getShared(
946
+				'EventEspresso\core\services\route_match\RouteMatchSpecificationManager'
947
+			);
948
+		} catch (Exception $exception) {
949
+			new ExceptionStackTraceDisplay($exception);
950
+		}
951
+		do_action('AHEE__EE_System__loadRouteMatchSpecifications');
952
+	}
953
+
954
+
955
+	/**
956
+	 * register_shortcodes_modules_and_widgets
957
+	 * generate lists of shortcodes and modules, then verify paths and classes
958
+	 * This is hooked into 'AHEE__EE_Bootstrap__register_shortcodes_modules_and_widgets'
959
+	 * which runs during the WP 'plugins_loaded' action at priority 7
960
+	 *
961
+	 * @access public
962
+	 * @return void
963
+	 * @throws Exception
964
+	 */
965
+	public function register_shortcodes_modules_and_widgets()
966
+	{
967
+		if ($this->request->isFrontend() || $this->request->isIframe() || $this->request->isAjax()) {
968
+			// load, register, and add shortcodes the new way
969
+			$this->loader->getShared('EventEspresso\core\services\shortcodes\ShortcodesManager');
970
+		}
971
+		do_action('AHEE__EE_System__register_shortcodes_modules_and_widgets');
972
+		// check for addons using old hook point
973
+		if (has_action('AHEE__EE_System__register_shortcodes_modules_and_addons')) {
974
+			$this->_incompatible_addon_error();
975
+		}
976
+	}
977
+
978
+
979
+	/**
980
+	 * _incompatible_addon_error
981
+	 *
982
+	 * @access public
983
+	 * @return void
984
+	 */
985
+	private function _incompatible_addon_error()
986
+	{
987
+		// get array of classes hooking into here
988
+		$class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
989
+			'AHEE__EE_System__register_shortcodes_modules_and_addons'
990
+		);
991
+		if (! empty($class_names)) {
992
+			$msg = __(
993
+				'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
994
+				'event_espresso'
995
+			);
996
+			$msg .= '<ul>';
997
+			foreach ($class_names as $class_name) {
998
+				$msg .= '<li><b>Event Espresso - '
999
+						. str_replace(
1000
+							array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'),
1001
+							'',
1002
+							$class_name
1003
+						) . '</b></li>';
1004
+			}
1005
+			$msg .= '</ul>';
1006
+			$msg .= __(
1007
+				'Compatibility issues can be avoided and/or resolved by keeping addons and plugins updated to the latest version.',
1008
+				'event_espresso'
1009
+			);
1010
+			// save list of incompatible addons to wp-options for later use
1011
+			add_option('ee_incompatible_addons', $class_names, '', 'no');
1012
+			if (is_admin()) {
1013
+				EE_Error::add_error($msg, __FILE__, __FUNCTION__, __LINE__);
1014
+			}
1015
+		}
1016
+	}
1017
+
1018
+
1019
+	/**
1020
+	 * brew_espresso
1021
+	 * begins the process of setting hooks for initializing EE in the correct order
1022
+	 * This is happening on the 'AHEE__EE_Bootstrap__brew_espresso' hook point
1023
+	 * which runs during the WP 'plugins_loaded' action at priority 9
1024
+	 *
1025
+	 * @return void
1026
+	 */
1027
+	public function brew_espresso()
1028
+	{
1029
+		do_action('AHEE__EE_System__brew_espresso__begin', $this);
1030
+		// load some final core systems
1031
+		add_action('init', array($this, 'set_hooks_for_core'), 1);
1032
+		add_action('init', array($this, 'perform_activations_upgrades_and_migrations'), 3);
1033
+		add_action('init', array($this, 'load_CPTs_and_session'), 5);
1034
+		add_action('init', array($this, 'load_controllers'), 7);
1035
+		add_action('init', array($this, 'core_loaded_and_ready'), 9);
1036
+		add_action('init', array($this, 'initialize'), 10);
1037
+		add_action('init', array($this, 'initialize_last'), 100);
1038
+		if (is_admin() && apply_filters('FHEE__EE_System__brew_espresso__load_pue', true)) {
1039
+			// pew pew pew
1040
+			$this->loader->getShared('EventEspresso\core\services\licensing\LicenseService');
1041
+			do_action('AHEE__EE_System__brew_espresso__after_pue_init');
1042
+		}
1043
+		do_action('AHEE__EE_System__brew_espresso__complete', $this);
1044
+	}
1045
+
1046
+
1047
+	/**
1048
+	 *    set_hooks_for_core
1049
+	 *
1050
+	 * @access public
1051
+	 * @return    void
1052
+	 * @throws EE_Error
1053
+	 */
1054
+	public function set_hooks_for_core()
1055
+	{
1056
+		$this->_deactivate_incompatible_addons();
1057
+		do_action('AHEE__EE_System__set_hooks_for_core');
1058
+		$this->loader->getShared('EventEspresso\core\domain\values\session\SessionLifespan');
1059
+		// caps need to be initialized on every request so that capability maps are set.
1060
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/8674
1061
+		$this->registry->CAP->init_caps();
1062
+	}
1063
+
1064
+
1065
+	/**
1066
+	 * Using the information gathered in EE_System::_incompatible_addon_error,
1067
+	 * deactivates any addons considered incompatible with the current version of EE
1068
+	 */
1069
+	private function _deactivate_incompatible_addons()
1070
+	{
1071
+		$incompatible_addons = get_option('ee_incompatible_addons', array());
1072
+		if (! empty($incompatible_addons)) {
1073
+			$active_plugins = get_option('active_plugins', array());
1074
+			foreach ($active_plugins as $active_plugin) {
1075
+				foreach ($incompatible_addons as $incompatible_addon) {
1076
+					if (strpos($active_plugin, $incompatible_addon) !== false) {
1077
+						unset($_GET['activate']);
1078
+						espresso_deactivate_plugin($active_plugin);
1079
+					}
1080
+				}
1081
+			}
1082
+		}
1083
+	}
1084
+
1085
+
1086
+	/**
1087
+	 *    perform_activations_upgrades_and_migrations
1088
+	 *
1089
+	 * @access public
1090
+	 * @return    void
1091
+	 */
1092
+	public function perform_activations_upgrades_and_migrations()
1093
+	{
1094
+		do_action('AHEE__EE_System__perform_activations_upgrades_and_migrations');
1095
+	}
1096
+
1097
+
1098
+	/**
1099
+	 * @return void
1100
+	 * @throws DomainException
1101
+	 */
1102
+	public function load_CPTs_and_session()
1103
+	{
1104
+		do_action('AHEE__EE_System__load_CPTs_and_session__start');
1105
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies $register_custom_taxonomies */
1106
+		$register_custom_taxonomies = $this->loader->getShared(
1107
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomies'
1108
+		);
1109
+		$register_custom_taxonomies->registerCustomTaxonomies();
1110
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes $register_custom_post_types */
1111
+		$register_custom_post_types = $this->loader->getShared(
1112
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomPostTypes'
1113
+		);
1114
+		$register_custom_post_types->registerCustomPostTypes();
1115
+		/** @var EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms $register_custom_taxonomy_terms */
1116
+		$register_custom_taxonomy_terms = $this->loader->getShared(
1117
+			'EventEspresso\core\domain\services\custom_post_types\RegisterCustomTaxonomyTerms'
1118
+		);
1119
+		$register_custom_taxonomy_terms->registerCustomTaxonomyTerms();
1120
+		// load legacy Custom Post Types and Taxonomies
1121
+		$this->loader->getShared('EE_Register_CPTs');
1122
+		do_action('AHEE__EE_System__load_CPTs_and_session__complete');
1123
+	}
1124
+
1125
+
1126
+	/**
1127
+	 * load_controllers
1128
+	 * this is the best place to load any additional controllers that needs access to EE core.
1129
+	 * it is expected that all basic core EE systems, that are not dependant on the current request are loaded at this
1130
+	 * time
1131
+	 *
1132
+	 * @access public
1133
+	 * @return void
1134
+	 */
1135
+	public function load_controllers()
1136
+	{
1137
+		do_action('AHEE__EE_System__load_controllers__start');
1138
+		// let's get it started
1139
+		if (! $this->maintenance_mode->level()
1140
+			&& ($this->request->isFrontend() || $this->request->isFrontAjax())
1141
+		) {
1142
+			do_action('AHEE__EE_System__load_controllers__load_front_controllers');
1143
+			$this->loader->getShared('EE_Front_Controller');
1144
+		} elseif ($this->request->isAdmin() || $this->request->isAdminAjax()) {
1145
+			do_action('AHEE__EE_System__load_controllers__load_admin_controllers');
1146
+			$this->loader->getShared('EE_Admin');
1147
+		} elseif ($this->request->isWordPressHeartbeat()) {
1148
+			$this->loader->getShared('EventEspresso\core\domain\services\admin\ajax\WordpressHeartbeat');
1149
+		}
1150
+		do_action('AHEE__EE_System__load_controllers__complete');
1151
+	}
1152
+
1153
+
1154
+	/**
1155
+	 * core_loaded_and_ready
1156
+	 * all of the basic EE core should be loaded at this point and available regardless of M-Mode
1157
+	 *
1158
+	 * @access public
1159
+	 * @return void
1160
+	 * @throws Exception
1161
+	 */
1162
+	public function core_loaded_and_ready()
1163
+	{
1164
+		if ($this->request->isAdmin()
1165
+			|| $this->request->isFrontend()
1166
+			|| $this->request->isIframe()
1167
+			|| $this->request->isWordPressApi()
1168
+		) {
1169
+			try {
1170
+				$this->loader->getShared('EventEspresso\core\services\assets\Registry');
1171
+				$this->loader->getShared('EventEspresso\core\domain\services\assets\CoreAssetManager');
1172
+				if ($this->canLoadBlocks()) {
1173
+					$this->loader->getShared(
1174
+						'EventEspresso\core\services\editor\BlockRegistrationManager'
1175
+					);
1176
+				}
1177
+			} catch (Exception $exception) {
1178
+				new ExceptionStackTraceDisplay($exception);
1179
+			}
1180
+		}
1181
+		if ($this->request->isAdmin()
1182
+			|| $this->request->isEeAjax()
1183
+			|| $this->request->isFrontend()
1184
+		) {
1185
+			$this->loader->getShared('EE_Session');
1186
+		}
1187
+		// integrate WP_Query with the EE models
1188
+		$this->loader->getShared('EE_CPT_Strategy');
1189
+		do_action('AHEE__EE_System__core_loaded_and_ready');
1190
+		// always load template tags, because it's faster than checking if it's a front-end request, and many page
1191
+		// builders require these even on the front-end
1192
+		require_once EE_PUBLIC . 'template_tags.php';
1193
+		do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1194
+	}
1195
+
1196
+
1197
+	/**
1198
+	 * initialize
1199
+	 * this is the best place to begin initializing client code
1200
+	 *
1201
+	 * @access public
1202
+	 * @return void
1203
+	 */
1204
+	public function initialize()
1205
+	{
1206
+		do_action('AHEE__EE_System__initialize');
1207
+	}
1208
+
1209
+
1210
+	/**
1211
+	 * initialize_last
1212
+	 * this is run really late during the WP init hook point, and ensures that mostly everything else that needs to
1213
+	 * initialize has done so
1214
+	 *
1215
+	 * @access public
1216
+	 * @return void
1217
+	 */
1218
+	public function initialize_last()
1219
+	{
1220
+		do_action('AHEE__EE_System__initialize_last');
1221
+		/** @var EventEspresso\core\domain\services\custom_post_types\RewriteRules $rewrite_rules */
1222
+		$rewrite_rules = $this->loader->getShared(
1223
+			'EventEspresso\core\domain\services\custom_post_types\RewriteRules'
1224
+		);
1225
+		$rewrite_rules->flushRewriteRules();
1226
+		add_action('admin_bar_init', array($this, 'addEspressoToolbar'));
1227
+		if (($this->request->isAjax() || $this->request->isAdmin())
1228
+			&& $this->maintenance_mode->models_can_query()) {
1229
+			$this->loader->getShared('EventEspresso\core\services\privacy\export\PersonalDataExporterManager');
1230
+			$this->loader->getShared('EventEspresso\core\services\privacy\erasure\PersonalDataEraserManager');
1231
+		}
1232
+	}
1233
+
1234
+
1235
+	/**
1236
+	 * @return void
1237
+	 * @throws EE_Error
1238
+	 */
1239
+	public function addEspressoToolbar()
1240
+	{
1241
+		$this->loader->getShared(
1242
+			'EventEspresso\core\domain\services\admin\AdminToolBar',
1243
+			array($this->registry->CAP)
1244
+		);
1245
+	}
1246
+
1247
+
1248
+	/**
1249
+	 * do_not_cache
1250
+	 * sets no cache headers and defines no cache constants for WP plugins
1251
+	 *
1252
+	 * @access public
1253
+	 * @return void
1254
+	 */
1255
+	public static function do_not_cache()
1256
+	{
1257
+		// set no cache constants
1258
+		if (! defined('DONOTCACHEPAGE')) {
1259
+			define('DONOTCACHEPAGE', true);
1260
+		}
1261
+		if (! defined('DONOTCACHCEOBJECT')) {
1262
+			define('DONOTCACHCEOBJECT', true);
1263
+		}
1264
+		if (! defined('DONOTCACHEDB')) {
1265
+			define('DONOTCACHEDB', true);
1266
+		}
1267
+		// add no cache headers
1268
+		add_action('send_headers', array('EE_System', 'nocache_headers'), 10);
1269
+		// plus a little extra for nginx and Google Chrome
1270
+		add_filter('nocache_headers', array('EE_System', 'extra_nocache_headers'), 10, 1);
1271
+		// prevent browsers from prefetching of the rel='next' link, because it may contain content that interferes with the registration process
1272
+		remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');
1273
+	}
1274
+
1275
+
1276
+	/**
1277
+	 *    extra_nocache_headers
1278
+	 *
1279
+	 * @access    public
1280
+	 * @param $headers
1281
+	 * @return    array
1282
+	 */
1283
+	public static function extra_nocache_headers($headers)
1284
+	{
1285
+		// for NGINX
1286
+		$headers['X-Accel-Expires'] = 0;
1287
+		// plus extra for Google Chrome since it doesn't seem to respect "no-cache", but WILL respect "no-store"
1288
+		$headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
1289
+		return $headers;
1290
+	}
1291
+
1292
+
1293
+	/**
1294
+	 *    nocache_headers
1295
+	 *
1296
+	 * @access    public
1297
+	 * @return    void
1298
+	 */
1299
+	public static function nocache_headers()
1300
+	{
1301
+		nocache_headers();
1302
+	}
1303
+
1304
+
1305
+	/**
1306
+	 * simply hooks into "wp_list_pages_exclude" filter (for wp_list_pages method) and makes sure EE critical pages are
1307
+	 * never returned with the function.
1308
+	 *
1309
+	 * @param  array $exclude_array any existing pages being excluded are in this array.
1310
+	 * @return array
1311
+	 */
1312
+	public function remove_pages_from_wp_list_pages($exclude_array)
1313
+	{
1314
+		return array_merge($exclude_array, $this->registry->CFG->core->get_critical_pages_array());
1315
+	}
1316
+
1317
+
1318
+	/**
1319
+	 * Return whether blocks can be registered/loaded or not.
1320
+	 * @return bool
1321
+	 */
1322
+	private function canLoadBlocks()
1323
+	{
1324
+		return apply_filters('FHEE__EE_System__canLoadBlocks', true)
1325
+			   && function_exists('register_block_type')
1326
+			   // don't load blocks if in the Divi page builder editor context
1327
+			   // @see https://github.com/eventespresso/event-espresso-core/issues/814
1328
+			   && ! $this->request->getRequestParam('et_fb', false);
1329
+	}
1330 1330
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
         EE_Maintenance_Mode $maintenance_mode = null
142 142
     ) {
143 143
         // check if class object is instantiated
144
-        if (! self::$_instance instanceof EE_System) {
144
+        if ( ! self::$_instance instanceof EE_System) {
145 145
             self::$_instance = new self($registry, $loader, $request, $maintenance_mode);
146 146
         }
147 147
         return self::$_instance;
@@ -263,7 +263,7 @@  discard block
 block discarded – undo
263 263
         $this->capabilities = $this->loader->getShared('EE_Capabilities');
264 264
         add_action(
265 265
             'AHEE__EE_Capabilities__init_caps__before_initialization',
266
-            function () {
266
+            function() {
267 267
                 LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
268 268
             }
269 269
         );
@@ -304,7 +304,7 @@  discard block
 block discarded – undo
304 304
     {
305 305
         // set autoloaders for all of the classes implementing EEI_Plugin_API
306 306
         // which provide helpers for EE plugin authors to more easily register certain components with EE.
307
-        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES . 'plugin_api');
307
+        EEH_Autoloader::instance()->register_autoloaders_for_each_file_in_folder(EE_LIBRARIES.'plugin_api');
308 308
         // load legacy EE_Request_Handler in case add-ons still need it
309 309
         $this->loader->getShared('EE_Request_Handler');
310 310
     }
@@ -325,14 +325,14 @@  discard block
 block discarded – undo
325 325
         $load_callback,
326 326
         $plugin_file_constant
327 327
     ) {
328
-        if (! defined($version_constant)) {
328
+        if ( ! defined($version_constant)) {
329 329
             return;
330 330
         }
331 331
         $addon_version = constant($version_constant);
332 332
         if ($addon_version && version_compare($addon_version, $min_version_required, '<')) {
333 333
             remove_action('AHEE__EE_System__load_espresso_addons', $load_callback);
334
-            if (! function_exists('deactivate_plugins')) {
335
-                require_once ABSPATH . 'wp-admin/includes/plugin.php';
334
+            if ( ! function_exists('deactivate_plugins')) {
335
+                require_once ABSPATH.'wp-admin/includes/plugin.php';
336 336
             }
337 337
             deactivate_plugins(plugin_basename(constant($plugin_file_constant)));
338 338
             unset($_GET['activate'], $_REQUEST['activate'], $_GET['activate-multi'], $_REQUEST['activate-multi']);
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
                     $min_version_required
347 347
                 ),
348 348
                 __FILE__,
349
-                __FUNCTION__ . "({$addon_name})",
349
+                __FUNCTION__."({$addon_name})",
350 350
                 __LINE__
351 351
             );
352 352
             EE_Error::get_notices(false, true);
@@ -397,7 +397,7 @@  discard block
 block discarded – undo
397 397
                 true
398 398
             )
399 399
         ) {
400
-            include_once EE_THIRD_PARTY . 'wp-api-basic-auth/basic-auth.php';
400
+            include_once EE_THIRD_PARTY.'wp-api-basic-auth/basic-auth.php';
401 401
         }
402 402
         do_action('AHEE__EE_System__load_espresso_addons__complete');
403 403
     }
@@ -499,11 +499,11 @@  discard block
 block discarded – undo
499 499
     private function fix_espresso_db_upgrade_option($espresso_db_update = null)
500 500
     {
501 501
         do_action('FHEE__EE_System__manage_fix_espresso_db_upgrade_option__begin', $espresso_db_update);
502
-        if (! $espresso_db_update) {
502
+        if ( ! $espresso_db_update) {
503 503
             $espresso_db_update = get_option('espresso_db_update');
504 504
         }
505 505
         // check that option is an array
506
-        if (! is_array($espresso_db_update)) {
506
+        if ( ! is_array($espresso_db_update)) {
507 507
             // if option is FALSE, then it never existed
508 508
             if ($espresso_db_update === false) {
509 509
                 // make $espresso_db_update an array and save option with autoload OFF
@@ -523,10 +523,10 @@  discard block
 block discarded – undo
523 523
                     // so it must be numerically-indexed, where values are versions installed...
524 524
                     // fix it!
525 525
                     $version_string = $should_be_array;
526
-                    $corrected_db_update[ $version_string ] = array('unknown-date');
526
+                    $corrected_db_update[$version_string] = array('unknown-date');
527 527
                 } else {
528 528
                     // ok it checks out
529
-                    $corrected_db_update[ $should_be_version_string ] = $should_be_array;
529
+                    $corrected_db_update[$should_be_version_string] = $should_be_array;
530 530
                 }
531 531
             }
532 532
             $espresso_db_update = $corrected_db_update;
@@ -609,13 +609,13 @@  discard block
 block discarded – undo
609 609
      */
610 610
     public function update_list_of_installed_versions($version_history = null, $current_version_to_add = null)
611 611
     {
612
-        if (! $version_history) {
612
+        if ( ! $version_history) {
613 613
             $version_history = $this->fix_espresso_db_upgrade_option($version_history);
614 614
         }
615 615
         if ($current_version_to_add === null) {
616 616
             $current_version_to_add = espresso_version();
617 617
         }
618
-        $version_history[ $current_version_to_add ][] = date('Y-m-d H:i:s', time());
618
+        $version_history[$current_version_to_add][] = date('Y-m-d H:i:s', time());
619 619
         // re-save
620 620
         return update_option('espresso_db_update', $version_history);
621 621
     }
@@ -705,7 +705,7 @@  discard block
 block discarded – undo
705 705
         if ($activation_history_for_addon) {
706 706
             // it exists, so this isn't a completely new install
707 707
             // check if this version already in that list of previously installed versions
708
-            if (! isset($activation_history_for_addon[ $version_to_upgrade_to ])) {
708
+            if ( ! isset($activation_history_for_addon[$version_to_upgrade_to])) {
709 709
                 // it a version we haven't seen before
710 710
                 if ($version_is_higher === 1) {
711 711
                     $req_type = EE_System::req_type_upgrade;
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
             foreach ($activation_history as $version => $times_activated) {
784 784
                 // check there is a record of when this version was activated. Otherwise,
785 785
                 // mark it as unknown
786
-                if (! $times_activated) {
786
+                if ( ! $times_activated) {
787 787
                     $times_activated = array('unknown-date');
788 788
                 }
789 789
                 if (is_string($times_activated)) {
@@ -814,7 +814,7 @@  discard block
 block discarded – undo
814 814
     {
815 815
         $notices = EE_Error::get_notices(false);
816 816
         // if current user is an admin and it's not an ajax or rest request
817
-        if (! isset($notices['errors'])
817
+        if ( ! isset($notices['errors'])
818 818
             && $this->request->isAdmin()
819 819
             && apply_filters(
820 820
                 'FHEE__EE_System__redirect_to_about_ee__do_redirect',
@@ -884,7 +884,7 @@  discard block
 block discarded – undo
884 884
     private function _parse_model_names()
885 885
     {
886 886
         // get all the files in the EE_MODELS folder that end in .model.php
887
-        $models = glob(EE_MODELS . '*.model.php');
887
+        $models = glob(EE_MODELS.'*.model.php');
888 888
         $model_names = array();
889 889
         $non_abstract_db_models = array();
890 890
         foreach ($models as $model) {
@@ -893,9 +893,9 @@  discard block
 block discarded – undo
893 893
             $short_name = str_replace('EEM_', '', $classname);
894 894
             $reflectionClass = new ReflectionClass($classname);
895 895
             if ($reflectionClass->isSubclassOf('EEM_Base') && ! $reflectionClass->isAbstract()) {
896
-                $non_abstract_db_models[ $short_name ] = $classname;
896
+                $non_abstract_db_models[$short_name] = $classname;
897 897
             }
898
-            $model_names[ $short_name ] = $classname;
898
+            $model_names[$short_name] = $classname;
899 899
         }
900 900
         $this->registry->models = apply_filters('FHEE__EE_System__parse_model_names', $model_names);
901 901
         $this->registry->non_abstract_db_models = apply_filters(
@@ -930,7 +930,7 @@  discard block
 block discarded – undo
930 930
             )
931 931
         );
932 932
         if ($domain->isCaffeinated()) {
933
-            require_once EE_CAFF_PATH . 'brewing_regular.php';
933
+            require_once EE_CAFF_PATH.'brewing_regular.php';
934 934
         }
935 935
     }
936 936
 
@@ -988,7 +988,7 @@  discard block
 block discarded – undo
988 988
         $class_names = EEH_Class_Tools::get_class_names_for_all_callbacks_on_hook(
989 989
             'AHEE__EE_System__register_shortcodes_modules_and_addons'
990 990
         );
991
-        if (! empty($class_names)) {
991
+        if ( ! empty($class_names)) {
992 992
             $msg = __(
993 993
                 'The following plugins, addons, or modules appear to be incompatible with this version of Event Espresso and were automatically deactivated to avoid fatal errors:',
994 994
                 'event_espresso'
@@ -1000,7 +1000,7 @@  discard block
 block discarded – undo
1000 1000
                             array('EE_', 'EEM_', 'EED_', 'EES_', 'EEW_'),
1001 1001
                             '',
1002 1002
                             $class_name
1003
-                        ) . '</b></li>';
1003
+                        ).'</b></li>';
1004 1004
             }
1005 1005
             $msg .= '</ul>';
1006 1006
             $msg .= __(
@@ -1069,7 +1069,7 @@  discard block
 block discarded – undo
1069 1069
     private function _deactivate_incompatible_addons()
1070 1070
     {
1071 1071
         $incompatible_addons = get_option('ee_incompatible_addons', array());
1072
-        if (! empty($incompatible_addons)) {
1072
+        if ( ! empty($incompatible_addons)) {
1073 1073
             $active_plugins = get_option('active_plugins', array());
1074 1074
             foreach ($active_plugins as $active_plugin) {
1075 1075
                 foreach ($incompatible_addons as $incompatible_addon) {
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
     {
1137 1137
         do_action('AHEE__EE_System__load_controllers__start');
1138 1138
         // let's get it started
1139
-        if (! $this->maintenance_mode->level()
1139
+        if ( ! $this->maintenance_mode->level()
1140 1140
             && ($this->request->isFrontend() || $this->request->isFrontAjax())
1141 1141
         ) {
1142 1142
             do_action('AHEE__EE_System__load_controllers__load_front_controllers');
@@ -1189,7 +1189,7 @@  discard block
 block discarded – undo
1189 1189
         do_action('AHEE__EE_System__core_loaded_and_ready');
1190 1190
         // always load template tags, because it's faster than checking if it's a front-end request, and many page
1191 1191
         // builders require these even on the front-end
1192
-        require_once EE_PUBLIC . 'template_tags.php';
1192
+        require_once EE_PUBLIC.'template_tags.php';
1193 1193
         do_action('AHEE__EE_System__set_hooks_for_shortcodes_modules_and_addons');
1194 1194
     }
1195 1195
 
@@ -1255,13 +1255,13 @@  discard block
 block discarded – undo
1255 1255
     public static function do_not_cache()
1256 1256
     {
1257 1257
         // set no cache constants
1258
-        if (! defined('DONOTCACHEPAGE')) {
1258
+        if ( ! defined('DONOTCACHEPAGE')) {
1259 1259
             define('DONOTCACHEPAGE', true);
1260 1260
         }
1261
-        if (! defined('DONOTCACHCEOBJECT')) {
1261
+        if ( ! defined('DONOTCACHCEOBJECT')) {
1262 1262
             define('DONOTCACHCEOBJECT', true);
1263 1263
         }
1264
-        if (! defined('DONOTCACHEDB')) {
1264
+        if ( ! defined('DONOTCACHEDB')) {
1265 1265
             define('DONOTCACHEDB', true);
1266 1266
         }
1267 1267
         // add no cache headers
Please login to merge, or discard this patch.
core/domain/services/contexts/RequestTypeContextDetector.php 2 patches
Indentation   +177 added lines, -177 removed lines patch added patch discarded remove patch
@@ -18,181 +18,181 @@
 block discarded – undo
18 18
 class RequestTypeContextDetector
19 19
 {
20 20
 
21
-    /**
22
-     * @var RequestTypeContextFactoryInterface $factory
23
-     */
24
-    private $factory;
25
-
26
-    /**
27
-     * @var RequestInterface $request
28
-     */
29
-    private $request;
30
-
31
-    /**
32
-     * @var array $globalRouteConditions
33
-     */
34
-    private $globalRouteConditions;
35
-
36
-
37
-    /**
38
-     * RequestTypeContextDetector constructor.
39
-     *
40
-     * @param RequestInterface                   $request
41
-     * @param RequestTypeContextFactoryInterface $factory
42
-     * @param array                              $globalRouteConditions an array for injecting values that would
43
-     *                                                                  otherwise be defined as global constants
44
-     *                                                                  or other global variables for the current
45
-     *                                                                  request route such as DOING_AJAX
46
-     */
47
-    public function __construct(
48
-        RequestInterface $request,
49
-        RequestTypeContextFactoryInterface $factory,
50
-        array $globalRouteConditions = array()
51
-    ) {
52
-        $this->request = $request;
53
-        $this->factory = $factory;
54
-        $this->globalRouteConditions = $globalRouteConditions;
55
-    }
56
-
57
-
58
-    /**
59
-     * @return mixed
60
-     */
61
-    private function getGlobalRouteCondition($globalRouteCondition, $default)
62
-    {
63
-        return isset($this->globalRouteConditions[ $globalRouteCondition ])
64
-            ? $this->globalRouteConditions[ $globalRouteCondition ]
65
-            : $default;
66
-    }
67
-
68
-
69
-    /**
70
-     * @return RequestTypeContext
71
-     * @throws InvalidArgumentException
72
-     */
73
-    public function detectRequestTypeContext()
74
-    {
75
-        // Detect error scrapes
76
-        if ($this->request->getRequestParam('wp_scrape_key')
77
-            && $this->request->getRequestParam('wp_scrape_nonce')
78
-        ) {
79
-            return $this->factory->create(RequestTypeContext::WP_SCRAPE);
80
-        }
81
-        // Detect EE REST API
82
-        if ($this->isEspressoRestApiRequest()) {
83
-            return $this->factory->create(RequestTypeContext::API);
84
-        }
85
-        // Detect WP REST API
86
-        if ($this->isWordPressRestApiRequest()) {
87
-            return $this->factory->create(RequestTypeContext::WP_API);
88
-        }
89
-        // Detect AJAX
90
-        if ($this->getGlobalRouteCondition('DOING_AJAX', false)) {
91
-            if (filter_var($this->request->getRequestParam('ee_front_ajax'), FILTER_VALIDATE_BOOLEAN)) {
92
-                return $this->factory->create(RequestTypeContext::AJAX_FRONT);
93
-            }
94
-            if (filter_var($this->request->getRequestParam('ee_admin_ajax'), FILTER_VALIDATE_BOOLEAN)) {
95
-                return $this->factory->create(RequestTypeContext::AJAX_ADMIN);
96
-            }
97
-            if ($this->request->getRequestParam('action') === 'heartbeat') {
98
-                return $this->factory->create(RequestTypeContext::AJAX_HEARTBEAT);
99
-            }
100
-            return $this->factory->create(RequestTypeContext::AJAX_OTHER);
101
-        }
102
-        // Detect WP_Cron
103
-        if ($this->isCronRequest()) {
104
-            return $this->factory->create(RequestTypeContext::CRON);
105
-        }
106
-        // Detect command line requests
107
-        if ($this->getGlobalRouteCondition('WP_CLI', false)) {
108
-            return $this->factory->create(RequestTypeContext::CLI);
109
-        }
110
-        // detect WordPress admin (ie: "Dashboard")
111
-        if ($this->getGlobalRouteCondition('is_admin', false)) {
112
-            return $this->factory->create(RequestTypeContext::ADMIN);
113
-        }
114
-        // Detect iFrames
115
-        if ($this->isIframeRoute()) {
116
-            return $this->factory->create(RequestTypeContext::IFRAME);
117
-        }
118
-        // Detect Feeds
119
-        if ($this->isFeedRequest()) {
120
-            return $this->factory->create(RequestTypeContext::FEED);
121
-        }
122
-        // and by process of elimination...
123
-        return $this->factory->create(RequestTypeContext::FRONTEND);
124
-    }
125
-
126
-
127
-    /**
128
-     * @return bool
129
-     */
130
-    private function isEspressoRestApiRequest()
131
-    {
132
-        // Check for URLs like http://mysite.com/?rest_route=/ee... and http://mysite.com/wp-json/ee/...
133
-        return strpos(
134
-            $this->request->getRequestParam('rest_route'),
135
-            '/' . Domain::API_NAMESPACE
136
-        ) === 0
137
-            || $this->uriPathMatches(trim(rest_get_url_prefix(), '/') . '/' . Domain::API_NAMESPACE);
138
-    }
139
-
140
-
141
-
142
-    /**
143
-     * @return bool
144
-     */
145
-    private function isWordPressRestApiRequest()
146
-    {
147
-        // Check for URLs like http://mysite.com/?rest_route=/.. and http://mysite.com/wp-json/...
148
-        return $this->request->getRequestParam('rest_route') !== ''
149
-            || $this->uriPathMatches(trim(rest_get_url_prefix(), '/'));
150
-    }
151
-
152
-
153
-    /**
154
-     * @return bool
155
-     */
156
-    private function isCronRequest()
157
-    {
158
-        return $this->uriPathMatches('wp-cron.php');
159
-    }
160
-
161
-
162
-    /**
163
-     * @return bool
164
-     */
165
-    private function isFeedRequest()
166
-    {
167
-        return $this->uriPathMatches('feed');
168
-    }
169
-
170
-
171
-    /**
172
-     * @param string $component
173
-     * @return bool
174
-     */
175
-    private function uriPathMatches($component)
176
-    {
177
-        $request_uri = $this->request->requestUri(true);
178
-        $parts = explode('?', $request_uri);
179
-        $path = trim(reset($parts), '/');
180
-        return strpos($path, $component) === 0;
181
-    }
182
-
183
-
184
-    /**
185
-     * @return bool
186
-     */
187
-    private function isIframeRoute()
188
-    {
189
-        $is_iframe_route = apply_filters(
190
-            'FHEE__EventEspresso_core_domain_services_contexts_RequestTypeContextDetector__isIframeRoute',
191
-            $this->request->getRequestParam('event_list', '') === 'iframe'
192
-            || $this->request->getRequestParam('ticket_selector', '') === 'iframe'
193
-            || $this->request->getRequestParam('calendar', '') === 'iframe',
194
-            $this
195
-        );
196
-        return filter_var($is_iframe_route, FILTER_VALIDATE_BOOLEAN);
197
-    }
21
+	/**
22
+	 * @var RequestTypeContextFactoryInterface $factory
23
+	 */
24
+	private $factory;
25
+
26
+	/**
27
+	 * @var RequestInterface $request
28
+	 */
29
+	private $request;
30
+
31
+	/**
32
+	 * @var array $globalRouteConditions
33
+	 */
34
+	private $globalRouteConditions;
35
+
36
+
37
+	/**
38
+	 * RequestTypeContextDetector constructor.
39
+	 *
40
+	 * @param RequestInterface                   $request
41
+	 * @param RequestTypeContextFactoryInterface $factory
42
+	 * @param array                              $globalRouteConditions an array for injecting values that would
43
+	 *                                                                  otherwise be defined as global constants
44
+	 *                                                                  or other global variables for the current
45
+	 *                                                                  request route such as DOING_AJAX
46
+	 */
47
+	public function __construct(
48
+		RequestInterface $request,
49
+		RequestTypeContextFactoryInterface $factory,
50
+		array $globalRouteConditions = array()
51
+	) {
52
+		$this->request = $request;
53
+		$this->factory = $factory;
54
+		$this->globalRouteConditions = $globalRouteConditions;
55
+	}
56
+
57
+
58
+	/**
59
+	 * @return mixed
60
+	 */
61
+	private function getGlobalRouteCondition($globalRouteCondition, $default)
62
+	{
63
+		return isset($this->globalRouteConditions[ $globalRouteCondition ])
64
+			? $this->globalRouteConditions[ $globalRouteCondition ]
65
+			: $default;
66
+	}
67
+
68
+
69
+	/**
70
+	 * @return RequestTypeContext
71
+	 * @throws InvalidArgumentException
72
+	 */
73
+	public function detectRequestTypeContext()
74
+	{
75
+		// Detect error scrapes
76
+		if ($this->request->getRequestParam('wp_scrape_key')
77
+			&& $this->request->getRequestParam('wp_scrape_nonce')
78
+		) {
79
+			return $this->factory->create(RequestTypeContext::WP_SCRAPE);
80
+		}
81
+		// Detect EE REST API
82
+		if ($this->isEspressoRestApiRequest()) {
83
+			return $this->factory->create(RequestTypeContext::API);
84
+		}
85
+		// Detect WP REST API
86
+		if ($this->isWordPressRestApiRequest()) {
87
+			return $this->factory->create(RequestTypeContext::WP_API);
88
+		}
89
+		// Detect AJAX
90
+		if ($this->getGlobalRouteCondition('DOING_AJAX', false)) {
91
+			if (filter_var($this->request->getRequestParam('ee_front_ajax'), FILTER_VALIDATE_BOOLEAN)) {
92
+				return $this->factory->create(RequestTypeContext::AJAX_FRONT);
93
+			}
94
+			if (filter_var($this->request->getRequestParam('ee_admin_ajax'), FILTER_VALIDATE_BOOLEAN)) {
95
+				return $this->factory->create(RequestTypeContext::AJAX_ADMIN);
96
+			}
97
+			if ($this->request->getRequestParam('action') === 'heartbeat') {
98
+				return $this->factory->create(RequestTypeContext::AJAX_HEARTBEAT);
99
+			}
100
+			return $this->factory->create(RequestTypeContext::AJAX_OTHER);
101
+		}
102
+		// Detect WP_Cron
103
+		if ($this->isCronRequest()) {
104
+			return $this->factory->create(RequestTypeContext::CRON);
105
+		}
106
+		// Detect command line requests
107
+		if ($this->getGlobalRouteCondition('WP_CLI', false)) {
108
+			return $this->factory->create(RequestTypeContext::CLI);
109
+		}
110
+		// detect WordPress admin (ie: "Dashboard")
111
+		if ($this->getGlobalRouteCondition('is_admin', false)) {
112
+			return $this->factory->create(RequestTypeContext::ADMIN);
113
+		}
114
+		// Detect iFrames
115
+		if ($this->isIframeRoute()) {
116
+			return $this->factory->create(RequestTypeContext::IFRAME);
117
+		}
118
+		// Detect Feeds
119
+		if ($this->isFeedRequest()) {
120
+			return $this->factory->create(RequestTypeContext::FEED);
121
+		}
122
+		// and by process of elimination...
123
+		return $this->factory->create(RequestTypeContext::FRONTEND);
124
+	}
125
+
126
+
127
+	/**
128
+	 * @return bool
129
+	 */
130
+	private function isEspressoRestApiRequest()
131
+	{
132
+		// Check for URLs like http://mysite.com/?rest_route=/ee... and http://mysite.com/wp-json/ee/...
133
+		return strpos(
134
+			$this->request->getRequestParam('rest_route'),
135
+			'/' . Domain::API_NAMESPACE
136
+		) === 0
137
+			|| $this->uriPathMatches(trim(rest_get_url_prefix(), '/') . '/' . Domain::API_NAMESPACE);
138
+	}
139
+
140
+
141
+
142
+	/**
143
+	 * @return bool
144
+	 */
145
+	private function isWordPressRestApiRequest()
146
+	{
147
+		// Check for URLs like http://mysite.com/?rest_route=/.. and http://mysite.com/wp-json/...
148
+		return $this->request->getRequestParam('rest_route') !== ''
149
+			|| $this->uriPathMatches(trim(rest_get_url_prefix(), '/'));
150
+	}
151
+
152
+
153
+	/**
154
+	 * @return bool
155
+	 */
156
+	private function isCronRequest()
157
+	{
158
+		return $this->uriPathMatches('wp-cron.php');
159
+	}
160
+
161
+
162
+	/**
163
+	 * @return bool
164
+	 */
165
+	private function isFeedRequest()
166
+	{
167
+		return $this->uriPathMatches('feed');
168
+	}
169
+
170
+
171
+	/**
172
+	 * @param string $component
173
+	 * @return bool
174
+	 */
175
+	private function uriPathMatches($component)
176
+	{
177
+		$request_uri = $this->request->requestUri(true);
178
+		$parts = explode('?', $request_uri);
179
+		$path = trim(reset($parts), '/');
180
+		return strpos($path, $component) === 0;
181
+	}
182
+
183
+
184
+	/**
185
+	 * @return bool
186
+	 */
187
+	private function isIframeRoute()
188
+	{
189
+		$is_iframe_route = apply_filters(
190
+			'FHEE__EventEspresso_core_domain_services_contexts_RequestTypeContextDetector__isIframeRoute',
191
+			$this->request->getRequestParam('event_list', '') === 'iframe'
192
+			|| $this->request->getRequestParam('ticket_selector', '') === 'iframe'
193
+			|| $this->request->getRequestParam('calendar', '') === 'iframe',
194
+			$this
195
+		);
196
+		return filter_var($is_iframe_route, FILTER_VALIDATE_BOOLEAN);
197
+	}
198 198
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -60,8 +60,8 @@  discard block
 block discarded – undo
60 60
      */
61 61
     private function getGlobalRouteCondition($globalRouteCondition, $default)
62 62
     {
63
-        return isset($this->globalRouteConditions[ $globalRouteCondition ])
64
-            ? $this->globalRouteConditions[ $globalRouteCondition ]
63
+        return isset($this->globalRouteConditions[$globalRouteCondition])
64
+            ? $this->globalRouteConditions[$globalRouteCondition]
65 65
             : $default;
66 66
     }
67 67
 
@@ -132,9 +132,9 @@  discard block
 block discarded – undo
132 132
         // Check for URLs like http://mysite.com/?rest_route=/ee... and http://mysite.com/wp-json/ee/...
133 133
         return strpos(
134 134
             $this->request->getRequestParam('rest_route'),
135
-            '/' . Domain::API_NAMESPACE
135
+            '/'.Domain::API_NAMESPACE
136 136
         ) === 0
137
-            || $this->uriPathMatches(trim(rest_get_url_prefix(), '/') . '/' . Domain::API_NAMESPACE);
137
+            || $this->uriPathMatches(trim(rest_get_url_prefix(), '/').'/'.Domain::API_NAMESPACE);
138 138
     }
139 139
 
140 140
 
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoCheckout.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -19,56 +19,56 @@
 block discarded – undo
19 19
 {
20 20
 
21 21
 
22
-    /**
23
-     * the actual shortcode tag that gets registered with WordPress
24
-     *
25
-     * @return string
26
-     */
27
-    public function getTag()
28
-    {
29
-        return 'ESPRESSO_CHECKOUT';
30
-    }
22
+	/**
23
+	 * the actual shortcode tag that gets registered with WordPress
24
+	 *
25
+	 * @return string
26
+	 */
27
+	public function getTag()
28
+	{
29
+		return 'ESPRESSO_CHECKOUT';
30
+	}
31 31
 
32 32
 
33
-    /**
34
-     * the time in seconds to cache the results of the processShortcode() method
35
-     * 0 means the processShortcode() results will NOT be cached at all
36
-     *
37
-     * @return int
38
-     */
39
-    public function cacheExpiration()
40
-    {
41
-        return 0;
42
-    }
33
+	/**
34
+	 * the time in seconds to cache the results of the processShortcode() method
35
+	 * 0 means the processShortcode() results will NOT be cached at all
36
+	 *
37
+	 * @return int
38
+	 */
39
+	public function cacheExpiration()
40
+	{
41
+		return 0;
42
+	}
43 43
 
44 44
 
45
-    /**
46
-     * a place for adding any initialization code that needs to run prior to wp_header().
47
-     * this may be required for shortcodes that utilize a corresponding module,
48
-     * and need to enqueue assets for that module
49
-     *
50
-     * @return void
51
-     */
52
-    public function initializeShortcode()
53
-    {
54
-        global $wp_query;
55
-        EED_Single_Page_Checkout::init($wp_query);
56
-        $this->shortcodeHasBeenInitialized();
57
-    }
45
+	/**
46
+	 * a place for adding any initialization code that needs to run prior to wp_header().
47
+	 * this may be required for shortcodes that utilize a corresponding module,
48
+	 * and need to enqueue assets for that module
49
+	 *
50
+	 * @return void
51
+	 */
52
+	public function initializeShortcode()
53
+	{
54
+		global $wp_query;
55
+		EED_Single_Page_Checkout::init($wp_query);
56
+		$this->shortcodeHasBeenInitialized();
57
+	}
58 58
 
59 59
 
60
-    /**
61
-     * callback that runs when the shortcode is encountered in post content.
62
-     * IMPORTANT !!!
63
-     * remember that shortcode content should be RETURNED and NOT echoed out
64
-     *
65
-     * @param array $attributes
66
-     * @return string
67
-     */
68
-    public function processShortcode($attributes = array())
69
-    {
70
-        /** @var ResponseInterface $response */
71
-        $response = LoaderFactory::getLoader()->getShared(ResponseInterface::class);
72
-        return $response->getOutput();
73
-    }
60
+	/**
61
+	 * callback that runs when the shortcode is encountered in post content.
62
+	 * IMPORTANT !!!
63
+	 * remember that shortcode content should be RETURNED and NOT echoed out
64
+	 *
65
+	 * @param array $attributes
66
+	 * @return string
67
+	 */
68
+	public function processShortcode($attributes = array())
69
+	{
70
+		/** @var ResponseInterface $response */
71
+		$response = LoaderFactory::getLoader()->getShared(ResponseInterface::class);
72
+		return $response->getOutput();
73
+	}
74 74
 }
Please login to merge, or discard this patch.
core/domain/entities/shortcodes/EspressoTxnPage.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -26,89 +26,89 @@
 block discarded – undo
26 26
 {
27 27
 
28 28
 
29
-    /**
30
-     * the actual shortcode tag that gets registered with WordPress
31
-     *
32
-     * @return string
33
-     */
34
-    public function getTag()
35
-    {
36
-        return 'ESPRESSO_TXN_PAGE';
37
-    }
29
+	/**
30
+	 * the actual shortcode tag that gets registered with WordPress
31
+	 *
32
+	 * @return string
33
+	 */
34
+	public function getTag()
35
+	{
36
+		return 'ESPRESSO_TXN_PAGE';
37
+	}
38 38
 
39 39
 
40
-    /**
41
-     * the time in seconds to cache the results of the processShortcode() method
42
-     * 0 means the processShortcode() results will NOT be cached at all
43
-     *
44
-     * @return int
45
-     */
46
-    public function cacheExpiration()
47
-    {
48
-        return 0;
49
-    }
40
+	/**
41
+	 * the time in seconds to cache the results of the processShortcode() method
42
+	 * 0 means the processShortcode() results will NOT be cached at all
43
+	 *
44
+	 * @return int
45
+	 */
46
+	public function cacheExpiration()
47
+	{
48
+		return 0;
49
+	}
50 50
 
51 51
 
52
-    /**
53
-     * a place for adding any initialization code that needs to run prior to wp_header().
54
-     * this may be required for shortcodes that utilize a corresponding module,
55
-     * and need to enqueue assets for that module
56
-     *
57
-     * @return void
58
-     * @throws Exception
59
-     * @throws EE_Error
60
-     */
61
-    public function initializeShortcode()
62
-    {
63
-        $transaction  = null;
64
-        $request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
65
-        $reg_url_link = $request->getRequestParam('e_reg_url_link');
66
-        if ($reg_url_link) {
67
-            /** @var EEM_Transaction $EEM_Transaction */
68
-            $EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
69
-            $transaction = $EEM_Transaction->get_transaction_from_reg_url_link($reg_url_link);
70
-        }
71
-        if ($transaction instanceof EE_Transaction) {
72
-            $payment_method = null;
73
-            $payment_method_slug = $request->getRequestParam('ee_payment_method');
74
-            if ($payment_method_slug) {
75
-                $payment_method = EEM_Payment_Method::instance()->get_one_by_slug($payment_method_slug);
76
-            }
77
-            if ($payment_method instanceof EE_Payment_Method && $payment_method->is_off_site()) {
78
-                $gateway = $payment_method->type_obj()->get_gateway();
79
-                if ($gateway instanceof EE_Offsite_Gateway
80
-                    && $gateway->handle_IPN_in_this_request(
81
-                        $request->requestParams(),
82
-                        true
83
-                    )
84
-                ) {
85
-                    /** @type EE_Payment_Processor $payment_processor */
86
-                    $payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
87
-                    $payment_processor->process_ipn($_REQUEST, $transaction, $payment_method);
88
-                }
89
-            }
90
-            // allow gateways to add a filter to stop rendering the page
91
-            if (apply_filters('FHEE__EES_Espresso_Txn_Page__run__exit', false)) {
92
-                exit;
93
-            }
94
-        }
95
-        $this->shortcodeHasBeenInitialized();
96
-    }
52
+	/**
53
+	 * a place for adding any initialization code that needs to run prior to wp_header().
54
+	 * this may be required for shortcodes that utilize a corresponding module,
55
+	 * and need to enqueue assets for that module
56
+	 *
57
+	 * @return void
58
+	 * @throws Exception
59
+	 * @throws EE_Error
60
+	 */
61
+	public function initializeShortcode()
62
+	{
63
+		$transaction  = null;
64
+		$request      = LoaderFactory::getLoader()->getShared(RequestInterface::class);
65
+		$reg_url_link = $request->getRequestParam('e_reg_url_link');
66
+		if ($reg_url_link) {
67
+			/** @var EEM_Transaction $EEM_Transaction */
68
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
69
+			$transaction = $EEM_Transaction->get_transaction_from_reg_url_link($reg_url_link);
70
+		}
71
+		if ($transaction instanceof EE_Transaction) {
72
+			$payment_method = null;
73
+			$payment_method_slug = $request->getRequestParam('ee_payment_method');
74
+			if ($payment_method_slug) {
75
+				$payment_method = EEM_Payment_Method::instance()->get_one_by_slug($payment_method_slug);
76
+			}
77
+			if ($payment_method instanceof EE_Payment_Method && $payment_method->is_off_site()) {
78
+				$gateway = $payment_method->type_obj()->get_gateway();
79
+				if ($gateway instanceof EE_Offsite_Gateway
80
+					&& $gateway->handle_IPN_in_this_request(
81
+						$request->requestParams(),
82
+						true
83
+					)
84
+				) {
85
+					/** @type EE_Payment_Processor $payment_processor */
86
+					$payment_processor = EE_Registry::instance()->load_core('Payment_Processor');
87
+					$payment_processor->process_ipn($_REQUEST, $transaction, $payment_method);
88
+				}
89
+			}
90
+			// allow gateways to add a filter to stop rendering the page
91
+			if (apply_filters('FHEE__EES_Espresso_Txn_Page__run__exit', false)) {
92
+				exit;
93
+			}
94
+		}
95
+		$this->shortcodeHasBeenInitialized();
96
+	}
97 97
 
98 98
 
99
-    /**
100
-     * callback that runs when the shortcode is encountered in post content.
101
-     * IMPORTANT !!!
102
-     * remember that shortcode content should be RETURNED and NOT echoed out
103
-     *
104
-     * @param array $attributes
105
-     * @return string
106
-     */
107
-    public function processShortcode($attributes = array())
108
-    {
109
-        return esc_html__(
110
-            'This is the Event Espresso Transactions page. This page receives instant payment notification (IPN) requests and should have a status of published, but should not be easily accessible by site visitors. Do not add it to your website\'s navigation menu or link to it from another page. Also, do not delete it or change its status to private.',
111
-            'event_espresso'
112
-        );
113
-    }
99
+	/**
100
+	 * callback that runs when the shortcode is encountered in post content.
101
+	 * IMPORTANT !!!
102
+	 * remember that shortcode content should be RETURNED and NOT echoed out
103
+	 *
104
+	 * @param array $attributes
105
+	 * @return string
106
+	 */
107
+	public function processShortcode($attributes = array())
108
+	{
109
+		return esc_html__(
110
+			'This is the Event Espresso Transactions page. This page receives instant payment notification (IPN) requests and should have a status of published, but should not be easily accessible by site visitors. Do not add it to your website\'s navigation menu or link to it from another page. Also, do not delete it or change its status to private.',
111
+			'event_espresso'
112
+		);
113
+	}
114 114
 }
Please login to merge, or discard this patch.
core/EE_Front_Controller.core.php 2 patches
Indentation   +474 added lines, -474 removed lines patch added patch discarded remove patch
@@ -17,478 +17,478 @@
 block discarded – undo
17 17
 final class EE_Front_Controller
18 18
 {
19 19
 
20
-    /**
21
-     * @var string
22
-     */
23
-    private $_template_path;
24
-
25
-    /**
26
-     * @var string
27
-     */
28
-    private $_template;
29
-
30
-    /**
31
-     * @type EE_Registry
32
-     */
33
-    protected $Registry;
34
-
35
-    /**
36
-     * @type EE_Request_Handler
37
-     */
38
-    protected $Request_Handler;
39
-
40
-    /**
41
-     * @type EE_Module_Request_Router
42
-     */
43
-    protected $Module_Request_Router;
44
-
45
-    /**
46
-     * @type CurrentPage
47
-     */
48
-    protected $current_page;
49
-
50
-
51
-    /**
52
-     *    class constructor
53
-     *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
54
-     *
55
-     * @access    public
56
-     * @param EE_Registry              $Registry
57
-     * @param CurrentPage              $EspressoPage
58
-     * @param EE_Module_Request_Router $Module_Request_Router
59
-     */
60
-    public function __construct(
61
-        EE_Registry $Registry,
62
-        CurrentPage $EspressoPage,
63
-        EE_Module_Request_Router $Module_Request_Router
64
-    ) {
65
-        $this->Registry              = $Registry;
66
-        $this->current_page          = $EspressoPage;
67
-        $this->Module_Request_Router = $Module_Request_Router;
68
-        // load other resources and begin to actually run shortcodes and modules
69
-        // analyse the incoming WP request
70
-        add_action('parse_request', array($this, 'get_request'), 1, 1);
71
-        // process request with module factory
72
-        add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
73
-        // before headers sent
74
-        add_action('wp', array($this, 'wp'), 5);
75
-        // primarily used to process any content shortcodes
76
-        add_action('template_redirect', array($this, 'templateRedirect'), 999);
77
-        // header
78
-        add_action('wp_head', array($this, 'header_meta_tag'), 5);
79
-        add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
80
-        add_filter('template_include', array($this, 'template_include'), 1);
81
-        // display errors
82
-        add_action('loop_start', array($this, 'display_errors'), 2);
83
-        // the content
84
-        // add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
85
-        // exclude our private cpt comments
86
-        add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
87
-        // make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
88
-        add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
89
-        // action hook EE
90
-        do_action('AHEE__EE_Front_Controller__construct__done', $this);
91
-    }
92
-
93
-
94
-    /**
95
-     * @return EE_Request_Handler
96
-     * @deprecated $VID:$
97
-     */
98
-    public function Request_Handler()
99
-    {
100
-        if (! $this->Request_Handler instanceof EE_Request_Handler){
101
-            $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102
-        }
103
-        return $this->Request_Handler;
104
-    }
105
-
106
-
107
-    /**
108
-     * @return EE_Module_Request_Router
109
-     */
110
-    public function Module_Request_Router()
111
-    {
112
-        return $this->Module_Request_Router;
113
-    }
114
-
115
-
116
-    /**
117
-     * @return LegacyShortcodesManager
118
-     * @deprecated $VID:$
119
-     */
120
-    public function getLegacyShortcodesManager()
121
-    {
122
-        return EE_Config::getLegacyShortcodesManager();
123
-    }
124
-
125
-
126
-
127
-
128
-
129
-    /***********************************************        INIT ACTION HOOK         ***********************************************/
130
-    /**
131
-     * filter_wp_comments
132
-     * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
133
-     * widgets/queries done on frontend
134
-     *
135
-     * @param  array $clauses array of comment clauses setup by WP_Comment_Query
136
-     * @return array array of comment clauses with modifications.
137
-     * @throws InvalidArgumentException
138
-     * @throws InvalidDataTypeException
139
-     * @throws InvalidInterfaceException
140
-     */
141
-    public function filter_wp_comments($clauses)
142
-    {
143
-        global $wpdb;
144
-        if (strpos($clauses['join'], $wpdb->posts) !== false) {
145
-            /** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
146
-            $custom_post_types = LoaderFactory::getLoader()->getShared(
147
-                'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
148
-            );
149
-            $cpts = $custom_post_types->getPrivateCustomPostTypes();
150
-            foreach ($cpts as $cpt => $details) {
151
-                $clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
152
-            }
153
-        }
154
-        return $clauses;
155
-    }
156
-
157
-
158
-    /**
159
-     * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
160
-     *
161
-     * @param  string $url incoming url
162
-     * @return string         final assembled url
163
-     */
164
-    public function maybe_force_admin_ajax_ssl($url)
165
-    {
166
-        if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
167
-            $url = str_replace('http://', 'https://', $url);
168
-        }
169
-        return $url;
170
-    }
171
-
172
-
173
-
174
-
175
-
176
-
177
-    /***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
178
-
179
-
180
-    /**
181
-     *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
182
-     *    default priority init phases have run
183
-     *
184
-     * @access    public
185
-     * @return    void
186
-     */
187
-    public function wp_loaded()
188
-    {
189
-    }
190
-
191
-
192
-
193
-
194
-
195
-    /***********************************************        PARSE_REQUEST HOOK         ***********************************************/
196
-    /**
197
-     *    _get_request
198
-     *
199
-     * @access public
200
-     * @param WP $WP
201
-     * @return void
202
-     */
203
-    public function get_request(WP $WP)
204
-    {
205
-        do_action('AHEE__EE_Front_Controller__get_request__start');
206
-        $this->current_page->parseQueryVars($WP);
207
-        do_action('AHEE__EE_Front_Controller__get_request__complete');
208
-        remove_action('parse_request', [$this, 'get_request'], 1);
209
-    }
210
-
211
-
212
-    /**
213
-     *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
214
-     *
215
-     * @access    public
216
-     * @param WP_Query $WP_Query
217
-     * @return    void
218
-     * @throws EE_Error
219
-     * @throws ReflectionException
220
-     */
221
-    public function pre_get_posts($WP_Query)
222
-    {
223
-        // only load Module_Request_Router if this is the main query
224
-        if ($this->Module_Request_Router instanceof EE_Module_Request_Router
225
-            && $WP_Query->is_main_query()
226
-        ) {
227
-            // cycle thru module routes
228
-            while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
229
-                // determine module and method for route
230
-                $module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
231
-                if ($module instanceof EED_Module) {
232
-                    // get registered view for route
233
-                    $this->_template_path = $this->Module_Request_Router->get_view($route);
234
-                    // grab module name
235
-                    $module_name = $module->module_name();
236
-                    // map the module to the module objects
237
-                    $this->Registry->modules->{$module_name} = $module;
238
-                }
239
-            }
240
-        }
241
-    }
242
-
243
-
244
-
245
-
246
-
247
-    /***********************************************        WP HOOK         ***********************************************/
248
-
249
-
250
-    /**
251
-     *    wp - basically last chance to do stuff before headers sent
252
-     *
253
-     * @access    public
254
-     * @return    void
255
-     */
256
-    public function wp()
257
-    {
258
-    }
259
-
260
-
261
-
262
-    /***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
263
-
264
-
265
-    /**
266
-     * callback for the "template_redirect" hook point
267
-     * checks sidebars for EE widgets
268
-     * loads resources and assets accordingly
269
-     *
270
-     * @return void
271
-     */
272
-    public function templateRedirect()
273
-    {
274
-        global $wp_query;
275
-        if (empty($wp_query->posts)) {
276
-            return;
277
-        }
278
-        // if we already know this is an espresso page, then load assets
279
-        $load_assets = $this->current_page->isEspressoPage();
280
-        // if we are already loading assets then just move along, otherwise check for widgets
281
-        $load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
282
-        if ($load_assets) {
283
-            add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
284
-            add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
285
-        }
286
-    }
287
-
288
-
289
-    /**
290
-     * builds list of active widgets then scans active sidebars looking for them
291
-     * returns true is an EE widget is found in an active sidebar
292
-     * Please Note: this does NOT mean that the sidebar or widget
293
-     * is actually in use in a given template, as that is unfortunately not known
294
-     * until a sidebar and it's widgets are actually loaded
295
-     *
296
-     * @return boolean
297
-     */
298
-    private function espresso_widgets_in_active_sidebars()
299
-    {
300
-        $espresso_widgets = array();
301
-        foreach ($this->Registry->widgets as $widget_class => $widget) {
302
-            $id_base = EspressoWidget::getIdBase($widget_class);
303
-            if (is_active_widget(false, false, $id_base)) {
304
-                $espresso_widgets[] = $id_base;
305
-            }
306
-        }
307
-        $all_sidebar_widgets = wp_get_sidebars_widgets();
308
-        foreach ($all_sidebar_widgets as $sidebar_widgets) {
309
-            if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
310
-                foreach ($sidebar_widgets as $sidebar_widget) {
311
-                    foreach ($espresso_widgets as $espresso_widget) {
312
-                        if (strpos($sidebar_widget, $espresso_widget) !== false) {
313
-                            return true;
314
-                        }
315
-                    }
316
-                }
317
-            }
318
-        }
319
-        return false;
320
-    }
321
-
322
-
323
-    /**
324
-     *    header_meta_tag
325
-     *
326
-     * @access    public
327
-     * @return    void
328
-     */
329
-    public function header_meta_tag()
330
-    {
331
-        print(
332
-        apply_filters(
333
-            'FHEE__EE_Front_Controller__header_meta_tag',
334
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
335
-        )
336
-        );
337
-
338
-        // let's exclude all event type taxonomy term archive pages from search engine indexing
339
-        // @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
340
-        // also exclude all critical pages from indexing
341
-        if ((
342
-                is_tax('espresso_event_type')
343
-                && get_option('blog_public') !== '0'
344
-            )
345
-            || is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
346
-        ) {
347
-            print(
348
-            apply_filters(
349
-                'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
350
-                '<meta name="robots" content="noindex,follow" />' . "\n"
351
-            )
352
-            );
353
-        }
354
-    }
355
-
356
-
357
-    /**
358
-     * wp_print_scripts
359
-     *
360
-     * @return void
361
-     * @throws EE_Error
362
-     */
363
-    public function wp_print_scripts()
364
-    {
365
-        global $post;
366
-        if (isset($post->EE_Event)
367
-            && $post->EE_Event instanceof EE_Event
368
-            && get_post_type() === 'espresso_events'
369
-            && is_singular()
370
-        ) {
371
-            EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
372
-        }
373
-    }
374
-
375
-
376
-    public function enqueueStyle()
377
-    {
378
-        wp_enqueue_style('espresso_default');
379
-        wp_enqueue_style('espresso_custom_css');
380
-    }
381
-
382
-
383
-
384
-    /***********************************************        WP_FOOTER         ***********************************************/
385
-
386
-
387
-    public function enqueueScripts()
388
-    {
389
-        wp_enqueue_script('espresso_core');
390
-    }
391
-
392
-
393
-    /**
394
-     * display_errors
395
-     *
396
-     * @access public
397
-     * @return void
398
-     * @throws DomainException
399
-     */
400
-    public function display_errors()
401
-    {
402
-        static $shown_already = false;
403
-        do_action('AHEE__EE_Front_Controller__display_errors__begin');
404
-        if (! $shown_already
405
-            && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
406
-            && is_main_query()
407
-            && ! is_feed()
408
-            && in_the_loop()
409
-            && did_action('wp_head')
410
-            && $this->current_page->isEspressoPage()
411
-        ) {
412
-            echo EE_Error::get_notices();
413
-            $shown_already = true;
414
-            EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
415
-        }
416
-        do_action('AHEE__EE_Front_Controller__display_errors__end');
417
-    }
418
-
419
-
420
-
421
-
422
-
423
-    /***********************************************        UTILITIES         ***********************************************/
424
-    /**
425
-     *    template_include
426
-     *
427
-     * @access    public
428
-     * @param   string $template_include_path
429
-     * @return    string
430
-     */
431
-    public function template_include($template_include_path = null)
432
-    {
433
-        if ($this->current_page->isEspressoPage()) {
434
-            $this->_template_path = ! empty($this->_template_path)
435
-                ? basename($this->_template_path)
436
-                : basename(
437
-                    $template_include_path
438
-                );
439
-            $template_path = EEH_Template::locate_template($this->_template_path, array(), false);
440
-            $this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
441
-            $this->_template = basename($this->_template_path);
442
-            return $this->_template_path;
443
-        }
444
-        return $template_include_path;
445
-    }
446
-
447
-
448
-    /**
449
-     * @param bool $with_path
450
-     * @return    string
451
-     */
452
-    public function get_selected_template($with_path = false)
453
-    {
454
-        return $with_path ? $this->_template_path : $this->_template;
455
-    }
456
-
457
-
458
-    /**
459
-     * @param string $shortcode_class
460
-     * @param WP     $wp
461
-     * @throws ReflectionException
462
-     * @deprecated 4.9.26
463
-     */
464
-    public function initialize_shortcode($shortcode_class = '', WP $wp = null)
465
-    {
466
-        EE_Error::doing_it_wrong(
467
-            __METHOD__,
468
-            __(
469
-                'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
470
-                'event_espresso'
471
-            ),
472
-            '4.9.26'
473
-        );
474
-        $this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
475
-    }
476
-
477
-
478
-    /**
479
-     * @return void
480
-     * @deprecated 4.9.57.p
481
-     */
482
-    public function loadPersistentAdminNoticeManager()
483
-    {
484
-    }
485
-
486
-
487
-    /**
488
-     * @return void
489
-     * @deprecated 4.9.64.p
490
-     */
491
-    public function employ_CPT_Strategy()
492
-    {
493
-    }
20
+	/**
21
+	 * @var string
22
+	 */
23
+	private $_template_path;
24
+
25
+	/**
26
+	 * @var string
27
+	 */
28
+	private $_template;
29
+
30
+	/**
31
+	 * @type EE_Registry
32
+	 */
33
+	protected $Registry;
34
+
35
+	/**
36
+	 * @type EE_Request_Handler
37
+	 */
38
+	protected $Request_Handler;
39
+
40
+	/**
41
+	 * @type EE_Module_Request_Router
42
+	 */
43
+	protected $Module_Request_Router;
44
+
45
+	/**
46
+	 * @type CurrentPage
47
+	 */
48
+	protected $current_page;
49
+
50
+
51
+	/**
52
+	 *    class constructor
53
+	 *    should fire after shortcode, module, addon, or other plugin's default priority init phases have run
54
+	 *
55
+	 * @access    public
56
+	 * @param EE_Registry              $Registry
57
+	 * @param CurrentPage              $EspressoPage
58
+	 * @param EE_Module_Request_Router $Module_Request_Router
59
+	 */
60
+	public function __construct(
61
+		EE_Registry $Registry,
62
+		CurrentPage $EspressoPage,
63
+		EE_Module_Request_Router $Module_Request_Router
64
+	) {
65
+		$this->Registry              = $Registry;
66
+		$this->current_page          = $EspressoPage;
67
+		$this->Module_Request_Router = $Module_Request_Router;
68
+		// load other resources and begin to actually run shortcodes and modules
69
+		// analyse the incoming WP request
70
+		add_action('parse_request', array($this, 'get_request'), 1, 1);
71
+		// process request with module factory
72
+		add_action('pre_get_posts', array($this, 'pre_get_posts'), 10, 1);
73
+		// before headers sent
74
+		add_action('wp', array($this, 'wp'), 5);
75
+		// primarily used to process any content shortcodes
76
+		add_action('template_redirect', array($this, 'templateRedirect'), 999);
77
+		// header
78
+		add_action('wp_head', array($this, 'header_meta_tag'), 5);
79
+		add_action('wp_print_scripts', array($this, 'wp_print_scripts'), 10);
80
+		add_filter('template_include', array($this, 'template_include'), 1);
81
+		// display errors
82
+		add_action('loop_start', array($this, 'display_errors'), 2);
83
+		// the content
84
+		// add_filter( 'the_content', array( $this, 'the_content' ), 5, 1 );
85
+		// exclude our private cpt comments
86
+		add_filter('comments_clauses', array($this, 'filter_wp_comments'), 10, 1);
87
+		// make sure any ajax requests will respect the url schema when requests are made against admin-ajax.php (http:// or https://)
88
+		add_filter('admin_url', array($this, 'maybe_force_admin_ajax_ssl'), 200, 1);
89
+		// action hook EE
90
+		do_action('AHEE__EE_Front_Controller__construct__done', $this);
91
+	}
92
+
93
+
94
+	/**
95
+	 * @return EE_Request_Handler
96
+	 * @deprecated $VID:$
97
+	 */
98
+	public function Request_Handler()
99
+	{
100
+		if (! $this->Request_Handler instanceof EE_Request_Handler){
101
+			$this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102
+		}
103
+		return $this->Request_Handler;
104
+	}
105
+
106
+
107
+	/**
108
+	 * @return EE_Module_Request_Router
109
+	 */
110
+	public function Module_Request_Router()
111
+	{
112
+		return $this->Module_Request_Router;
113
+	}
114
+
115
+
116
+	/**
117
+	 * @return LegacyShortcodesManager
118
+	 * @deprecated $VID:$
119
+	 */
120
+	public function getLegacyShortcodesManager()
121
+	{
122
+		return EE_Config::getLegacyShortcodesManager();
123
+	}
124
+
125
+
126
+
127
+
128
+
129
+	/***********************************************        INIT ACTION HOOK         ***********************************************/
130
+	/**
131
+	 * filter_wp_comments
132
+	 * This simply makes sure that any "private" EE CPTs do not have their comments show up in any wp comment
133
+	 * widgets/queries done on frontend
134
+	 *
135
+	 * @param  array $clauses array of comment clauses setup by WP_Comment_Query
136
+	 * @return array array of comment clauses with modifications.
137
+	 * @throws InvalidArgumentException
138
+	 * @throws InvalidDataTypeException
139
+	 * @throws InvalidInterfaceException
140
+	 */
141
+	public function filter_wp_comments($clauses)
142
+	{
143
+		global $wpdb;
144
+		if (strpos($clauses['join'], $wpdb->posts) !== false) {
145
+			/** @var EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions $custom_post_types */
146
+			$custom_post_types = LoaderFactory::getLoader()->getShared(
147
+				'EventEspresso\core\domain\entities\custom_post_types\CustomPostTypeDefinitions'
148
+			);
149
+			$cpts = $custom_post_types->getPrivateCustomPostTypes();
150
+			foreach ($cpts as $cpt => $details) {
151
+				$clauses['where'] .= $wpdb->prepare(" AND $wpdb->posts.post_type != %s", $cpt);
152
+			}
153
+		}
154
+		return $clauses;
155
+	}
156
+
157
+
158
+	/**
159
+	 * this just makes sure that if the site is using ssl that we force that for any admin ajax calls from frontend
160
+	 *
161
+	 * @param  string $url incoming url
162
+	 * @return string         final assembled url
163
+	 */
164
+	public function maybe_force_admin_ajax_ssl($url)
165
+	{
166
+		if (is_ssl() && preg_match('/admin-ajax.php/', $url)) {
167
+			$url = str_replace('http://', 'https://', $url);
168
+		}
169
+		return $url;
170
+	}
171
+
172
+
173
+
174
+
175
+
176
+
177
+	/***********************************************        WP_LOADED ACTION HOOK         ***********************************************/
178
+
179
+
180
+	/**
181
+	 *    wp_loaded - should fire after shortcode, module, addon, or other plugin's have been registered and their
182
+	 *    default priority init phases have run
183
+	 *
184
+	 * @access    public
185
+	 * @return    void
186
+	 */
187
+	public function wp_loaded()
188
+	{
189
+	}
190
+
191
+
192
+
193
+
194
+
195
+	/***********************************************        PARSE_REQUEST HOOK         ***********************************************/
196
+	/**
197
+	 *    _get_request
198
+	 *
199
+	 * @access public
200
+	 * @param WP $WP
201
+	 * @return void
202
+	 */
203
+	public function get_request(WP $WP)
204
+	{
205
+		do_action('AHEE__EE_Front_Controller__get_request__start');
206
+		$this->current_page->parseQueryVars($WP);
207
+		do_action('AHEE__EE_Front_Controller__get_request__complete');
208
+		remove_action('parse_request', [$this, 'get_request'], 1);
209
+	}
210
+
211
+
212
+	/**
213
+	 *    pre_get_posts - basically a module factory for instantiating modules and selecting the final view template
214
+	 *
215
+	 * @access    public
216
+	 * @param WP_Query $WP_Query
217
+	 * @return    void
218
+	 * @throws EE_Error
219
+	 * @throws ReflectionException
220
+	 */
221
+	public function pre_get_posts($WP_Query)
222
+	{
223
+		// only load Module_Request_Router if this is the main query
224
+		if ($this->Module_Request_Router instanceof EE_Module_Request_Router
225
+			&& $WP_Query->is_main_query()
226
+		) {
227
+			// cycle thru module routes
228
+			while ($route = $this->Module_Request_Router->get_route($WP_Query)) {
229
+				// determine module and method for route
230
+				$module = $this->Module_Request_Router->resolve_route($route[0], $route[1]);
231
+				if ($module instanceof EED_Module) {
232
+					// get registered view for route
233
+					$this->_template_path = $this->Module_Request_Router->get_view($route);
234
+					// grab module name
235
+					$module_name = $module->module_name();
236
+					// map the module to the module objects
237
+					$this->Registry->modules->{$module_name} = $module;
238
+				}
239
+			}
240
+		}
241
+	}
242
+
243
+
244
+
245
+
246
+
247
+	/***********************************************        WP HOOK         ***********************************************/
248
+
249
+
250
+	/**
251
+	 *    wp - basically last chance to do stuff before headers sent
252
+	 *
253
+	 * @access    public
254
+	 * @return    void
255
+	 */
256
+	public function wp()
257
+	{
258
+	}
259
+
260
+
261
+
262
+	/***********************     GET_HEADER && WP_HEAD HOOK     ***********************/
263
+
264
+
265
+	/**
266
+	 * callback for the "template_redirect" hook point
267
+	 * checks sidebars for EE widgets
268
+	 * loads resources and assets accordingly
269
+	 *
270
+	 * @return void
271
+	 */
272
+	public function templateRedirect()
273
+	{
274
+		global $wp_query;
275
+		if (empty($wp_query->posts)) {
276
+			return;
277
+		}
278
+		// if we already know this is an espresso page, then load assets
279
+		$load_assets = $this->current_page->isEspressoPage();
280
+		// if we are already loading assets then just move along, otherwise check for widgets
281
+		$load_assets = $load_assets || $this->espresso_widgets_in_active_sidebars();
282
+		if ($load_assets) {
283
+			add_action('wp_enqueue_scripts', array($this, 'enqueueStyle'), 10);
284
+			add_action('wp_print_footer_scripts', array($this, 'enqueueScripts'), 10);
285
+		}
286
+	}
287
+
288
+
289
+	/**
290
+	 * builds list of active widgets then scans active sidebars looking for them
291
+	 * returns true is an EE widget is found in an active sidebar
292
+	 * Please Note: this does NOT mean that the sidebar or widget
293
+	 * is actually in use in a given template, as that is unfortunately not known
294
+	 * until a sidebar and it's widgets are actually loaded
295
+	 *
296
+	 * @return boolean
297
+	 */
298
+	private function espresso_widgets_in_active_sidebars()
299
+	{
300
+		$espresso_widgets = array();
301
+		foreach ($this->Registry->widgets as $widget_class => $widget) {
302
+			$id_base = EspressoWidget::getIdBase($widget_class);
303
+			if (is_active_widget(false, false, $id_base)) {
304
+				$espresso_widgets[] = $id_base;
305
+			}
306
+		}
307
+		$all_sidebar_widgets = wp_get_sidebars_widgets();
308
+		foreach ($all_sidebar_widgets as $sidebar_widgets) {
309
+			if (is_array($sidebar_widgets) && ! empty($sidebar_widgets)) {
310
+				foreach ($sidebar_widgets as $sidebar_widget) {
311
+					foreach ($espresso_widgets as $espresso_widget) {
312
+						if (strpos($sidebar_widget, $espresso_widget) !== false) {
313
+							return true;
314
+						}
315
+					}
316
+				}
317
+			}
318
+		}
319
+		return false;
320
+	}
321
+
322
+
323
+	/**
324
+	 *    header_meta_tag
325
+	 *
326
+	 * @access    public
327
+	 * @return    void
328
+	 */
329
+	public function header_meta_tag()
330
+	{
331
+		print(
332
+		apply_filters(
333
+			'FHEE__EE_Front_Controller__header_meta_tag',
334
+			'<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
335
+		)
336
+		);
337
+
338
+		// let's exclude all event type taxonomy term archive pages from search engine indexing
339
+		// @see https://events.codebasehq.com/projects/event-espresso/tickets/10249
340
+		// also exclude all critical pages from indexing
341
+		if ((
342
+				is_tax('espresso_event_type')
343
+				&& get_option('blog_public') !== '0'
344
+			)
345
+			|| is_page(EE_Registry::instance()->CFG->core->get_critical_pages_array())
346
+		) {
347
+			print(
348
+			apply_filters(
349
+				'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
350
+				'<meta name="robots" content="noindex,follow" />' . "\n"
351
+			)
352
+			);
353
+		}
354
+	}
355
+
356
+
357
+	/**
358
+	 * wp_print_scripts
359
+	 *
360
+	 * @return void
361
+	 * @throws EE_Error
362
+	 */
363
+	public function wp_print_scripts()
364
+	{
365
+		global $post;
366
+		if (isset($post->EE_Event)
367
+			&& $post->EE_Event instanceof EE_Event
368
+			&& get_post_type() === 'espresso_events'
369
+			&& is_singular()
370
+		) {
371
+			EEH_Schema::add_json_linked_data_for_event($post->EE_Event);
372
+		}
373
+	}
374
+
375
+
376
+	public function enqueueStyle()
377
+	{
378
+		wp_enqueue_style('espresso_default');
379
+		wp_enqueue_style('espresso_custom_css');
380
+	}
381
+
382
+
383
+
384
+	/***********************************************        WP_FOOTER         ***********************************************/
385
+
386
+
387
+	public function enqueueScripts()
388
+	{
389
+		wp_enqueue_script('espresso_core');
390
+	}
391
+
392
+
393
+	/**
394
+	 * display_errors
395
+	 *
396
+	 * @access public
397
+	 * @return void
398
+	 * @throws DomainException
399
+	 */
400
+	public function display_errors()
401
+	{
402
+		static $shown_already = false;
403
+		do_action('AHEE__EE_Front_Controller__display_errors__begin');
404
+		if (! $shown_already
405
+			&& apply_filters('FHEE__EE_Front_Controller__display_errors', true)
406
+			&& is_main_query()
407
+			&& ! is_feed()
408
+			&& in_the_loop()
409
+			&& did_action('wp_head')
410
+			&& $this->current_page->isEspressoPage()
411
+		) {
412
+			echo EE_Error::get_notices();
413
+			$shown_already = true;
414
+			EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
415
+		}
416
+		do_action('AHEE__EE_Front_Controller__display_errors__end');
417
+	}
418
+
419
+
420
+
421
+
422
+
423
+	/***********************************************        UTILITIES         ***********************************************/
424
+	/**
425
+	 *    template_include
426
+	 *
427
+	 * @access    public
428
+	 * @param   string $template_include_path
429
+	 * @return    string
430
+	 */
431
+	public function template_include($template_include_path = null)
432
+	{
433
+		if ($this->current_page->isEspressoPage()) {
434
+			$this->_template_path = ! empty($this->_template_path)
435
+				? basename($this->_template_path)
436
+				: basename(
437
+					$template_include_path
438
+				);
439
+			$template_path = EEH_Template::locate_template($this->_template_path, array(), false);
440
+			$this->_template_path = ! empty($template_path) ? $template_path : $template_include_path;
441
+			$this->_template = basename($this->_template_path);
442
+			return $this->_template_path;
443
+		}
444
+		return $template_include_path;
445
+	}
446
+
447
+
448
+	/**
449
+	 * @param bool $with_path
450
+	 * @return    string
451
+	 */
452
+	public function get_selected_template($with_path = false)
453
+	{
454
+		return $with_path ? $this->_template_path : $this->_template;
455
+	}
456
+
457
+
458
+	/**
459
+	 * @param string $shortcode_class
460
+	 * @param WP     $wp
461
+	 * @throws ReflectionException
462
+	 * @deprecated 4.9.26
463
+	 */
464
+	public function initialize_shortcode($shortcode_class = '', WP $wp = null)
465
+	{
466
+		EE_Error::doing_it_wrong(
467
+			__METHOD__,
468
+			__(
469
+				'Usage is deprecated. Please use \EventEspresso\core\services\shortcodes\LegacyShortcodesManager::initializeShortcode() instead.',
470
+				'event_espresso'
471
+			),
472
+			'4.9.26'
473
+		);
474
+		$this->getLegacyShortcodesManager()->initializeShortcode($shortcode_class, $wp);
475
+	}
476
+
477
+
478
+	/**
479
+	 * @return void
480
+	 * @deprecated 4.9.57.p
481
+	 */
482
+	public function loadPersistentAdminNoticeManager()
483
+	{
484
+	}
485
+
486
+
487
+	/**
488
+	 * @return void
489
+	 * @deprecated 4.9.64.p
490
+	 */
491
+	public function employ_CPT_Strategy()
492
+	{
493
+	}
494 494
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
      */
98 98
     public function Request_Handler()
99 99
     {
100
-        if (! $this->Request_Handler instanceof EE_Request_Handler){
100
+        if ( ! $this->Request_Handler instanceof EE_Request_Handler) {
101 101
             $this->Request_Handler = LoaderFactory::getLoader()->getShared('EE_Request_Handler');
102 102
         }
103 103
         return $this->Request_Handler;
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
         print(
332 332
         apply_filters(
333 333
             'FHEE__EE_Front_Controller__header_meta_tag',
334
-            '<meta name="generator" content="Event Espresso Version ' . EVENT_ESPRESSO_VERSION . "\" />\n"
334
+            '<meta name="generator" content="Event Espresso Version '.EVENT_ESPRESSO_VERSION."\" />\n"
335 335
         )
336 336
         );
337 337
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
             print(
348 348
             apply_filters(
349 349
                 'FHEE__EE_Front_Controller__header_meta_tag__noindex_for_event_type',
350
-                '<meta name="robots" content="noindex,follow" />' . "\n"
350
+                '<meta name="robots" content="noindex,follow" />'."\n"
351 351
             )
352 352
             );
353 353
         }
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
     {
402 402
         static $shown_already = false;
403 403
         do_action('AHEE__EE_Front_Controller__display_errors__begin');
404
-        if (! $shown_already
404
+        if ( ! $shown_already
405 405
             && apply_filters('FHEE__EE_Front_Controller__display_errors', true)
406 406
             && is_main_query()
407 407
             && ! is_feed()
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
         ) {
412 412
             echo EE_Error::get_notices();
413 413
             $shown_already = true;
414
-            EEH_Template::display_template(EE_TEMPLATES . 'espresso-ajax-notices.template.php');
414
+            EEH_Template::display_template(EE_TEMPLATES.'espresso-ajax-notices.template.php');
415 415
         }
416 416
         do_action('AHEE__EE_Front_Controller__display_errors__end');
417 417
     }
Please login to merge, or discard this patch.