Completed
Branch ENH/mobile-browser-state-optio... (915400)
by
unknown
26:47 queued 18:09
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6460 added lines, -6460 removed lines patch added patch discarded remove patch
@@ -35,6466 +35,6466 @@
 block discarded – undo
35 35
 abstract class EEM_Base extends EE_Base implements ResettableInterface
36 36
 {
37 37
 
38
-    /**
39
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
-     * They almost always WILL NOT, but it's not necessarily a requirement.
42
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
-     *
44
-     * @var boolean
45
-     */
46
-    private $_values_already_prepared_by_model_object = 0;
47
-
48
-    /**
49
-     * when $_values_already_prepared_by_model_object equals this, we assume
50
-     * the data is just like form input that needs to have the model fields'
51
-     * prepare_for_set and prepare_for_use_in_db called on it
52
-     */
53
-    const not_prepared_by_model_object = 0;
54
-
55
-    /**
56
-     * when $_values_already_prepared_by_model_object equals this, we
57
-     * assume this value is coming from a model object and doesn't need to have
58
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
59
-     */
60
-    const prepared_by_model_object = 1;
61
-
62
-    /**
63
-     * when $_values_already_prepared_by_model_object equals this, we assume
64
-     * the values are already to be used in the database (ie no processing is done
65
-     * on them by the model's fields)
66
-     */
67
-    const prepared_for_use_in_db = 2;
68
-
69
-
70
-    protected $singular_item = 'Item';
71
-
72
-    protected $plural_item   = 'Items';
73
-
74
-    /**
75
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
-     */
77
-    protected $_tables;
78
-
79
-    /**
80
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
-     *
84
-     * @var \EE_Model_Field_Base[][] $_fields
85
-     */
86
-    protected $_fields;
87
-
88
-    /**
89
-     * array of different kinds of relations
90
-     *
91
-     * @var \EE_Model_Relation_Base[] $_model_relations
92
-     */
93
-    protected $_model_relations;
94
-
95
-    /**
96
-     * @var \EE_Index[] $_indexes
97
-     */
98
-    protected $_indexes = array();
99
-
100
-    /**
101
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
102
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
-     * by setting the same columns as used in these queries in the query yourself.
104
-     *
105
-     * @var EE_Default_Where_Conditions
106
-     */
107
-    protected $_default_where_conditions_strategy;
108
-
109
-    /**
110
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
-     * This is particularly useful when you want something between 'none' and 'default'
112
-     *
113
-     * @var EE_Default_Where_Conditions
114
-     */
115
-    protected $_minimum_where_conditions_strategy;
116
-
117
-    /**
118
-     * String describing how to find the "owner" of this model's objects.
119
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
-     * But when there isn't, this indicates which related model, or transiently-related model,
121
-     * has the foreign key to the wp_users table.
122
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
-     * related to events, and events have a foreign key to wp_users.
124
-     * On EEM_Transaction, this would be 'Transaction.Event'
125
-     *
126
-     * @var string
127
-     */
128
-    protected $_model_chain_to_wp_user = '';
129
-
130
-    /**
131
-     * String describing how to find the model with a password controlling access to this model. This property has the
132
-     * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
-     * This value is the path of models to follow to arrive at the model with the password field.
134
-     * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
-     * model with a password that should affect reading this on the front-end.
136
-     * Eg this is an empty string for the Event model because it has a password.
137
-     * This is null for the Registration model, because its event's password has no bearing on whether
138
-     * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
-     * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
-     * should hide tickets for datetimes for events that have a password set.
141
-     * @var string |null
142
-     */
143
-    protected $model_chain_to_password = null;
144
-
145
-    /**
146
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
-     * don't need it (particularly CPT models)
148
-     *
149
-     * @var bool
150
-     */
151
-    protected $_ignore_where_strategy = false;
152
-
153
-    /**
154
-     * String used in caps relating to this model. Eg, if the caps relating to this
155
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
-     *
157
-     * @var string. If null it hasn't been initialized yet. If false then we
158
-     * have indicated capabilities don't apply to this
159
-     */
160
-    protected $_caps_slug = null;
161
-
162
-    /**
163
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
-     * and next-level keys are capability names, and each's value is a
165
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
-     * they specify which context to use (ie, frontend, backend, edit or delete)
167
-     * and then each capability in the corresponding sub-array that they're missing
168
-     * adds the where conditions onto the query.
169
-     *
170
-     * @var array
171
-     */
172
-    protected $_cap_restrictions = array(
173
-        self::caps_read       => array(),
174
-        self::caps_read_admin => array(),
175
-        self::caps_edit       => array(),
176
-        self::caps_delete     => array(),
177
-    );
178
-
179
-    /**
180
-     * Array defining which cap restriction generators to use to create default
181
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
182
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
-     * automatically set this to false (not just null).
185
-     *
186
-     * @var EE_Restriction_Generator_Base[]
187
-     */
188
-    protected $_cap_restriction_generators = array();
189
-
190
-    /**
191
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
-     */
193
-    const caps_read       = 'read';
194
-
195
-    const caps_read_admin = 'read_admin';
196
-
197
-    const caps_edit       = 'edit';
198
-
199
-    const caps_delete     = 'delete';
200
-
201
-    /**
202
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
-     * maps to 'read' because when looking for relevant permissions we're going to use
205
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
206
-     *
207
-     * @var array
208
-     */
209
-    protected $_cap_contexts_to_cap_action_map = array(
210
-        self::caps_read       => 'read',
211
-        self::caps_read_admin => 'read',
212
-        self::caps_edit       => 'edit',
213
-        self::caps_delete     => 'delete',
214
-    );
215
-
216
-    /**
217
-     * Timezone
218
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
-     * EE_Datetime_Field data type will have access to it.
222
-     *
223
-     * @var string
224
-     */
225
-    protected $_timezone;
226
-
227
-
228
-    /**
229
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
-     * multisite.
231
-     *
232
-     * @var int
233
-     */
234
-    protected static $_model_query_blog_id;
235
-
236
-    /**
237
-     * A copy of _fields, except the array keys are the model names pointed to by
238
-     * the field
239
-     *
240
-     * @var EE_Model_Field_Base[]
241
-     */
242
-    private $_cache_foreign_key_to_fields = array();
243
-
244
-    /**
245
-     * Cached list of all the fields on the model, indexed by their name
246
-     *
247
-     * @var EE_Model_Field_Base[]
248
-     */
249
-    private $_cached_fields = null;
250
-
251
-    /**
252
-     * Cached list of all the fields on the model, except those that are
253
-     * marked as only pertinent to the database
254
-     *
255
-     * @var EE_Model_Field_Base[]
256
-     */
257
-    private $_cached_fields_non_db_only = null;
258
-
259
-    /**
260
-     * A cached reference to the primary key for quick lookup
261
-     *
262
-     * @var EE_Model_Field_Base
263
-     */
264
-    private $_primary_key_field = null;
265
-
266
-    /**
267
-     * Flag indicating whether this model has a primary key or not
268
-     *
269
-     * @var boolean
270
-     */
271
-    protected $_has_primary_key_field = null;
272
-
273
-    /**
274
-     * array in the format:  [ FK alias => full PK ]
275
-     * where keys are local column name aliases for foreign keys
276
-     * and values are the fully qualified column name for the primary key they represent
277
-     *  ex:
278
-     *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
-     *
280
-     * @var array $foreign_key_aliases
281
-     */
282
-    protected $foreign_key_aliases = [];
283
-
284
-    /**
285
-     * Whether or not this model is based off a table in WP core only (CPTs should set
286
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
-     * This should be true for models that deal with data that should exist independent of EE.
288
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
290
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
292
-     * @var boolean
293
-     */
294
-    protected $_wp_core_model = false;
295
-
296
-    /**
297
-     * @var bool stores whether this model has a password field or not.
298
-     * null until initialized by hasPasswordField()
299
-     */
300
-    protected $has_password_field;
301
-
302
-    /**
303
-     * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
-     */
305
-    protected $password_field;
306
-
307
-    /**
308
-     *    List of valid operators that can be used for querying.
309
-     * The keys are all operators we'll accept, the values are the real SQL
310
-     * operators used
311
-     *
312
-     * @var array
313
-     */
314
-    protected $_valid_operators = array(
315
-        '='           => '=',
316
-        '<='          => '<=',
317
-        '<'           => '<',
318
-        '>='          => '>=',
319
-        '>'           => '>',
320
-        '!='          => '!=',
321
-        'LIKE'        => 'LIKE',
322
-        'like'        => 'LIKE',
323
-        'NOT_LIKE'    => 'NOT LIKE',
324
-        'not_like'    => 'NOT LIKE',
325
-        'NOT LIKE'    => 'NOT LIKE',
326
-        'not like'    => 'NOT LIKE',
327
-        'IN'          => 'IN',
328
-        'in'          => 'IN',
329
-        'NOT_IN'      => 'NOT IN',
330
-        'not_in'      => 'NOT IN',
331
-        'NOT IN'      => 'NOT IN',
332
-        'not in'      => 'NOT IN',
333
-        'between'     => 'BETWEEN',
334
-        'BETWEEN'     => 'BETWEEN',
335
-        'IS_NOT_NULL' => 'IS NOT NULL',
336
-        'is_not_null' => 'IS NOT NULL',
337
-        'IS NOT NULL' => 'IS NOT NULL',
338
-        'is not null' => 'IS NOT NULL',
339
-        'IS_NULL'     => 'IS NULL',
340
-        'is_null'     => 'IS NULL',
341
-        'IS NULL'     => 'IS NULL',
342
-        'is null'     => 'IS NULL',
343
-        'REGEXP'      => 'REGEXP',
344
-        'regexp'      => 'REGEXP',
345
-        'NOT_REGEXP'  => 'NOT REGEXP',
346
-        'not_regexp'  => 'NOT REGEXP',
347
-        'NOT REGEXP'  => 'NOT REGEXP',
348
-        'not regexp'  => 'NOT REGEXP',
349
-    );
350
-
351
-    /**
352
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
-     *
354
-     * @var array
355
-     */
356
-    protected $_in_style_operators = array('IN', 'NOT IN');
357
-
358
-    /**
359
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
-     * '12-31-2012'"
361
-     *
362
-     * @var array
363
-     */
364
-    protected $_between_style_operators = array('BETWEEN');
365
-
366
-    /**
367
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
-     * @var array
369
-     */
370
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
-    /**
372
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
-     * on a join table.
374
-     *
375
-     * @var array
376
-     */
377
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
-
379
-    /**
380
-     * Allowed values for $query_params['order'] for ordering in queries
381
-     *
382
-     * @var array
383
-     */
384
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
-
386
-    /**
387
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
389
-     *
390
-     * @var array
391
-     */
392
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
-
394
-    /**
395
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
397
-     *
398
-     * @var array
399
-     */
400
-    private $_allowed_query_params = array(
401
-        0,
402
-        'limit',
403
-        'order_by',
404
-        'group_by',
405
-        'having',
406
-        'force_join',
407
-        'order',
408
-        'on_join_limit',
409
-        'default_where_conditions',
410
-        'caps',
411
-        'extra_selects',
412
-        'exclude_protected',
413
-    );
414
-
415
-    /**
416
-     * All the data types that can be used in $wpdb->prepare statements.
417
-     *
418
-     * @var array
419
-     */
420
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
-
422
-    /**
423
-     * @var EE_Registry $EE
424
-     */
425
-    protected $EE = null;
426
-
427
-
428
-    /**
429
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
-     *
431
-     * @var int
432
-     */
433
-    protected $_show_next_x_db_queries = 0;
434
-
435
-    /**
436
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
-     * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
-     * WHERE, GROUP_BY, etc.
439
-     *
440
-     * @var CustomSelects
441
-     */
442
-    protected $_custom_selections = array();
443
-
444
-    /**
445
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
-     * caches every model object we've fetched from the DB on this request
447
-     *
448
-     * @var array
449
-     */
450
-    protected $_entity_map;
451
-
452
-    /**
453
-     * @var LoaderInterface $loader
454
-     */
455
-    private static $loader;
456
-
457
-
458
-    /**
459
-     * constant used to show EEM_Base has not yet verified the db on this http request
460
-     */
461
-    const db_verified_none = 0;
462
-
463
-    /**
464
-     * constant used to show EEM_Base has verified the EE core db on this http request,
465
-     * but not the addons' dbs
466
-     */
467
-    const db_verified_core = 1;
468
-
469
-    /**
470
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
-     * the EE core db too)
472
-     */
473
-    const db_verified_addons = 2;
474
-
475
-    /**
476
-     * indicates whether an EEM_Base child has already re-verified the DB
477
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
478
-     * looking like EEM_Base::db_verified_*
479
-     *
480
-     * @var int - 0 = none, 1 = core, 2 = addons
481
-     */
482
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
483
-
484
-    /**
485
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
-     *        registrations for non-trashed tickets for non-trashed datetimes)
488
-     */
489
-    const default_where_conditions_all = 'all';
490
-
491
-    /**
492
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
-     *        models which share tables with other models, this can return data for the wrong model.
497
-     */
498
-    const default_where_conditions_this_only = 'this_model_only';
499
-
500
-    /**
501
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
-     */
505
-    const default_where_conditions_others_only = 'other_models_only';
506
-
507
-    /**
508
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
511
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
-     *        (regardless of whether those events and venues are trashed)
513
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
-     *        events.
515
-     */
516
-    const default_where_conditions_minimum_all = 'minimum';
517
-
518
-    /**
519
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
-     *        not)
523
-     */
524
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
-
526
-    /**
527
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
-     *        it's possible it will return table entries for other models. You should use
530
-     *        EEM_Base::default_where_conditions_minimum_all instead.
531
-     */
532
-    const default_where_conditions_none = 'none';
533
-
534
-
535
-
536
-    /**
537
-     * About all child constructors:
538
-     * they should define the _tables, _fields and _model_relations arrays.
539
-     * Should ALWAYS be called after child constructor.
540
-     * In order to make the child constructors to be as simple as possible, this parent constructor
541
-     * finalizes constructing all the object's attributes.
542
-     * Generally, rather than requiring a child to code
543
-     * $this->_tables = array(
544
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
-     *        ...);
546
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
-     * each EE_Table has a function to set the table's alias after the constructor, using
548
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
-     * do something similar.
550
-     *
551
-     * @param null $timezone
552
-     * @throws EE_Error
553
-     */
554
-    protected function __construct($timezone = null)
555
-    {
556
-        // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
-            throw new EE_Error(
559
-                sprintf(
560
-                    __(
561
-                        '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.',
562
-                        'event_espresso'
563
-                    ),
564
-                    get_class($this)
565
-                )
566
-            );
567
-        }
568
-        /**
569
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
-         */
571
-        if (empty(EEM_Base::$_model_query_blog_id)) {
572
-            EEM_Base::set_model_query_blog_id();
573
-        }
574
-        /**
575
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
-         * just use EE_Register_Model_Extension
577
-         *
578
-         * @var EE_Table_Base[] $_tables
579
-         */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
-        foreach ($this->_tables as $table_alias => $table_obj) {
582
-            /** @var $table_obj EE_Table_Base */
583
-            $table_obj->_construct_finalize_with_alias($table_alias);
584
-            if ($table_obj instanceof EE_Secondary_Table) {
585
-                /** @var $table_obj EE_Secondary_Table */
586
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
-            }
588
-        }
589
-        /**
590
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
-         * EE_Register_Model_Extension
592
-         *
593
-         * @param EE_Model_Field_Base[] $_fields
594
-         */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
-        $this->_invalidate_field_caches();
597
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
599
-                throw new EE_Error(sprintf(__(
600
-                    "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
-                    'event_espresso'
602
-                ), $table_alias, implode(",", $this->_fields)));
603
-            }
604
-            foreach ($fields_for_table as $field_name => $field_obj) {
605
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
-                // primary key field base has a slightly different _construct_finalize
607
-                /** @var $field_obj EE_Model_Field_Base */
608
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
-            }
610
-        }
611
-        // everything is related to Extra_Meta
612
-        if (get_class($this) !== 'EEM_Extra_Meta') {
613
-            // make extra meta related to everything, but don't block deleting things just
614
-            // because they have related extra meta info. For now just orphan those extra meta
615
-            // in the future we should automatically delete them
616
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
-        }
618
-        // and change logs
619
-        if (get_class($this) !== 'EEM_Change_Log') {
620
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
-        }
622
-        /**
623
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
-         * EE_Register_Model_Extension
625
-         *
626
-         * @param EE_Model_Relation_Base[] $_model_relations
627
-         */
628
-        $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
630
-            $this->_model_relations
631
-        );
632
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
633
-            /** @var $relation_obj EE_Model_Relation_Base */
634
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
-        }
636
-        foreach ($this->_indexes as $index_name => $index_obj) {
637
-            /** @var $index_obj EE_Index */
638
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
-        }
640
-        $this->set_timezone($timezone);
641
-        // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
643
-            // nothing was set during child constructor, so set default
644
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
-        }
646
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
648
-            // nothing was set during child constructor, so set default
649
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
-        }
651
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
-        // if the cap slug hasn't been set, and we haven't set it to false on purpose
653
-        // to indicate to NOT set it, set it to the logical default
654
-        if ($this->_caps_slug === null) {
655
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
-        }
657
-        // initialize the standard cap restriction generators if none were specified by the child constructor
658
-        if ($this->_cap_restriction_generators !== false) {
659
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
-                        new EE_Restriction_Generator_Protected(),
664
-                        $cap_context,
665
-                        $this
666
-                    );
667
-                }
668
-            }
669
-        }
670
-        // if there are cap restriction generators, use them to make the default cap restrictions
671
-        if ($this->_cap_restriction_generators !== false) {
672
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
674
-                    continue;
675
-                }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
-                    throw new EE_Error(
678
-                        sprintf(
679
-                            __(
680
-                                '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.',
681
-                                'event_espresso'
682
-                            ),
683
-                            $context,
684
-                            $this->get_this_model_name()
685
-                        )
686
-                    );
687
-                }
688
-                $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
690
-                    $generator_object->_construct_finalize($this, $action);
691
-                }
692
-            }
693
-        }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
695
-    }
696
-
697
-
698
-
699
-    /**
700
-     * Used to set the $_model_query_blog_id static property.
701
-     *
702
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
-     *                      value for get_current_blog_id() will be used.
704
-     */
705
-    public static function set_model_query_blog_id($blog_id = 0)
706
-    {
707
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
-    }
709
-
710
-
711
-
712
-    /**
713
-     * Returns whatever is set as the internal $model_query_blog_id.
714
-     *
715
-     * @return int
716
-     */
717
-    public static function get_model_query_blog_id()
718
-    {
719
-        return EEM_Base::$_model_query_blog_id;
720
-    }
721
-
722
-
723
-
724
-    /**
725
-     * This function is a singleton method used to instantiate the Espresso_model object
726
-     *
727
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
-     *                                (and any incoming timezone data that gets saved).
729
-     *                                Note this just sends the timezone info to the date time model field objects.
730
-     *                                Default is NULL
731
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
-     * @return static (as in the concrete child class)
733
-     * @throws EE_Error
734
-     * @throws InvalidArgumentException
735
-     * @throws InvalidDataTypeException
736
-     * @throws InvalidInterfaceException
737
-     */
738
-    public static function instance($timezone = null)
739
-    {
740
-        // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
742
-            // instantiate Espresso_model
743
-            static::$_instance = new static(
744
-                $timezone,
745
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
-            );
747
-        }
748
-        // we might have a timezone set, let set_timezone decide what to do with it
749
-        static::$_instance->set_timezone($timezone);
750
-        // Espresso_model object
751
-        return static::$_instance;
752
-    }
753
-
754
-
755
-
756
-    /**
757
-     * resets the model and returns it
758
-     *
759
-     * @param null | string $timezone
760
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
-     * all its properties reset; if it wasn't instantiated, returns null)
762
-     * @throws EE_Error
763
-     * @throws ReflectionException
764
-     * @throws InvalidArgumentException
765
-     * @throws InvalidDataTypeException
766
-     * @throws InvalidInterfaceException
767
-     */
768
-    public static function reset($timezone = null)
769
-    {
770
-        if (static::$_instance instanceof EEM_Base) {
771
-            // let's try to NOT swap out the current instance for a new one
772
-            // because if someone has a reference to it, we can't remove their reference
773
-            // so it's best to keep using the same reference, but change the original object
774
-            // reset all its properties to their original values as defined in the class
775
-            $r = new ReflectionClass(get_class(static::$_instance));
776
-            $static_properties = $r->getStaticProperties();
777
-            foreach ($r->getDefaultProperties() as $property => $value) {
778
-                // don't set instance to null like it was originally,
779
-                // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
781
-                    static::$_instance->{$property} = $value;
782
-                }
783
-            }
784
-            // and then directly call its constructor again, like we would if we were creating a new one
785
-            static::$_instance->__construct(
786
-                $timezone,
787
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
-            );
789
-            return self::instance();
790
-        }
791
-        return null;
792
-    }
793
-
794
-
795
-
796
-    /**
797
-     * @return LoaderInterface
798
-     * @throws InvalidArgumentException
799
-     * @throws InvalidDataTypeException
800
-     * @throws InvalidInterfaceException
801
-     */
802
-    private static function getLoader()
803
-    {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
805
-            EEM_Base::$loader = LoaderFactory::getLoader();
806
-        }
807
-        return EEM_Base::$loader;
808
-    }
809
-
810
-
811
-
812
-    /**
813
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
-     *
815
-     * @param  boolean $translated return localized strings or JUST the array.
816
-     * @return array
817
-     * @throws EE_Error
818
-     * @throws InvalidArgumentException
819
-     * @throws InvalidDataTypeException
820
-     * @throws InvalidInterfaceException
821
-     */
822
-    public function status_array($translated = false)
823
-    {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
825
-            return array();
826
-        }
827
-        $model_name = $this->get_this_model_name();
828
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
-        $status_array = array();
831
-        foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
833
-        }
834
-        return $translated
835
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
-            : $status_array;
837
-    }
838
-
839
-
840
-
841
-    /**
842
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
-     *
844
-     * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
-     *                             or if you have the development copy of EE you can view this at the path:
846
-     *                             /docs/G--Model-System/model-query-params.md
847
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
-     *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
-     *                                        array( array(
852
-     *                                        'OR'=>array(
853
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
-     *                                        )
856
-     *                                        ),
857
-     *                                        'limit'=>10,
858
-     *                                        'group_by'=>'TXN_ID'
859
-     *                                        ));
860
-     *                                        get all the answers to the question titled "shirt size" for event with id
861
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
-     *                                        'Question.QST_display_text'=>'shirt size',
863
-     *                                        'Registration.Event.EVT_ID'=>12
864
-     *                                        ),
865
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
866
-     *                                        ));
867
-     * @throws EE_Error
868
-     */
869
-    public function get_all($query_params = array())
870
-    {
871
-        if (isset($query_params['limit'])
872
-            && ! isset($query_params['group_by'])
873
-        ) {
874
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
-        }
876
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
-    }
878
-
879
-
880
-
881
-    /**
882
-     * Modifies the query parameters so we only get back model objects
883
-     * that "belong" to the current user
884
-     *
885
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
-     */
888
-    public function alter_query_params_to_only_include_mine($query_params = array())
889
-    {
890
-        $wp_user_field_name = $this->wp_user_field_name();
891
-        if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
-        }
894
-        return $query_params;
895
-    }
896
-
897
-
898
-
899
-    /**
900
-     * Returns the name of the field's name that points to the WP_User table
901
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
-     * foreign key to the WP_User table)
903
-     *
904
-     * @return string|boolean string on success, boolean false when there is no
905
-     * foreign key to the WP_User table
906
-     */
907
-    public function wp_user_field_name()
908
-    {
909
-        try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
911
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
-                $last_model_name = end($models_to_follow_to_wp_users);
913
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
-            } else {
916
-                $model_with_fk_to_wp_users = $this;
917
-                $model_chain_to_wp_user = '';
918
-            }
919
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
921
-        } catch (EE_Error $e) {
922
-            return false;
923
-        }
924
-    }
925
-
926
-
927
-
928
-    /**
929
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
930
-     * (or transiently-related model) has a foreign key to the wp_users table;
931
-     * useful for finding if model objects of this type are 'owned' by the current user.
932
-     * This is an empty string when the foreign key is on this model and when it isn't,
933
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
934
-     * (or transiently-related model)
935
-     *
936
-     * @return string
937
-     */
938
-    public function model_chain_to_wp_user()
939
-    {
940
-        return $this->_model_chain_to_wp_user;
941
-    }
942
-
943
-
944
-
945
-    /**
946
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
-     * like how registrations don't have a foreign key to wp_users, but the
948
-     * events they are for are), or is unrelated to wp users.
949
-     * generally available
950
-     *
951
-     * @return boolean
952
-     */
953
-    public function is_owned()
954
-    {
955
-        if ($this->model_chain_to_wp_user()) {
956
-            return true;
957
-        }
958
-        try {
959
-            $this->get_foreign_key_to('WP_User');
960
-            return true;
961
-        } catch (EE_Error $e) {
962
-            return false;
963
-        }
964
-    }
965
-
966
-
967
-    /**
968
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
-     * the model)
971
-     *
972
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
-     *                                  fields on the model, and the models we joined to in the query. However, you can
976
-     *                                  override this and set the select to "*", or a specific column name, like
977
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
-     *                                  the aliases used to refer to this selection, and values are to be
980
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
-     * @throws EE_Error
984
-     * @throws InvalidArgumentException
985
-     */
986
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
-    {
988
-        $this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
-        ;
990
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
991
-        $select_expressions = $columns_to_select === null
992
-            ? $this->_construct_default_select_sql($model_query_info)
993
-            : '';
994
-        if ($this->_custom_selections instanceof CustomSelects) {
995
-            $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
-            $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
998
-                : $custom_expressions;
999
-        }
1000
-
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
-    }
1004
-
1005
-
1006
-    /**
1007
-     * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
-     * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
-     * method of including extra select information.
1010
-     *
1011
-     * @param array             $query_params
1012
-     * @param null|array|string $columns_to_select
1013
-     * @return null|CustomSelects
1014
-     * @throws InvalidArgumentException
1015
-     */
1016
-    protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
-    {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
-            return null;
1020
-        }
1021
-        $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
-        $selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
-        return new CustomSelects($selects);
1024
-    }
1025
-
1026
-
1027
-
1028
-    /**
1029
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1030
-     * but you can use the model query params to more easily
1031
-     * take care of joins, field preparation etc.
1032
-     *
1033
-     * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1037
-     *                                  override this and set the select to "*", or a specific column name, like
1038
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
-     *                                  the aliases used to refer to this selection, and values are to be
1041
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
-     * @throws EE_Error
1045
-     */
1046
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
-    {
1048
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
-    }
1050
-
1051
-
1052
-
1053
-    /**
1054
-     * For creating a custom select statement
1055
-     *
1056
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
-     *                                 SQL, and 1=>is the datatype
1059
-     * @throws EE_Error
1060
-     * @return string
1061
-     */
1062
-    private function _construct_select_from_input($columns_to_select)
1063
-    {
1064
-        if (is_array($columns_to_select)) {
1065
-            $select_sql_array = array();
1066
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
-                    throw new EE_Error(
1069
-                        sprintf(
1070
-                            __(
1071
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
-                                'event_espresso'
1073
-                            ),
1074
-                            $selection_and_datatype,
1075
-                            $alias
1076
-                        )
1077
-                    );
1078
-                }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
-                    throw new EE_Error(
1081
-                        sprintf(
1082
-                            esc_html__(
1083
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
-                                'event_espresso'
1085
-                            ),
1086
-                            $selection_and_datatype[1],
1087
-                            $selection_and_datatype[0],
1088
-                            $alias,
1089
-                            implode(', ', $this->_valid_wpdb_data_types)
1090
-                        )
1091
-                    );
1092
-                }
1093
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
-            }
1095
-            $columns_to_select_string = implode(', ', $select_sql_array);
1096
-        } else {
1097
-            $columns_to_select_string = $columns_to_select;
1098
-        }
1099
-        return $columns_to_select_string;
1100
-    }
1101
-
1102
-
1103
-
1104
-    /**
1105
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
-     *
1107
-     * @return string
1108
-     * @throws EE_Error
1109
-     */
1110
-    public function primary_key_name()
1111
-    {
1112
-        return $this->get_primary_key_field()->get_name();
1113
-    }
1114
-
1115
-
1116
-    /**
1117
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
-     * If there is no primary key on this model, $id is treated as primary key string
1119
-     *
1120
-     * @param mixed $id int or string, depending on the type of the model's primary key
1121
-     * @return EE_Base_Class
1122
-     * @throws EE_Error
1123
-     */
1124
-    public function get_one_by_ID($id)
1125
-    {
1126
-        if ($this->get_from_entity_map($id)) {
1127
-            return $this->get_from_entity_map($id);
1128
-        }
1129
-        $model_object = $this->get_one(
1130
-            $this->alter_query_params_to_restrict_by_ID(
1131
-                $id,
1132
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
-            )
1134
-        );
1135
-        $className = $this->_get_class_name();
1136
-        if ($model_object instanceof $className) {
1137
-            // make sure valid objects get added to the entity map
1138
-            // so that the next call to this method doesn't trigger another trip to the db
1139
-            $this->add_to_entity_map($model_object);
1140
-        }
1141
-        return $model_object;
1142
-    }
1143
-
1144
-
1145
-
1146
-    /**
1147
-     * Alters query parameters to only get items with this ID are returned.
1148
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
-     * or could just be a simple primary key ID
1150
-     *
1151
-     * @param int   $id
1152
-     * @param array $query_params
1153
-     * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
-     * @throws EE_Error
1155
-     */
1156
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
-    {
1158
-        if (! isset($query_params[0])) {
1159
-            $query_params[0] = array();
1160
-        }
1161
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1162
-        if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1164
-        } else {
1165
-            // no primary key, so the $id must be from the get_index_primary_key_string()
1166
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
-        }
1168
-        return $query_params;
1169
-    }
1170
-
1171
-
1172
-
1173
-    /**
1174
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
-     * array. If no item is found, null is returned.
1176
-     *
1177
-     * @param array $query_params like EEM_Base's $query_params variable.
1178
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
-     * @throws EE_Error
1180
-     */
1181
-    public function get_one($query_params = array())
1182
-    {
1183
-        if (! is_array($query_params)) {
1184
-            EE_Error::doing_it_wrong(
1185
-                'EEM_Base::get_one',
1186
-                sprintf(
1187
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
-                    gettype($query_params)
1189
-                ),
1190
-                '4.6.0'
1191
-            );
1192
-            $query_params = array();
1193
-        }
1194
-        $query_params['limit'] = 1;
1195
-        $items = $this->get_all($query_params);
1196
-        if (empty($items)) {
1197
-            return null;
1198
-        }
1199
-        return array_shift($items);
1200
-    }
1201
-
1202
-
1203
-
1204
-    /**
1205
-     * Returns the next x number of items in sequence from the given value as
1206
-     * found in the database matching the given query conditions.
1207
-     *
1208
-     * @param mixed $current_field_value    Value used for the reference point.
1209
-     * @param null  $field_to_order_by      What field is used for the
1210
-     *                                      reference point.
1211
-     * @param int   $limit                  How many to return.
1212
-     * @param array $query_params           Extra conditions on the query.
1213
-     * @param null  $columns_to_select      If left null, then an array of
1214
-     *                                      EE_Base_Class objects is returned,
1215
-     *                                      otherwise you can indicate just the
1216
-     *                                      columns you want returned.
1217
-     * @return EE_Base_Class[]|array
1218
-     * @throws EE_Error
1219
-     */
1220
-    public function next_x(
1221
-        $current_field_value,
1222
-        $field_to_order_by = null,
1223
-        $limit = 1,
1224
-        $query_params = array(),
1225
-        $columns_to_select = null
1226
-    ) {
1227
-        return $this->_get_consecutive(
1228
-            $current_field_value,
1229
-            '>',
1230
-            $field_to_order_by,
1231
-            $limit,
1232
-            $query_params,
1233
-            $columns_to_select
1234
-        );
1235
-    }
1236
-
1237
-
1238
-
1239
-    /**
1240
-     * Returns the previous x number of items in sequence from the given value
1241
-     * as found in the database matching the given query conditions.
1242
-     *
1243
-     * @param mixed $current_field_value    Value used for the reference point.
1244
-     * @param null  $field_to_order_by      What field is used for the
1245
-     *                                      reference point.
1246
-     * @param int   $limit                  How many to return.
1247
-     * @param array $query_params           Extra conditions on the query.
1248
-     * @param null  $columns_to_select      If left null, then an array of
1249
-     *                                      EE_Base_Class objects is returned,
1250
-     *                                      otherwise you can indicate just the
1251
-     *                                      columns you want returned.
1252
-     * @return EE_Base_Class[]|array
1253
-     * @throws EE_Error
1254
-     */
1255
-    public function previous_x(
1256
-        $current_field_value,
1257
-        $field_to_order_by = null,
1258
-        $limit = 1,
1259
-        $query_params = array(),
1260
-        $columns_to_select = null
1261
-    ) {
1262
-        return $this->_get_consecutive(
1263
-            $current_field_value,
1264
-            '<',
1265
-            $field_to_order_by,
1266
-            $limit,
1267
-            $query_params,
1268
-            $columns_to_select
1269
-        );
1270
-    }
1271
-
1272
-
1273
-
1274
-    /**
1275
-     * Returns the next item in sequence from the given value as found in the
1276
-     * database matching the given query conditions.
1277
-     *
1278
-     * @param mixed $current_field_value    Value used for the reference point.
1279
-     * @param null  $field_to_order_by      What field is used for the
1280
-     *                                      reference point.
1281
-     * @param array $query_params           Extra conditions on the query.
1282
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
-     *                                      object is returned, otherwise you
1284
-     *                                      can indicate just the columns you
1285
-     *                                      want and a single array indexed by
1286
-     *                                      the columns will be returned.
1287
-     * @return EE_Base_Class|null|array()
1288
-     * @throws EE_Error
1289
-     */
1290
-    public function next(
1291
-        $current_field_value,
1292
-        $field_to_order_by = null,
1293
-        $query_params = array(),
1294
-        $columns_to_select = null
1295
-    ) {
1296
-        $results = $this->_get_consecutive(
1297
-            $current_field_value,
1298
-            '>',
1299
-            $field_to_order_by,
1300
-            1,
1301
-            $query_params,
1302
-            $columns_to_select
1303
-        );
1304
-        return empty($results) ? null : reset($results);
1305
-    }
1306
-
1307
-
1308
-
1309
-    /**
1310
-     * Returns the previous item in sequence from the given value as found in
1311
-     * the database matching the given query conditions.
1312
-     *
1313
-     * @param mixed $current_field_value    Value used for the reference point.
1314
-     * @param null  $field_to_order_by      What field is used for the
1315
-     *                                      reference point.
1316
-     * @param array $query_params           Extra conditions on the query.
1317
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
-     *                                      object is returned, otherwise you
1319
-     *                                      can indicate just the columns you
1320
-     *                                      want and a single array indexed by
1321
-     *                                      the columns will be returned.
1322
-     * @return EE_Base_Class|null|array()
1323
-     * @throws EE_Error
1324
-     */
1325
-    public function previous(
1326
-        $current_field_value,
1327
-        $field_to_order_by = null,
1328
-        $query_params = array(),
1329
-        $columns_to_select = null
1330
-    ) {
1331
-        $results = $this->_get_consecutive(
1332
-            $current_field_value,
1333
-            '<',
1334
-            $field_to_order_by,
1335
-            1,
1336
-            $query_params,
1337
-            $columns_to_select
1338
-        );
1339
-        return empty($results) ? null : reset($results);
1340
-    }
1341
-
1342
-
1343
-
1344
-    /**
1345
-     * Returns the a consecutive number of items in sequence from the given
1346
-     * value as found in the database matching the given query conditions.
1347
-     *
1348
-     * @param mixed  $current_field_value   Value used for the reference point.
1349
-     * @param string $operand               What operand is used for the sequence.
1350
-     * @param string $field_to_order_by     What field is used for the reference point.
1351
-     * @param int    $limit                 How many to return.
1352
-     * @param array  $query_params          Extra conditions on the query.
1353
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
-     *                                      otherwise you can indicate just the columns you want returned.
1355
-     * @return EE_Base_Class[]|array
1356
-     * @throws EE_Error
1357
-     */
1358
-    protected function _get_consecutive(
1359
-        $current_field_value,
1360
-        $operand = '>',
1361
-        $field_to_order_by = null,
1362
-        $limit = 1,
1363
-        $query_params = array(),
1364
-        $columns_to_select = null
1365
-    ) {
1366
-        // if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
-        if (empty($field_to_order_by)) {
1368
-            if ($this->has_primary_key_field()) {
1369
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1370
-            } else {
1371
-                if (WP_DEBUG) {
1372
-                    throw new EE_Error(__(
1373
-                        '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).',
1374
-                        'event_espresso'
1375
-                    ));
1376
-                }
1377
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
-                return array();
1379
-            }
1380
-        }
1381
-        if (! is_array($query_params)) {
1382
-            EE_Error::doing_it_wrong(
1383
-                'EEM_Base::_get_consecutive',
1384
-                sprintf(
1385
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
-                    gettype($query_params)
1387
-                ),
1388
-                '4.6.0'
1389
-            );
1390
-            $query_params = array();
1391
-        }
1392
-        // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
-        $query_params['limit'] = $limit;
1395
-        // set direction
1396
-        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
-        $query_params['order_by'] = $operand === '>'
1398
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
-        // if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
-        if (empty($columns_to_select)) {
1402
-            return $this->get_all($query_params);
1403
-        }
1404
-        // getting just the fields
1405
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
-    }
1407
-
1408
-
1409
-
1410
-    /**
1411
-     * This sets the _timezone property after model object has been instantiated.
1412
-     *
1413
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
-     */
1415
-    public function set_timezone($timezone)
1416
-    {
1417
-        if ($timezone !== null) {
1418
-            $this->_timezone = $timezone;
1419
-        }
1420
-        // note we need to loop through relations and set the timezone on those objects as well.
1421
-        foreach ($this->_model_relations as $relation) {
1422
-            $relation->set_timezone($timezone);
1423
-        }
1424
-        // and finally we do the same for any datetime fields
1425
-        foreach ($this->_fields as $field) {
1426
-            if ($field instanceof EE_Datetime_Field) {
1427
-                $field->set_timezone($timezone);
1428
-            }
1429
-        }
1430
-    }
1431
-
1432
-
1433
-
1434
-    /**
1435
-     * This just returns whatever is set for the current timezone.
1436
-     *
1437
-     * @access public
1438
-     * @return string
1439
-     */
1440
-    public function get_timezone()
1441
-    {
1442
-        // first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
-        if (empty($this->_timezone)) {
1444
-            foreach ($this->_fields as $field) {
1445
-                if ($field instanceof EE_Datetime_Field) {
1446
-                    $this->set_timezone($field->get_timezone());
1447
-                    break;
1448
-                }
1449
-            }
1450
-        }
1451
-        // if timezone STILL empty then return the default timezone for the site.
1452
-        if (empty($this->_timezone)) {
1453
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
-        }
1455
-        return $this->_timezone;
1456
-    }
1457
-
1458
-
1459
-
1460
-    /**
1461
-     * This returns the date formats set for the given field name and also ensures that
1462
-     * $this->_timezone property is set correctly.
1463
-     *
1464
-     * @since 4.6.x
1465
-     * @param string $field_name The name of the field the formats are being retrieved for.
1466
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
-     * @return array formats in an array with the date format first, and the time format last.
1469
-     */
1470
-    public function get_formats_for($field_name, $pretty = false)
1471
-    {
1472
-        $field_settings = $this->field_settings_for($field_name);
1473
-        // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1475
-            throw new EE_Error(sprintf(__(
1476
-                '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.',
1477
-                'event_espresso'
1478
-            ), $field_name));
1479
-        }
1480
-        // while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
-        // the field.
1482
-        $this->_timezone = $field_settings->get_timezone();
1483
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
-    }
1485
-
1486
-
1487
-
1488
-    /**
1489
-     * This returns the current time in a format setup for a query on this model.
1490
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
-     * it will return:
1492
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
-     *  NOW
1494
-     *  - or a unix timestamp (equivalent to time())
1495
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
-     * @since 4.6.x
1499
-     * @param string $field_name       The field the current time is needed for.
1500
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
-     *                                 formatted string matching the set format for the field in the set timezone will
1502
-     *                                 be returned.
1503
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
-     *                                 exception is triggered.
1507
-     */
1508
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
-    {
1510
-        $formats = $this->get_formats_for($field_name);
1511
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
-        if ($timestamp) {
1513
-            return $DateTime->format('U');
1514
-        }
1515
-        // not returning timestamp, so return formatted string in timezone.
1516
-        switch ($what) {
1517
-            case 'time':
1518
-                return $DateTime->format($formats[1]);
1519
-                break;
1520
-            case 'date':
1521
-                return $DateTime->format($formats[0]);
1522
-                break;
1523
-            default:
1524
-                return $DateTime->format(implode(' ', $formats));
1525
-                break;
1526
-        }
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
-     * for the model are.  Returns a DateTime object.
1534
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
-     * ignored.
1537
-     *
1538
-     * @param string $field_name      The field being setup.
1539
-     * @param string $timestring      The date time string being used.
1540
-     * @param string $incoming_format The format for the time string.
1541
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
-     *                                format is
1544
-     *                                'U', this is ignored.
1545
-     * @return DateTime
1546
-     * @throws EE_Error
1547
-     */
1548
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
-    {
1550
-        // just using this to ensure the timezone is set correctly internally
1551
-        $this->get_formats_for($field_name);
1552
-        // load EEH_DTT_Helper
1553
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
-        EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
-    }
1558
-
1559
-
1560
-
1561
-    /**
1562
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
-     *
1564
-     * @return EE_Table_Base[]
1565
-     */
1566
-    public function get_tables()
1567
-    {
1568
-        return $this->_tables;
1569
-    }
1570
-
1571
-
1572
-
1573
-    /**
1574
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
-     * model object with EVT_ID = 1
1580
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
-     * are not specified)
1585
-     *
1586
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1591
-     *                                         ID=34, we'd use this method as follows:
1592
-     *                                         EEM_Transaction::instance()->update(
1593
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
-     *                                         array(array('TXN_ID'=>34)));
1595
-     * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
-     *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
-     *                                         TRUE, it is assumed that you've already called
1602
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
-     *                                         malicious javascript. However, if
1604
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
-     *                                         and every other field, before insertion. We provide this parameter
1607
-     *                                         because model objects perform their prepare_for_set function on all
1608
-     *                                         their values, and so don't need to be called again (and in many cases,
1609
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
-     *                                         prepare_for_set method...)
1611
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
-     *                                         in this model's entity map according to $fields_n_values that match
1613
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1614
-     *                                         by setting this to FALSE, but be aware that model objects being used
1615
-     *                                         could get out-of-sync with the database
1616
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
-     *                                         bad)
1619
-     * @throws EE_Error
1620
-     */
1621
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
-    {
1623
-        if (! is_array($query_params)) {
1624
-            EE_Error::doing_it_wrong(
1625
-                'EEM_Base::update',
1626
-                sprintf(
1627
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
-                    gettype($query_params)
1629
-                ),
1630
-                '4.6.0'
1631
-            );
1632
-            $query_params = array();
1633
-        }
1634
-        /**
1635
-         * Action called before a model update call has been made.
1636
-         *
1637
-         * @param EEM_Base $model
1638
-         * @param array    $fields_n_values the updated fields and their new values
1639
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
-         */
1641
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
-        /**
1643
-         * Filters the fields about to be updated given the query parameters. You can provide the
1644
-         * $query_params to $this->get_all() to find exactly which records will be updated
1645
-         *
1646
-         * @param array    $fields_n_values fields and their new values
1647
-         * @param EEM_Base $model           the model being queried
1648
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
-         */
1650
-        $fields_n_values = (array) apply_filters(
1651
-            'FHEE__EEM_Base__update__fields_n_values',
1652
-            $fields_n_values,
1653
-            $this,
1654
-            $query_params
1655
-        );
1656
-        // need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
-        // to do that, for each table, verify that it's PK isn't null.
1658
-        $tables = $this->get_tables();
1659
-        // and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
-        // NOTE: we should make this code more efficient by NOT querying twice
1661
-        // before the real update, but that needs to first go through ALPHA testing
1662
-        // as it's dangerous. says Mike August 8 2014
1663
-        // we want to make sure the default_where strategy is ignored
1664
-        $this->_ignore_where_strategy = true;
1665
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
-        foreach ($wpdb_select_results as $wpdb_result) {
1667
-            // type cast stdClass as array
1668
-            $wpdb_result = (array) $wpdb_result;
1669
-            // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
-            if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
-            } else {
1673
-                // 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)
1674
-                $main_table_pk_value = null;
1675
-            }
1676
-            // 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
1677
-            // 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
1678
-            if (count($tables) > 1) {
1679
-                // foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
-                // in that table, and so we'll want to insert one
1681
-                foreach ($tables as $table_obj) {
1682
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
-                    // if there is no private key for this table on the results, it means there's no entry
1684
-                    // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1687
-                    ) {
1688
-                        $success = $this->_insert_into_specific_table(
1689
-                            $table_obj,
1690
-                            $fields_n_values,
1691
-                            $main_table_pk_value
1692
-                        );
1693
-                        // if we died here, report the error
1694
-                        if (! $success) {
1695
-                            return false;
1696
-                        }
1697
-                    }
1698
-                }
1699
-            }
1700
-            //              //and now check that if we have cached any models by that ID on the model, that
1701
-            //              //they also get updated properly
1702
-            //              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
-            //              if( $model_object ){
1704
-            //                  foreach( $fields_n_values as $field => $value ){
1705
-            //                      $model_object->set($field, $value);
1706
-            // let's make sure default_where strategy is followed now
1707
-            $this->_ignore_where_strategy = false;
1708
-        }
1709
-        // if we want to keep model objects in sync, AND
1710
-        // if this wasn't called from a model object (to update itself)
1711
-        // then we want to make sure we keep all the existing
1712
-        // model objects in sync with the db
1713
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
-            if ($this->has_primary_key_field()) {
1715
-                $model_objs_affected_ids = $this->get_col($query_params);
1716
-            } else {
1717
-                // we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
-                $model_objs_affected_ids = array();
1720
-                foreach ($models_affected_key_columns as $row) {
1721
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
-                }
1724
-            }
1725
-            if (! $model_objs_affected_ids) {
1726
-                // wait wait wait- if nothing was affected let's stop here
1727
-                return 0;
1728
-            }
1729
-            foreach ($model_objs_affected_ids as $id) {
1730
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
-                if ($model_obj_in_entity_map) {
1732
-                    foreach ($fields_n_values as $field => $new_value) {
1733
-                        $model_obj_in_entity_map->set($field, $new_value);
1734
-                    }
1735
-                }
1736
-            }
1737
-            // if there is a primary key on this model, we can now do a slight optimization
1738
-            if ($this->has_primary_key_field()) {
1739
-                // we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
-                $query_params = array(
1741
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
-                    'limit'                    => count($model_objs_affected_ids),
1743
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
-                );
1745
-            }
1746
-        }
1747
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
-        $SQL = "UPDATE "
1749
-               . $model_query_info->get_full_join_sql()
1750
-               . " SET "
1751
-               . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
-        /**
1755
-         * Action called after a model update call has been made.
1756
-         *
1757
-         * @param EEM_Base $model
1758
-         * @param array    $fields_n_values the updated fields and their new values
1759
-         * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
-         * @param int      $rows_affected
1761
-         */
1762
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1764
-    }
1765
-
1766
-
1767
-
1768
-    /**
1769
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
-     * are teh values of the field specified (or by default the primary key field)
1771
-     * that matched the query params. Note that you should pass the name of the
1772
-     * model FIELD, not the database table's column name.
1773
-     *
1774
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
-     * @param string $field_to_select
1776
-     * @return array just like $wpdb->get_col()
1777
-     * @throws EE_Error
1778
-     */
1779
-    public function get_col($query_params = array(), $field_to_select = null)
1780
-    {
1781
-        if ($field_to_select) {
1782
-            $field = $this->field_settings_for($field_to_select);
1783
-        } elseif ($this->has_primary_key_field()) {
1784
-            $field = $this->get_primary_key_field();
1785
-        } else {
1786
-            // no primary key, just grab the first column
1787
-            $field = reset($this->field_settings());
1788
-        }
1789
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
-        $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
-        return $this->_do_wpdb_query('get_col', array($SQL));
1793
-    }
1794
-
1795
-
1796
-
1797
-    /**
1798
-     * Returns a single column value for a single row from the database
1799
-     *
1800
-     * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
-     * @param string $field_to_select @see EEM_Base::get_col()
1802
-     * @return string
1803
-     * @throws EE_Error
1804
-     */
1805
-    public function get_var($query_params = array(), $field_to_select = null)
1806
-    {
1807
-        $query_params['limit'] = 1;
1808
-        $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1810
-            return reset($col);
1811
-        }
1812
-        return null;
1813
-    }
1814
-
1815
-
1816
-
1817
-    /**
1818
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
-     * injection, but currently no further filtering is done
1821
-     *
1822
-     * @global      $wpdb
1823
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
-     *                               be updated to in the DB
1825
-     * @return string of SQL
1826
-     * @throws EE_Error
1827
-     */
1828
-    public function _construct_update_sql($fields_n_values)
1829
-    {
1830
-        /** @type WPDB $wpdb */
1831
-        global $wpdb;
1832
-        $cols_n_values = array();
1833
-        foreach ($fields_n_values as $field_name => $value) {
1834
-            $field_obj = $this->field_settings_for($field_name);
1835
-            // if the value is NULL, we want to assign the value to that.
1836
-            // wpdb->prepare doesn't really handle that properly
1837
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
-            $value_sql = $prepared_value === null ? 'NULL'
1839
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
-        }
1842
-        return implode(",", $cols_n_values);
1843
-    }
1844
-
1845
-
1846
-
1847
-    /**
1848
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
-     * Performs a HARD delete, meaning the database row should always be removed,
1850
-     * not just have a flag field on it switched
1851
-     * Wrapper for EEM_Base::delete_permanently()
1852
-     *
1853
-     * @param mixed $id
1854
-     * @param boolean $allow_blocking
1855
-     * @return int the number of rows deleted
1856
-     * @throws EE_Error
1857
-     */
1858
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
-    {
1860
-        return $this->delete_permanently(
1861
-            array(
1862
-                array($this->get_primary_key_field()->get_name() => $id),
1863
-                'limit' => 1,
1864
-            ),
1865
-            $allow_blocking
1866
-        );
1867
-    }
1868
-
1869
-
1870
-
1871
-    /**
1872
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
-     * Wrapper for EEM_Base::delete()
1874
-     *
1875
-     * @param mixed $id
1876
-     * @param boolean $allow_blocking
1877
-     * @return int the number of rows deleted
1878
-     * @throws EE_Error
1879
-     */
1880
-    public function delete_by_ID($id, $allow_blocking = true)
1881
-    {
1882
-        return $this->delete(
1883
-            array(
1884
-                array($this->get_primary_key_field()->get_name() => $id),
1885
-                'limit' => 1,
1886
-            ),
1887
-            $allow_blocking
1888
-        );
1889
-    }
1890
-
1891
-
1892
-
1893
-    /**
1894
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1895
-     * meaning if the model has a field that indicates its been "trashed" or
1896
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1897
-     *
1898
-     * @see EEM_Base::delete_permanently
1899
-     * @param array   $query_params
1900
-     * @param boolean $allow_blocking
1901
-     * @return int how many rows got deleted
1902
-     * @throws EE_Error
1903
-     */
1904
-    public function delete($query_params, $allow_blocking = true)
1905
-    {
1906
-        return $this->delete_permanently($query_params, $allow_blocking);
1907
-    }
1908
-
1909
-
1910
-
1911
-    /**
1912
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1913
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
-     * as archived, not actually deleted
1915
-     *
1916
-     * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
-     *                                deletes regardless of other objects which may depend on it. Its generally
1920
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
-     *                                DB
1922
-     * @return int how many rows got deleted
1923
-     * @throws EE_Error
1924
-     */
1925
-    public function delete_permanently($query_params, $allow_blocking = true)
1926
-    {
1927
-        /**
1928
-         * Action called just before performing a real deletion query. You can use the
1929
-         * model and its $query_params to find exactly which items will be deleted
1930
-         *
1931
-         * @param EEM_Base $model
1932
-         * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1934
-         *                                 to block (prevent) this deletion
1935
-         */
1936
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
-        // some MySQL databases may be running safe mode, which may restrict
1938
-        // deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
-        // to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
-        // to delete them
1941
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
-            $columns_and_ids_for_deleting
1945
-        );
1946
-        /**
1947
-         * Allows client code to act on the items being deleted before the query is actually executed.
1948
-         *
1949
-         * @param EEM_Base $this  The model instance being acted on.
1950
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
-         *                                                  derived from the incoming query parameters.
1954
-         *                                                  @see details on the structure of this array in the phpdocs
1955
-         *                                                  for the `_get_ids_for_delete_method`
1956
-         *
1957
-         */
1958
-        do_action(
1959
-            'AHEE__EEM_Base__delete__before_query',
1960
-            $this,
1961
-            $query_params,
1962
-            $allow_blocking,
1963
-            $columns_and_ids_for_deleting
1964
-        );
1965
-        if ($deletion_where_query_part) {
1966
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
-            $table_aliases = array_keys($this->_tables);
1968
-            $SQL = "DELETE "
1969
-                   . implode(", ", $table_aliases)
1970
-                   . " FROM "
1971
-                   . $model_query_info->get_full_join_sql()
1972
-                   . " WHERE "
1973
-                   . $deletion_where_query_part;
1974
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
-        } else {
1976
-            $rows_deleted = 0;
1977
-        }
1978
-
1979
-        // Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
-        // there was no error with the delete query.
1981
-        if ($this->has_primary_key_field()
1982
-            && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
-        ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
-            foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
-                }
1990
-            }
1991
-
1992
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
-            // `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
-            // unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
-            // (although it is possible).
1996
-            // Note this can be skipped by using the provided filter and returning false.
1997
-            if (apply_filters(
1998
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
-                ! $this instanceof EEM_Extra_Meta,
2000
-                $this
2001
-            )) {
2002
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2003
-                    0 => array(
2004
-                        'EXM_type' => $this->get_this_model_name(),
2005
-                        'OBJ_ID'   => array(
2006
-                            'IN',
2007
-                            $ids_for_removal
2008
-                        )
2009
-                    )
2010
-                ));
2011
-            }
2012
-        }
2013
-
2014
-        /**
2015
-         * Action called just after performing a real deletion query. Although at this point the
2016
-         * items should have been deleted
2017
-         *
2018
-         * @param EEM_Base $model
2019
-         * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
-         * @param int      $rows_deleted
2021
-         */
2022
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2024
-    }
2025
-
2026
-
2027
-
2028
-    /**
2029
-     * Checks all the relations that throw error messages when there are blocking related objects
2030
-     * for related model objects. If there are any related model objects on those relations,
2031
-     * adds an EE_Error, and return true
2032
-     *
2033
-     * @param EE_Base_Class|int $this_model_obj_or_id
2034
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
-     *                                                 should be ignored when determining whether there are related
2036
-     *                                                 model objects which block this model object's deletion. Useful
2037
-     *                                                 if you know A is related to B and are considering deleting A,
2038
-     *                                                 but want to see if A has any other objects blocking its deletion
2039
-     *                                                 before removing the relation between A and B
2040
-     * @return boolean
2041
-     * @throws EE_Error
2042
-     */
2043
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
-    {
2045
-        // first, if $ignore_this_model_obj was supplied, get its model
2046
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
-            $ignored_model = $ignore_this_model_obj->get_model();
2048
-        } else {
2049
-            $ignored_model = null;
2050
-        }
2051
-        // now check all the relations of $this_model_obj_or_id and see if there
2052
-        // are any related model objects blocking it?
2053
-        $is_blocked = false;
2054
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2056
-                // if $ignore_this_model_obj was supplied, then for the query
2057
-                // on that model needs to be told to ignore $ignore_this_model_obj
2058
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
-                        array(
2061
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2062
-                                '!=',
2063
-                                $ignore_this_model_obj->ID(),
2064
-                            ),
2065
-                        ),
2066
-                    ));
2067
-                } else {
2068
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
-                }
2070
-                if ($related_model_objects) {
2071
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
-                    $is_blocked = true;
2073
-                }
2074
-            }
2075
-        }
2076
-        return $is_blocked;
2077
-    }
2078
-
2079
-
2080
-    /**
2081
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
-     * @param array $row_results_for_deleting
2083
-     * @param bool  $allow_blocking
2084
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
-     *                 deleted. Example:
2088
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2089
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
-     *                 where each element is a group of columns and values that get deleted. Example:
2091
-     *                      array(
2092
-     *                          0 => array(
2093
-     *                              'Term_Relationship.object_id' => 1
2094
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2095
-     *                          ),
2096
-     *                          1 => array(
2097
-     *                              'Term_Relationship.object_id' => 1
2098
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2099
-     *                          )
2100
-     *                      )
2101
-     * @throws EE_Error
2102
-     */
2103
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
-    {
2105
-        $ids_to_delete_indexed_by_column = array();
2106
-        if ($this->has_primary_key_field()) {
2107
-            $primary_table = $this->_get_main_table();
2108
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
-            $other_tables = $this->_get_other_tables();
2110
-            $ids_to_delete_indexed_by_column = $query = array();
2111
-            foreach ($row_results_for_deleting as $item_to_delete) {
2112
-                // before we mark this item for deletion,
2113
-                // make sure there's no related entities blocking its deletion (if we're checking)
2114
-                if ($allow_blocking
2115
-                    && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
-                    )
2118
-                ) {
2119
-                    continue;
2120
-                }
2121
-                // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
-                }
2126
-            }
2127
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
-            $fields = $this->get_combined_primary_key_fields();
2129
-            foreach ($row_results_for_deleting as $item_to_delete) {
2130
-                $ids_to_delete_indexed_by_column_for_row = array();
2131
-                foreach ($fields as $cpk_field) {
2132
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2135
-                    }
2136
-                }
2137
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
-            }
2139
-        } else {
2140
-            // so there's no primary key and no combined key...
2141
-            // sorry, can't help you
2142
-            throw new EE_Error(
2143
-                sprintf(
2144
-                    __(
2145
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
-                        "event_espresso"
2147
-                    ),
2148
-                    get_class($this)
2149
-                )
2150
-            );
2151
-        }
2152
-        return $ids_to_delete_indexed_by_column;
2153
-    }
2154
-
2155
-
2156
-    /**
2157
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
-     * the corresponding query_part for the query performing the delete.
2159
-     *
2160
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
-     * @return string
2162
-     * @throws EE_Error
2163
-     */
2164
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
-    {
2166
-        $query_part = '';
2167
-        if (empty($ids_to_delete_indexed_by_column)) {
2168
-            return $query_part;
2169
-        } elseif ($this->has_primary_key_field()) {
2170
-            $query = array();
2171
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
-                // make sure we have unique $ids
2173
-                $ids = array_unique($ids);
2174
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2175
-            }
2176
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
-            $ways_to_identify_a_row = array();
2179
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180
-                $values_for_each_combined_primary_key_for_a_row = array();
2181
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2183
-                }
2184
-                $ways_to_identify_a_row[] = '('
2185
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2186
-                                            . ')';
2187
-            }
2188
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2189
-        }
2190
-        return $query_part;
2191
-    }
2192
-
2193
-
2194
-
2195
-    /**
2196
-     * Gets the model field by the fully qualified name
2197
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2198
-     * @return EE_Model_Field_Base
2199
-     */
2200
-    public function get_field_by_column($qualified_column_name)
2201
-    {
2202
-        foreach ($this->field_settings(true) as $field_name => $field_obj) {
2203
-            if ($field_obj->get_qualified_column() === $qualified_column_name) {
2204
-                return $field_obj;
2205
-            }
2206
-        }
2207
-        throw new EE_Error(
2208
-            sprintf(
2209
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2210
-                $this->get_this_model_name(),
2211
-                $qualified_column_name
2212
-            )
2213
-        );
2214
-    }
2215
-
2216
-
2217
-
2218
-    /**
2219
-     * Count all the rows that match criteria the model query params.
2220
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2221
-     * column
2222
-     *
2223
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2224
-     * @param string $field_to_count field on model to count by (not column name)
2225
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2226
-     *                               that by the setting $distinct to TRUE;
2227
-     * @return int
2228
-     * @throws EE_Error
2229
-     */
2230
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2231
-    {
2232
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2233
-        if ($field_to_count) {
2234
-            $field_obj = $this->field_settings_for($field_to_count);
2235
-            $column_to_count = $field_obj->get_qualified_column();
2236
-        } elseif ($this->has_primary_key_field()) {
2237
-            $pk_field_obj = $this->get_primary_key_field();
2238
-            $column_to_count = $pk_field_obj->get_qualified_column();
2239
-        } else {
2240
-            // there's no primary key
2241
-            // if we're counting distinct items, and there's no primary key,
2242
-            // we need to list out the columns for distinction;
2243
-            // otherwise we can just use star
2244
-            if ($distinct) {
2245
-                $columns_to_use = array();
2246
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2247
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2248
-                }
2249
-                $column_to_count = implode(',', $columns_to_use);
2250
-            } else {
2251
-                $column_to_count = '*';
2252
-            }
2253
-        }
2254
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2256
-        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257
-    }
2258
-
2259
-
2260
-
2261
-    /**
2262
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2263
-     *
2264
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2265
-     * @param string $field_to_sum name of field (array key in $_fields array)
2266
-     * @return float
2267
-     * @throws EE_Error
2268
-     */
2269
-    public function sum($query_params, $field_to_sum = null)
2270
-    {
2271
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
-        if ($field_to_sum) {
2273
-            $field_obj = $this->field_settings_for($field_to_sum);
2274
-        } else {
2275
-            $field_obj = $this->get_primary_key_field();
2276
-        }
2277
-        $column_to_count = $field_obj->get_qualified_column();
2278
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2279
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280
-        $data_type = $field_obj->get_wpdb_data_type();
2281
-        if ($data_type === '%d' || $data_type === '%s') {
2282
-            return (float) $return_value;
2283
-        }
2284
-        // must be %f
2285
-        return (float) $return_value;
2286
-    }
2287
-
2288
-
2289
-
2290
-    /**
2291
-     * Just calls the specified method on $wpdb with the given arguments
2292
-     * Consolidates a little extra error handling code
2293
-     *
2294
-     * @param string $wpdb_method
2295
-     * @param array  $arguments_to_provide
2296
-     * @throws EE_Error
2297
-     * @global wpdb  $wpdb
2298
-     * @return mixed
2299
-     */
2300
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2301
-    {
2302
-        // if we're in maintenance mode level 2, DON'T run any queries
2303
-        // because level 2 indicates the database needs updating and
2304
-        // is probably out of sync with the code
2305
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2306
-            throw new EE_Error(sprintf(__(
2307
-                "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.",
2308
-                "event_espresso"
2309
-            )));
2310
-        }
2311
-        /** @type WPDB $wpdb */
2312
-        global $wpdb;
2313
-        if (! method_exists($wpdb, $wpdb_method)) {
2314
-            throw new EE_Error(sprintf(__(
2315
-                'There is no method named "%s" on Wordpress\' $wpdb object',
2316
-                'event_espresso'
2317
-            ), $wpdb_method));
2318
-        }
2319
-        if (WP_DEBUG) {
2320
-            $old_show_errors_value = $wpdb->show_errors;
2321
-            $wpdb->show_errors(false);
2322
-        }
2323
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2324
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2325
-        if (WP_DEBUG) {
2326
-            $wpdb->show_errors($old_show_errors_value);
2327
-            if (! empty($wpdb->last_error)) {
2328
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329
-            }
2330
-            if ($result === false) {
2331
-                throw new EE_Error(sprintf(__(
2332
-                    'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
-                    'event_espresso'
2334
-                ), $wpdb_method, var_export($arguments_to_provide, true)));
2335
-            }
2336
-        } elseif ($result === false) {
2337
-            EE_Error::add_error(
2338
-                sprintf(
2339
-                    __(
2340
-                        '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"',
2341
-                        'event_espresso'
2342
-                    ),
2343
-                    $wpdb_method,
2344
-                    var_export($arguments_to_provide, true),
2345
-                    $wpdb->last_error
2346
-                ),
2347
-                __FILE__,
2348
-                __FUNCTION__,
2349
-                __LINE__
2350
-            );
2351
-        }
2352
-        return $result;
2353
-    }
2354
-
2355
-
2356
-
2357
-    /**
2358
-     * Attempts to run the indicated WPDB method with the provided arguments,
2359
-     * and if there's an error tries to verify the DB is correct. Uses
2360
-     * the static property EEM_Base::$_db_verification_level to determine whether
2361
-     * we should try to fix the EE core db, the addons, or just give up
2362
-     *
2363
-     * @param string $wpdb_method
2364
-     * @param array  $arguments_to_provide
2365
-     * @return mixed
2366
-     */
2367
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2368
-    {
2369
-        /** @type WPDB $wpdb */
2370
-        global $wpdb;
2371
-        $wpdb->last_error = null;
2372
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2373
-        // was there an error running the query? but we don't care on new activations
2374
-        // (we're going to setup the DB anyway on new activations)
2375
-        if (($result === false || ! empty($wpdb->last_error))
2376
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2377
-        ) {
2378
-            switch (EEM_Base::$_db_verification_level) {
2379
-                case EEM_Base::db_verified_none:
2380
-                    // let's double-check core's DB
2381
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2382
-                    break;
2383
-                case EEM_Base::db_verified_core:
2384
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2385
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2386
-                    break;
2387
-                case EEM_Base::db_verified_addons:
2388
-                    // ummmm... you in trouble
2389
-                    return $result;
2390
-                    break;
2391
-            }
2392
-            if (! empty($error_message)) {
2393
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394
-                trigger_error($error_message);
2395
-            }
2396
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2397
-        }
2398
-        return $result;
2399
-    }
2400
-
2401
-
2402
-
2403
-    /**
2404
-     * Verifies the EE core database is up-to-date and records that we've done it on
2405
-     * EEM_Base::$_db_verification_level
2406
-     *
2407
-     * @param string $wpdb_method
2408
-     * @param array  $arguments_to_provide
2409
-     * @return string
2410
-     */
2411
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2412
-    {
2413
-        /** @type WPDB $wpdb */
2414
-        global $wpdb;
2415
-        // ok remember that we've already attempted fixing the core db, in case the problem persists
2416
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2417
-        $error_message = sprintf(
2418
-            __(
2419
-                'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2420
-                'event_espresso'
2421
-            ),
2422
-            $wpdb->last_error,
2423
-            $wpdb_method,
2424
-            wp_json_encode($arguments_to_provide)
2425
-        );
2426
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2427
-        return $error_message;
2428
-    }
2429
-
2430
-
2431
-
2432
-    /**
2433
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2434
-     * EEM_Base::$_db_verification_level
2435
-     *
2436
-     * @param $wpdb_method
2437
-     * @param $arguments_to_provide
2438
-     * @return string
2439
-     */
2440
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2441
-    {
2442
-        /** @type WPDB $wpdb */
2443
-        global $wpdb;
2444
-        // ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2445
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2446
-        $error_message = sprintf(
2447
-            __(
2448
-                'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2449
-                'event_espresso'
2450
-            ),
2451
-            $wpdb->last_error,
2452
-            $wpdb_method,
2453
-            wp_json_encode($arguments_to_provide)
2454
-        );
2455
-        EE_System::instance()->initialize_addons();
2456
-        return $error_message;
2457
-    }
2458
-
2459
-
2460
-
2461
-    /**
2462
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2463
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2464
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2465
-     * ..."
2466
-     *
2467
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2468
-     * @return string
2469
-     */
2470
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471
-    {
2472
-        return " FROM " . $model_query_info->get_full_join_sql() .
2473
-               $model_query_info->get_where_sql() .
2474
-               $model_query_info->get_group_by_sql() .
2475
-               $model_query_info->get_having_sql() .
2476
-               $model_query_info->get_order_by_sql() .
2477
-               $model_query_info->get_limit_sql();
2478
-    }
2479
-
2480
-
2481
-
2482
-    /**
2483
-     * Set to easily debug the next X queries ran from this model.
2484
-     *
2485
-     * @param int $count
2486
-     */
2487
-    public function show_next_x_db_queries($count = 1)
2488
-    {
2489
-        $this->_show_next_x_db_queries = $count;
2490
-    }
2491
-
2492
-
2493
-
2494
-    /**
2495
-     * @param $sql_query
2496
-     */
2497
-    public function show_db_query_if_previously_requested($sql_query)
2498
-    {
2499
-        if ($this->_show_next_x_db_queries > 0) {
2500
-            echo $sql_query;
2501
-            $this->_show_next_x_db_queries--;
2502
-        }
2503
-    }
2504
-
2505
-
2506
-
2507
-    /**
2508
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2509
-     * There are the 3 cases:
2510
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2511
-     * $otherModelObject has no ID, it is first saved.
2512
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2513
-     * has no ID, it is first saved.
2514
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2515
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2516
-     * join table
2517
-     *
2518
-     * @param        EE_Base_Class                     /int $thisModelObject
2519
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2520
-     * @param string $relationName                     , key in EEM_Base::_relations
2521
-     *                                                 an attendee to a group, you also want to specify which role they
2522
-     *                                                 will have in that group. So you would use this parameter to
2523
-     *                                                 specify array('role-column-name'=>'role-id')
2524
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2525
-     *                                                 to for relation to methods that allow you to further specify
2526
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2527
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2528
-     *                                                 because these will be inserted in any new rows created as well.
2529
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2530
-     * @throws EE_Error
2531
-     */
2532
-    public function add_relationship_to(
2533
-        $id_or_obj,
2534
-        $other_model_id_or_obj,
2535
-        $relationName,
2536
-        $extra_join_model_fields_n_values = array()
2537
-    ) {
2538
-        $relation_obj = $this->related_settings_for($relationName);
2539
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2540
-    }
2541
-
2542
-
2543
-
2544
-    /**
2545
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2546
-     * There are the 3 cases:
2547
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2548
-     * error
2549
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2550
-     * an error
2551
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2552
-     *
2553
-     * @param        EE_Base_Class /int $id_or_obj
2554
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2555
-     * @param string $relationName key in EEM_Base::_relations
2556
-     * @return boolean of success
2557
-     * @throws EE_Error
2558
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2559
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2560
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2561
-     *                             because these will be inserted in any new rows created as well.
2562
-     */
2563
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2564
-    {
2565
-        $relation_obj = $this->related_settings_for($relationName);
2566
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2567
-    }
2568
-
2569
-
2570
-
2571
-    /**
2572
-     * @param mixed           $id_or_obj
2573
-     * @param string          $relationName
2574
-     * @param array           $where_query_params
2575
-     * @param EE_Base_Class[] objects to which relations were removed
2576
-     * @return \EE_Base_Class[]
2577
-     * @throws EE_Error
2578
-     */
2579
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2580
-    {
2581
-        $relation_obj = $this->related_settings_for($relationName);
2582
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2583
-    }
2584
-
2585
-
2586
-
2587
-    /**
2588
-     * Gets all the related items of the specified $model_name, using $query_params.
2589
-     * Note: by default, we remove the "default query params"
2590
-     * because we want to get even deleted items etc.
2591
-     *
2592
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2593
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2594
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2595
-     * @return EE_Base_Class[]
2596
-     * @throws EE_Error
2597
-     */
2598
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2599
-    {
2600
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2601
-        $relation_settings = $this->related_settings_for($model_name);
2602
-        return $relation_settings->get_all_related($model_obj, $query_params);
2603
-    }
2604
-
2605
-
2606
-
2607
-    /**
2608
-     * Deletes all the model objects across the relation indicated by $model_name
2609
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2610
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2611
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2612
-     *
2613
-     * @param EE_Base_Class|int|string $id_or_obj
2614
-     * @param string                   $model_name
2615
-     * @param array                    $query_params
2616
-     * @return int how many deleted
2617
-     * @throws EE_Error
2618
-     */
2619
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2620
-    {
2621
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2622
-        $relation_settings = $this->related_settings_for($model_name);
2623
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2624
-    }
2625
-
2626
-
2627
-
2628
-    /**
2629
-     * Hard deletes all the model objects across the relation indicated by $model_name
2630
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2631
-     * the model objects can't be hard deleted because of blocking related model objects,
2632
-     * just does a soft-delete on them instead.
2633
-     *
2634
-     * @param EE_Base_Class|int|string $id_or_obj
2635
-     * @param string                   $model_name
2636
-     * @param array                    $query_params
2637
-     * @return int how many deleted
2638
-     * @throws EE_Error
2639
-     */
2640
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2641
-    {
2642
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2643
-        $relation_settings = $this->related_settings_for($model_name);
2644
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2645
-    }
2646
-
2647
-
2648
-
2649
-    /**
2650
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2651
-     * unless otherwise specified in the $query_params
2652
-     *
2653
-     * @param        int             /EE_Base_Class $id_or_obj
2654
-     * @param string $model_name     like 'Event', or 'Registration'
2655
-     * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2656
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2657
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2658
-     *                               that by the setting $distinct to TRUE;
2659
-     * @return int
2660
-     * @throws EE_Error
2661
-     */
2662
-    public function count_related(
2663
-        $id_or_obj,
2664
-        $model_name,
2665
-        $query_params = array(),
2666
-        $field_to_count = null,
2667
-        $distinct = false
2668
-    ) {
2669
-        $related_model = $this->get_related_model_obj($model_name);
2670
-        // we're just going to use the query params on the related model's normal get_all query,
2671
-        // except add a condition to say to match the current mod
2672
-        if (! isset($query_params['default_where_conditions'])) {
2673
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674
-        }
2675
-        $this_model_name = $this->get_this_model_name();
2676
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2678
-        return $related_model->count($query_params, $field_to_count, $distinct);
2679
-    }
2680
-
2681
-
2682
-
2683
-    /**
2684
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2685
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2686
-     *
2687
-     * @param        int           /EE_Base_Class $id_or_obj
2688
-     * @param string $model_name   like 'Event', or 'Registration'
2689
-     * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2690
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2691
-     * @return float
2692
-     * @throws EE_Error
2693
-     */
2694
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695
-    {
2696
-        $related_model = $this->get_related_model_obj($model_name);
2697
-        if (! is_array($query_params)) {
2698
-            EE_Error::doing_it_wrong(
2699
-                'EEM_Base::sum_related',
2700
-                sprintf(
2701
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2702
-                    gettype($query_params)
2703
-                ),
2704
-                '4.6.0'
2705
-            );
2706
-            $query_params = array();
2707
-        }
2708
-        // we're just going to use the query params on the related model's normal get_all query,
2709
-        // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2711
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
-        }
2713
-        $this_model_name = $this->get_this_model_name();
2714
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
-        return $related_model->sum($query_params, $field_to_sum);
2717
-    }
2718
-
2719
-
2720
-
2721
-    /**
2722
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
-     * $modelObject
2724
-     *
2725
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
-     * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2728
-     * @return EE_Base_Class
2729
-     * @throws EE_Error
2730
-     */
2731
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
-    {
2733
-        $query_params['limit'] = 1;
2734
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
-        if ($results) {
2736
-            return array_shift($results);
2737
-        }
2738
-        return null;
2739
-    }
2740
-
2741
-
2742
-
2743
-    /**
2744
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
-     *
2746
-     * @return string
2747
-     */
2748
-    public function get_this_model_name()
2749
-    {
2750
-        return str_replace("EEM_", "", get_class($this));
2751
-    }
2752
-
2753
-
2754
-
2755
-    /**
2756
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
-     *
2758
-     * @return EE_Any_Foreign_Model_Name_Field
2759
-     * @throws EE_Error
2760
-     */
2761
-    public function get_field_containing_related_model_name()
2762
-    {
2763
-        foreach ($this->field_settings(true) as $field) {
2764
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
-                $field_with_model_name = $field;
2766
-            }
2767
-        }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
-            throw new EE_Error(sprintf(
2770
-                __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771
-                $this->get_this_model_name()
2772
-            ));
2773
-        }
2774
-        return $field_with_model_name;
2775
-    }
2776
-
2777
-
2778
-
2779
-    /**
2780
-     * Inserts a new entry into the database, for each table.
2781
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2782
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2783
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2784
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2785
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2786
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2787
-     *
2788
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2789
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2790
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2791
-     *                              of EEM_Base)
2792
-     * @return int|string new primary key on main table that got inserted
2793
-     * @throws EE_Error
2794
-     */
2795
-    public function insert($field_n_values)
2796
-    {
2797
-        /**
2798
-         * Filters the fields and their values before inserting an item using the models
2799
-         *
2800
-         * @param array    $fields_n_values keys are the fields and values are their new values
2801
-         * @param EEM_Base $model           the model used
2802
-         */
2803
-        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2804
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2805
-            $main_table = $this->_get_main_table();
2806
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2807
-            if ($new_id !== false) {
2808
-                foreach ($this->_get_other_tables() as $other_table) {
2809
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2810
-                }
2811
-            }
2812
-            /**
2813
-             * Done just after attempting to insert a new model object
2814
-             *
2815
-             * @param EEM_Base   $model           used
2816
-             * @param array      $fields_n_values fields and their values
2817
-             * @param int|string the              ID of the newly-inserted model object
2818
-             */
2819
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2820
-            return $new_id;
2821
-        }
2822
-        return false;
2823
-    }
2824
-
2825
-
2826
-
2827
-    /**
2828
-     * Checks that the result would satisfy the unique indexes on this model
2829
-     *
2830
-     * @param array  $field_n_values
2831
-     * @param string $action
2832
-     * @return boolean
2833
-     * @throws EE_Error
2834
-     */
2835
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2836
-    {
2837
-        foreach ($this->unique_indexes() as $index_name => $index) {
2838
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2839
-            if ($this->exists(array($uniqueness_where_params))) {
2840
-                EE_Error::add_error(
2841
-                    sprintf(
2842
-                        __(
2843
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2844
-                            "event_espresso"
2845
-                        ),
2846
-                        $action,
2847
-                        $this->_get_class_name(),
2848
-                        $index_name,
2849
-                        implode(",", $index->field_names()),
2850
-                        http_build_query($uniqueness_where_params)
2851
-                    ),
2852
-                    __FILE__,
2853
-                    __FUNCTION__,
2854
-                    __LINE__
2855
-                );
2856
-                return false;
2857
-            }
2858
-        }
2859
-        return true;
2860
-    }
2861
-
2862
-
2863
-
2864
-    /**
2865
-     * Checks the database for an item that conflicts (ie, if this item were
2866
-     * saved to the DB would break some uniqueness requirement, like a primary key
2867
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2868
-     * can be either an EE_Base_Class or an array of fields n values
2869
-     *
2870
-     * @param EE_Base_Class|array $obj_or_fields_array
2871
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2872
-     *                                                 when looking for conflicts
2873
-     *                                                 (ie, if false, we ignore the model object's primary key
2874
-     *                                                 when finding "conflicts". If true, it's also considered).
2875
-     *                                                 Only works for INT primary key,
2876
-     *                                                 STRING primary keys cannot be ignored
2877
-     * @throws EE_Error
2878
-     * @return EE_Base_Class|array
2879
-     */
2880
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2881
-    {
2882
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2883
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2884
-        } elseif (is_array($obj_or_fields_array)) {
2885
-            $fields_n_values = $obj_or_fields_array;
2886
-        } else {
2887
-            throw new EE_Error(
2888
-                sprintf(
2889
-                    __(
2890
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2891
-                        "event_espresso"
2892
-                    ),
2893
-                    get_class($this),
2894
-                    $obj_or_fields_array
2895
-                )
2896
-            );
2897
-        }
2898
-        $query_params = array();
2899
-        if ($this->has_primary_key_field()
2900
-            && ($include_primary_key
2901
-                || $this->get_primary_key_field()
2902
-                   instanceof
2903
-                   EE_Primary_Key_String_Field)
2904
-            && isset($fields_n_values[ $this->primary_key_name() ])
2905
-        ) {
2906
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2907
-        }
2908
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2911
-        }
2912
-        // if there is nothing to base this search on, then we shouldn't find anything
2913
-        if (empty($query_params)) {
2914
-            return array();
2915
-        }
2916
-        return $this->get_one($query_params);
2917
-    }
2918
-
2919
-
2920
-
2921
-    /**
2922
-     * Like count, but is optimized and returns a boolean instead of an int
2923
-     *
2924
-     * @param array $query_params
2925
-     * @return boolean
2926
-     * @throws EE_Error
2927
-     */
2928
-    public function exists($query_params)
2929
-    {
2930
-        $query_params['limit'] = 1;
2931
-        return $this->count($query_params) > 0;
2932
-    }
2933
-
2934
-
2935
-
2936
-    /**
2937
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2938
-     *
2939
-     * @param int|string $id
2940
-     * @return boolean
2941
-     * @throws EE_Error
2942
-     */
2943
-    public function exists_by_ID($id)
2944
-    {
2945
-        return $this->exists(
2946
-            array(
2947
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2948
-                array(
2949
-                    $this->primary_key_name() => $id,
2950
-                ),
2951
-            )
2952
-        );
2953
-    }
2954
-
2955
-
2956
-
2957
-    /**
2958
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2959
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2960
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2961
-     * on the main table)
2962
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2963
-     * cases where we want to call it directly rather than via insert().
2964
-     *
2965
-     * @access   protected
2966
-     * @param EE_Table_Base $table
2967
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2968
-     *                                       float
2969
-     * @param int           $new_id          for now we assume only int keys
2970
-     * @throws EE_Error
2971
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2972
-     * @return int ID of new row inserted, or FALSE on failure
2973
-     */
2974
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2975
-    {
2976
-        global $wpdb;
2977
-        $insertion_col_n_values = array();
2978
-        $format_for_insertion = array();
2979
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2980
-        foreach ($fields_on_table as $field_name => $field_obj) {
2981
-            // check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2982
-            if ($field_obj->is_auto_increment()) {
2983
-                continue;
2984
-            }
2985
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986
-            // if the value we want to assign it to is NULL, just don't mention it for the insertion
2987
-            if ($prepared_value !== null) {
2988
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2989
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990
-            }
2991
-        }
2992
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2993
-            // its not the main table, so we should have already saved the main table's PK which we just inserted
2994
-            // so add the fk to the main table as a column
2995
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2997
-        }
2998
-        // insert the new entry
2999
-        $result = $this->_do_wpdb_query(
3000
-            'insert',
3001
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3002
-        );
3003
-        if ($result === false) {
3004
-            return false;
3005
-        }
3006
-        // ok, now what do we return for the ID of the newly-inserted thing?
3007
-        if ($this->has_primary_key_field()) {
3008
-            if ($this->get_primary_key_field()->is_auto_increment()) {
3009
-                return $wpdb->insert_id;
3010
-            }
3011
-            // it's not an auto-increment primary key, so
3012
-            // it must have been supplied
3013
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3014
-        }
3015
-        // we can't return a  primary key because there is none. instead return
3016
-        // a unique string indicating this model
3017
-        return $this->get_index_primary_key_string($fields_n_values);
3018
-    }
3019
-
3020
-
3021
-
3022
-    /**
3023
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3024
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3025
-     * and there is no default, we pass it along. WPDB will take care of it)
3026
-     *
3027
-     * @param EE_Model_Field_Base $field_obj
3028
-     * @param array               $fields_n_values
3029
-     * @return mixed string|int|float depending on what the table column will be expecting
3030
-     * @throws EE_Error
3031
-     */
3032
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033
-    {
3034
-        // if this field doesn't allow nullable, don't allow it
3035
-        if (! $field_obj->is_nullable()
3036
-            && (
3037
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3038
-                || $fields_n_values[ $field_obj->get_name() ] === null
3039
-            )
3040
-        ) {
3041
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3042
-        }
3043
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
-            ? $fields_n_values[ $field_obj->get_name() ]
3045
-            : null;
3046
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047
-    }
3048
-
3049
-
3050
-
3051
-    /**
3052
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3053
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3054
-     * the field's prepare_for_set() method.
3055
-     *
3056
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3057
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3058
-     *                                   top of file)
3059
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3060
-     *                                   $value is a custom selection
3061
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3062
-     */
3063
-    private function _prepare_value_for_use_in_db($value, $field)
3064
-    {
3065
-        if ($field && $field instanceof EE_Model_Field_Base) {
3066
-            // phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3067
-            switch ($this->_values_already_prepared_by_model_object) {
3068
-                /** @noinspection PhpMissingBreakStatementInspection */
3069
-                case self::not_prepared_by_model_object:
3070
-                    $value = $field->prepare_for_set($value);
3071
-                // purposefully left out "return"
3072
-                case self::prepared_by_model_object:
3073
-                    /** @noinspection SuspiciousAssignmentsInspection */
3074
-                    $value = $field->prepare_for_use_in_db($value);
3075
-                case self::prepared_for_use_in_db:
3076
-                    // leave the value alone
3077
-            }
3078
-            return $value;
3079
-            // phpcs:enable
3080
-        }
3081
-        return $value;
3082
-    }
3083
-
3084
-
3085
-
3086
-    /**
3087
-     * Returns the main table on this model
3088
-     *
3089
-     * @return EE_Primary_Table
3090
-     * @throws EE_Error
3091
-     */
3092
-    protected function _get_main_table()
3093
-    {
3094
-        foreach ($this->_tables as $table) {
3095
-            if ($table instanceof EE_Primary_Table) {
3096
-                return $table;
3097
-            }
3098
-        }
3099
-        throw new EE_Error(sprintf(__(
3100
-            'There are no main tables on %s. They should be added to _tables array in the constructor',
3101
-            'event_espresso'
3102
-        ), get_class($this)));
3103
-    }
3104
-
3105
-
3106
-
3107
-    /**
3108
-     * table
3109
-     * returns EE_Primary_Table table name
3110
-     *
3111
-     * @return string
3112
-     * @throws EE_Error
3113
-     */
3114
-    public function table()
3115
-    {
3116
-        return $this->_get_main_table()->get_table_name();
3117
-    }
3118
-
3119
-
3120
-
3121
-    /**
3122
-     * table
3123
-     * returns first EE_Secondary_Table table name
3124
-     *
3125
-     * @return string
3126
-     */
3127
-    public function second_table()
3128
-    {
3129
-        // grab second table from tables array
3130
-        $second_table = end($this->_tables);
3131
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3132
-    }
3133
-
3134
-
3135
-
3136
-    /**
3137
-     * get_table_obj_by_alias
3138
-     * returns table name given it's alias
3139
-     *
3140
-     * @param string $table_alias
3141
-     * @return EE_Primary_Table | EE_Secondary_Table
3142
-     */
3143
-    public function get_table_obj_by_alias($table_alias = '')
3144
-    {
3145
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3146
-    }
3147
-
3148
-
3149
-
3150
-    /**
3151
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3152
-     *
3153
-     * @return EE_Secondary_Table[]
3154
-     */
3155
-    protected function _get_other_tables()
3156
-    {
3157
-        $other_tables = array();
3158
-        foreach ($this->_tables as $table_alias => $table) {
3159
-            if ($table instanceof EE_Secondary_Table) {
3160
-                $other_tables[ $table_alias ] = $table;
3161
-            }
3162
-        }
3163
-        return $other_tables;
3164
-    }
3165
-
3166
-
3167
-
3168
-    /**
3169
-     * Finds all the fields that correspond to the given table
3170
-     *
3171
-     * @param string $table_alias , array key in EEM_Base::_tables
3172
-     * @return EE_Model_Field_Base[]
3173
-     */
3174
-    public function _get_fields_for_table($table_alias)
3175
-    {
3176
-        return $this->_fields[ $table_alias ];
3177
-    }
3178
-
3179
-
3180
-
3181
-    /**
3182
-     * Recurses through all the where parameters, and finds all the related models we'll need
3183
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3184
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3185
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3186
-     * related Registration, Transaction, and Payment models.
3187
-     *
3188
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3189
-     * @return EE_Model_Query_Info_Carrier
3190
-     * @throws EE_Error
3191
-     */
3192
-    public function _extract_related_models_from_query($query_params)
3193
-    {
3194
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3195
-        if (array_key_exists(0, $query_params)) {
3196
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3197
-        }
3198
-        if (array_key_exists('group_by', $query_params)) {
3199
-            if (is_array($query_params['group_by'])) {
3200
-                $this->_extract_related_models_from_sub_params_array_values(
3201
-                    $query_params['group_by'],
3202
-                    $query_info_carrier,
3203
-                    'group_by'
3204
-                );
3205
-            } elseif (! empty($query_params['group_by'])) {
3206
-                $this->_extract_related_model_info_from_query_param(
3207
-                    $query_params['group_by'],
3208
-                    $query_info_carrier,
3209
-                    'group_by'
3210
-                );
3211
-            }
3212
-        }
3213
-        if (array_key_exists('having', $query_params)) {
3214
-            $this->_extract_related_models_from_sub_params_array_keys(
3215
-                $query_params[0],
3216
-                $query_info_carrier,
3217
-                'having'
3218
-            );
3219
-        }
3220
-        if (array_key_exists('order_by', $query_params)) {
3221
-            if (is_array($query_params['order_by'])) {
3222
-                $this->_extract_related_models_from_sub_params_array_keys(
3223
-                    $query_params['order_by'],
3224
-                    $query_info_carrier,
3225
-                    'order_by'
3226
-                );
3227
-            } elseif (! empty($query_params['order_by'])) {
3228
-                $this->_extract_related_model_info_from_query_param(
3229
-                    $query_params['order_by'],
3230
-                    $query_info_carrier,
3231
-                    'order_by'
3232
-                );
3233
-            }
3234
-        }
3235
-        if (array_key_exists('force_join', $query_params)) {
3236
-            $this->_extract_related_models_from_sub_params_array_values(
3237
-                $query_params['force_join'],
3238
-                $query_info_carrier,
3239
-                'force_join'
3240
-            );
3241
-        }
3242
-        $this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3243
-        return $query_info_carrier;
3244
-    }
3245
-
3246
-
3247
-
3248
-    /**
3249
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3250
-     *
3251
-     * @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
3252
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3253
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3254
-     * @throws EE_Error
3255
-     * @return \EE_Model_Query_Info_Carrier
3256
-     */
3257
-    private function _extract_related_models_from_sub_params_array_keys(
3258
-        $sub_query_params,
3259
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260
-        $query_param_type
3261
-    ) {
3262
-        if (! empty($sub_query_params)) {
3263
-            $sub_query_params = (array) $sub_query_params;
3264
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3266
-                $this->_extract_related_model_info_from_query_param(
3267
-                    $param,
3268
-                    $model_query_info_carrier,
3269
-                    $query_param_type
3270
-                );
3271
-                // if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3272
-                // indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3273
-                // extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3274
-                // of array('Registration.TXN_ID'=>23)
3275
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
-                    if (! is_array($possibly_array_of_params)) {
3278
-                        throw new EE_Error(sprintf(
3279
-                            __(
3280
-                                "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'))",
3281
-                                "event_espresso"
3282
-                            ),
3283
-                            $param,
3284
-                            $possibly_array_of_params
3285
-                        ));
3286
-                    }
3287
-                    $this->_extract_related_models_from_sub_params_array_keys(
3288
-                        $possibly_array_of_params,
3289
-                        $model_query_info_carrier,
3290
-                        $query_param_type
3291
-                    );
3292
-                } elseif ($query_param_type === 0 // ie WHERE
3293
-                          && is_array($possibly_array_of_params)
3294
-                          && isset($possibly_array_of_params[2])
3295
-                          && $possibly_array_of_params[2] == true
3296
-                ) {
3297
-                    // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298
-                    // indicating that $possible_array_of_params[1] is actually a field name,
3299
-                    // from which we should extract query parameters!
3300
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301
-                        throw new EE_Error(sprintf(__(
3302
-                            "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303
-                            "event_espresso"
3304
-                        ), $query_param_type, implode(",", $possibly_array_of_params)));
3305
-                    }
3306
-                    $this->_extract_related_model_info_from_query_param(
3307
-                        $possibly_array_of_params[1],
3308
-                        $model_query_info_carrier,
3309
-                        $query_param_type
3310
-                    );
3311
-                }
3312
-            }
3313
-        }
3314
-        return $model_query_info_carrier;
3315
-    }
3316
-
3317
-
3318
-
3319
-    /**
3320
-     * For extracting related models from forced_joins, where the array values contain the info about what
3321
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3322
-     *
3323
-     * @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
3324
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3325
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3326
-     * @throws EE_Error
3327
-     * @return \EE_Model_Query_Info_Carrier
3328
-     */
3329
-    private function _extract_related_models_from_sub_params_array_values(
3330
-        $sub_query_params,
3331
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332
-        $query_param_type
3333
-    ) {
3334
-        if (! empty($sub_query_params)) {
3335
-            if (! is_array($sub_query_params)) {
3336
-                throw new EE_Error(sprintf(
3337
-                    __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338
-                    $sub_query_params
3339
-                ));
3340
-            }
3341
-            foreach ($sub_query_params as $param) {
3342
-                // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
-                $this->_extract_related_model_info_from_query_param(
3344
-                    $param,
3345
-                    $model_query_info_carrier,
3346
-                    $query_param_type
3347
-                );
3348
-            }
3349
-        }
3350
-        return $model_query_info_carrier;
3351
-    }
3352
-
3353
-
3354
-    /**
3355
-     * Extract all the query parts from  model query params
3356
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3357
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3358
-     * but use them in a different order. Eg, we need to know what models we are querying
3359
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3360
-     * other models before we can finalize the where clause SQL.
3361
-     *
3362
-     * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3363
-     * @throws EE_Error
3364
-     * @return EE_Model_Query_Info_Carrier
3365
-     * @throws ModelConfigurationException
3366
-     */
3367
-    public function _create_model_query_info_carrier($query_params)
3368
-    {
3369
-        if (! is_array($query_params)) {
3370
-            EE_Error::doing_it_wrong(
3371
-                'EEM_Base::_create_model_query_info_carrier',
3372
-                sprintf(
3373
-                    __(
3374
-                        '$query_params should be an array, you passed a variable of type %s',
3375
-                        'event_espresso'
3376
-                    ),
3377
-                    gettype($query_params)
3378
-                ),
3379
-                '4.6.0'
3380
-            );
3381
-            $query_params = array();
3382
-        }
3383
-        $query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3384
-        // first check if we should alter the query to account for caps or not
3385
-        // because the caps might require us to do extra joins
3386
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3387
-            $query_params[0] = array_replace_recursive(
3388
-                $query_params[0],
3389
-                $this->caps_where_conditions(
3390
-                    $query_params['caps']
3391
-                )
3392
-            );
3393
-        }
3394
-
3395
-        // check if we should alter the query to remove data related to protected
3396
-        // custom post types
3397
-        if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3398
-            $where_param_key_for_password = $this->modelChainAndPassword();
3399
-            // only include if related to a cpt where no password has been set
3400
-            $query_params[0]['OR*nopassword'] = array(
3401
-                $where_param_key_for_password => '',
3402
-                $where_param_key_for_password . '*' => array('IS_NULL')
3403
-            );
3404
-        }
3405
-        $query_object = $this->_extract_related_models_from_query($query_params);
3406
-        // verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3407
-        foreach ($query_params[0] as $key => $value) {
3408
-            if (is_int($key)) {
3409
-                throw new EE_Error(
3410
-                    sprintf(
3411
-                        __(
3412
-                            "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.",
3413
-                            "event_espresso"
3414
-                        ),
3415
-                        $key,
3416
-                        var_export($value, true),
3417
-                        var_export($query_params, true),
3418
-                        get_class($this)
3419
-                    )
3420
-                );
3421
-            }
3422
-        }
3423
-        if (array_key_exists('default_where_conditions', $query_params)
3424
-            && ! empty($query_params['default_where_conditions'])
3425
-        ) {
3426
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3427
-        } else {
3428
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3429
-        }
3430
-        $query_params[0] = array_merge(
3431
-            $this->_get_default_where_conditions_for_models_in_query(
3432
-                $query_object,
3433
-                $use_default_where_conditions,
3434
-                $query_params[0]
3435
-            ),
3436
-            $query_params[0]
3437
-        );
3438
-        $query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3439
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3440
-        // So we need to setup a subquery and use that for the main join.
3441
-        // Note for now this only works on the primary table for the model.
3442
-        // So for instance, you could set the limit array like this:
3443
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3444
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3445
-            $query_object->set_main_model_join_sql(
3446
-                $this->_construct_limit_join_select(
3447
-                    $query_params['on_join_limit'][0],
3448
-                    $query_params['on_join_limit'][1]
3449
-                )
3450
-            );
3451
-        }
3452
-        // set limit
3453
-        if (array_key_exists('limit', $query_params)) {
3454
-            if (is_array($query_params['limit'])) {
3455
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456
-                    $e = sprintf(
3457
-                        __(
3458
-                            "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)",
3459
-                            "event_espresso"
3460
-                        ),
3461
-                        http_build_query($query_params['limit'])
3462
-                    );
3463
-                    throw new EE_Error($e . "|" . $e);
3464
-                }
3465
-                // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
-            } elseif (! empty($query_params['limit'])) {
3468
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3469
-            }
3470
-        }
3471
-        // set order by
3472
-        if (array_key_exists('order_by', $query_params)) {
3473
-            if (is_array($query_params['order_by'])) {
3474
-                // if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3475
-                // specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3476
-                // including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3477
-                if (array_key_exists('order', $query_params)) {
3478
-                    throw new EE_Error(
3479
-                        sprintf(
3480
-                            __(
3481
-                                "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 ",
3482
-                                "event_espresso"
3483
-                            ),
3484
-                            get_class($this),
3485
-                            implode(", ", array_keys($query_params['order_by'])),
3486
-                            implode(", ", $query_params['order_by']),
3487
-                            $query_params['order']
3488
-                        )
3489
-                    );
3490
-                }
3491
-                $this->_extract_related_models_from_sub_params_array_keys(
3492
-                    $query_params['order_by'],
3493
-                    $query_object,
3494
-                    'order_by'
3495
-                );
3496
-                // assume it's an array of fields to order by
3497
-                $order_array = array();
3498
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499
-                    $order = $this->_extract_order($order);
3500
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3501
-                }
3502
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
-            } elseif (! empty($query_params['order_by'])) {
3504
-                $this->_extract_related_model_info_from_query_param(
3505
-                    $query_params['order_by'],
3506
-                    $query_object,
3507
-                    'order',
3508
-                    $query_params['order_by']
3509
-                );
3510
-                $order = isset($query_params['order'])
3511
-                    ? $this->_extract_order($query_params['order'])
3512
-                    : 'DESC';
3513
-                $query_object->set_order_by_sql(
3514
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3515
-                );
3516
-            }
3517
-        }
3518
-        // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
-        if (! array_key_exists('order_by', $query_params)
3520
-            && array_key_exists('order', $query_params)
3521
-            && ! empty($query_params['order'])
3522
-        ) {
3523
-            $pk_field = $this->get_primary_key_field();
3524
-            $order = $this->_extract_order($query_params['order']);
3525
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3526
-        }
3527
-        // set group by
3528
-        if (array_key_exists('group_by', $query_params)) {
3529
-            if (is_array($query_params['group_by'])) {
3530
-                // it's an array, so assume we'll be grouping by a bunch of stuff
3531
-                $group_by_array = array();
3532
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534
-                }
3535
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
-            } elseif (! empty($query_params['group_by'])) {
3537
-                $query_object->set_group_by_sql(
3538
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3539
-                );
3540
-            }
3541
-        }
3542
-        // set having
3543
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3544
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3545
-        }
3546
-        // now, just verify they didn't pass anything wack
3547
-        foreach ($query_params as $query_key => $query_value) {
3548
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3549
-                throw new EE_Error(
3550
-                    sprintf(
3551
-                        __(
3552
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3553
-                            'event_espresso'
3554
-                        ),
3555
-                        $query_key,
3556
-                        get_class($this),
3557
-                        //                      print_r( $this->_allowed_query_params, TRUE )
3558
-                        implode(',', $this->_allowed_query_params)
3559
-                    )
3560
-                );
3561
-            }
3562
-        }
3563
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3564
-        if (empty($main_model_join_sql)) {
3565
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3566
-        }
3567
-        return $query_object;
3568
-    }
3569
-
3570
-
3571
-
3572
-    /**
3573
-     * Gets the where conditions that should be imposed on the query based on the
3574
-     * context (eg reading frontend, backend, edit or delete).
3575
-     *
3576
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3577
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3578
-     * @throws EE_Error
3579
-     */
3580
-    public function caps_where_conditions($context = self::caps_read)
3581
-    {
3582
-        EEM_Base::verify_is_valid_cap_context($context);
3583
-        $cap_where_conditions = array();
3584
-        $cap_restrictions = $this->caps_missing($context);
3585
-        /**
3586
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3587
-         */
3588
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3589
-            $cap_where_conditions = array_replace_recursive(
3590
-                $cap_where_conditions,
3591
-                $restriction_if_no_cap->get_default_where_conditions()
3592
-            );
3593
-        }
3594
-        return apply_filters(
3595
-            'FHEE__EEM_Base__caps_where_conditions__return',
3596
-            $cap_where_conditions,
3597
-            $this,
3598
-            $context,
3599
-            $cap_restrictions
3600
-        );
3601
-    }
3602
-
3603
-
3604
-
3605
-    /**
3606
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3607
-     * otherwise throws an exception
3608
-     *
3609
-     * @param string $should_be_order_string
3610
-     * @return string either ASC, asc, DESC or desc
3611
-     * @throws EE_Error
3612
-     */
3613
-    private function _extract_order($should_be_order_string)
3614
-    {
3615
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3616
-            return $should_be_order_string;
3617
-        }
3618
-        throw new EE_Error(
3619
-            sprintf(
3620
-                __(
3621
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3622
-                    "event_espresso"
3623
-                ),
3624
-                get_class($this),
3625
-                $should_be_order_string
3626
-            )
3627
-        );
3628
-    }
3629
-
3630
-
3631
-
3632
-    /**
3633
-     * Looks at all the models which are included in this query, and asks each
3634
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3635
-     * so they can be merged
3636
-     *
3637
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3638
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3639
-     *                                                                  'none' means NO default where conditions will
3640
-     *                                                                  be used AT ALL during this query.
3641
-     *                                                                  'other_models_only' means default where
3642
-     *                                                                  conditions from other models will be used, but
3643
-     *                                                                  not for this primary model. 'all', the default,
3644
-     *                                                                  means default where conditions will apply as
3645
-     *                                                                  normal
3646
-     * @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
3647
-     * @throws EE_Error
3648
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3649
-     */
3650
-    private function _get_default_where_conditions_for_models_in_query(
3651
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3652
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3653
-        $where_query_params = array()
3654
-    ) {
3655
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657
-            throw new EE_Error(sprintf(
3658
-                __(
3659
-                    "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3660
-                    "event_espresso"
3661
-                ),
3662
-                $use_default_where_conditions,
3663
-                implode(", ", $allowed_used_default_where_conditions_values)
3664
-            ));
3665
-        }
3666
-        $universal_query_params = array();
3667
-        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3668
-            $universal_query_params = $this->_get_default_where_conditions();
3669
-        } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3670
-            $universal_query_params = $this->_get_minimum_where_conditions();
3671
-        }
3672
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3673
-            $related_model = $this->get_related_model_obj($model_name);
3674
-            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3675
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3676
-            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3677
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3678
-            } else {
3679
-                // we don't want to add full or even minimum default where conditions from this model, so just continue
3680
-                continue;
3681
-            }
3682
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3683
-                $related_model_universal_where_params,
3684
-                $where_query_params,
3685
-                $related_model,
3686
-                $model_relation_path
3687
-            );
3688
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3689
-                $universal_query_params,
3690
-                $overrides
3691
-            );
3692
-        }
3693
-        return $universal_query_params;
3694
-    }
3695
-
3696
-
3697
-
3698
-    /**
3699
-     * Determines whether or not we should use default where conditions for the model in question
3700
-     * (this model, or other related models).
3701
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3702
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3703
-     * We should use default where conditions on related models when they requested to use default where conditions
3704
-     * on all models, or specifically just on other related models
3705
-     * @param      $default_where_conditions_value
3706
-     * @param bool $for_this_model false means this is for OTHER related models
3707
-     * @return bool
3708
-     */
3709
-    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3710
-    {
3711
-        return (
3712
-                   $for_this_model
3713
-                   && in_array(
3714
-                       $default_where_conditions_value,
3715
-                       array(
3716
-                           EEM_Base::default_where_conditions_all,
3717
-                           EEM_Base::default_where_conditions_this_only,
3718
-                           EEM_Base::default_where_conditions_minimum_others,
3719
-                       ),
3720
-                       true
3721
-                   )
3722
-               )
3723
-               || (
3724
-                   ! $for_this_model
3725
-                   && in_array(
3726
-                       $default_where_conditions_value,
3727
-                       array(
3728
-                           EEM_Base::default_where_conditions_all,
3729
-                           EEM_Base::default_where_conditions_others_only,
3730
-                       ),
3731
-                       true
3732
-                   )
3733
-               );
3734
-    }
3735
-
3736
-    /**
3737
-     * Determines whether or not we should use default minimum conditions for the model in question
3738
-     * (this model, or other related models).
3739
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3740
-     * where conditions.
3741
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3742
-     * on this model or others
3743
-     * @param      $default_where_conditions_value
3744
-     * @param bool $for_this_model false means this is for OTHER related models
3745
-     * @return bool
3746
-     */
3747
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3748
-    {
3749
-        return (
3750
-                   $for_this_model
3751
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3752
-               )
3753
-               || (
3754
-                   ! $for_this_model
3755
-                   && in_array(
3756
-                       $default_where_conditions_value,
3757
-                       array(
3758
-                           EEM_Base::default_where_conditions_minimum_others,
3759
-                           EEM_Base::default_where_conditions_minimum_all,
3760
-                       ),
3761
-                       true
3762
-                   )
3763
-               );
3764
-    }
3765
-
3766
-
3767
-    /**
3768
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3769
-     * then we also add a special where condition which allows for that model's primary key
3770
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3771
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3772
-     *
3773
-     * @param array    $default_where_conditions
3774
-     * @param array    $provided_where_conditions
3775
-     * @param EEM_Base $model
3776
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3777
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3778
-     * @throws EE_Error
3779
-     */
3780
-    private function _override_defaults_or_make_null_friendly(
3781
-        $default_where_conditions,
3782
-        $provided_where_conditions,
3783
-        $model,
3784
-        $model_relation_path
3785
-    ) {
3786
-        $null_friendly_where_conditions = array();
3787
-        $none_overridden = true;
3788
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3789
-        foreach ($default_where_conditions as $key => $val) {
3790
-            if (isset($provided_where_conditions[ $key ])) {
3791
-                $none_overridden = false;
3792
-            } else {
3793
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3794
-            }
3795
-        }
3796
-        if ($none_overridden && $default_where_conditions) {
3797
-            if ($model->has_primary_key_field()) {
3798
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3799
-                                                                                . "."
3800
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3801
-            }/*else{
38
+	/**
39
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
40
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
41
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
42
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	private $_values_already_prepared_by_model_object = 0;
47
+
48
+	/**
49
+	 * when $_values_already_prepared_by_model_object equals this, we assume
50
+	 * the data is just like form input that needs to have the model fields'
51
+	 * prepare_for_set and prepare_for_use_in_db called on it
52
+	 */
53
+	const not_prepared_by_model_object = 0;
54
+
55
+	/**
56
+	 * when $_values_already_prepared_by_model_object equals this, we
57
+	 * assume this value is coming from a model object and doesn't need to have
58
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
59
+	 */
60
+	const prepared_by_model_object = 1;
61
+
62
+	/**
63
+	 * when $_values_already_prepared_by_model_object equals this, we assume
64
+	 * the values are already to be used in the database (ie no processing is done
65
+	 * on them by the model's fields)
66
+	 */
67
+	const prepared_for_use_in_db = 2;
68
+
69
+
70
+	protected $singular_item = 'Item';
71
+
72
+	protected $plural_item   = 'Items';
73
+
74
+	/**
75
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
76
+	 */
77
+	protected $_tables;
78
+
79
+	/**
80
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
81
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
82
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
83
+	 *
84
+	 * @var \EE_Model_Field_Base[][] $_fields
85
+	 */
86
+	protected $_fields;
87
+
88
+	/**
89
+	 * array of different kinds of relations
90
+	 *
91
+	 * @var \EE_Model_Relation_Base[] $_model_relations
92
+	 */
93
+	protected $_model_relations;
94
+
95
+	/**
96
+	 * @var \EE_Index[] $_indexes
97
+	 */
98
+	protected $_indexes = array();
99
+
100
+	/**
101
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
102
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
103
+	 * by setting the same columns as used in these queries in the query yourself.
104
+	 *
105
+	 * @var EE_Default_Where_Conditions
106
+	 */
107
+	protected $_default_where_conditions_strategy;
108
+
109
+	/**
110
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
111
+	 * This is particularly useful when you want something between 'none' and 'default'
112
+	 *
113
+	 * @var EE_Default_Where_Conditions
114
+	 */
115
+	protected $_minimum_where_conditions_strategy;
116
+
117
+	/**
118
+	 * String describing how to find the "owner" of this model's objects.
119
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
120
+	 * But when there isn't, this indicates which related model, or transiently-related model,
121
+	 * has the foreign key to the wp_users table.
122
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
123
+	 * related to events, and events have a foreign key to wp_users.
124
+	 * On EEM_Transaction, this would be 'Transaction.Event'
125
+	 *
126
+	 * @var string
127
+	 */
128
+	protected $_model_chain_to_wp_user = '';
129
+
130
+	/**
131
+	 * String describing how to find the model with a password controlling access to this model. This property has the
132
+	 * same format as $_model_chain_to_wp_user. This is primarily used by the query param "exclude_protected".
133
+	 * This value is the path of models to follow to arrive at the model with the password field.
134
+	 * If it is an empty string, it means this model has the password field. If it is null, it means there is no
135
+	 * model with a password that should affect reading this on the front-end.
136
+	 * Eg this is an empty string for the Event model because it has a password.
137
+	 * This is null for the Registration model, because its event's password has no bearing on whether
138
+	 * you can read the registration or not on the front-end (it just depends on your capabilities.)
139
+	 * This is 'Datetime.Event' on the Ticket model, because model queries for tickets that set "exclude_protected"
140
+	 * should hide tickets for datetimes for events that have a password set.
141
+	 * @var string |null
142
+	 */
143
+	protected $model_chain_to_password = null;
144
+
145
+	/**
146
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
147
+	 * don't need it (particularly CPT models)
148
+	 *
149
+	 * @var bool
150
+	 */
151
+	protected $_ignore_where_strategy = false;
152
+
153
+	/**
154
+	 * String used in caps relating to this model. Eg, if the caps relating to this
155
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
156
+	 *
157
+	 * @var string. If null it hasn't been initialized yet. If false then we
158
+	 * have indicated capabilities don't apply to this
159
+	 */
160
+	protected $_caps_slug = null;
161
+
162
+	/**
163
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
164
+	 * and next-level keys are capability names, and each's value is a
165
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
166
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
167
+	 * and then each capability in the corresponding sub-array that they're missing
168
+	 * adds the where conditions onto the query.
169
+	 *
170
+	 * @var array
171
+	 */
172
+	protected $_cap_restrictions = array(
173
+		self::caps_read       => array(),
174
+		self::caps_read_admin => array(),
175
+		self::caps_edit       => array(),
176
+		self::caps_delete     => array(),
177
+	);
178
+
179
+	/**
180
+	 * Array defining which cap restriction generators to use to create default
181
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
182
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
183
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
184
+	 * automatically set this to false (not just null).
185
+	 *
186
+	 * @var EE_Restriction_Generator_Base[]
187
+	 */
188
+	protected $_cap_restriction_generators = array();
189
+
190
+	/**
191
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
192
+	 */
193
+	const caps_read       = 'read';
194
+
195
+	const caps_read_admin = 'read_admin';
196
+
197
+	const caps_edit       = 'edit';
198
+
199
+	const caps_delete     = 'delete';
200
+
201
+	/**
202
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
203
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
204
+	 * maps to 'read' because when looking for relevant permissions we're going to use
205
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
206
+	 *
207
+	 * @var array
208
+	 */
209
+	protected $_cap_contexts_to_cap_action_map = array(
210
+		self::caps_read       => 'read',
211
+		self::caps_read_admin => 'read',
212
+		self::caps_edit       => 'edit',
213
+		self::caps_delete     => 'delete',
214
+	);
215
+
216
+	/**
217
+	 * Timezone
218
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
219
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
220
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
221
+	 * EE_Datetime_Field data type will have access to it.
222
+	 *
223
+	 * @var string
224
+	 */
225
+	protected $_timezone;
226
+
227
+
228
+	/**
229
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
230
+	 * multisite.
231
+	 *
232
+	 * @var int
233
+	 */
234
+	protected static $_model_query_blog_id;
235
+
236
+	/**
237
+	 * A copy of _fields, except the array keys are the model names pointed to by
238
+	 * the field
239
+	 *
240
+	 * @var EE_Model_Field_Base[]
241
+	 */
242
+	private $_cache_foreign_key_to_fields = array();
243
+
244
+	/**
245
+	 * Cached list of all the fields on the model, indexed by their name
246
+	 *
247
+	 * @var EE_Model_Field_Base[]
248
+	 */
249
+	private $_cached_fields = null;
250
+
251
+	/**
252
+	 * Cached list of all the fields on the model, except those that are
253
+	 * marked as only pertinent to the database
254
+	 *
255
+	 * @var EE_Model_Field_Base[]
256
+	 */
257
+	private $_cached_fields_non_db_only = null;
258
+
259
+	/**
260
+	 * A cached reference to the primary key for quick lookup
261
+	 *
262
+	 * @var EE_Model_Field_Base
263
+	 */
264
+	private $_primary_key_field = null;
265
+
266
+	/**
267
+	 * Flag indicating whether this model has a primary key or not
268
+	 *
269
+	 * @var boolean
270
+	 */
271
+	protected $_has_primary_key_field = null;
272
+
273
+	/**
274
+	 * array in the format:  [ FK alias => full PK ]
275
+	 * where keys are local column name aliases for foreign keys
276
+	 * and values are the fully qualified column name for the primary key they represent
277
+	 *  ex:
278
+	 *      [ 'Event.EVT_wp_user' => 'WP_User.ID' ]
279
+	 *
280
+	 * @var array $foreign_key_aliases
281
+	 */
282
+	protected $foreign_key_aliases = [];
283
+
284
+	/**
285
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
286
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
287
+	 * This should be true for models that deal with data that should exist independent of EE.
288
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
289
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
290
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
291
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
292
+	 * @var boolean
293
+	 */
294
+	protected $_wp_core_model = false;
295
+
296
+	/**
297
+	 * @var bool stores whether this model has a password field or not.
298
+	 * null until initialized by hasPasswordField()
299
+	 */
300
+	protected $has_password_field;
301
+
302
+	/**
303
+	 * @var EE_Password_Field|null Automatically set when calling getPasswordField()
304
+	 */
305
+	protected $password_field;
306
+
307
+	/**
308
+	 *    List of valid operators that can be used for querying.
309
+	 * The keys are all operators we'll accept, the values are the real SQL
310
+	 * operators used
311
+	 *
312
+	 * @var array
313
+	 */
314
+	protected $_valid_operators = array(
315
+		'='           => '=',
316
+		'<='          => '<=',
317
+		'<'           => '<',
318
+		'>='          => '>=',
319
+		'>'           => '>',
320
+		'!='          => '!=',
321
+		'LIKE'        => 'LIKE',
322
+		'like'        => 'LIKE',
323
+		'NOT_LIKE'    => 'NOT LIKE',
324
+		'not_like'    => 'NOT LIKE',
325
+		'NOT LIKE'    => 'NOT LIKE',
326
+		'not like'    => 'NOT LIKE',
327
+		'IN'          => 'IN',
328
+		'in'          => 'IN',
329
+		'NOT_IN'      => 'NOT IN',
330
+		'not_in'      => 'NOT IN',
331
+		'NOT IN'      => 'NOT IN',
332
+		'not in'      => 'NOT IN',
333
+		'between'     => 'BETWEEN',
334
+		'BETWEEN'     => 'BETWEEN',
335
+		'IS_NOT_NULL' => 'IS NOT NULL',
336
+		'is_not_null' => 'IS NOT NULL',
337
+		'IS NOT NULL' => 'IS NOT NULL',
338
+		'is not null' => 'IS NOT NULL',
339
+		'IS_NULL'     => 'IS NULL',
340
+		'is_null'     => 'IS NULL',
341
+		'IS NULL'     => 'IS NULL',
342
+		'is null'     => 'IS NULL',
343
+		'REGEXP'      => 'REGEXP',
344
+		'regexp'      => 'REGEXP',
345
+		'NOT_REGEXP'  => 'NOT REGEXP',
346
+		'not_regexp'  => 'NOT REGEXP',
347
+		'NOT REGEXP'  => 'NOT REGEXP',
348
+		'not regexp'  => 'NOT REGEXP',
349
+	);
350
+
351
+	/**
352
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
353
+	 *
354
+	 * @var array
355
+	 */
356
+	protected $_in_style_operators = array('IN', 'NOT IN');
357
+
358
+	/**
359
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
360
+	 * '12-31-2012'"
361
+	 *
362
+	 * @var array
363
+	 */
364
+	protected $_between_style_operators = array('BETWEEN');
365
+
366
+	/**
367
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
368
+	 * @var array
369
+	 */
370
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
371
+	/**
372
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
373
+	 * on a join table.
374
+	 *
375
+	 * @var array
376
+	 */
377
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
378
+
379
+	/**
380
+	 * Allowed values for $query_params['order'] for ordering in queries
381
+	 *
382
+	 * @var array
383
+	 */
384
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
385
+
386
+	/**
387
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
388
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
389
+	 *
390
+	 * @var array
391
+	 */
392
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
393
+
394
+	/**
395
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
396
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
397
+	 *
398
+	 * @var array
399
+	 */
400
+	private $_allowed_query_params = array(
401
+		0,
402
+		'limit',
403
+		'order_by',
404
+		'group_by',
405
+		'having',
406
+		'force_join',
407
+		'order',
408
+		'on_join_limit',
409
+		'default_where_conditions',
410
+		'caps',
411
+		'extra_selects',
412
+		'exclude_protected',
413
+	);
414
+
415
+	/**
416
+	 * All the data types that can be used in $wpdb->prepare statements.
417
+	 *
418
+	 * @var array
419
+	 */
420
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
421
+
422
+	/**
423
+	 * @var EE_Registry $EE
424
+	 */
425
+	protected $EE = null;
426
+
427
+
428
+	/**
429
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
430
+	 *
431
+	 * @var int
432
+	 */
433
+	protected $_show_next_x_db_queries = 0;
434
+
435
+	/**
436
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
437
+	 * it gets saved on this property as an instance of CustomSelects so those selections can be used in
438
+	 * WHERE, GROUP_BY, etc.
439
+	 *
440
+	 * @var CustomSelects
441
+	 */
442
+	protected $_custom_selections = array();
443
+
444
+	/**
445
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
446
+	 * caches every model object we've fetched from the DB on this request
447
+	 *
448
+	 * @var array
449
+	 */
450
+	protected $_entity_map;
451
+
452
+	/**
453
+	 * @var LoaderInterface $loader
454
+	 */
455
+	private static $loader;
456
+
457
+
458
+	/**
459
+	 * constant used to show EEM_Base has not yet verified the db on this http request
460
+	 */
461
+	const db_verified_none = 0;
462
+
463
+	/**
464
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
465
+	 * but not the addons' dbs
466
+	 */
467
+	const db_verified_core = 1;
468
+
469
+	/**
470
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
471
+	 * the EE core db too)
472
+	 */
473
+	const db_verified_addons = 2;
474
+
475
+	/**
476
+	 * indicates whether an EEM_Base child has already re-verified the DB
477
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
478
+	 * looking like EEM_Base::db_verified_*
479
+	 *
480
+	 * @var int - 0 = none, 1 = core, 2 = addons
481
+	 */
482
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
483
+
484
+	/**
485
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
486
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
487
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
488
+	 */
489
+	const default_where_conditions_all = 'all';
490
+
491
+	/**
492
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
493
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
494
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
495
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
496
+	 *        models which share tables with other models, this can return data for the wrong model.
497
+	 */
498
+	const default_where_conditions_this_only = 'this_model_only';
499
+
500
+	/**
501
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
502
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
503
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
504
+	 */
505
+	const default_where_conditions_others_only = 'other_models_only';
506
+
507
+	/**
508
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
509
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
510
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
511
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
512
+	 *        (regardless of whether those events and venues are trashed)
513
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
514
+	 *        events.
515
+	 */
516
+	const default_where_conditions_minimum_all = 'minimum';
517
+
518
+	/**
519
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
520
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
521
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
522
+	 *        not)
523
+	 */
524
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
525
+
526
+	/**
527
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
528
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
529
+	 *        it's possible it will return table entries for other models. You should use
530
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
531
+	 */
532
+	const default_where_conditions_none = 'none';
533
+
534
+
535
+
536
+	/**
537
+	 * About all child constructors:
538
+	 * they should define the _tables, _fields and _model_relations arrays.
539
+	 * Should ALWAYS be called after child constructor.
540
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
541
+	 * finalizes constructing all the object's attributes.
542
+	 * Generally, rather than requiring a child to code
543
+	 * $this->_tables = array(
544
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
545
+	 *        ...);
546
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
547
+	 * each EE_Table has a function to set the table's alias after the constructor, using
548
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
549
+	 * do something similar.
550
+	 *
551
+	 * @param null $timezone
552
+	 * @throws EE_Error
553
+	 */
554
+	protected function __construct($timezone = null)
555
+	{
556
+		// check that the model has not been loaded too soon
557
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
558
+			throw new EE_Error(
559
+				sprintf(
560
+					__(
561
+						'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.',
562
+						'event_espresso'
563
+					),
564
+					get_class($this)
565
+				)
566
+			);
567
+		}
568
+		/**
569
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
570
+		 */
571
+		if (empty(EEM_Base::$_model_query_blog_id)) {
572
+			EEM_Base::set_model_query_blog_id();
573
+		}
574
+		/**
575
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
576
+		 * just use EE_Register_Model_Extension
577
+		 *
578
+		 * @var EE_Table_Base[] $_tables
579
+		 */
580
+		$this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
581
+		foreach ($this->_tables as $table_alias => $table_obj) {
582
+			/** @var $table_obj EE_Table_Base */
583
+			$table_obj->_construct_finalize_with_alias($table_alias);
584
+			if ($table_obj instanceof EE_Secondary_Table) {
585
+				/** @var $table_obj EE_Secondary_Table */
586
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
587
+			}
588
+		}
589
+		/**
590
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
591
+		 * EE_Register_Model_Extension
592
+		 *
593
+		 * @param EE_Model_Field_Base[] $_fields
594
+		 */
595
+		$this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
596
+		$this->_invalidate_field_caches();
597
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
598
+			if (! array_key_exists($table_alias, $this->_tables)) {
599
+				throw new EE_Error(sprintf(__(
600
+					"Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601
+					'event_espresso'
602
+				), $table_alias, implode(",", $this->_fields)));
603
+			}
604
+			foreach ($fields_for_table as $field_name => $field_obj) {
605
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
606
+				// primary key field base has a slightly different _construct_finalize
607
+				/** @var $field_obj EE_Model_Field_Base */
608
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
609
+			}
610
+		}
611
+		// everything is related to Extra_Meta
612
+		if (get_class($this) !== 'EEM_Extra_Meta') {
613
+			// make extra meta related to everything, but don't block deleting things just
614
+			// because they have related extra meta info. For now just orphan those extra meta
615
+			// in the future we should automatically delete them
616
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
617
+		}
618
+		// and change logs
619
+		if (get_class($this) !== 'EEM_Change_Log') {
620
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
621
+		}
622
+		/**
623
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
624
+		 * EE_Register_Model_Extension
625
+		 *
626
+		 * @param EE_Model_Relation_Base[] $_model_relations
627
+		 */
628
+		$this->_model_relations = (array) apply_filters(
629
+			'FHEE__' . get_class($this) . '__construct__model_relations',
630
+			$this->_model_relations
631
+		);
632
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
633
+			/** @var $relation_obj EE_Model_Relation_Base */
634
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
635
+		}
636
+		foreach ($this->_indexes as $index_name => $index_obj) {
637
+			/** @var $index_obj EE_Index */
638
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
639
+		}
640
+		$this->set_timezone($timezone);
641
+		// finalize default where condition strategy, or set default
642
+		if (! $this->_default_where_conditions_strategy) {
643
+			// nothing was set during child constructor, so set default
644
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645
+		}
646
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
647
+		if (! $this->_minimum_where_conditions_strategy) {
648
+			// nothing was set during child constructor, so set default
649
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650
+		}
651
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
652
+		// if the cap slug hasn't been set, and we haven't set it to false on purpose
653
+		// to indicate to NOT set it, set it to the logical default
654
+		if ($this->_caps_slug === null) {
655
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
656
+		}
657
+		// initialize the standard cap restriction generators if none were specified by the child constructor
658
+		if ($this->_cap_restriction_generators !== false) {
659
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
+				if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
+					$this->_cap_restriction_generators[ $cap_context ] = apply_filters(
662
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663
+						new EE_Restriction_Generator_Protected(),
664
+						$cap_context,
665
+						$this
666
+					);
667
+				}
668
+			}
669
+		}
670
+		// if there are cap restriction generators, use them to make the default cap restrictions
671
+		if ($this->_cap_restriction_generators !== false) {
672
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
+				if (! $generator_object) {
674
+					continue;
675
+				}
676
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
677
+					throw new EE_Error(
678
+						sprintf(
679
+							__(
680
+								'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.',
681
+								'event_espresso'
682
+							),
683
+							$context,
684
+							$this->get_this_model_name()
685
+						)
686
+					);
687
+				}
688
+				$action = $this->cap_action_for_context($context);
689
+				if (! $generator_object->construction_finalized()) {
690
+					$generator_object->_construct_finalize($this, $action);
691
+				}
692
+			}
693
+		}
694
+		do_action('AHEE__' . get_class($this) . '__construct__end');
695
+	}
696
+
697
+
698
+
699
+	/**
700
+	 * Used to set the $_model_query_blog_id static property.
701
+	 *
702
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
703
+	 *                      value for get_current_blog_id() will be used.
704
+	 */
705
+	public static function set_model_query_blog_id($blog_id = 0)
706
+	{
707
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
708
+	}
709
+
710
+
711
+
712
+	/**
713
+	 * Returns whatever is set as the internal $model_query_blog_id.
714
+	 *
715
+	 * @return int
716
+	 */
717
+	public static function get_model_query_blog_id()
718
+	{
719
+		return EEM_Base::$_model_query_blog_id;
720
+	}
721
+
722
+
723
+
724
+	/**
725
+	 * This function is a singleton method used to instantiate the Espresso_model object
726
+	 *
727
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
728
+	 *                                (and any incoming timezone data that gets saved).
729
+	 *                                Note this just sends the timezone info to the date time model field objects.
730
+	 *                                Default is NULL
731
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
732
+	 * @return static (as in the concrete child class)
733
+	 * @throws EE_Error
734
+	 * @throws InvalidArgumentException
735
+	 * @throws InvalidDataTypeException
736
+	 * @throws InvalidInterfaceException
737
+	 */
738
+	public static function instance($timezone = null)
739
+	{
740
+		// check if instance of Espresso_model already exists
741
+		if (! static::$_instance instanceof static) {
742
+			// instantiate Espresso_model
743
+			static::$_instance = new static(
744
+				$timezone,
745
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
746
+			);
747
+		}
748
+		// we might have a timezone set, let set_timezone decide what to do with it
749
+		static::$_instance->set_timezone($timezone);
750
+		// Espresso_model object
751
+		return static::$_instance;
752
+	}
753
+
754
+
755
+
756
+	/**
757
+	 * resets the model and returns it
758
+	 *
759
+	 * @param null | string $timezone
760
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
761
+	 * all its properties reset; if it wasn't instantiated, returns null)
762
+	 * @throws EE_Error
763
+	 * @throws ReflectionException
764
+	 * @throws InvalidArgumentException
765
+	 * @throws InvalidDataTypeException
766
+	 * @throws InvalidInterfaceException
767
+	 */
768
+	public static function reset($timezone = null)
769
+	{
770
+		if (static::$_instance instanceof EEM_Base) {
771
+			// let's try to NOT swap out the current instance for a new one
772
+			// because if someone has a reference to it, we can't remove their reference
773
+			// so it's best to keep using the same reference, but change the original object
774
+			// reset all its properties to their original values as defined in the class
775
+			$r = new ReflectionClass(get_class(static::$_instance));
776
+			$static_properties = $r->getStaticProperties();
777
+			foreach ($r->getDefaultProperties() as $property => $value) {
778
+				// don't set instance to null like it was originally,
779
+				// but it's static anyways, and we're ignoring static properties (for now at least)
780
+				if (! isset($static_properties[ $property ])) {
781
+					static::$_instance->{$property} = $value;
782
+				}
783
+			}
784
+			// and then directly call its constructor again, like we would if we were creating a new one
785
+			static::$_instance->__construct(
786
+				$timezone,
787
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
788
+			);
789
+			return self::instance();
790
+		}
791
+		return null;
792
+	}
793
+
794
+
795
+
796
+	/**
797
+	 * @return LoaderInterface
798
+	 * @throws InvalidArgumentException
799
+	 * @throws InvalidDataTypeException
800
+	 * @throws InvalidInterfaceException
801
+	 */
802
+	private static function getLoader()
803
+	{
804
+		if (! EEM_Base::$loader instanceof LoaderInterface) {
805
+			EEM_Base::$loader = LoaderFactory::getLoader();
806
+		}
807
+		return EEM_Base::$loader;
808
+	}
809
+
810
+
811
+
812
+	/**
813
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
814
+	 *
815
+	 * @param  boolean $translated return localized strings or JUST the array.
816
+	 * @return array
817
+	 * @throws EE_Error
818
+	 * @throws InvalidArgumentException
819
+	 * @throws InvalidDataTypeException
820
+	 * @throws InvalidInterfaceException
821
+	 */
822
+	public function status_array($translated = false)
823
+	{
824
+		if (! array_key_exists('Status', $this->_model_relations)) {
825
+			return array();
826
+		}
827
+		$model_name = $this->get_this_model_name();
828
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
829
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830
+		$status_array = array();
831
+		foreach ($stati as $status) {
832
+			$status_array[ $status->ID() ] = $status->get('STS_code');
833
+		}
834
+		return $translated
835
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
836
+			: $status_array;
837
+	}
838
+
839
+
840
+
841
+	/**
842
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
843
+	 *
844
+	 * @param array $query_params  @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
845
+	 *                             or if you have the development copy of EE you can view this at the path:
846
+	 *                             /docs/G--Model-System/model-query-params.md
847
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
848
+	 *                                        from EE_Base_Class[], use get_all_wpdb_results(). Array keys are object IDs (if there is a primary key on the model.
849
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
850
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
851
+	 *                                        array( array(
852
+	 *                                        'OR'=>array(
853
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
854
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
855
+	 *                                        )
856
+	 *                                        ),
857
+	 *                                        'limit'=>10,
858
+	 *                                        'group_by'=>'TXN_ID'
859
+	 *                                        ));
860
+	 *                                        get all the answers to the question titled "shirt size" for event with id
861
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
862
+	 *                                        'Question.QST_display_text'=>'shirt size',
863
+	 *                                        'Registration.Event.EVT_ID'=>12
864
+	 *                                        ),
865
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
866
+	 *                                        ));
867
+	 * @throws EE_Error
868
+	 */
869
+	public function get_all($query_params = array())
870
+	{
871
+		if (isset($query_params['limit'])
872
+			&& ! isset($query_params['group_by'])
873
+		) {
874
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
875
+		}
876
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
877
+	}
878
+
879
+
880
+
881
+	/**
882
+	 * Modifies the query parameters so we only get back model objects
883
+	 * that "belong" to the current user
884
+	 *
885
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
886
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
887
+	 */
888
+	public function alter_query_params_to_only_include_mine($query_params = array())
889
+	{
890
+		$wp_user_field_name = $this->wp_user_field_name();
891
+		if ($wp_user_field_name) {
892
+			$query_params[0][ $wp_user_field_name ] = get_current_user_id();
893
+		}
894
+		return $query_params;
895
+	}
896
+
897
+
898
+
899
+	/**
900
+	 * Returns the name of the field's name that points to the WP_User table
901
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
902
+	 * foreign key to the WP_User table)
903
+	 *
904
+	 * @return string|boolean string on success, boolean false when there is no
905
+	 * foreign key to the WP_User table
906
+	 */
907
+	public function wp_user_field_name()
908
+	{
909
+		try {
910
+			if (! empty($this->_model_chain_to_wp_user)) {
911
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912
+				$last_model_name = end($models_to_follow_to_wp_users);
913
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
915
+			} else {
916
+				$model_with_fk_to_wp_users = $this;
917
+				$model_chain_to_wp_user = '';
918
+			}
919
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
921
+		} catch (EE_Error $e) {
922
+			return false;
923
+		}
924
+	}
925
+
926
+
927
+
928
+	/**
929
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
930
+	 * (or transiently-related model) has a foreign key to the wp_users table;
931
+	 * useful for finding if model objects of this type are 'owned' by the current user.
932
+	 * This is an empty string when the foreign key is on this model and when it isn't,
933
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
934
+	 * (or transiently-related model)
935
+	 *
936
+	 * @return string
937
+	 */
938
+	public function model_chain_to_wp_user()
939
+	{
940
+		return $this->_model_chain_to_wp_user;
941
+	}
942
+
943
+
944
+
945
+	/**
946
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
947
+	 * like how registrations don't have a foreign key to wp_users, but the
948
+	 * events they are for are), or is unrelated to wp users.
949
+	 * generally available
950
+	 *
951
+	 * @return boolean
952
+	 */
953
+	public function is_owned()
954
+	{
955
+		if ($this->model_chain_to_wp_user()) {
956
+			return true;
957
+		}
958
+		try {
959
+			$this->get_foreign_key_to('WP_User');
960
+			return true;
961
+		} catch (EE_Error $e) {
962
+			return false;
963
+		}
964
+	}
965
+
966
+
967
+	/**
968
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
969
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
970
+	 * the model)
971
+	 *
972
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
973
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
974
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
975
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
976
+	 *                                  override this and set the select to "*", or a specific column name, like
977
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
978
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
979
+	 *                                  the aliases used to refer to this selection, and values are to be
980
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
981
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
982
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
983
+	 * @throws EE_Error
984
+	 * @throws InvalidArgumentException
985
+	 */
986
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
987
+	{
988
+		$this->_custom_selections = $this->getCustomSelection($query_params, $columns_to_select);
989
+		;
990
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
991
+		$select_expressions = $columns_to_select === null
992
+			? $this->_construct_default_select_sql($model_query_info)
993
+			: '';
994
+		if ($this->_custom_selections instanceof CustomSelects) {
995
+			$custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996
+			$select_expressions .= $select_expressions
997
+				? ', ' . $custom_expressions
998
+				: $custom_expressions;
999
+		}
1000
+
1001
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1002
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003
+	}
1004
+
1005
+
1006
+	/**
1007
+	 * Get a CustomSelects object if the $query_params or $columns_to_select allows for it.
1008
+	 * Note: $query_params['extra_selects'] will always override any $columns_to_select values. It is the preferred
1009
+	 * method of including extra select information.
1010
+	 *
1011
+	 * @param array             $query_params
1012
+	 * @param null|array|string $columns_to_select
1013
+	 * @return null|CustomSelects
1014
+	 * @throws InvalidArgumentException
1015
+	 */
1016
+	protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017
+	{
1018
+		if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019
+			return null;
1020
+		}
1021
+		$selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
1022
+		$selects = is_string($selects) ? explode(',', $selects) : $selects;
1023
+		return new CustomSelects($selects);
1024
+	}
1025
+
1026
+
1027
+
1028
+	/**
1029
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1030
+	 * but you can use the model query params to more easily
1031
+	 * take care of joins, field preparation etc.
1032
+	 *
1033
+	 * @param array  $query_params      @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1034
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1035
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1036
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1037
+	 *                                  override this and set the select to "*", or a specific column name, like
1038
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1039
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1040
+	 *                                  the aliases used to refer to this selection, and values are to be
1041
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1042
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1043
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1047
+	{
1048
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1049
+	}
1050
+
1051
+
1052
+
1053
+	/**
1054
+	 * For creating a custom select statement
1055
+	 *
1056
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1057
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1058
+	 *                                 SQL, and 1=>is the datatype
1059
+	 * @throws EE_Error
1060
+	 * @return string
1061
+	 */
1062
+	private function _construct_select_from_input($columns_to_select)
1063
+	{
1064
+		if (is_array($columns_to_select)) {
1065
+			$select_sql_array = array();
1066
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068
+					throw new EE_Error(
1069
+						sprintf(
1070
+							__(
1071
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1072
+								'event_espresso'
1073
+							),
1074
+							$selection_and_datatype,
1075
+							$alias
1076
+						)
1077
+					);
1078
+				}
1079
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080
+					throw new EE_Error(
1081
+						sprintf(
1082
+							esc_html__(
1083
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1084
+								'event_espresso'
1085
+							),
1086
+							$selection_and_datatype[1],
1087
+							$selection_and_datatype[0],
1088
+							$alias,
1089
+							implode(', ', $this->_valid_wpdb_data_types)
1090
+						)
1091
+					);
1092
+				}
1093
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1094
+			}
1095
+			$columns_to_select_string = implode(', ', $select_sql_array);
1096
+		} else {
1097
+			$columns_to_select_string = $columns_to_select;
1098
+		}
1099
+		return $columns_to_select_string;
1100
+	}
1101
+
1102
+
1103
+
1104
+	/**
1105
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1106
+	 *
1107
+	 * @return string
1108
+	 * @throws EE_Error
1109
+	 */
1110
+	public function primary_key_name()
1111
+	{
1112
+		return $this->get_primary_key_field()->get_name();
1113
+	}
1114
+
1115
+
1116
+	/**
1117
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1118
+	 * If there is no primary key on this model, $id is treated as primary key string
1119
+	 *
1120
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1121
+	 * @return EE_Base_Class
1122
+	 * @throws EE_Error
1123
+	 */
1124
+	public function get_one_by_ID($id)
1125
+	{
1126
+		if ($this->get_from_entity_map($id)) {
1127
+			return $this->get_from_entity_map($id);
1128
+		}
1129
+		$model_object = $this->get_one(
1130
+			$this->alter_query_params_to_restrict_by_ID(
1131
+				$id,
1132
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1133
+			)
1134
+		);
1135
+		$className = $this->_get_class_name();
1136
+		if ($model_object instanceof $className) {
1137
+			// make sure valid objects get added to the entity map
1138
+			// so that the next call to this method doesn't trigger another trip to the db
1139
+			$this->add_to_entity_map($model_object);
1140
+		}
1141
+		return $model_object;
1142
+	}
1143
+
1144
+
1145
+
1146
+	/**
1147
+	 * Alters query parameters to only get items with this ID are returned.
1148
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1149
+	 * or could just be a simple primary key ID
1150
+	 *
1151
+	 * @param int   $id
1152
+	 * @param array $query_params
1153
+	 * @return array of normal query params, @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1154
+	 * @throws EE_Error
1155
+	 */
1156
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157
+	{
1158
+		if (! isset($query_params[0])) {
1159
+			$query_params[0] = array();
1160
+		}
1161
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1162
+		if ($conditions_from_id === null) {
1163
+			$query_params[0][ $this->primary_key_name() ] = $id;
1164
+		} else {
1165
+			// no primary key, so the $id must be from the get_index_primary_key_string()
1166
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1167
+		}
1168
+		return $query_params;
1169
+	}
1170
+
1171
+
1172
+
1173
+	/**
1174
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1175
+	 * array. If no item is found, null is returned.
1176
+	 *
1177
+	 * @param array $query_params like EEM_Base's $query_params variable.
1178
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1179
+	 * @throws EE_Error
1180
+	 */
1181
+	public function get_one($query_params = array())
1182
+	{
1183
+		if (! is_array($query_params)) {
1184
+			EE_Error::doing_it_wrong(
1185
+				'EEM_Base::get_one',
1186
+				sprintf(
1187
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1188
+					gettype($query_params)
1189
+				),
1190
+				'4.6.0'
1191
+			);
1192
+			$query_params = array();
1193
+		}
1194
+		$query_params['limit'] = 1;
1195
+		$items = $this->get_all($query_params);
1196
+		if (empty($items)) {
1197
+			return null;
1198
+		}
1199
+		return array_shift($items);
1200
+	}
1201
+
1202
+
1203
+
1204
+	/**
1205
+	 * Returns the next x number of items in sequence from the given value as
1206
+	 * found in the database matching the given query conditions.
1207
+	 *
1208
+	 * @param mixed $current_field_value    Value used for the reference point.
1209
+	 * @param null  $field_to_order_by      What field is used for the
1210
+	 *                                      reference point.
1211
+	 * @param int   $limit                  How many to return.
1212
+	 * @param array $query_params           Extra conditions on the query.
1213
+	 * @param null  $columns_to_select      If left null, then an array of
1214
+	 *                                      EE_Base_Class objects is returned,
1215
+	 *                                      otherwise you can indicate just the
1216
+	 *                                      columns you want returned.
1217
+	 * @return EE_Base_Class[]|array
1218
+	 * @throws EE_Error
1219
+	 */
1220
+	public function next_x(
1221
+		$current_field_value,
1222
+		$field_to_order_by = null,
1223
+		$limit = 1,
1224
+		$query_params = array(),
1225
+		$columns_to_select = null
1226
+	) {
1227
+		return $this->_get_consecutive(
1228
+			$current_field_value,
1229
+			'>',
1230
+			$field_to_order_by,
1231
+			$limit,
1232
+			$query_params,
1233
+			$columns_to_select
1234
+		);
1235
+	}
1236
+
1237
+
1238
+
1239
+	/**
1240
+	 * Returns the previous x number of items in sequence from the given value
1241
+	 * as found in the database matching the given query conditions.
1242
+	 *
1243
+	 * @param mixed $current_field_value    Value used for the reference point.
1244
+	 * @param null  $field_to_order_by      What field is used for the
1245
+	 *                                      reference point.
1246
+	 * @param int   $limit                  How many to return.
1247
+	 * @param array $query_params           Extra conditions on the query.
1248
+	 * @param null  $columns_to_select      If left null, then an array of
1249
+	 *                                      EE_Base_Class objects is returned,
1250
+	 *                                      otherwise you can indicate just the
1251
+	 *                                      columns you want returned.
1252
+	 * @return EE_Base_Class[]|array
1253
+	 * @throws EE_Error
1254
+	 */
1255
+	public function previous_x(
1256
+		$current_field_value,
1257
+		$field_to_order_by = null,
1258
+		$limit = 1,
1259
+		$query_params = array(),
1260
+		$columns_to_select = null
1261
+	) {
1262
+		return $this->_get_consecutive(
1263
+			$current_field_value,
1264
+			'<',
1265
+			$field_to_order_by,
1266
+			$limit,
1267
+			$query_params,
1268
+			$columns_to_select
1269
+		);
1270
+	}
1271
+
1272
+
1273
+
1274
+	/**
1275
+	 * Returns the next item in sequence from the given value as found in the
1276
+	 * database matching the given query conditions.
1277
+	 *
1278
+	 * @param mixed $current_field_value    Value used for the reference point.
1279
+	 * @param null  $field_to_order_by      What field is used for the
1280
+	 *                                      reference point.
1281
+	 * @param array $query_params           Extra conditions on the query.
1282
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1283
+	 *                                      object is returned, otherwise you
1284
+	 *                                      can indicate just the columns you
1285
+	 *                                      want and a single array indexed by
1286
+	 *                                      the columns will be returned.
1287
+	 * @return EE_Base_Class|null|array()
1288
+	 * @throws EE_Error
1289
+	 */
1290
+	public function next(
1291
+		$current_field_value,
1292
+		$field_to_order_by = null,
1293
+		$query_params = array(),
1294
+		$columns_to_select = null
1295
+	) {
1296
+		$results = $this->_get_consecutive(
1297
+			$current_field_value,
1298
+			'>',
1299
+			$field_to_order_by,
1300
+			1,
1301
+			$query_params,
1302
+			$columns_to_select
1303
+		);
1304
+		return empty($results) ? null : reset($results);
1305
+	}
1306
+
1307
+
1308
+
1309
+	/**
1310
+	 * Returns the previous item in sequence from the given value as found in
1311
+	 * the database matching the given query conditions.
1312
+	 *
1313
+	 * @param mixed $current_field_value    Value used for the reference point.
1314
+	 * @param null  $field_to_order_by      What field is used for the
1315
+	 *                                      reference point.
1316
+	 * @param array $query_params           Extra conditions on the query.
1317
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1318
+	 *                                      object is returned, otherwise you
1319
+	 *                                      can indicate just the columns you
1320
+	 *                                      want and a single array indexed by
1321
+	 *                                      the columns will be returned.
1322
+	 * @return EE_Base_Class|null|array()
1323
+	 * @throws EE_Error
1324
+	 */
1325
+	public function previous(
1326
+		$current_field_value,
1327
+		$field_to_order_by = null,
1328
+		$query_params = array(),
1329
+		$columns_to_select = null
1330
+	) {
1331
+		$results = $this->_get_consecutive(
1332
+			$current_field_value,
1333
+			'<',
1334
+			$field_to_order_by,
1335
+			1,
1336
+			$query_params,
1337
+			$columns_to_select
1338
+		);
1339
+		return empty($results) ? null : reset($results);
1340
+	}
1341
+
1342
+
1343
+
1344
+	/**
1345
+	 * Returns the a consecutive number of items in sequence from the given
1346
+	 * value as found in the database matching the given query conditions.
1347
+	 *
1348
+	 * @param mixed  $current_field_value   Value used for the reference point.
1349
+	 * @param string $operand               What operand is used for the sequence.
1350
+	 * @param string $field_to_order_by     What field is used for the reference point.
1351
+	 * @param int    $limit                 How many to return.
1352
+	 * @param array  $query_params          Extra conditions on the query.
1353
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1354
+	 *                                      otherwise you can indicate just the columns you want returned.
1355
+	 * @return EE_Base_Class[]|array
1356
+	 * @throws EE_Error
1357
+	 */
1358
+	protected function _get_consecutive(
1359
+		$current_field_value,
1360
+		$operand = '>',
1361
+		$field_to_order_by = null,
1362
+		$limit = 1,
1363
+		$query_params = array(),
1364
+		$columns_to_select = null
1365
+	) {
1366
+		// if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1367
+		if (empty($field_to_order_by)) {
1368
+			if ($this->has_primary_key_field()) {
1369
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1370
+			} else {
1371
+				if (WP_DEBUG) {
1372
+					throw new EE_Error(__(
1373
+						'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).',
1374
+						'event_espresso'
1375
+					));
1376
+				}
1377
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1378
+				return array();
1379
+			}
1380
+		}
1381
+		if (! is_array($query_params)) {
1382
+			EE_Error::doing_it_wrong(
1383
+				'EEM_Base::_get_consecutive',
1384
+				sprintf(
1385
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1386
+					gettype($query_params)
1387
+				),
1388
+				'4.6.0'
1389
+			);
1390
+			$query_params = array();
1391
+		}
1392
+		// let's add the where query param for consecutive look up.
1393
+		$query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1394
+		$query_params['limit'] = $limit;
1395
+		// set direction
1396
+		$incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1397
+		$query_params['order_by'] = $operand === '>'
1398
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1399
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1400
+		// if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1401
+		if (empty($columns_to_select)) {
1402
+			return $this->get_all($query_params);
1403
+		}
1404
+		// getting just the fields
1405
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1406
+	}
1407
+
1408
+
1409
+
1410
+	/**
1411
+	 * This sets the _timezone property after model object has been instantiated.
1412
+	 *
1413
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1414
+	 */
1415
+	public function set_timezone($timezone)
1416
+	{
1417
+		if ($timezone !== null) {
1418
+			$this->_timezone = $timezone;
1419
+		}
1420
+		// note we need to loop through relations and set the timezone on those objects as well.
1421
+		foreach ($this->_model_relations as $relation) {
1422
+			$relation->set_timezone($timezone);
1423
+		}
1424
+		// and finally we do the same for any datetime fields
1425
+		foreach ($this->_fields as $field) {
1426
+			if ($field instanceof EE_Datetime_Field) {
1427
+				$field->set_timezone($timezone);
1428
+			}
1429
+		}
1430
+	}
1431
+
1432
+
1433
+
1434
+	/**
1435
+	 * This just returns whatever is set for the current timezone.
1436
+	 *
1437
+	 * @access public
1438
+	 * @return string
1439
+	 */
1440
+	public function get_timezone()
1441
+	{
1442
+		// first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1443
+		if (empty($this->_timezone)) {
1444
+			foreach ($this->_fields as $field) {
1445
+				if ($field instanceof EE_Datetime_Field) {
1446
+					$this->set_timezone($field->get_timezone());
1447
+					break;
1448
+				}
1449
+			}
1450
+		}
1451
+		// if timezone STILL empty then return the default timezone for the site.
1452
+		if (empty($this->_timezone)) {
1453
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1454
+		}
1455
+		return $this->_timezone;
1456
+	}
1457
+
1458
+
1459
+
1460
+	/**
1461
+	 * This returns the date formats set for the given field name and also ensures that
1462
+	 * $this->_timezone property is set correctly.
1463
+	 *
1464
+	 * @since 4.6.x
1465
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1466
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1467
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1468
+	 * @return array formats in an array with the date format first, and the time format last.
1469
+	 */
1470
+	public function get_formats_for($field_name, $pretty = false)
1471
+	{
1472
+		$field_settings = $this->field_settings_for($field_name);
1473
+		// if not a valid EE_Datetime_Field then throw error
1474
+		if (! $field_settings instanceof EE_Datetime_Field) {
1475
+			throw new EE_Error(sprintf(__(
1476
+				'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.',
1477
+				'event_espresso'
1478
+			), $field_name));
1479
+		}
1480
+		// while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1481
+		// the field.
1482
+		$this->_timezone = $field_settings->get_timezone();
1483
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1484
+	}
1485
+
1486
+
1487
+
1488
+	/**
1489
+	 * This returns the current time in a format setup for a query on this model.
1490
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1491
+	 * it will return:
1492
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1493
+	 *  NOW
1494
+	 *  - or a unix timestamp (equivalent to time())
1495
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1496
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1497
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1498
+	 * @since 4.6.x
1499
+	 * @param string $field_name       The field the current time is needed for.
1500
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1501
+	 *                                 formatted string matching the set format for the field in the set timezone will
1502
+	 *                                 be returned.
1503
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1504
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1505
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1506
+	 *                                 exception is triggered.
1507
+	 */
1508
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1509
+	{
1510
+		$formats = $this->get_formats_for($field_name);
1511
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1512
+		if ($timestamp) {
1513
+			return $DateTime->format('U');
1514
+		}
1515
+		// not returning timestamp, so return formatted string in timezone.
1516
+		switch ($what) {
1517
+			case 'time':
1518
+				return $DateTime->format($formats[1]);
1519
+				break;
1520
+			case 'date':
1521
+				return $DateTime->format($formats[0]);
1522
+				break;
1523
+			default:
1524
+				return $DateTime->format(implode(' ', $formats));
1525
+				break;
1526
+		}
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1533
+	 * for the model are.  Returns a DateTime object.
1534
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1535
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1536
+	 * ignored.
1537
+	 *
1538
+	 * @param string $field_name      The field being setup.
1539
+	 * @param string $timestring      The date time string being used.
1540
+	 * @param string $incoming_format The format for the time string.
1541
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1542
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1543
+	 *                                format is
1544
+	 *                                'U', this is ignored.
1545
+	 * @return DateTime
1546
+	 * @throws EE_Error
1547
+	 */
1548
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1549
+	{
1550
+		// just using this to ensure the timezone is set correctly internally
1551
+		$this->get_formats_for($field_name);
1552
+		// load EEH_DTT_Helper
1553
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1554
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1555
+		EEH_DTT_Helper::setTimezone($incomingDateTime, new DateTimeZone($this->_timezone));
1556
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime);
1557
+	}
1558
+
1559
+
1560
+
1561
+	/**
1562
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1563
+	 *
1564
+	 * @return EE_Table_Base[]
1565
+	 */
1566
+	public function get_tables()
1567
+	{
1568
+		return $this->_tables;
1569
+	}
1570
+
1571
+
1572
+
1573
+	/**
1574
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1575
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1576
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1577
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1578
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1579
+	 * model object with EVT_ID = 1
1580
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1581
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1582
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1583
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1584
+	 * are not specified)
1585
+	 *
1586
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1587
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1588
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1589
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1590
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1591
+	 *                                         ID=34, we'd use this method as follows:
1592
+	 *                                         EEM_Transaction::instance()->update(
1593
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1594
+	 *                                         array(array('TXN_ID'=>34)));
1595
+	 * @param array   $query_params            @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1596
+	 *                                         Eg, consider updating Question's QST_admin_label field is of type
1597
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1598
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1599
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1600
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1601
+	 *                                         TRUE, it is assumed that you've already called
1602
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1603
+	 *                                         malicious javascript. However, if
1604
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1605
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1606
+	 *                                         and every other field, before insertion. We provide this parameter
1607
+	 *                                         because model objects perform their prepare_for_set function on all
1608
+	 *                                         their values, and so don't need to be called again (and in many cases,
1609
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1610
+	 *                                         prepare_for_set method...)
1611
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1612
+	 *                                         in this model's entity map according to $fields_n_values that match
1613
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1614
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1615
+	 *                                         could get out-of-sync with the database
1616
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1617
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1618
+	 *                                         bad)
1619
+	 * @throws EE_Error
1620
+	 */
1621
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622
+	{
1623
+		if (! is_array($query_params)) {
1624
+			EE_Error::doing_it_wrong(
1625
+				'EEM_Base::update',
1626
+				sprintf(
1627
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1628
+					gettype($query_params)
1629
+				),
1630
+				'4.6.0'
1631
+			);
1632
+			$query_params = array();
1633
+		}
1634
+		/**
1635
+		 * Action called before a model update call has been made.
1636
+		 *
1637
+		 * @param EEM_Base $model
1638
+		 * @param array    $fields_n_values the updated fields and their new values
1639
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1640
+		 */
1641
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1642
+		/**
1643
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1644
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1645
+		 *
1646
+		 * @param array    $fields_n_values fields and their new values
1647
+		 * @param EEM_Base $model           the model being queried
1648
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1649
+		 */
1650
+		$fields_n_values = (array) apply_filters(
1651
+			'FHEE__EEM_Base__update__fields_n_values',
1652
+			$fields_n_values,
1653
+			$this,
1654
+			$query_params
1655
+		);
1656
+		// need to verify that, for any entry we want to update, there are entries in each secondary table.
1657
+		// to do that, for each table, verify that it's PK isn't null.
1658
+		$tables = $this->get_tables();
1659
+		// and if the other tables don't have a row for each table-to-be-updated, we'll insert one with whatever values available in the current update query
1660
+		// NOTE: we should make this code more efficient by NOT querying twice
1661
+		// before the real update, but that needs to first go through ALPHA testing
1662
+		// as it's dangerous. says Mike August 8 2014
1663
+		// we want to make sure the default_where strategy is ignored
1664
+		$this->_ignore_where_strategy = true;
1665
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1666
+		foreach ($wpdb_select_results as $wpdb_result) {
1667
+			// type cast stdClass as array
1668
+			$wpdb_result = (array) $wpdb_result;
1669
+			// get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670
+			if ($this->has_primary_key_field()) {
1671
+				$main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1672
+			} else {
1673
+				// 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)
1674
+				$main_table_pk_value = null;
1675
+			}
1676
+			// 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
1677
+			// 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
1678
+			if (count($tables) > 1) {
1679
+				// foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1680
+				// in that table, and so we'll want to insert one
1681
+				foreach ($tables as $table_obj) {
1682
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683
+					// if there is no private key for this table on the results, it means there's no entry
1684
+					// in this table, right? so insert a row in the current table, using any fields available
1685
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+						   && $wpdb_result[ $this_table_pk_column ])
1687
+					) {
1688
+						$success = $this->_insert_into_specific_table(
1689
+							$table_obj,
1690
+							$fields_n_values,
1691
+							$main_table_pk_value
1692
+						);
1693
+						// if we died here, report the error
1694
+						if (! $success) {
1695
+							return false;
1696
+						}
1697
+					}
1698
+				}
1699
+			}
1700
+			//              //and now check that if we have cached any models by that ID on the model, that
1701
+			//              //they also get updated properly
1702
+			//              $model_object = $this->get_from_entity_map( $main_table_pk_value );
1703
+			//              if( $model_object ){
1704
+			//                  foreach( $fields_n_values as $field => $value ){
1705
+			//                      $model_object->set($field, $value);
1706
+			// let's make sure default_where strategy is followed now
1707
+			$this->_ignore_where_strategy = false;
1708
+		}
1709
+		// if we want to keep model objects in sync, AND
1710
+		// if this wasn't called from a model object (to update itself)
1711
+		// then we want to make sure we keep all the existing
1712
+		// model objects in sync with the db
1713
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1714
+			if ($this->has_primary_key_field()) {
1715
+				$model_objs_affected_ids = $this->get_col($query_params);
1716
+			} else {
1717
+				// we need to select a bunch of columns and then combine them into the the "index primary key string"s
1718
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1719
+				$model_objs_affected_ids = array();
1720
+				foreach ($models_affected_key_columns as $row) {
1721
+					$combined_index_key = $this->get_index_primary_key_string($row);
1722
+					$model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1723
+				}
1724
+			}
1725
+			if (! $model_objs_affected_ids) {
1726
+				// wait wait wait- if nothing was affected let's stop here
1727
+				return 0;
1728
+			}
1729
+			foreach ($model_objs_affected_ids as $id) {
1730
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1731
+				if ($model_obj_in_entity_map) {
1732
+					foreach ($fields_n_values as $field => $new_value) {
1733
+						$model_obj_in_entity_map->set($field, $new_value);
1734
+					}
1735
+				}
1736
+			}
1737
+			// if there is a primary key on this model, we can now do a slight optimization
1738
+			if ($this->has_primary_key_field()) {
1739
+				// we already know what we want to update. So let's make the query simpler so it's a little more efficient
1740
+				$query_params = array(
1741
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1742
+					'limit'                    => count($model_objs_affected_ids),
1743
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1744
+				);
1745
+			}
1746
+		}
1747
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1748
+		$SQL = "UPDATE "
1749
+			   . $model_query_info->get_full_join_sql()
1750
+			   . " SET "
1751
+			   . $this->_construct_update_sql($fields_n_values)
1752
+			   . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754
+		/**
1755
+		 * Action called after a model update call has been made.
1756
+		 *
1757
+		 * @param EEM_Base $model
1758
+		 * @param array    $fields_n_values the updated fields and their new values
1759
+		 * @param array    $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1760
+		 * @param int      $rows_affected
1761
+		 */
1762
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
+		return $rows_affected;// how many supposedly got updated
1764
+	}
1765
+
1766
+
1767
+
1768
+	/**
1769
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1770
+	 * are teh values of the field specified (or by default the primary key field)
1771
+	 * that matched the query params. Note that you should pass the name of the
1772
+	 * model FIELD, not the database table's column name.
1773
+	 *
1774
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1775
+	 * @param string $field_to_select
1776
+	 * @return array just like $wpdb->get_col()
1777
+	 * @throws EE_Error
1778
+	 */
1779
+	public function get_col($query_params = array(), $field_to_select = null)
1780
+	{
1781
+		if ($field_to_select) {
1782
+			$field = $this->field_settings_for($field_to_select);
1783
+		} elseif ($this->has_primary_key_field()) {
1784
+			$field = $this->get_primary_key_field();
1785
+		} else {
1786
+			// no primary key, just grab the first column
1787
+			$field = reset($this->field_settings());
1788
+		}
1789
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1790
+		$select_expressions = $field->get_qualified_column();
1791
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1792
+		return $this->_do_wpdb_query('get_col', array($SQL));
1793
+	}
1794
+
1795
+
1796
+
1797
+	/**
1798
+	 * Returns a single column value for a single row from the database
1799
+	 *
1800
+	 * @param array  $query_params    @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1801
+	 * @param string $field_to_select @see EEM_Base::get_col()
1802
+	 * @return string
1803
+	 * @throws EE_Error
1804
+	 */
1805
+	public function get_var($query_params = array(), $field_to_select = null)
1806
+	{
1807
+		$query_params['limit'] = 1;
1808
+		$col = $this->get_col($query_params, $field_to_select);
1809
+		if (! empty($col)) {
1810
+			return reset($col);
1811
+		}
1812
+		return null;
1813
+	}
1814
+
1815
+
1816
+
1817
+	/**
1818
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1819
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1820
+	 * injection, but currently no further filtering is done
1821
+	 *
1822
+	 * @global      $wpdb
1823
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1824
+	 *                               be updated to in the DB
1825
+	 * @return string of SQL
1826
+	 * @throws EE_Error
1827
+	 */
1828
+	public function _construct_update_sql($fields_n_values)
1829
+	{
1830
+		/** @type WPDB $wpdb */
1831
+		global $wpdb;
1832
+		$cols_n_values = array();
1833
+		foreach ($fields_n_values as $field_name => $value) {
1834
+			$field_obj = $this->field_settings_for($field_name);
1835
+			// if the value is NULL, we want to assign the value to that.
1836
+			// wpdb->prepare doesn't really handle that properly
1837
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838
+			$value_sql = $prepared_value === null ? 'NULL'
1839
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1841
+		}
1842
+		return implode(",", $cols_n_values);
1843
+	}
1844
+
1845
+
1846
+
1847
+	/**
1848
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1849
+	 * Performs a HARD delete, meaning the database row should always be removed,
1850
+	 * not just have a flag field on it switched
1851
+	 * Wrapper for EEM_Base::delete_permanently()
1852
+	 *
1853
+	 * @param mixed $id
1854
+	 * @param boolean $allow_blocking
1855
+	 * @return int the number of rows deleted
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1859
+	{
1860
+		return $this->delete_permanently(
1861
+			array(
1862
+				array($this->get_primary_key_field()->get_name() => $id),
1863
+				'limit' => 1,
1864
+			),
1865
+			$allow_blocking
1866
+		);
1867
+	}
1868
+
1869
+
1870
+
1871
+	/**
1872
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1873
+	 * Wrapper for EEM_Base::delete()
1874
+	 *
1875
+	 * @param mixed $id
1876
+	 * @param boolean $allow_blocking
1877
+	 * @return int the number of rows deleted
1878
+	 * @throws EE_Error
1879
+	 */
1880
+	public function delete_by_ID($id, $allow_blocking = true)
1881
+	{
1882
+		return $this->delete(
1883
+			array(
1884
+				array($this->get_primary_key_field()->get_name() => $id),
1885
+				'limit' => 1,
1886
+			),
1887
+			$allow_blocking
1888
+		);
1889
+	}
1890
+
1891
+
1892
+
1893
+	/**
1894
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1895
+	 * meaning if the model has a field that indicates its been "trashed" or
1896
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1897
+	 *
1898
+	 * @see EEM_Base::delete_permanently
1899
+	 * @param array   $query_params
1900
+	 * @param boolean $allow_blocking
1901
+	 * @return int how many rows got deleted
1902
+	 * @throws EE_Error
1903
+	 */
1904
+	public function delete($query_params, $allow_blocking = true)
1905
+	{
1906
+		return $this->delete_permanently($query_params, $allow_blocking);
1907
+	}
1908
+
1909
+
1910
+
1911
+	/**
1912
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1913
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1914
+	 * as archived, not actually deleted
1915
+	 *
1916
+	 * @param array   $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1917
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1918
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1919
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1920
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1921
+	 *                                DB
1922
+	 * @return int how many rows got deleted
1923
+	 * @throws EE_Error
1924
+	 */
1925
+	public function delete_permanently($query_params, $allow_blocking = true)
1926
+	{
1927
+		/**
1928
+		 * Action called just before performing a real deletion query. You can use the
1929
+		 * model and its $query_params to find exactly which items will be deleted
1930
+		 *
1931
+		 * @param EEM_Base $model
1932
+		 * @param array    $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
1933
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1934
+		 *                                 to block (prevent) this deletion
1935
+		 */
1936
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1937
+		// some MySQL databases may be running safe mode, which may restrict
1938
+		// deletion if there is no KEY column used in the WHERE statement of a deletion.
1939
+		// to get around this, we first do a SELECT, get all the IDs, and then run another query
1940
+		// to delete them
1941
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1942
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1943
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1944
+			$columns_and_ids_for_deleting
1945
+		);
1946
+		/**
1947
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1948
+		 *
1949
+		 * @param EEM_Base $this  The model instance being acted on.
1950
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1951
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1952
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1953
+		 *                                                  derived from the incoming query parameters.
1954
+		 *                                                  @see details on the structure of this array in the phpdocs
1955
+		 *                                                  for the `_get_ids_for_delete_method`
1956
+		 *
1957
+		 */
1958
+		do_action(
1959
+			'AHEE__EEM_Base__delete__before_query',
1960
+			$this,
1961
+			$query_params,
1962
+			$allow_blocking,
1963
+			$columns_and_ids_for_deleting
1964
+		);
1965
+		if ($deletion_where_query_part) {
1966
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1967
+			$table_aliases = array_keys($this->_tables);
1968
+			$SQL = "DELETE "
1969
+				   . implode(", ", $table_aliases)
1970
+				   . " FROM "
1971
+				   . $model_query_info->get_full_join_sql()
1972
+				   . " WHERE "
1973
+				   . $deletion_where_query_part;
1974
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1975
+		} else {
1976
+			$rows_deleted = 0;
1977
+		}
1978
+
1979
+		// Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1980
+		// there was no error with the delete query.
1981
+		if ($this->has_primary_key_field()
1982
+			&& $rows_deleted !== false
1983
+			&& isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1984
+		) {
1985
+			$ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1986
+			foreach ($ids_for_removal as $id) {
1987
+				if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
+					unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1989
+				}
1990
+			}
1991
+
1992
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1993
+			// `EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
1994
+			// unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
1995
+			// (although it is possible).
1996
+			// Note this can be skipped by using the provided filter and returning false.
1997
+			if (apply_filters(
1998
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
1999
+				! $this instanceof EEM_Extra_Meta,
2000
+				$this
2001
+			)) {
2002
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2003
+					0 => array(
2004
+						'EXM_type' => $this->get_this_model_name(),
2005
+						'OBJ_ID'   => array(
2006
+							'IN',
2007
+							$ids_for_removal
2008
+						)
2009
+					)
2010
+				));
2011
+			}
2012
+		}
2013
+
2014
+		/**
2015
+		 * Action called just after performing a real deletion query. Although at this point the
2016
+		 * items should have been deleted
2017
+		 *
2018
+		 * @param EEM_Base $model
2019
+		 * @param array    $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2020
+		 * @param int      $rows_deleted
2021
+		 */
2022
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
+		return $rows_deleted;// how many supposedly got deleted
2024
+	}
2025
+
2026
+
2027
+
2028
+	/**
2029
+	 * Checks all the relations that throw error messages when there are blocking related objects
2030
+	 * for related model objects. If there are any related model objects on those relations,
2031
+	 * adds an EE_Error, and return true
2032
+	 *
2033
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2034
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2035
+	 *                                                 should be ignored when determining whether there are related
2036
+	 *                                                 model objects which block this model object's deletion. Useful
2037
+	 *                                                 if you know A is related to B and are considering deleting A,
2038
+	 *                                                 but want to see if A has any other objects blocking its deletion
2039
+	 *                                                 before removing the relation between A and B
2040
+	 * @return boolean
2041
+	 * @throws EE_Error
2042
+	 */
2043
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2044
+	{
2045
+		// first, if $ignore_this_model_obj was supplied, get its model
2046
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2047
+			$ignored_model = $ignore_this_model_obj->get_model();
2048
+		} else {
2049
+			$ignored_model = null;
2050
+		}
2051
+		// now check all the relations of $this_model_obj_or_id and see if there
2052
+		// are any related model objects blocking it?
2053
+		$is_blocked = false;
2054
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2055
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2056
+				// if $ignore_this_model_obj was supplied, then for the query
2057
+				// on that model needs to be told to ignore $ignore_this_model_obj
2058
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2059
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2060
+						array(
2061
+							$ignored_model->get_primary_key_field()->get_name() => array(
2062
+								'!=',
2063
+								$ignore_this_model_obj->ID(),
2064
+							),
2065
+						),
2066
+					));
2067
+				} else {
2068
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2069
+				}
2070
+				if ($related_model_objects) {
2071
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2072
+					$is_blocked = true;
2073
+				}
2074
+			}
2075
+		}
2076
+		return $is_blocked;
2077
+	}
2078
+
2079
+
2080
+	/**
2081
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2082
+	 * @param array $row_results_for_deleting
2083
+	 * @param bool  $allow_blocking
2084
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2085
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2086
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2087
+	 *                 deleted. Example:
2088
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2089
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2090
+	 *                 where each element is a group of columns and values that get deleted. Example:
2091
+	 *                      array(
2092
+	 *                          0 => array(
2093
+	 *                              'Term_Relationship.object_id' => 1
2094
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2095
+	 *                          ),
2096
+	 *                          1 => array(
2097
+	 *                              'Term_Relationship.object_id' => 1
2098
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2099
+	 *                          )
2100
+	 *                      )
2101
+	 * @throws EE_Error
2102
+	 */
2103
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2104
+	{
2105
+		$ids_to_delete_indexed_by_column = array();
2106
+		if ($this->has_primary_key_field()) {
2107
+			$primary_table = $this->_get_main_table();
2108
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2109
+			$other_tables = $this->_get_other_tables();
2110
+			$ids_to_delete_indexed_by_column = $query = array();
2111
+			foreach ($row_results_for_deleting as $item_to_delete) {
2112
+				// before we mark this item for deletion,
2113
+				// make sure there's no related entities blocking its deletion (if we're checking)
2114
+				if ($allow_blocking
2115
+					&& $this->delete_is_blocked_by_related_models(
2116
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2117
+					)
2118
+				) {
2119
+					continue;
2120
+				}
2121
+				// primary table deletes
2122
+				if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
+					$ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
+						$item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2125
+				}
2126
+			}
2127
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2128
+			$fields = $this->get_combined_primary_key_fields();
2129
+			foreach ($row_results_for_deleting as $item_to_delete) {
2130
+				$ids_to_delete_indexed_by_column_for_row = array();
2131
+				foreach ($fields as $cpk_field) {
2132
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2133
+						$ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
+							$item_to_delete[ $cpk_field->get_qualified_column() ];
2135
+					}
2136
+				}
2137
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2138
+			}
2139
+		} else {
2140
+			// so there's no primary key and no combined key...
2141
+			// sorry, can't help you
2142
+			throw new EE_Error(
2143
+				sprintf(
2144
+					__(
2145
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2146
+						"event_espresso"
2147
+					),
2148
+					get_class($this)
2149
+				)
2150
+			);
2151
+		}
2152
+		return $ids_to_delete_indexed_by_column;
2153
+	}
2154
+
2155
+
2156
+	/**
2157
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2158
+	 * the corresponding query_part for the query performing the delete.
2159
+	 *
2160
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2161
+	 * @return string
2162
+	 * @throws EE_Error
2163
+	 */
2164
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column)
2165
+	{
2166
+		$query_part = '';
2167
+		if (empty($ids_to_delete_indexed_by_column)) {
2168
+			return $query_part;
2169
+		} elseif ($this->has_primary_key_field()) {
2170
+			$query = array();
2171
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172
+				// make sure we have unique $ids
2173
+				$ids = array_unique($ids);
2174
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2175
+			}
2176
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2178
+			$ways_to_identify_a_row = array();
2179
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180
+				$values_for_each_combined_primary_key_for_a_row = array();
2181
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2183
+				}
2184
+				$ways_to_identify_a_row[] = '('
2185
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2186
+											. ')';
2187
+			}
2188
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2189
+		}
2190
+		return $query_part;
2191
+	}
2192
+
2193
+
2194
+
2195
+	/**
2196
+	 * Gets the model field by the fully qualified name
2197
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2198
+	 * @return EE_Model_Field_Base
2199
+	 */
2200
+	public function get_field_by_column($qualified_column_name)
2201
+	{
2202
+		foreach ($this->field_settings(true) as $field_name => $field_obj) {
2203
+			if ($field_obj->get_qualified_column() === $qualified_column_name) {
2204
+				return $field_obj;
2205
+			}
2206
+		}
2207
+		throw new EE_Error(
2208
+			sprintf(
2209
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2210
+				$this->get_this_model_name(),
2211
+				$qualified_column_name
2212
+			)
2213
+		);
2214
+	}
2215
+
2216
+
2217
+
2218
+	/**
2219
+	 * Count all the rows that match criteria the model query params.
2220
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2221
+	 * column
2222
+	 *
2223
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2224
+	 * @param string $field_to_count field on model to count by (not column name)
2225
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2226
+	 *                               that by the setting $distinct to TRUE;
2227
+	 * @return int
2228
+	 * @throws EE_Error
2229
+	 */
2230
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2231
+	{
2232
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2233
+		if ($field_to_count) {
2234
+			$field_obj = $this->field_settings_for($field_to_count);
2235
+			$column_to_count = $field_obj->get_qualified_column();
2236
+		} elseif ($this->has_primary_key_field()) {
2237
+			$pk_field_obj = $this->get_primary_key_field();
2238
+			$column_to_count = $pk_field_obj->get_qualified_column();
2239
+		} else {
2240
+			// there's no primary key
2241
+			// if we're counting distinct items, and there's no primary key,
2242
+			// we need to list out the columns for distinction;
2243
+			// otherwise we can just use star
2244
+			if ($distinct) {
2245
+				$columns_to_use = array();
2246
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2247
+					$columns_to_use[] = $field_obj->get_qualified_column();
2248
+				}
2249
+				$column_to_count = implode(',', $columns_to_use);
2250
+			} else {
2251
+				$column_to_count = '*';
2252
+			}
2253
+		}
2254
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2256
+		return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257
+	}
2258
+
2259
+
2260
+
2261
+	/**
2262
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2263
+	 *
2264
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2265
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2266
+	 * @return float
2267
+	 * @throws EE_Error
2268
+	 */
2269
+	public function sum($query_params, $field_to_sum = null)
2270
+	{
2271
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2272
+		if ($field_to_sum) {
2273
+			$field_obj = $this->field_settings_for($field_to_sum);
2274
+		} else {
2275
+			$field_obj = $this->get_primary_key_field();
2276
+		}
2277
+		$column_to_count = $field_obj->get_qualified_column();
2278
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2279
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280
+		$data_type = $field_obj->get_wpdb_data_type();
2281
+		if ($data_type === '%d' || $data_type === '%s') {
2282
+			return (float) $return_value;
2283
+		}
2284
+		// must be %f
2285
+		return (float) $return_value;
2286
+	}
2287
+
2288
+
2289
+
2290
+	/**
2291
+	 * Just calls the specified method on $wpdb with the given arguments
2292
+	 * Consolidates a little extra error handling code
2293
+	 *
2294
+	 * @param string $wpdb_method
2295
+	 * @param array  $arguments_to_provide
2296
+	 * @throws EE_Error
2297
+	 * @global wpdb  $wpdb
2298
+	 * @return mixed
2299
+	 */
2300
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2301
+	{
2302
+		// if we're in maintenance mode level 2, DON'T run any queries
2303
+		// because level 2 indicates the database needs updating and
2304
+		// is probably out of sync with the code
2305
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2306
+			throw new EE_Error(sprintf(__(
2307
+				"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.",
2308
+				"event_espresso"
2309
+			)));
2310
+		}
2311
+		/** @type WPDB $wpdb */
2312
+		global $wpdb;
2313
+		if (! method_exists($wpdb, $wpdb_method)) {
2314
+			throw new EE_Error(sprintf(__(
2315
+				'There is no method named "%s" on Wordpress\' $wpdb object',
2316
+				'event_espresso'
2317
+			), $wpdb_method));
2318
+		}
2319
+		if (WP_DEBUG) {
2320
+			$old_show_errors_value = $wpdb->show_errors;
2321
+			$wpdb->show_errors(false);
2322
+		}
2323
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2324
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2325
+		if (WP_DEBUG) {
2326
+			$wpdb->show_errors($old_show_errors_value);
2327
+			if (! empty($wpdb->last_error)) {
2328
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329
+			}
2330
+			if ($result === false) {
2331
+				throw new EE_Error(sprintf(__(
2332
+					'WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
+					'event_espresso'
2334
+				), $wpdb_method, var_export($arguments_to_provide, true)));
2335
+			}
2336
+		} elseif ($result === false) {
2337
+			EE_Error::add_error(
2338
+				sprintf(
2339
+					__(
2340
+						'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"',
2341
+						'event_espresso'
2342
+					),
2343
+					$wpdb_method,
2344
+					var_export($arguments_to_provide, true),
2345
+					$wpdb->last_error
2346
+				),
2347
+				__FILE__,
2348
+				__FUNCTION__,
2349
+				__LINE__
2350
+			);
2351
+		}
2352
+		return $result;
2353
+	}
2354
+
2355
+
2356
+
2357
+	/**
2358
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2359
+	 * and if there's an error tries to verify the DB is correct. Uses
2360
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2361
+	 * we should try to fix the EE core db, the addons, or just give up
2362
+	 *
2363
+	 * @param string $wpdb_method
2364
+	 * @param array  $arguments_to_provide
2365
+	 * @return mixed
2366
+	 */
2367
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2368
+	{
2369
+		/** @type WPDB $wpdb */
2370
+		global $wpdb;
2371
+		$wpdb->last_error = null;
2372
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2373
+		// was there an error running the query? but we don't care on new activations
2374
+		// (we're going to setup the DB anyway on new activations)
2375
+		if (($result === false || ! empty($wpdb->last_error))
2376
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2377
+		) {
2378
+			switch (EEM_Base::$_db_verification_level) {
2379
+				case EEM_Base::db_verified_none:
2380
+					// let's double-check core's DB
2381
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2382
+					break;
2383
+				case EEM_Base::db_verified_core:
2384
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2385
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2386
+					break;
2387
+				case EEM_Base::db_verified_addons:
2388
+					// ummmm... you in trouble
2389
+					return $result;
2390
+					break;
2391
+			}
2392
+			if (! empty($error_message)) {
2393
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394
+				trigger_error($error_message);
2395
+			}
2396
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2397
+		}
2398
+		return $result;
2399
+	}
2400
+
2401
+
2402
+
2403
+	/**
2404
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2405
+	 * EEM_Base::$_db_verification_level
2406
+	 *
2407
+	 * @param string $wpdb_method
2408
+	 * @param array  $arguments_to_provide
2409
+	 * @return string
2410
+	 */
2411
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2412
+	{
2413
+		/** @type WPDB $wpdb */
2414
+		global $wpdb;
2415
+		// ok remember that we've already attempted fixing the core db, in case the problem persists
2416
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2417
+		$error_message = sprintf(
2418
+			__(
2419
+				'WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2420
+				'event_espresso'
2421
+			),
2422
+			$wpdb->last_error,
2423
+			$wpdb_method,
2424
+			wp_json_encode($arguments_to_provide)
2425
+		);
2426
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2427
+		return $error_message;
2428
+	}
2429
+
2430
+
2431
+
2432
+	/**
2433
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2434
+	 * EEM_Base::$_db_verification_level
2435
+	 *
2436
+	 * @param $wpdb_method
2437
+	 * @param $arguments_to_provide
2438
+	 * @return string
2439
+	 */
2440
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2441
+	{
2442
+		/** @type WPDB $wpdb */
2443
+		global $wpdb;
2444
+		// ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2445
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2446
+		$error_message = sprintf(
2447
+			__(
2448
+				'WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2449
+				'event_espresso'
2450
+			),
2451
+			$wpdb->last_error,
2452
+			$wpdb_method,
2453
+			wp_json_encode($arguments_to_provide)
2454
+		);
2455
+		EE_System::instance()->initialize_addons();
2456
+		return $error_message;
2457
+	}
2458
+
2459
+
2460
+
2461
+	/**
2462
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2463
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2464
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2465
+	 * ..."
2466
+	 *
2467
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2468
+	 * @return string
2469
+	 */
2470
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471
+	{
2472
+		return " FROM " . $model_query_info->get_full_join_sql() .
2473
+			   $model_query_info->get_where_sql() .
2474
+			   $model_query_info->get_group_by_sql() .
2475
+			   $model_query_info->get_having_sql() .
2476
+			   $model_query_info->get_order_by_sql() .
2477
+			   $model_query_info->get_limit_sql();
2478
+	}
2479
+
2480
+
2481
+
2482
+	/**
2483
+	 * Set to easily debug the next X queries ran from this model.
2484
+	 *
2485
+	 * @param int $count
2486
+	 */
2487
+	public function show_next_x_db_queries($count = 1)
2488
+	{
2489
+		$this->_show_next_x_db_queries = $count;
2490
+	}
2491
+
2492
+
2493
+
2494
+	/**
2495
+	 * @param $sql_query
2496
+	 */
2497
+	public function show_db_query_if_previously_requested($sql_query)
2498
+	{
2499
+		if ($this->_show_next_x_db_queries > 0) {
2500
+			echo $sql_query;
2501
+			$this->_show_next_x_db_queries--;
2502
+		}
2503
+	}
2504
+
2505
+
2506
+
2507
+	/**
2508
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2509
+	 * There are the 3 cases:
2510
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2511
+	 * $otherModelObject has no ID, it is first saved.
2512
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2513
+	 * has no ID, it is first saved.
2514
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2515
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2516
+	 * join table
2517
+	 *
2518
+	 * @param        EE_Base_Class                     /int $thisModelObject
2519
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2520
+	 * @param string $relationName                     , key in EEM_Base::_relations
2521
+	 *                                                 an attendee to a group, you also want to specify which role they
2522
+	 *                                                 will have in that group. So you would use this parameter to
2523
+	 *                                                 specify array('role-column-name'=>'role-id')
2524
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2525
+	 *                                                 to for relation to methods that allow you to further specify
2526
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2527
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2528
+	 *                                                 because these will be inserted in any new rows created as well.
2529
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2530
+	 * @throws EE_Error
2531
+	 */
2532
+	public function add_relationship_to(
2533
+		$id_or_obj,
2534
+		$other_model_id_or_obj,
2535
+		$relationName,
2536
+		$extra_join_model_fields_n_values = array()
2537
+	) {
2538
+		$relation_obj = $this->related_settings_for($relationName);
2539
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2540
+	}
2541
+
2542
+
2543
+
2544
+	/**
2545
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2546
+	 * There are the 3 cases:
2547
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2548
+	 * error
2549
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2550
+	 * an error
2551
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2552
+	 *
2553
+	 * @param        EE_Base_Class /int $id_or_obj
2554
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2555
+	 * @param string $relationName key in EEM_Base::_relations
2556
+	 * @return boolean of success
2557
+	 * @throws EE_Error
2558
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2559
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2560
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2561
+	 *                             because these will be inserted in any new rows created as well.
2562
+	 */
2563
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2564
+	{
2565
+		$relation_obj = $this->related_settings_for($relationName);
2566
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2567
+	}
2568
+
2569
+
2570
+
2571
+	/**
2572
+	 * @param mixed           $id_or_obj
2573
+	 * @param string          $relationName
2574
+	 * @param array           $where_query_params
2575
+	 * @param EE_Base_Class[] objects to which relations were removed
2576
+	 * @return \EE_Base_Class[]
2577
+	 * @throws EE_Error
2578
+	 */
2579
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2580
+	{
2581
+		$relation_obj = $this->related_settings_for($relationName);
2582
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2583
+	}
2584
+
2585
+
2586
+
2587
+	/**
2588
+	 * Gets all the related items of the specified $model_name, using $query_params.
2589
+	 * Note: by default, we remove the "default query params"
2590
+	 * because we want to get even deleted items etc.
2591
+	 *
2592
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2593
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2594
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2595
+	 * @return EE_Base_Class[]
2596
+	 * @throws EE_Error
2597
+	 */
2598
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2599
+	{
2600
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2601
+		$relation_settings = $this->related_settings_for($model_name);
2602
+		return $relation_settings->get_all_related($model_obj, $query_params);
2603
+	}
2604
+
2605
+
2606
+
2607
+	/**
2608
+	 * Deletes all the model objects across the relation indicated by $model_name
2609
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2610
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2611
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2612
+	 *
2613
+	 * @param EE_Base_Class|int|string $id_or_obj
2614
+	 * @param string                   $model_name
2615
+	 * @param array                    $query_params
2616
+	 * @return int how many deleted
2617
+	 * @throws EE_Error
2618
+	 */
2619
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2620
+	{
2621
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2622
+		$relation_settings = $this->related_settings_for($model_name);
2623
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2624
+	}
2625
+
2626
+
2627
+
2628
+	/**
2629
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2630
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2631
+	 * the model objects can't be hard deleted because of blocking related model objects,
2632
+	 * just does a soft-delete on them instead.
2633
+	 *
2634
+	 * @param EE_Base_Class|int|string $id_or_obj
2635
+	 * @param string                   $model_name
2636
+	 * @param array                    $query_params
2637
+	 * @return int how many deleted
2638
+	 * @throws EE_Error
2639
+	 */
2640
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2641
+	{
2642
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2643
+		$relation_settings = $this->related_settings_for($model_name);
2644
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2645
+	}
2646
+
2647
+
2648
+
2649
+	/**
2650
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2651
+	 * unless otherwise specified in the $query_params
2652
+	 *
2653
+	 * @param        int             /EE_Base_Class $id_or_obj
2654
+	 * @param string $model_name     like 'Event', or 'Registration'
2655
+	 * @param array  $query_params   @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2656
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2657
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2658
+	 *                               that by the setting $distinct to TRUE;
2659
+	 * @return int
2660
+	 * @throws EE_Error
2661
+	 */
2662
+	public function count_related(
2663
+		$id_or_obj,
2664
+		$model_name,
2665
+		$query_params = array(),
2666
+		$field_to_count = null,
2667
+		$distinct = false
2668
+	) {
2669
+		$related_model = $this->get_related_model_obj($model_name);
2670
+		// we're just going to use the query params on the related model's normal get_all query,
2671
+		// except add a condition to say to match the current mod
2672
+		if (! isset($query_params['default_where_conditions'])) {
2673
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674
+		}
2675
+		$this_model_name = $this->get_this_model_name();
2676
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2678
+		return $related_model->count($query_params, $field_to_count, $distinct);
2679
+	}
2680
+
2681
+
2682
+
2683
+	/**
2684
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2685
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2686
+	 *
2687
+	 * @param        int           /EE_Base_Class $id_or_obj
2688
+	 * @param string $model_name   like 'Event', or 'Registration'
2689
+	 * @param array  $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2690
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2691
+	 * @return float
2692
+	 * @throws EE_Error
2693
+	 */
2694
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695
+	{
2696
+		$related_model = $this->get_related_model_obj($model_name);
2697
+		if (! is_array($query_params)) {
2698
+			EE_Error::doing_it_wrong(
2699
+				'EEM_Base::sum_related',
2700
+				sprintf(
2701
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2702
+					gettype($query_params)
2703
+				),
2704
+				'4.6.0'
2705
+			);
2706
+			$query_params = array();
2707
+		}
2708
+		// we're just going to use the query params on the related model's normal get_all query,
2709
+		// except add a condition to say to match the current mod
2710
+		if (! isset($query_params['default_where_conditions'])) {
2711
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712
+		}
2713
+		$this_model_name = $this->get_this_model_name();
2714
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
+		$query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2716
+		return $related_model->sum($query_params, $field_to_sum);
2717
+	}
2718
+
2719
+
2720
+
2721
+	/**
2722
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2723
+	 * $modelObject
2724
+	 *
2725
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2726
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2727
+	 * @param array               $query_params     @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
2728
+	 * @return EE_Base_Class
2729
+	 * @throws EE_Error
2730
+	 */
2731
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2732
+	{
2733
+		$query_params['limit'] = 1;
2734
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2735
+		if ($results) {
2736
+			return array_shift($results);
2737
+		}
2738
+		return null;
2739
+	}
2740
+
2741
+
2742
+
2743
+	/**
2744
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2745
+	 *
2746
+	 * @return string
2747
+	 */
2748
+	public function get_this_model_name()
2749
+	{
2750
+		return str_replace("EEM_", "", get_class($this));
2751
+	}
2752
+
2753
+
2754
+
2755
+	/**
2756
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2757
+	 *
2758
+	 * @return EE_Any_Foreign_Model_Name_Field
2759
+	 * @throws EE_Error
2760
+	 */
2761
+	public function get_field_containing_related_model_name()
2762
+	{
2763
+		foreach ($this->field_settings(true) as $field) {
2764
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2765
+				$field_with_model_name = $field;
2766
+			}
2767
+		}
2768
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2769
+			throw new EE_Error(sprintf(
2770
+				__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771
+				$this->get_this_model_name()
2772
+			));
2773
+		}
2774
+		return $field_with_model_name;
2775
+	}
2776
+
2777
+
2778
+
2779
+	/**
2780
+	 * Inserts a new entry into the database, for each table.
2781
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2782
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2783
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2784
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2785
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2786
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2787
+	 *
2788
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2789
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2790
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2791
+	 *                              of EEM_Base)
2792
+	 * @return int|string new primary key on main table that got inserted
2793
+	 * @throws EE_Error
2794
+	 */
2795
+	public function insert($field_n_values)
2796
+	{
2797
+		/**
2798
+		 * Filters the fields and their values before inserting an item using the models
2799
+		 *
2800
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2801
+		 * @param EEM_Base $model           the model used
2802
+		 */
2803
+		$field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2804
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2805
+			$main_table = $this->_get_main_table();
2806
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2807
+			if ($new_id !== false) {
2808
+				foreach ($this->_get_other_tables() as $other_table) {
2809
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2810
+				}
2811
+			}
2812
+			/**
2813
+			 * Done just after attempting to insert a new model object
2814
+			 *
2815
+			 * @param EEM_Base   $model           used
2816
+			 * @param array      $fields_n_values fields and their values
2817
+			 * @param int|string the              ID of the newly-inserted model object
2818
+			 */
2819
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2820
+			return $new_id;
2821
+		}
2822
+		return false;
2823
+	}
2824
+
2825
+
2826
+
2827
+	/**
2828
+	 * Checks that the result would satisfy the unique indexes on this model
2829
+	 *
2830
+	 * @param array  $field_n_values
2831
+	 * @param string $action
2832
+	 * @return boolean
2833
+	 * @throws EE_Error
2834
+	 */
2835
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2836
+	{
2837
+		foreach ($this->unique_indexes() as $index_name => $index) {
2838
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2839
+			if ($this->exists(array($uniqueness_where_params))) {
2840
+				EE_Error::add_error(
2841
+					sprintf(
2842
+						__(
2843
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2844
+							"event_espresso"
2845
+						),
2846
+						$action,
2847
+						$this->_get_class_name(),
2848
+						$index_name,
2849
+						implode(",", $index->field_names()),
2850
+						http_build_query($uniqueness_where_params)
2851
+					),
2852
+					__FILE__,
2853
+					__FUNCTION__,
2854
+					__LINE__
2855
+				);
2856
+				return false;
2857
+			}
2858
+		}
2859
+		return true;
2860
+	}
2861
+
2862
+
2863
+
2864
+	/**
2865
+	 * Checks the database for an item that conflicts (ie, if this item were
2866
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2867
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2868
+	 * can be either an EE_Base_Class or an array of fields n values
2869
+	 *
2870
+	 * @param EE_Base_Class|array $obj_or_fields_array
2871
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2872
+	 *                                                 when looking for conflicts
2873
+	 *                                                 (ie, if false, we ignore the model object's primary key
2874
+	 *                                                 when finding "conflicts". If true, it's also considered).
2875
+	 *                                                 Only works for INT primary key,
2876
+	 *                                                 STRING primary keys cannot be ignored
2877
+	 * @throws EE_Error
2878
+	 * @return EE_Base_Class|array
2879
+	 */
2880
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2881
+	{
2882
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2883
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2884
+		} elseif (is_array($obj_or_fields_array)) {
2885
+			$fields_n_values = $obj_or_fields_array;
2886
+		} else {
2887
+			throw new EE_Error(
2888
+				sprintf(
2889
+					__(
2890
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2891
+						"event_espresso"
2892
+					),
2893
+					get_class($this),
2894
+					$obj_or_fields_array
2895
+				)
2896
+			);
2897
+		}
2898
+		$query_params = array();
2899
+		if ($this->has_primary_key_field()
2900
+			&& ($include_primary_key
2901
+				|| $this->get_primary_key_field()
2902
+				   instanceof
2903
+				   EE_Primary_Key_String_Field)
2904
+			&& isset($fields_n_values[ $this->primary_key_name() ])
2905
+		) {
2906
+			$query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2907
+		}
2908
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
+			$query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2911
+		}
2912
+		// if there is nothing to base this search on, then we shouldn't find anything
2913
+		if (empty($query_params)) {
2914
+			return array();
2915
+		}
2916
+		return $this->get_one($query_params);
2917
+	}
2918
+
2919
+
2920
+
2921
+	/**
2922
+	 * Like count, but is optimized and returns a boolean instead of an int
2923
+	 *
2924
+	 * @param array $query_params
2925
+	 * @return boolean
2926
+	 * @throws EE_Error
2927
+	 */
2928
+	public function exists($query_params)
2929
+	{
2930
+		$query_params['limit'] = 1;
2931
+		return $this->count($query_params) > 0;
2932
+	}
2933
+
2934
+
2935
+
2936
+	/**
2937
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2938
+	 *
2939
+	 * @param int|string $id
2940
+	 * @return boolean
2941
+	 * @throws EE_Error
2942
+	 */
2943
+	public function exists_by_ID($id)
2944
+	{
2945
+		return $this->exists(
2946
+			array(
2947
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2948
+				array(
2949
+					$this->primary_key_name() => $id,
2950
+				),
2951
+			)
2952
+		);
2953
+	}
2954
+
2955
+
2956
+
2957
+	/**
2958
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2959
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2960
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2961
+	 * on the main table)
2962
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2963
+	 * cases where we want to call it directly rather than via insert().
2964
+	 *
2965
+	 * @access   protected
2966
+	 * @param EE_Table_Base $table
2967
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2968
+	 *                                       float
2969
+	 * @param int           $new_id          for now we assume only int keys
2970
+	 * @throws EE_Error
2971
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2972
+	 * @return int ID of new row inserted, or FALSE on failure
2973
+	 */
2974
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2975
+	{
2976
+		global $wpdb;
2977
+		$insertion_col_n_values = array();
2978
+		$format_for_insertion = array();
2979
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2980
+		foreach ($fields_on_table as $field_name => $field_obj) {
2981
+			// check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2982
+			if ($field_obj->is_auto_increment()) {
2983
+				continue;
2984
+			}
2985
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986
+			// if the value we want to assign it to is NULL, just don't mention it for the insertion
2987
+			if ($prepared_value !== null) {
2988
+				$insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2989
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990
+			}
2991
+		}
2992
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2993
+			// its not the main table, so we should have already saved the main table's PK which we just inserted
2994
+			// so add the fk to the main table as a column
2995
+			$insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
+			$format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2997
+		}
2998
+		// insert the new entry
2999
+		$result = $this->_do_wpdb_query(
3000
+			'insert',
3001
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion)
3002
+		);
3003
+		if ($result === false) {
3004
+			return false;
3005
+		}
3006
+		// ok, now what do we return for the ID of the newly-inserted thing?
3007
+		if ($this->has_primary_key_field()) {
3008
+			if ($this->get_primary_key_field()->is_auto_increment()) {
3009
+				return $wpdb->insert_id;
3010
+			}
3011
+			// it's not an auto-increment primary key, so
3012
+			// it must have been supplied
3013
+			return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3014
+		}
3015
+		// we can't return a  primary key because there is none. instead return
3016
+		// a unique string indicating this model
3017
+		return $this->get_index_primary_key_string($fields_n_values);
3018
+	}
3019
+
3020
+
3021
+
3022
+	/**
3023
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3024
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3025
+	 * and there is no default, we pass it along. WPDB will take care of it)
3026
+	 *
3027
+	 * @param EE_Model_Field_Base $field_obj
3028
+	 * @param array               $fields_n_values
3029
+	 * @return mixed string|int|float depending on what the table column will be expecting
3030
+	 * @throws EE_Error
3031
+	 */
3032
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033
+	{
3034
+		// if this field doesn't allow nullable, don't allow it
3035
+		if (! $field_obj->is_nullable()
3036
+			&& (
3037
+				! isset($fields_n_values[ $field_obj->get_name() ])
3038
+				|| $fields_n_values[ $field_obj->get_name() ] === null
3039
+			)
3040
+		) {
3041
+			$fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3042
+		}
3043
+		$unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
+			? $fields_n_values[ $field_obj->get_name() ]
3045
+			: null;
3046
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047
+	}
3048
+
3049
+
3050
+
3051
+	/**
3052
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3053
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3054
+	 * the field's prepare_for_set() method.
3055
+	 *
3056
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3057
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3058
+	 *                                   top of file)
3059
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3060
+	 *                                   $value is a custom selection
3061
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3062
+	 */
3063
+	private function _prepare_value_for_use_in_db($value, $field)
3064
+	{
3065
+		if ($field && $field instanceof EE_Model_Field_Base) {
3066
+			// phpcs:disable PSR2.ControlStructures.SwitchDeclaration.TerminatingComment
3067
+			switch ($this->_values_already_prepared_by_model_object) {
3068
+				/** @noinspection PhpMissingBreakStatementInspection */
3069
+				case self::not_prepared_by_model_object:
3070
+					$value = $field->prepare_for_set($value);
3071
+				// purposefully left out "return"
3072
+				case self::prepared_by_model_object:
3073
+					/** @noinspection SuspiciousAssignmentsInspection */
3074
+					$value = $field->prepare_for_use_in_db($value);
3075
+				case self::prepared_for_use_in_db:
3076
+					// leave the value alone
3077
+			}
3078
+			return $value;
3079
+			// phpcs:enable
3080
+		}
3081
+		return $value;
3082
+	}
3083
+
3084
+
3085
+
3086
+	/**
3087
+	 * Returns the main table on this model
3088
+	 *
3089
+	 * @return EE_Primary_Table
3090
+	 * @throws EE_Error
3091
+	 */
3092
+	protected function _get_main_table()
3093
+	{
3094
+		foreach ($this->_tables as $table) {
3095
+			if ($table instanceof EE_Primary_Table) {
3096
+				return $table;
3097
+			}
3098
+		}
3099
+		throw new EE_Error(sprintf(__(
3100
+			'There are no main tables on %s. They should be added to _tables array in the constructor',
3101
+			'event_espresso'
3102
+		), get_class($this)));
3103
+	}
3104
+
3105
+
3106
+
3107
+	/**
3108
+	 * table
3109
+	 * returns EE_Primary_Table table name
3110
+	 *
3111
+	 * @return string
3112
+	 * @throws EE_Error
3113
+	 */
3114
+	public function table()
3115
+	{
3116
+		return $this->_get_main_table()->get_table_name();
3117
+	}
3118
+
3119
+
3120
+
3121
+	/**
3122
+	 * table
3123
+	 * returns first EE_Secondary_Table table name
3124
+	 *
3125
+	 * @return string
3126
+	 */
3127
+	public function second_table()
3128
+	{
3129
+		// grab second table from tables array
3130
+		$second_table = end($this->_tables);
3131
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3132
+	}
3133
+
3134
+
3135
+
3136
+	/**
3137
+	 * get_table_obj_by_alias
3138
+	 * returns table name given it's alias
3139
+	 *
3140
+	 * @param string $table_alias
3141
+	 * @return EE_Primary_Table | EE_Secondary_Table
3142
+	 */
3143
+	public function get_table_obj_by_alias($table_alias = '')
3144
+	{
3145
+		return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3146
+	}
3147
+
3148
+
3149
+
3150
+	/**
3151
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3152
+	 *
3153
+	 * @return EE_Secondary_Table[]
3154
+	 */
3155
+	protected function _get_other_tables()
3156
+	{
3157
+		$other_tables = array();
3158
+		foreach ($this->_tables as $table_alias => $table) {
3159
+			if ($table instanceof EE_Secondary_Table) {
3160
+				$other_tables[ $table_alias ] = $table;
3161
+			}
3162
+		}
3163
+		return $other_tables;
3164
+	}
3165
+
3166
+
3167
+
3168
+	/**
3169
+	 * Finds all the fields that correspond to the given table
3170
+	 *
3171
+	 * @param string $table_alias , array key in EEM_Base::_tables
3172
+	 * @return EE_Model_Field_Base[]
3173
+	 */
3174
+	public function _get_fields_for_table($table_alias)
3175
+	{
3176
+		return $this->_fields[ $table_alias ];
3177
+	}
3178
+
3179
+
3180
+
3181
+	/**
3182
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3183
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3184
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3185
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3186
+	 * related Registration, Transaction, and Payment models.
3187
+	 *
3188
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3189
+	 * @return EE_Model_Query_Info_Carrier
3190
+	 * @throws EE_Error
3191
+	 */
3192
+	public function _extract_related_models_from_query($query_params)
3193
+	{
3194
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3195
+		if (array_key_exists(0, $query_params)) {
3196
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3197
+		}
3198
+		if (array_key_exists('group_by', $query_params)) {
3199
+			if (is_array($query_params['group_by'])) {
3200
+				$this->_extract_related_models_from_sub_params_array_values(
3201
+					$query_params['group_by'],
3202
+					$query_info_carrier,
3203
+					'group_by'
3204
+				);
3205
+			} elseif (! empty($query_params['group_by'])) {
3206
+				$this->_extract_related_model_info_from_query_param(
3207
+					$query_params['group_by'],
3208
+					$query_info_carrier,
3209
+					'group_by'
3210
+				);
3211
+			}
3212
+		}
3213
+		if (array_key_exists('having', $query_params)) {
3214
+			$this->_extract_related_models_from_sub_params_array_keys(
3215
+				$query_params[0],
3216
+				$query_info_carrier,
3217
+				'having'
3218
+			);
3219
+		}
3220
+		if (array_key_exists('order_by', $query_params)) {
3221
+			if (is_array($query_params['order_by'])) {
3222
+				$this->_extract_related_models_from_sub_params_array_keys(
3223
+					$query_params['order_by'],
3224
+					$query_info_carrier,
3225
+					'order_by'
3226
+				);
3227
+			} elseif (! empty($query_params['order_by'])) {
3228
+				$this->_extract_related_model_info_from_query_param(
3229
+					$query_params['order_by'],
3230
+					$query_info_carrier,
3231
+					'order_by'
3232
+				);
3233
+			}
3234
+		}
3235
+		if (array_key_exists('force_join', $query_params)) {
3236
+			$this->_extract_related_models_from_sub_params_array_values(
3237
+				$query_params['force_join'],
3238
+				$query_info_carrier,
3239
+				'force_join'
3240
+			);
3241
+		}
3242
+		$this->extractRelatedModelsFromCustomSelects($query_info_carrier);
3243
+		return $query_info_carrier;
3244
+	}
3245
+
3246
+
3247
+
3248
+	/**
3249
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3250
+	 *
3251
+	 * @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
3252
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3253
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3254
+	 * @throws EE_Error
3255
+	 * @return \EE_Model_Query_Info_Carrier
3256
+	 */
3257
+	private function _extract_related_models_from_sub_params_array_keys(
3258
+		$sub_query_params,
3259
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260
+		$query_param_type
3261
+	) {
3262
+		if (! empty($sub_query_params)) {
3263
+			$sub_query_params = (array) $sub_query_params;
3264
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3266
+				$this->_extract_related_model_info_from_query_param(
3267
+					$param,
3268
+					$model_query_info_carrier,
3269
+					$query_param_type
3270
+				);
3271
+				// if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3272
+				// indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3273
+				// extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3274
+				// of array('Registration.TXN_ID'=>23)
3275
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
+					if (! is_array($possibly_array_of_params)) {
3278
+						throw new EE_Error(sprintf(
3279
+							__(
3280
+								"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'))",
3281
+								"event_espresso"
3282
+							),
3283
+							$param,
3284
+							$possibly_array_of_params
3285
+						));
3286
+					}
3287
+					$this->_extract_related_models_from_sub_params_array_keys(
3288
+						$possibly_array_of_params,
3289
+						$model_query_info_carrier,
3290
+						$query_param_type
3291
+					);
3292
+				} elseif ($query_param_type === 0 // ie WHERE
3293
+						  && is_array($possibly_array_of_params)
3294
+						  && isset($possibly_array_of_params[2])
3295
+						  && $possibly_array_of_params[2] == true
3296
+				) {
3297
+					// then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298
+					// indicating that $possible_array_of_params[1] is actually a field name,
3299
+					// from which we should extract query parameters!
3300
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301
+						throw new EE_Error(sprintf(__(
3302
+							"Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303
+							"event_espresso"
3304
+						), $query_param_type, implode(",", $possibly_array_of_params)));
3305
+					}
3306
+					$this->_extract_related_model_info_from_query_param(
3307
+						$possibly_array_of_params[1],
3308
+						$model_query_info_carrier,
3309
+						$query_param_type
3310
+					);
3311
+				}
3312
+			}
3313
+		}
3314
+		return $model_query_info_carrier;
3315
+	}
3316
+
3317
+
3318
+
3319
+	/**
3320
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3321
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3322
+	 *
3323
+	 * @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
3324
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3325
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3326
+	 * @throws EE_Error
3327
+	 * @return \EE_Model_Query_Info_Carrier
3328
+	 */
3329
+	private function _extract_related_models_from_sub_params_array_values(
3330
+		$sub_query_params,
3331
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332
+		$query_param_type
3333
+	) {
3334
+		if (! empty($sub_query_params)) {
3335
+			if (! is_array($sub_query_params)) {
3336
+				throw new EE_Error(sprintf(
3337
+					__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338
+					$sub_query_params
3339
+				));
3340
+			}
3341
+			foreach ($sub_query_params as $param) {
3342
+				// $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3343
+				$this->_extract_related_model_info_from_query_param(
3344
+					$param,
3345
+					$model_query_info_carrier,
3346
+					$query_param_type
3347
+				);
3348
+			}
3349
+		}
3350
+		return $model_query_info_carrier;
3351
+	}
3352
+
3353
+
3354
+	/**
3355
+	 * Extract all the query parts from  model query params
3356
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3357
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3358
+	 * but use them in a different order. Eg, we need to know what models we are querying
3359
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3360
+	 * other models before we can finalize the where clause SQL.
3361
+	 *
3362
+	 * @param array $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
3363
+	 * @throws EE_Error
3364
+	 * @return EE_Model_Query_Info_Carrier
3365
+	 * @throws ModelConfigurationException
3366
+	 */
3367
+	public function _create_model_query_info_carrier($query_params)
3368
+	{
3369
+		if (! is_array($query_params)) {
3370
+			EE_Error::doing_it_wrong(
3371
+				'EEM_Base::_create_model_query_info_carrier',
3372
+				sprintf(
3373
+					__(
3374
+						'$query_params should be an array, you passed a variable of type %s',
3375
+						'event_espresso'
3376
+					),
3377
+					gettype($query_params)
3378
+				),
3379
+				'4.6.0'
3380
+			);
3381
+			$query_params = array();
3382
+		}
3383
+		$query_params[0] = isset($query_params[0]) ? $query_params[0] : array();
3384
+		// first check if we should alter the query to account for caps or not
3385
+		// because the caps might require us to do extra joins
3386
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3387
+			$query_params[0] = array_replace_recursive(
3388
+				$query_params[0],
3389
+				$this->caps_where_conditions(
3390
+					$query_params['caps']
3391
+				)
3392
+			);
3393
+		}
3394
+
3395
+		// check if we should alter the query to remove data related to protected
3396
+		// custom post types
3397
+		if (isset($query_params['exclude_protected']) && $query_params['exclude_protected'] === true) {
3398
+			$where_param_key_for_password = $this->modelChainAndPassword();
3399
+			// only include if related to a cpt where no password has been set
3400
+			$query_params[0]['OR*nopassword'] = array(
3401
+				$where_param_key_for_password => '',
3402
+				$where_param_key_for_password . '*' => array('IS_NULL')
3403
+			);
3404
+		}
3405
+		$query_object = $this->_extract_related_models_from_query($query_params);
3406
+		// verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3407
+		foreach ($query_params[0] as $key => $value) {
3408
+			if (is_int($key)) {
3409
+				throw new EE_Error(
3410
+					sprintf(
3411
+						__(
3412
+							"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.",
3413
+							"event_espresso"
3414
+						),
3415
+						$key,
3416
+						var_export($value, true),
3417
+						var_export($query_params, true),
3418
+						get_class($this)
3419
+					)
3420
+				);
3421
+			}
3422
+		}
3423
+		if (array_key_exists('default_where_conditions', $query_params)
3424
+			&& ! empty($query_params['default_where_conditions'])
3425
+		) {
3426
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3427
+		} else {
3428
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3429
+		}
3430
+		$query_params[0] = array_merge(
3431
+			$this->_get_default_where_conditions_for_models_in_query(
3432
+				$query_object,
3433
+				$use_default_where_conditions,
3434
+				$query_params[0]
3435
+			),
3436
+			$query_params[0]
3437
+		);
3438
+		$query_object->set_where_sql($this->_construct_where_clause($query_params[0]));
3439
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3440
+		// So we need to setup a subquery and use that for the main join.
3441
+		// Note for now this only works on the primary table for the model.
3442
+		// So for instance, you could set the limit array like this:
3443
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3444
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3445
+			$query_object->set_main_model_join_sql(
3446
+				$this->_construct_limit_join_select(
3447
+					$query_params['on_join_limit'][0],
3448
+					$query_params['on_join_limit'][1]
3449
+				)
3450
+			);
3451
+		}
3452
+		// set limit
3453
+		if (array_key_exists('limit', $query_params)) {
3454
+			if (is_array($query_params['limit'])) {
3455
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456
+					$e = sprintf(
3457
+						__(
3458
+							"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)",
3459
+							"event_espresso"
3460
+						),
3461
+						http_build_query($query_params['limit'])
3462
+					);
3463
+					throw new EE_Error($e . "|" . $e);
3464
+				}
3465
+				// they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
+			} elseif (! empty($query_params['limit'])) {
3468
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3469
+			}
3470
+		}
3471
+		// set order by
3472
+		if (array_key_exists('order_by', $query_params)) {
3473
+			if (is_array($query_params['order_by'])) {
3474
+				// if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3475
+				// specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3476
+				// including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3477
+				if (array_key_exists('order', $query_params)) {
3478
+					throw new EE_Error(
3479
+						sprintf(
3480
+							__(
3481
+								"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 ",
3482
+								"event_espresso"
3483
+							),
3484
+							get_class($this),
3485
+							implode(", ", array_keys($query_params['order_by'])),
3486
+							implode(", ", $query_params['order_by']),
3487
+							$query_params['order']
3488
+						)
3489
+					);
3490
+				}
3491
+				$this->_extract_related_models_from_sub_params_array_keys(
3492
+					$query_params['order_by'],
3493
+					$query_object,
3494
+					'order_by'
3495
+				);
3496
+				// assume it's an array of fields to order by
3497
+				$order_array = array();
3498
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499
+					$order = $this->_extract_order($order);
3500
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3501
+				}
3502
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
+			} elseif (! empty($query_params['order_by'])) {
3504
+				$this->_extract_related_model_info_from_query_param(
3505
+					$query_params['order_by'],
3506
+					$query_object,
3507
+					'order',
3508
+					$query_params['order_by']
3509
+				);
3510
+				$order = isset($query_params['order'])
3511
+					? $this->_extract_order($query_params['order'])
3512
+					: 'DESC';
3513
+				$query_object->set_order_by_sql(
3514
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3515
+				);
3516
+			}
3517
+		}
3518
+		// if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
+		if (! array_key_exists('order_by', $query_params)
3520
+			&& array_key_exists('order', $query_params)
3521
+			&& ! empty($query_params['order'])
3522
+		) {
3523
+			$pk_field = $this->get_primary_key_field();
3524
+			$order = $this->_extract_order($query_params['order']);
3525
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3526
+		}
3527
+		// set group by
3528
+		if (array_key_exists('group_by', $query_params)) {
3529
+			if (is_array($query_params['group_by'])) {
3530
+				// it's an array, so assume we'll be grouping by a bunch of stuff
3531
+				$group_by_array = array();
3532
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534
+				}
3535
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
+			} elseif (! empty($query_params['group_by'])) {
3537
+				$query_object->set_group_by_sql(
3538
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3539
+				);
3540
+			}
3541
+		}
3542
+		// set having
3543
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3544
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3545
+		}
3546
+		// now, just verify they didn't pass anything wack
3547
+		foreach ($query_params as $query_key => $query_value) {
3548
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3549
+				throw new EE_Error(
3550
+					sprintf(
3551
+						__(
3552
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3553
+							'event_espresso'
3554
+						),
3555
+						$query_key,
3556
+						get_class($this),
3557
+						//                      print_r( $this->_allowed_query_params, TRUE )
3558
+						implode(',', $this->_allowed_query_params)
3559
+					)
3560
+				);
3561
+			}
3562
+		}
3563
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3564
+		if (empty($main_model_join_sql)) {
3565
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3566
+		}
3567
+		return $query_object;
3568
+	}
3569
+
3570
+
3571
+
3572
+	/**
3573
+	 * Gets the where conditions that should be imposed on the query based on the
3574
+	 * context (eg reading frontend, backend, edit or delete).
3575
+	 *
3576
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3577
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3578
+	 * @throws EE_Error
3579
+	 */
3580
+	public function caps_where_conditions($context = self::caps_read)
3581
+	{
3582
+		EEM_Base::verify_is_valid_cap_context($context);
3583
+		$cap_where_conditions = array();
3584
+		$cap_restrictions = $this->caps_missing($context);
3585
+		/**
3586
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3587
+		 */
3588
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3589
+			$cap_where_conditions = array_replace_recursive(
3590
+				$cap_where_conditions,
3591
+				$restriction_if_no_cap->get_default_where_conditions()
3592
+			);
3593
+		}
3594
+		return apply_filters(
3595
+			'FHEE__EEM_Base__caps_where_conditions__return',
3596
+			$cap_where_conditions,
3597
+			$this,
3598
+			$context,
3599
+			$cap_restrictions
3600
+		);
3601
+	}
3602
+
3603
+
3604
+
3605
+	/**
3606
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3607
+	 * otherwise throws an exception
3608
+	 *
3609
+	 * @param string $should_be_order_string
3610
+	 * @return string either ASC, asc, DESC or desc
3611
+	 * @throws EE_Error
3612
+	 */
3613
+	private function _extract_order($should_be_order_string)
3614
+	{
3615
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3616
+			return $should_be_order_string;
3617
+		}
3618
+		throw new EE_Error(
3619
+			sprintf(
3620
+				__(
3621
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3622
+					"event_espresso"
3623
+				),
3624
+				get_class($this),
3625
+				$should_be_order_string
3626
+			)
3627
+		);
3628
+	}
3629
+
3630
+
3631
+
3632
+	/**
3633
+	 * Looks at all the models which are included in this query, and asks each
3634
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3635
+	 * so they can be merged
3636
+	 *
3637
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3638
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3639
+	 *                                                                  'none' means NO default where conditions will
3640
+	 *                                                                  be used AT ALL during this query.
3641
+	 *                                                                  'other_models_only' means default where
3642
+	 *                                                                  conditions from other models will be used, but
3643
+	 *                                                                  not for this primary model. 'all', the default,
3644
+	 *                                                                  means default where conditions will apply as
3645
+	 *                                                                  normal
3646
+	 * @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
3647
+	 * @throws EE_Error
3648
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3649
+	 */
3650
+	private function _get_default_where_conditions_for_models_in_query(
3651
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3652
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3653
+		$where_query_params = array()
3654
+	) {
3655
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657
+			throw new EE_Error(sprintf(
3658
+				__(
3659
+					"You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3660
+					"event_espresso"
3661
+				),
3662
+				$use_default_where_conditions,
3663
+				implode(", ", $allowed_used_default_where_conditions_values)
3664
+			));
3665
+		}
3666
+		$universal_query_params = array();
3667
+		if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3668
+			$universal_query_params = $this->_get_default_where_conditions();
3669
+		} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3670
+			$universal_query_params = $this->_get_minimum_where_conditions();
3671
+		}
3672
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3673
+			$related_model = $this->get_related_model_obj($model_name);
3674
+			if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3675
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3676
+			} elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3677
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3678
+			} else {
3679
+				// we don't want to add full or even minimum default where conditions from this model, so just continue
3680
+				continue;
3681
+			}
3682
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3683
+				$related_model_universal_where_params,
3684
+				$where_query_params,
3685
+				$related_model,
3686
+				$model_relation_path
3687
+			);
3688
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3689
+				$universal_query_params,
3690
+				$overrides
3691
+			);
3692
+		}
3693
+		return $universal_query_params;
3694
+	}
3695
+
3696
+
3697
+
3698
+	/**
3699
+	 * Determines whether or not we should use default where conditions for the model in question
3700
+	 * (this model, or other related models).
3701
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3702
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3703
+	 * We should use default where conditions on related models when they requested to use default where conditions
3704
+	 * on all models, or specifically just on other related models
3705
+	 * @param      $default_where_conditions_value
3706
+	 * @param bool $for_this_model false means this is for OTHER related models
3707
+	 * @return bool
3708
+	 */
3709
+	private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3710
+	{
3711
+		return (
3712
+				   $for_this_model
3713
+				   && in_array(
3714
+					   $default_where_conditions_value,
3715
+					   array(
3716
+						   EEM_Base::default_where_conditions_all,
3717
+						   EEM_Base::default_where_conditions_this_only,
3718
+						   EEM_Base::default_where_conditions_minimum_others,
3719
+					   ),
3720
+					   true
3721
+				   )
3722
+			   )
3723
+			   || (
3724
+				   ! $for_this_model
3725
+				   && in_array(
3726
+					   $default_where_conditions_value,
3727
+					   array(
3728
+						   EEM_Base::default_where_conditions_all,
3729
+						   EEM_Base::default_where_conditions_others_only,
3730
+					   ),
3731
+					   true
3732
+				   )
3733
+			   );
3734
+	}
3735
+
3736
+	/**
3737
+	 * Determines whether or not we should use default minimum conditions for the model in question
3738
+	 * (this model, or other related models).
3739
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3740
+	 * where conditions.
3741
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3742
+	 * on this model or others
3743
+	 * @param      $default_where_conditions_value
3744
+	 * @param bool $for_this_model false means this is for OTHER related models
3745
+	 * @return bool
3746
+	 */
3747
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3748
+	{
3749
+		return (
3750
+				   $for_this_model
3751
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3752
+			   )
3753
+			   || (
3754
+				   ! $for_this_model
3755
+				   && in_array(
3756
+					   $default_where_conditions_value,
3757
+					   array(
3758
+						   EEM_Base::default_where_conditions_minimum_others,
3759
+						   EEM_Base::default_where_conditions_minimum_all,
3760
+					   ),
3761
+					   true
3762
+				   )
3763
+			   );
3764
+	}
3765
+
3766
+
3767
+	/**
3768
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3769
+	 * then we also add a special where condition which allows for that model's primary key
3770
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3771
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3772
+	 *
3773
+	 * @param array    $default_where_conditions
3774
+	 * @param array    $provided_where_conditions
3775
+	 * @param EEM_Base $model
3776
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3777
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3778
+	 * @throws EE_Error
3779
+	 */
3780
+	private function _override_defaults_or_make_null_friendly(
3781
+		$default_where_conditions,
3782
+		$provided_where_conditions,
3783
+		$model,
3784
+		$model_relation_path
3785
+	) {
3786
+		$null_friendly_where_conditions = array();
3787
+		$none_overridden = true;
3788
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3789
+		foreach ($default_where_conditions as $key => $val) {
3790
+			if (isset($provided_where_conditions[ $key ])) {
3791
+				$none_overridden = false;
3792
+			} else {
3793
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3794
+			}
3795
+		}
3796
+		if ($none_overridden && $default_where_conditions) {
3797
+			if ($model->has_primary_key_field()) {
3798
+				$null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3799
+																				. "."
3800
+																				. $model->primary_key_name() ] = array('IS NULL');
3801
+			}/*else{
3802 3802
                 //@todo NO PK, use other defaults
3803 3803
             }*/
3804
-        }
3805
-        return $null_friendly_where_conditions;
3806
-    }
3807
-
3808
-
3809
-
3810
-    /**
3811
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3812
-     * default where conditions on all get_all, update, and delete queries done by this model.
3813
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3814
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3815
-     *
3816
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3817
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3818
-     */
3819
-    private function _get_default_where_conditions($model_relation_path = null)
3820
-    {
3821
-        if ($this->_ignore_where_strategy) {
3822
-            return array();
3823
-        }
3824
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3825
-    }
3826
-
3827
-
3828
-
3829
-    /**
3830
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3831
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3832
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3833
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3834
-     * Similar to _get_default_where_conditions
3835
-     *
3836
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3837
-     * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
-     */
3839
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3840
-    {
3841
-        if ($this->_ignore_where_strategy) {
3842
-            return array();
3843
-        }
3844
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3845
-    }
3846
-
3847
-
3848
-
3849
-    /**
3850
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3851
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3852
-     *
3853
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3854
-     * @return string
3855
-     * @throws EE_Error
3856
-     */
3857
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3858
-    {
3859
-        $selects = $this->_get_columns_to_select_for_this_model();
3860
-        foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3861
-            $name_of_other_model_included) {
3862
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3863
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3864
-            foreach ($other_model_selects as $key => $value) {
3865
-                $selects[] = $value;
3866
-            }
3867
-        }
3868
-        return implode(", ", $selects);
3869
-    }
3870
-
3871
-
3872
-
3873
-    /**
3874
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3875
-     * So that's going to be the columns for all the fields on the model
3876
-     *
3877
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3878
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3879
-     */
3880
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3881
-    {
3882
-        $fields = $this->field_settings();
3883
-        $selects = array();
3884
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3885
-            $model_relation_chain,
3886
-            $this->get_this_model_name()
3887
-        );
3888
-        foreach ($fields as $field_obj) {
3889
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3890
-                         . $field_obj->get_table_alias()
3891
-                         . "."
3892
-                         . $field_obj->get_table_column()
3893
-                         . " AS '"
3894
-                         . $table_alias_with_model_relation_chain_prefix
3895
-                         . $field_obj->get_table_alias()
3896
-                         . "."
3897
-                         . $field_obj->get_table_column()
3898
-                         . "'";
3899
-        }
3900
-        // make sure we are also getting the PKs of each table
3901
-        $tables = $this->get_tables();
3902
-        if (count($tables) > 1) {
3903
-            foreach ($tables as $table_obj) {
3904
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905
-                                       . $table_obj->get_fully_qualified_pk_column();
3906
-                if (! in_array($qualified_pk_column, $selects)) {
3907
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908
-                }
3909
-            }
3910
-        }
3911
-        return $selects;
3912
-    }
3913
-
3914
-
3915
-
3916
-    /**
3917
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3918
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3919
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3920
-     * SQL for joining, and the data types
3921
-     *
3922
-     * @param null|string                 $original_query_param
3923
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3924
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3925
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3926
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3927
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3928
-     *                                                          or 'Registration's
3929
-     * @param string                      $original_query_param what it originally was (eg
3930
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3931
-     *                                                          matches $query_param
3932
-     * @throws EE_Error
3933
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3934
-     */
3935
-    private function _extract_related_model_info_from_query_param(
3936
-        $query_param,
3937
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3938
-        $query_param_type,
3939
-        $original_query_param = null
3940
-    ) {
3941
-        if ($original_query_param === null) {
3942
-            $original_query_param = $query_param;
3943
-        }
3944
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3945
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3946
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3947
-        $allow_fields = in_array(
3948
-            $query_param_type,
3949
-            array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3950
-            true
3951
-        );
3952
-        // check to see if we have a field on this model
3953
-        $this_model_fields = $this->field_settings(true);
3954
-        if (array_key_exists($query_param, $this_model_fields)) {
3955
-            if ($allow_fields) {
3956
-                return;
3957
-            }
3958
-            throw new EE_Error(
3959
-                sprintf(
3960
-                    __(
3961
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3962
-                        "event_espresso"
3963
-                    ),
3964
-                    $query_param,
3965
-                    get_class($this),
3966
-                    $query_param_type,
3967
-                    $original_query_param
3968
-                )
3969
-            );
3970
-        }
3971
-        // check if this is a special logic query param
3972
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3973
-            if ($allow_logic_query_params) {
3974
-                return;
3975
-            }
3976
-            throw new EE_Error(
3977
-                sprintf(
3978
-                    __(
3979
-                        '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',
3980
-                        'event_espresso'
3981
-                    ),
3982
-                    implode('", "', $this->_logic_query_param_keys),
3983
-                    $query_param,
3984
-                    get_class($this),
3985
-                    '<br />',
3986
-                    "\t"
3987
-                    . ' $passed_in_query_info = <pre>'
3988
-                    . print_r($passed_in_query_info, true)
3989
-                    . '</pre>'
3990
-                    . "\n\t"
3991
-                    . ' $query_param_type = '
3992
-                    . $query_param_type
3993
-                    . "\n\t"
3994
-                    . ' $original_query_param = '
3995
-                    . $original_query_param
3996
-                )
3997
-            );
3998
-        }
3999
-        // check if it's a custom selection
4000
-        if ($this->_custom_selections instanceof CustomSelects
4001
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4002
-        ) {
4003
-            return;
4004
-        }
4005
-        // check if has a model name at the beginning
4006
-        // and
4007
-        // check if it's a field on a related model
4008
-        if ($this->extractJoinModelFromQueryParams(
4009
-            $passed_in_query_info,
4010
-            $query_param,
4011
-            $original_query_param,
4012
-            $query_param_type
4013
-        )) {
4014
-            return;
4015
-        }
4016
-
4017
-        // ok so $query_param didn't start with a model name
4018
-        // and we previously confirmed it wasn't a logic query param or field on the current model
4019
-        // it's wack, that's what it is
4020
-        throw new EE_Error(
4021
-            sprintf(
4022
-                esc_html__(
4023
-                    "There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4024
-                    "event_espresso"
4025
-                ),
4026
-                $query_param,
4027
-                get_class($this),
4028
-                $query_param_type,
4029
-                $original_query_param
4030
-            )
4031
-        );
4032
-    }
4033
-
4034
-
4035
-    /**
4036
-     * Extracts any possible join model information from the provided possible_join_string.
4037
-     * This method will read the provided $possible_join_string value and determine if there are any possible model join
4038
-     * parts that should be added to the query.
4039
-     *
4040
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4041
-     * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4042
-     * @param null|string                 $original_query_param
4043
-     * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4044
-     *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4045
-     * @return bool  returns true if a join was added and false if not.
4046
-     * @throws EE_Error
4047
-     */
4048
-    private function extractJoinModelFromQueryParams(
4049
-        EE_Model_Query_Info_Carrier $query_info_carrier,
4050
-        $possible_join_string,
4051
-        $original_query_param,
4052
-        $query_parameter_type
4053
-    ) {
4054
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4056
-                $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4058
-                if ($possible_join_string === '') {
4059
-                    // nothing left to $query_param
4060
-                    // we should actually end in a field name, not a model like this!
4061
-                    throw new EE_Error(
4062
-                        sprintf(
4063
-                            esc_html__(
4064
-                                "Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4065
-                                "event_espresso"
4066
-                            ),
4067
-                            $possible_join_string,
4068
-                            $query_parameter_type,
4069
-                            get_class($this),
4070
-                            $valid_related_model_name
4071
-                        )
4072
-                    );
4073
-                }
4074
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4075
-                $related_model_obj->_extract_related_model_info_from_query_param(
4076
-                    $possible_join_string,
4077
-                    $query_info_carrier,
4078
-                    $query_parameter_type,
4079
-                    $original_query_param
4080
-                );
4081
-                return true;
4082
-            }
4083
-            if ($possible_join_string === $valid_related_model_name) {
4084
-                $this->_add_join_to_model(
4085
-                    $valid_related_model_name,
4086
-                    $query_info_carrier,
4087
-                    $original_query_param
4088
-                );
4089
-                return true;
4090
-            }
4091
-        }
4092
-        return false;
4093
-    }
4094
-
4095
-
4096
-    /**
4097
-     * Extracts related models from Custom Selects and sets up any joins for those related models.
4098
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
4099
-     * @throws EE_Error
4100
-     */
4101
-    private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4102
-    {
4103
-        if ($this->_custom_selections instanceof CustomSelects
4104
-            && ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4105
-                || $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4106
-            )
4107
-        ) {
4108
-            $original_selects = $this->_custom_selections->originalSelects();
4109
-            foreach ($original_selects as $alias => $select_configuration) {
4110
-                $this->extractJoinModelFromQueryParams(
4111
-                    $query_info_carrier,
4112
-                    $select_configuration[0],
4113
-                    $select_configuration[0],
4114
-                    'custom_selects'
4115
-                );
4116
-            }
4117
-        }
4118
-    }
4119
-
4120
-
4121
-
4122
-    /**
4123
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4124
-     * and store it on $passed_in_query_info
4125
-     *
4126
-     * @param string                      $model_name
4127
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4128
-     * @param string                      $original_query_param used to extract the relation chain between the queried
4129
-     *                                                          model and $model_name. Eg, if we are querying Event,
4130
-     *                                                          and are adding a join to 'Payment' with the original
4131
-     *                                                          query param key
4132
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4133
-     *                                                          to extract 'Registration.Transaction.Payment', in case
4134
-     *                                                          Payment wants to add default query params so that it
4135
-     *                                                          will know what models to prepend onto its default query
4136
-     *                                                          params or in case it wants to rename tables (in case
4137
-     *                                                          there are multiple joins to the same table)
4138
-     * @return void
4139
-     * @throws EE_Error
4140
-     */
4141
-    private function _add_join_to_model(
4142
-        $model_name,
4143
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
4144
-        $original_query_param
4145
-    ) {
4146
-        $relation_obj = $this->related_settings_for($model_name);
4147
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4148
-        // check if the relation is HABTM, because then we're essentially doing two joins
4149
-        // If so, join first to the JOIN table, and add its data types, and then continue as normal
4150
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4151
-            $join_model_obj = $relation_obj->get_join_model();
4152
-            // replace the model specified with the join model for this relation chain, whi
4153
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4154
-                $model_name,
4155
-                $join_model_obj->get_this_model_name(),
4156
-                $model_relation_chain
4157
-            );
4158
-            $passed_in_query_info->merge(
4159
-                new EE_Model_Query_Info_Carrier(
4160
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4161
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4162
-                )
4163
-            );
4164
-        }
4165
-        // now just join to the other table pointed to by the relation object, and add its data types
4166
-        $passed_in_query_info->merge(
4167
-            new EE_Model_Query_Info_Carrier(
4168
-                array($model_relation_chain => $model_name),
4169
-                $relation_obj->get_join_statement($model_relation_chain)
4170
-            )
4171
-        );
4172
-    }
4173
-
4174
-
4175
-
4176
-    /**
4177
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4178
-     *
4179
-     * @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
4180
-     * @return string of SQL
4181
-     * @throws EE_Error
4182
-     */
4183
-    private function _construct_where_clause($where_params)
4184
-    {
4185
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186
-        if ($SQL) {
4187
-            return " WHERE " . $SQL;
4188
-        }
4189
-        return '';
4190
-    }
4191
-
4192
-
4193
-
4194
-    /**
4195
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4196
-     * and should be passed HAVING parameters, not WHERE parameters
4197
-     *
4198
-     * @param array $having_params
4199
-     * @return string
4200
-     * @throws EE_Error
4201
-     */
4202
-    private function _construct_having_clause($having_params)
4203
-    {
4204
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205
-        if ($SQL) {
4206
-            return " HAVING " . $SQL;
4207
-        }
4208
-        return '';
4209
-    }
4210
-
4211
-
4212
-    /**
4213
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4214
-     * Event_Meta.meta_value = 'foo'))"
4215
-     *
4216
-     * @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
4217
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4218
-     * @throws EE_Error
4219
-     * @return string of SQL
4220
-     */
4221
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4222
-    {
4223
-        $where_clauses = array();
4224
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4226
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4227
-                switch ($query_param) {
4228
-                    case 'not':
4229
-                    case 'NOT':
4230
-                        $where_clauses[] = "! ("
4231
-                                           . $this->_construct_condition_clause_recursive(
4232
-                                               $op_and_value_or_sub_condition,
4233
-                                               $glue
4234
-                                           )
4235
-                                           . ")";
4236
-                        break;
4237
-                    case 'and':
4238
-                    case 'AND':
4239
-                        $where_clauses[] = " ("
4240
-                                           . $this->_construct_condition_clause_recursive(
4241
-                                               $op_and_value_or_sub_condition,
4242
-                                               ' AND '
4243
-                                           )
4244
-                                           . ")";
4245
-                        break;
4246
-                    case 'or':
4247
-                    case 'OR':
4248
-                        $where_clauses[] = " ("
4249
-                                           . $this->_construct_condition_clause_recursive(
4250
-                                               $op_and_value_or_sub_condition,
4251
-                                               ' OR '
4252
-                                           )
4253
-                                           . ")";
4254
-                        break;
4255
-                }
4256
-            } else {
4257
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4258
-                // if it's not a normal field, maybe it's a custom selection?
4259
-                if (! $field_obj) {
4260
-                    if ($this->_custom_selections instanceof CustomSelects) {
4261
-                        $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262
-                    } else {
4263
-                        throw new EE_Error(sprintf(__(
4264
-                            "%s is neither a valid model field name, nor a custom selection",
4265
-                            "event_espresso"
4266
-                        ), $query_param));
4267
-                    }
4268
-                }
4269
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4271
-            }
4272
-        }
4273
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4274
-    }
4275
-
4276
-
4277
-
4278
-    /**
4279
-     * Takes the input parameter and extract the table name (alias) and column name
4280
-     *
4281
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4282
-     * @throws EE_Error
4283
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4284
-     */
4285
-    private function _deduce_column_name_from_query_param($query_param)
4286
-    {
4287
-        $field = $this->_deduce_field_from_query_param($query_param);
4288
-        if ($field) {
4289
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4290
-                $field->get_model_name(),
4291
-                $query_param
4292
-            );
4293
-            return $table_alias_prefix . $field->get_qualified_column();
4294
-        }
4295
-        if ($this->_custom_selections instanceof CustomSelects
4296
-            && in_array($query_param, $this->_custom_selections->columnAliases(), true)
4297
-        ) {
4298
-            // maybe it's custom selection item?
4299
-            // if so, just use it as the "column name"
4300
-            return $query_param;
4301
-        }
4302
-        $custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4303
-            ? implode(',', $this->_custom_selections->columnAliases())
4304
-            : '';
4305
-        throw new EE_Error(
4306
-            sprintf(
4307
-                __(
4308
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4309
-                    "event_espresso"
4310
-                ),
4311
-                $query_param,
4312
-                $custom_select_aliases
4313
-            )
4314
-        );
4315
-    }
4316
-
4317
-
4318
-
4319
-    /**
4320
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4321
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4322
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4323
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4324
-     *
4325
-     * @param string $condition_query_param_key
4326
-     * @return string
4327
-     */
4328
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4329
-    {
4330
-        $pos_of_star = strpos($condition_query_param_key, '*');
4331
-        if ($pos_of_star === false) {
4332
-            return $condition_query_param_key;
4333
-        }
4334
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4335
-        return $condition_query_param_sans_star;
4336
-    }
4337
-
4338
-
4339
-
4340
-    /**
4341
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4342
-     *
4343
-     * @param                            mixed      array | string    $op_and_value
4344
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4345
-     * @throws EE_Error
4346
-     * @return string
4347
-     */
4348
-    private function _construct_op_and_value($op_and_value, $field_obj)
4349
-    {
4350
-        if (is_array($op_and_value)) {
4351
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
-            if (! $operator) {
4353
-                $php_array_like_string = array();
4354
-                foreach ($op_and_value as $key => $value) {
4355
-                    $php_array_like_string[] = "$key=>$value";
4356
-                }
4357
-                throw new EE_Error(
4358
-                    sprintf(
4359
-                        __(
4360
-                            "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))",
4361
-                            "event_espresso"
4362
-                        ),
4363
-                        implode(",", $php_array_like_string)
4364
-                    )
4365
-                );
4366
-            }
4367
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4368
-        } else {
4369
-            $operator = '=';
4370
-            $value = $op_and_value;
4371
-        }
4372
-        // check to see if the value is actually another field
4373
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4375
-        }
4376
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377
-            // in this case, the value should be an array, or at least a comma-separated list
4378
-            // it will need to handle a little differently
4379
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4380
-            // note: $cleaned_value has already been run through $wpdb->prepare()
4381
-            return $operator . SP . $cleaned_value;
4382
-        }
4383
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384
-            // the value should be an array with count of two.
4385
-            if (count($value) !== 2) {
4386
-                throw new EE_Error(
4387
-                    sprintf(
4388
-                        __(
4389
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4390
-                            'event_espresso'
4391
-                        ),
4392
-                        "BETWEEN"
4393
-                    )
4394
-                );
4395
-            }
4396
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
-            return $operator . SP . $cleaned_value;
4398
-        }
4399
-        if (in_array($operator, $this->valid_null_style_operators())) {
4400
-            if ($value !== null) {
4401
-                throw new EE_Error(
4402
-                    sprintf(
4403
-                        __(
4404
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4405
-                            "event_espresso"
4406
-                        ),
4407
-                        $value,
4408
-                        $operator
4409
-                    )
4410
-                );
4411
-            }
4412
-            return $operator;
4413
-        }
4414
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415
-            // if the operator is 'LIKE', we want to allow percent signs (%) and not
4416
-            // remove other junk. So just treat it as a string.
4417
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4418
-        }
4419
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4421
-        }
4422
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423
-            throw new EE_Error(
4424
-                sprintf(
4425
-                    __(
4426
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4427
-                        'event_espresso'
4428
-                    ),
4429
-                    $operator,
4430
-                    $operator
4431
-                )
4432
-            );
4433
-        }
4434
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435
-            throw new EE_Error(
4436
-                sprintf(
4437
-                    __(
4438
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4439
-                        'event_espresso'
4440
-                    ),
4441
-                    $operator,
4442
-                    $operator
4443
-                )
4444
-            );
4445
-        }
4446
-        throw new EE_Error(
4447
-            sprintf(
4448
-                __(
4449
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4450
-                    "event_espresso"
4451
-                ),
4452
-                http_build_query($op_and_value)
4453
-            )
4454
-        );
4455
-    }
4456
-
4457
-
4458
-
4459
-    /**
4460
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4461
-     *
4462
-     * @param array                      $values
4463
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4464
-     *                                              '%s'
4465
-     * @return string
4466
-     * @throws EE_Error
4467
-     */
4468
-    public function _construct_between_value($values, $field_obj)
4469
-    {
4470
-        $cleaned_values = array();
4471
-        foreach ($values as $value) {
4472
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473
-        }
4474
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4475
-    }
4476
-
4477
-
4478
-
4479
-    /**
4480
-     * Takes an array or a comma-separated list of $values and cleans them
4481
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4482
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4483
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4484
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4485
-     *
4486
-     * @param mixed                      $values    array or comma-separated string
4487
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4488
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4489
-     * @throws EE_Error
4490
-     */
4491
-    public function _construct_in_value($values, $field_obj)
4492
-    {
4493
-        // check if the value is a CSV list
4494
-        if (is_string($values)) {
4495
-            // in which case, turn it into an array
4496
-            $values = explode(",", $values);
4497
-        }
4498
-        $cleaned_values = array();
4499
-        foreach ($values as $value) {
4500
-            $cleaned_values[] = $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($cleaned_values)) {
4506
-            $all_fields = $this->field_settings();
4507
-            $a_field = array_shift($all_fields);
4508
-            $main_table = $this->_get_main_table();
4509
-            $cleaned_values[] = "SELECT "
4510
-                                . $a_field->get_table_column()
4511
-                                . " FROM "
4512
-                                . $main_table->get_table_name()
4513
-                                . " WHERE FALSE";
4514
-        }
4515
-        return "(" . implode(",", $cleaned_values) . ")";
4516
-    }
4517
-
4518
-
4519
-
4520
-    /**
4521
-     * @param mixed                      $value
4522
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4523
-     * @throws EE_Error
4524
-     * @return false|null|string
4525
-     */
4526
-    private function _wpdb_prepare_using_field($value, $field_obj)
4527
-    {
4528
-        /** @type WPDB $wpdb */
4529
-        global $wpdb;
4530
-        if ($field_obj instanceof EE_Model_Field_Base) {
4531
-            return $wpdb->prepare(
4532
-                $field_obj->get_wpdb_data_type(),
4533
-                $this->_prepare_value_for_use_in_db($value, $field_obj)
4534
-            );
4535
-        } //$field_obj should really just be a data type
4536
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537
-            throw new EE_Error(
4538
-                sprintf(
4539
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4540
-                    $field_obj,
4541
-                    implode(",", $this->_valid_wpdb_data_types)
4542
-                )
4543
-            );
4544
-        }
4545
-        return $wpdb->prepare($field_obj, $value);
4546
-    }
4547
-
4548
-
4549
-
4550
-    /**
4551
-     * Takes the input parameter and finds the model field that it indicates.
4552
-     *
4553
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4554
-     * @throws EE_Error
4555
-     * @return EE_Model_Field_Base
4556
-     */
4557
-    protected function _deduce_field_from_query_param($query_param_name)
4558
-    {
4559
-        // ok, now proceed with deducing which part is the model's name, and which is the field's name
4560
-        // which will help us find the database table and column
4561
-        $query_param_parts = explode(".", $query_param_name);
4562
-        if (empty($query_param_parts)) {
4563
-            throw new EE_Error(sprintf(__(
4564
-                "_extract_column_name is empty when trying to extract column and table name from %s",
4565
-                'event_espresso'
4566
-            ), $query_param_name));
4567
-        }
4568
-        $number_of_parts = count($query_param_parts);
4569
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4570
-        if ($number_of_parts === 1) {
4571
-            $field_name = $last_query_param_part;
4572
-            $model_obj = $this;
4573
-        } else {// $number_of_parts >= 2
4574
-            // the last part is the column name, and there are only 2parts. therefore...
4575
-            $field_name = $last_query_param_part;
4576
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4577
-        }
4578
-        try {
4579
-            return $model_obj->field_settings_for($field_name);
4580
-        } catch (EE_Error $e) {
4581
-            return null;
4582
-        }
4583
-    }
4584
-
4585
-
4586
-
4587
-    /**
4588
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4589
-     * alias and column which corresponds to it
4590
-     *
4591
-     * @param string $field_name
4592
-     * @throws EE_Error
4593
-     * @return string
4594
-     */
4595
-    public function _get_qualified_column_for_field($field_name)
4596
-    {
4597
-        $all_fields = $this->field_settings();
4598
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4599
-        if ($field) {
4600
-            return $field->get_qualified_column();
4601
-        }
4602
-        throw new EE_Error(
4603
-            sprintf(
4604
-                __(
4605
-                    "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.",
4606
-                    'event_espresso'
4607
-                ),
4608
-                $field_name,
4609
-                get_class($this)
4610
-            )
4611
-        );
4612
-    }
4613
-
4614
-
4615
-
4616
-    /**
4617
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4618
-     * Example usage:
4619
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4620
-     *      array(),
4621
-     *      ARRAY_A,
4622
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4623
-     *  );
4624
-     * is equivalent to
4625
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4626
-     * and
4627
-     *  EEM_Event::instance()->get_all_wpdb_results(
4628
-     *      array(
4629
-     *          array(
4630
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4631
-     *          ),
4632
-     *          ARRAY_A,
4633
-     *          implode(
4634
-     *              ', ',
4635
-     *              array_merge(
4636
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4637
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4638
-     *              )
4639
-     *          )
4640
-     *      )
4641
-     *  );
4642
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4643
-     *
4644
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4645
-     *                                            and the one whose fields you are selecting for example: when querying
4646
-     *                                            tickets model and selecting fields from the tickets model you would
4647
-     *                                            leave this parameter empty, because no models are needed to join
4648
-     *                                            between the queried model and the selected one. Likewise when
4649
-     *                                            querying the datetime model and selecting fields from the tickets
4650
-     *                                            model, it would also be left empty, because there is a direct
4651
-     *                                            relation from datetimes to tickets, so no model is needed to join
4652
-     *                                            them together. However, when querying from the event model and
4653
-     *                                            selecting fields from the ticket model, you should provide the string
4654
-     *                                            'Datetime', indicating that the event model must first join to the
4655
-     *                                            datetime model in order to find its relation to ticket model.
4656
-     *                                            Also, when querying from the venue model and selecting fields from
4657
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4658
-     *                                            indicating you need to join the venue model to the event model,
4659
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4660
-     *                                            This string is used to deduce the prefix that gets added onto the
4661
-     *                                            models' tables qualified columns
4662
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4663
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4664
-     *                                            qualified column names
4665
-     * @return array|string
4666
-     */
4667
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668
-    {
4669
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4670
-        $qualified_columns = array();
4671
-        foreach ($this->field_settings() as $field_name => $field) {
4672
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4673
-        }
4674
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675
-    }
4676
-
4677
-
4678
-
4679
-    /**
4680
-     * constructs the select use on special limit joins
4681
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4682
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4683
-     * (as that is typically where the limits would be set).
4684
-     *
4685
-     * @param  string       $table_alias The table the select is being built for
4686
-     * @param  mixed|string $limit       The limit for this select
4687
-     * @return string                The final select join element for the query.
4688
-     */
4689
-    public function _construct_limit_join_select($table_alias, $limit)
4690
-    {
4691
-        $SQL = '';
4692
-        foreach ($this->_tables as $table_obj) {
4693
-            if ($table_obj instanceof EE_Primary_Table) {
4694
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4695
-                    ? $table_obj->get_select_join_limit($limit)
4696
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4697
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4698
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4699
-                    ? $table_obj->get_select_join_limit_join($limit)
4700
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4701
-            }
4702
-        }
4703
-        return $SQL;
4704
-    }
4705
-
4706
-
4707
-
4708
-    /**
4709
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4710
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4711
-     *
4712
-     * @return string SQL
4713
-     * @throws EE_Error
4714
-     */
4715
-    public function _construct_internal_join()
4716
-    {
4717
-        $SQL = $this->_get_main_table()->get_table_sql();
4718
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4719
-        return $SQL;
4720
-    }
4721
-
4722
-
4723
-
4724
-    /**
4725
-     * Constructs the SQL for joining all the tables on this model.
4726
-     * Normally $alias should be the primary table's alias, but in cases where
4727
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4728
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4729
-     * alias, this will construct SQL like:
4730
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4731
-     * With $alias being a secondary table's alias, this will construct SQL like:
4732
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4733
-     *
4734
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4735
-     * @return string
4736
-     */
4737
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4738
-    {
4739
-        $SQL = '';
4740
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4741
-        foreach ($this->_tables as $table_obj) {
4742
-            if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4743
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4744
-                    // so we're joining to this table, meaning the table is already in
4745
-                    // the FROM statement, BUT the primary table isn't. So we want
4746
-                    // to add the inverse join sql
4747
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4748
-                } else {
4749
-                    // just add a regular JOIN to this table from the primary table
4750
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4751
-                }
4752
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4753
-        }
4754
-        return $SQL;
4755
-    }
4756
-
4757
-
4758
-
4759
-    /**
4760
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4761
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4762
-     * their data type (eg, '%s', '%d', etc)
4763
-     *
4764
-     * @return array
4765
-     */
4766
-    public function _get_data_types()
4767
-    {
4768
-        $data_types = array();
4769
-        foreach ($this->field_settings() as $field_obj) {
4770
-            // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771
-            /** @var $field_obj EE_Model_Field_Base */
4772
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4773
-        }
4774
-        return $data_types;
4775
-    }
4776
-
4777
-
4778
-
4779
-    /**
4780
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4781
-     *
4782
-     * @param string $model_name
4783
-     * @throws EE_Error
4784
-     * @return EEM_Base
4785
-     */
4786
-    public function get_related_model_obj($model_name)
4787
-    {
4788
-        $model_classname = "EEM_" . $model_name;
4789
-        if (! class_exists($model_classname)) {
4790
-            throw new EE_Error(sprintf(__(
4791
-                "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792
-                'event_espresso'
4793
-            ), $model_name, $model_classname));
4794
-        }
4795
-        return call_user_func($model_classname . "::instance");
4796
-    }
4797
-
4798
-
4799
-
4800
-    /**
4801
-     * Returns the array of EE_ModelRelations for this model.
4802
-     *
4803
-     * @return EE_Model_Relation_Base[]
4804
-     */
4805
-    public function relation_settings()
4806
-    {
4807
-        return $this->_model_relations;
4808
-    }
4809
-
4810
-
4811
-
4812
-    /**
4813
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4814
-     * because without THOSE models, this model probably doesn't have much purpose.
4815
-     * (Eg, without an event, datetimes have little purpose.)
4816
-     *
4817
-     * @return EE_Belongs_To_Relation[]
4818
-     */
4819
-    public function belongs_to_relations()
4820
-    {
4821
-        $belongs_to_relations = array();
4822
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4825
-            }
4826
-        }
4827
-        return $belongs_to_relations;
4828
-    }
4829
-
4830
-
4831
-
4832
-    /**
4833
-     * Returns the specified EE_Model_Relation, or throws an exception
4834
-     *
4835
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4836
-     * @throws EE_Error
4837
-     * @return EE_Model_Relation_Base
4838
-     */
4839
-    public function related_settings_for($relation_name)
4840
-    {
4841
-        $relatedModels = $this->relation_settings();
4842
-        if (! array_key_exists($relation_name, $relatedModels)) {
4843
-            throw new EE_Error(
4844
-                sprintf(
4845
-                    __(
4846
-                        'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4847
-                        'event_espresso'
4848
-                    ),
4849
-                    $relation_name,
4850
-                    $this->_get_class_name(),
4851
-                    implode(', ', array_keys($relatedModels))
4852
-                )
4853
-            );
4854
-        }
4855
-        return $relatedModels[ $relation_name ];
4856
-    }
4857
-
4858
-
4859
-
4860
-    /**
4861
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4862
-     * fields
4863
-     *
4864
-     * @param string $fieldName
4865
-     * @param boolean $include_db_only_fields
4866
-     * @throws EE_Error
4867
-     * @return EE_Model_Field_Base
4868
-     */
4869
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4870
-    {
4871
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4872
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4873
-            throw new EE_Error(sprintf(
4874
-                __("There is no field/column '%s' on '%s'", 'event_espresso'),
4875
-                $fieldName,
4876
-                get_class($this)
4877
-            ));
4878
-        }
4879
-        return $fieldSettings[ $fieldName ];
4880
-    }
4881
-
4882
-
4883
-
4884
-    /**
4885
-     * Checks if this field exists on this model
4886
-     *
4887
-     * @param string $fieldName a key in the model's _field_settings array
4888
-     * @return boolean
4889
-     */
4890
-    public function has_field($fieldName)
4891
-    {
4892
-        $fieldSettings = $this->field_settings(true);
4893
-        if (isset($fieldSettings[ $fieldName ])) {
4894
-            return true;
4895
-        }
4896
-        return false;
4897
-    }
4898
-
4899
-
4900
-
4901
-    /**
4902
-     * Returns whether or not this model has a relation to the specified model
4903
-     *
4904
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4905
-     * @return boolean
4906
-     */
4907
-    public function has_relation($relation_name)
4908
-    {
4909
-        $relations = $this->relation_settings();
4910
-        if (isset($relations[ $relation_name ])) {
4911
-            return true;
4912
-        }
4913
-        return false;
4914
-    }
4915
-
4916
-
4917
-
4918
-    /**
4919
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4920
-     * Eg, on EE_Answer that would be ANS_ID field object
4921
-     *
4922
-     * @param $field_obj
4923
-     * @return boolean
4924
-     */
4925
-    public function is_primary_key_field($field_obj)
4926
-    {
4927
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4928
-    }
4929
-
4930
-
4931
-
4932
-    /**
4933
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
-     * Eg, on EE_Answer that would be ANS_ID field object
4935
-     *
4936
-     * @return EE_Model_Field_Base
4937
-     * @throws EE_Error
4938
-     */
4939
-    public function get_primary_key_field()
4940
-    {
4941
-        if ($this->_primary_key_field === null) {
4942
-            foreach ($this->field_settings(true) as $field_obj) {
4943
-                if ($this->is_primary_key_field($field_obj)) {
4944
-                    $this->_primary_key_field = $field_obj;
4945
-                    break;
4946
-                }
4947
-            }
4948
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949
-                throw new EE_Error(sprintf(
4950
-                    __("There is no Primary Key defined on model %s", 'event_espresso'),
4951
-                    get_class($this)
4952
-                ));
4953
-            }
4954
-        }
4955
-        return $this->_primary_key_field;
4956
-    }
4957
-
4958
-
4959
-
4960
-    /**
4961
-     * Returns whether or not not there is a primary key on this model.
4962
-     * Internally does some caching.
4963
-     *
4964
-     * @return boolean
4965
-     */
4966
-    public function has_primary_key_field()
4967
-    {
4968
-        if ($this->_has_primary_key_field === null) {
4969
-            try {
4970
-                $this->get_primary_key_field();
4971
-                $this->_has_primary_key_field = true;
4972
-            } catch (EE_Error $e) {
4973
-                $this->_has_primary_key_field = false;
4974
-            }
4975
-        }
4976
-        return $this->_has_primary_key_field;
4977
-    }
4978
-
4979
-
4980
-
4981
-    /**
4982
-     * Finds the first field of type $field_class_name.
4983
-     *
4984
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4985
-     *                                 EE_Foreign_Key_Field, etc
4986
-     * @return EE_Model_Field_Base or null if none is found
4987
-     */
4988
-    public function get_a_field_of_type($field_class_name)
4989
-    {
4990
-        foreach ($this->field_settings() as $field) {
4991
-            if ($field instanceof $field_class_name) {
4992
-                return $field;
4993
-            }
4994
-        }
4995
-        return null;
4996
-    }
4997
-
4998
-
4999
-
5000
-    /**
5001
-     * Gets a foreign key field pointing to model.
5002
-     *
5003
-     * @param string $model_name eg Event, Registration, not EEM_Event
5004
-     * @return EE_Foreign_Key_Field_Base
5005
-     * @throws EE_Error
5006
-     */
5007
-    public function get_foreign_key_to($model_name)
5008
-    {
5009
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5010
-            foreach ($this->field_settings() as $field) {
5011
-                if ($field instanceof EE_Foreign_Key_Field_Base
5012
-                    && in_array($model_name, $field->get_model_names_pointed_to())
5013
-                ) {
5014
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5015
-                    break;
5016
-                }
5017
-            }
5018
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5019
-                throw new EE_Error(sprintf(__(
5020
-                    "There is no foreign key field pointing to model %s on model %s",
5021
-                    'event_espresso'
5022
-                ), $model_name, get_class($this)));
5023
-            }
5024
-        }
5025
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5026
-    }
5027
-
5028
-
5029
-
5030
-    /**
5031
-     * Gets the table name (including $wpdb->prefix) for the table alias
5032
-     *
5033
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5034
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5035
-     *                            Either one works
5036
-     * @return string
5037
-     */
5038
-    public function get_table_for_alias($table_alias)
5039
-    {
5040
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5042
-    }
5043
-
5044
-
5045
-
5046
-    /**
5047
-     * Returns a flat array of all field son this model, instead of organizing them
5048
-     * by table_alias as they are in the constructor.
5049
-     *
5050
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5051
-     * @return EE_Model_Field_Base[] where the keys are the field's name
5052
-     */
5053
-    public function field_settings($include_db_only_fields = false)
5054
-    {
5055
-        if ($include_db_only_fields) {
5056
-            if ($this->_cached_fields === null) {
5057
-                $this->_cached_fields = array();
5058
-                foreach ($this->_fields as $fields_corresponding_to_table) {
5059
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5061
-                    }
5062
-                }
5063
-            }
5064
-            return $this->_cached_fields;
5065
-        }
5066
-        if ($this->_cached_fields_non_db_only === null) {
5067
-            $this->_cached_fields_non_db_only = array();
5068
-            foreach ($this->_fields as $fields_corresponding_to_table) {
5069
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070
-                    /** @var $field_obj EE_Model_Field_Base */
5071
-                    if (! $field_obj->is_db_only_field()) {
5072
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5073
-                    }
5074
-                }
5075
-            }
5076
-        }
5077
-        return $this->_cached_fields_non_db_only;
5078
-    }
5079
-
5080
-
5081
-
5082
-    /**
5083
-     *        cycle though array of attendees and create objects out of each item
5084
-     *
5085
-     * @access        private
5086
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5087
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5088
-     *                           numerically indexed)
5089
-     * @throws EE_Error
5090
-     */
5091
-    protected function _create_objects($rows = array())
5092
-    {
5093
-        $array_of_objects = array();
5094
-        if (empty($rows)) {
5095
-            return array();
5096
-        }
5097
-        $count_if_model_has_no_primary_key = 0;
5098
-        $has_primary_key = $this->has_primary_key_field();
5099
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5100
-        foreach ((array) $rows as $row) {
5101
-            if (empty($row)) {
5102
-                // wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5103
-                return array();
5104
-            }
5105
-            // check if we've already set this object in the results array,
5106
-            // in which case there's no need to process it further (again)
5107
-            if ($has_primary_key) {
5108
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5109
-                    $row,
5110
-                    $primary_key_field->get_qualified_column(),
5111
-                    $primary_key_field->get_table_column()
5112
-                );
5113
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5114
-                    continue;
5115
-                }
5116
-            }
5117
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
5118
-            if (! $classInstance) {
5119
-                throw new EE_Error(
5120
-                    sprintf(
5121
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
5122
-                        $this->get_this_model_name(),
5123
-                        http_build_query($row)
5124
-                    )
5125
-                );
5126
-            }
5127
-            // set the timezone on the instantiated objects
5128
-            $classInstance->set_timezone($this->_timezone);
5129
-            // make sure if there is any timezone setting present that we set the timezone for the object
5130
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
-            $array_of_objects[ $key ] = $classInstance;
5132
-            // also, for all the relations of type BelongsTo, see if we can cache
5133
-            // those related models
5134
-            // (we could do this for other relations too, but if there are conditions
5135
-            // that filtered out some fo the results, then we'd be caching an incomplete set
5136
-            // so it requires a little more thought than just caching them immediately...)
5137
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
5138
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
5139
-                    // check if this model's INFO is present. If so, cache it on the model
5140
-                    $other_model = $relation_obj->get_other_model();
5141
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5142
-                    // if we managed to make a model object from the results, cache it on the main model object
5143
-                    if ($other_model_obj_maybe) {
5144
-                        // set timezone on these other model objects if they are present
5145
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
5146
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
5147
-                    }
5148
-                }
5149
-            }
5150
-            // also, if this was a custom select query, let's see if there are any results for the custom select fields
5151
-            // and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5152
-            // the field in the CustomSelects object
5153
-            if ($this->_custom_selections instanceof CustomSelects) {
5154
-                $classInstance->setCustomSelectsValues(
5155
-                    $this->getValuesForCustomSelectAliasesFromResults($row)
5156
-                );
5157
-            }
5158
-        }
5159
-        return $array_of_objects;
5160
-    }
5161
-
5162
-
5163
-    /**
5164
-     * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5165
-     * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5166
-     *
5167
-     * @param array $db_results_row
5168
-     * @return array
5169
-     */
5170
-    protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5171
-    {
5172
-        $results = array();
5173
-        if ($this->_custom_selections instanceof CustomSelects) {
5174
-            foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
-                if (isset($db_results_row[ $alias ])) {
5176
-                    $results[ $alias ] = $this->convertValueToDataType(
5177
-                        $db_results_row[ $alias ],
5178
-                        $this->_custom_selections->getDataTypeForAlias($alias)
5179
-                    );
5180
-                }
5181
-            }
5182
-        }
5183
-        return $results;
5184
-    }
5185
-
5186
-
5187
-    /**
5188
-     * This will set the value for the given alias
5189
-     * @param string $value
5190
-     * @param string $datatype (one of %d, %s, %f)
5191
-     * @return int|string|float (int for %d, string for %s, float for %f)
5192
-     */
5193
-    protected function convertValueToDataType($value, $datatype)
5194
-    {
5195
-        switch ($datatype) {
5196
-            case '%f':
5197
-                return (float) $value;
5198
-            case '%d':
5199
-                return (int) $value;
5200
-            default:
5201
-                return (string) $value;
5202
-        }
5203
-    }
5204
-
5205
-
5206
-    /**
5207
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5208
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5209
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5210
-     * object (as set in the model_field!).
5211
-     *
5212
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5213
-     */
5214
-    public function create_default_object()
5215
-    {
5216
-        $this_model_fields_and_values = array();
5217
-        // setup the row using default values;
5218
-        foreach ($this->field_settings() as $field_name => $field_obj) {
5219
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5220
-        }
5221
-        $className = $this->_get_class_name();
5222
-        $classInstance = EE_Registry::instance()
5223
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
5224
-        return $classInstance;
5225
-    }
5226
-
5227
-
5228
-
5229
-    /**
5230
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5231
-     *                             or an stdClass where each property is the name of a column,
5232
-     * @return EE_Base_Class
5233
-     * @throws EE_Error
5234
-     */
5235
-    public function instantiate_class_from_array_or_object($cols_n_values)
5236
-    {
5237
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5238
-            $cols_n_values = get_object_vars($cols_n_values);
5239
-        }
5240
-        $primary_key = null;
5241
-        // make sure the array only has keys that are fields/columns on this model
5242
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5245
-        }
5246
-        $className = $this->_get_class_name();
5247
-        // check we actually found results that we can use to build our model object
5248
-        // if not, return null
5249
-        if ($this->has_primary_key_field()) {
5250
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5251
-                return null;
5252
-            }
5253
-        } elseif ($this->unique_indexes()) {
5254
-            $first_column = reset($this_model_fields_n_values);
5255
-            if (empty($first_column)) {
5256
-                return null;
5257
-            }
5258
-        }
5259
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260
-        if ($primary_key) {
5261
-            $classInstance = $this->get_from_entity_map($primary_key);
5262
-            if (! $classInstance) {
5263
-                $classInstance = EE_Registry::instance()
5264
-                                            ->load_class(
5265
-                                                $className,
5266
-                                                array($this_model_fields_n_values, $this->_timezone),
5267
-                                                true,
5268
-                                                false
5269
-                                            );
5270
-                // add this new object to the entity map
5271
-                $classInstance = $this->add_to_entity_map($classInstance);
5272
-            }
5273
-        } else {
5274
-            $classInstance = EE_Registry::instance()
5275
-                                        ->load_class(
5276
-                                            $className,
5277
-                                            array($this_model_fields_n_values, $this->_timezone),
5278
-                                            true,
5279
-                                            false
5280
-                                        );
5281
-        }
5282
-        return $classInstance;
5283
-    }
5284
-
5285
-
5286
-
5287
-    /**
5288
-     * Gets the model object from the  entity map if it exists
5289
-     *
5290
-     * @param int|string $id the ID of the model object
5291
-     * @return EE_Base_Class
5292
-     */
5293
-    public function get_from_entity_map($id)
5294
-    {
5295
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5297
-    }
5298
-
5299
-
5300
-
5301
-    /**
5302
-     * add_to_entity_map
5303
-     * Adds the object to the model's entity mappings
5304
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5305
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5306
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5307
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5308
-     *        then this method should be called immediately after the update query
5309
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5310
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5311
-     *
5312
-     * @param    EE_Base_Class $object
5313
-     * @throws EE_Error
5314
-     * @return \EE_Base_Class
5315
-     */
5316
-    public function add_to_entity_map(EE_Base_Class $object)
5317
-    {
5318
-        $className = $this->_get_class_name();
5319
-        if (! $object instanceof $className) {
5320
-            throw new EE_Error(sprintf(
5321
-                __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322
-                is_object($object) ? get_class($object) : $object,
5323
-                $className
5324
-            ));
5325
-        }
5326
-        /** @var $object EE_Base_Class */
5327
-        if (! $object->ID()) {
5328
-            throw new EE_Error(sprintf(__(
5329
-                "You tried storing a model object with NO ID in the %s entity mapper.",
5330
-                "event_espresso"
5331
-            ), get_class($this)));
5332
-        }
5333
-        // double check it's not already there
5334
-        $classInstance = $this->get_from_entity_map($object->ID());
5335
-        if ($classInstance) {
5336
-            return $classInstance;
5337
-        }
5338
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5339
-        return $object;
5340
-    }
5341
-
5342
-
5343
-
5344
-    /**
5345
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5346
-     * if no identifier is provided, then the entire entity map is emptied
5347
-     *
5348
-     * @param int|string $id the ID of the model object
5349
-     * @return boolean
5350
-     */
5351
-    public function clear_entity_map($id = null)
5352
-    {
5353
-        if (empty($id)) {
5354
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5355
-            return true;
5356
-        }
5357
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5359
-            return true;
5360
-        }
5361
-        return false;
5362
-    }
5363
-
5364
-
5365
-
5366
-    /**
5367
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5368
-     * Given an array where keys are column (or column alias) names and values,
5369
-     * returns an array of their corresponding field names and database values
5370
-     *
5371
-     * @param array $cols_n_values
5372
-     * @return array
5373
-     */
5374
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5375
-    {
5376
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5377
-    }
5378
-
5379
-
5380
-
5381
-    /**
5382
-     * _deduce_fields_n_values_from_cols_n_values
5383
-     * Given an array where keys are column (or column alias) names and values,
5384
-     * returns an array of their corresponding field names and database values
5385
-     *
5386
-     * @param string $cols_n_values
5387
-     * @return array
5388
-     */
5389
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
-    {
5391
-        $this_model_fields_n_values = array();
5392
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5393
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5394
-                $cols_n_values,
5395
-                $table_obj->get_fully_qualified_pk_column(),
5396
-                $table_obj->get_pk_column()
5397
-            );
5398
-            // there is a primary key on this table and its not set. Use defaults for all its columns
5399
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
-                    if (! $field_obj->is_db_only_field()) {
5402
-                        // prepare field as if its coming from db
5403
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5405
-                    }
5406
-                }
5407
-            } else {
5408
-                // the table's rows existed. Use their values
5409
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
-                    if (! $field_obj->is_db_only_field()) {
5411
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5412
-                            $cols_n_values,
5413
-                            $field_obj->get_qualified_column(),
5414
-                            $field_obj->get_table_column()
5415
-                        );
5416
-                    }
5417
-                }
5418
-            }
5419
-        }
5420
-        return $this_model_fields_n_values;
5421
-    }
5422
-
5423
-
5424
-    /**
5425
-     * @param $cols_n_values
5426
-     * @param $qualified_column
5427
-     * @param $regular_column
5428
-     * @return null
5429
-     * @throws EE_Error
5430
-     * @throws ReflectionException
5431
-     */
5432
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5433
-    {
5434
-        $value = null;
5435
-        // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436
-        // does the field on the model relate to this column retrieved from the db?
5437
-        // or is it a db-only field? (not relating to the model)
5438
-        if (isset($cols_n_values[ $qualified_column ])) {
5439
-            $value = $cols_n_values[ $qualified_column ];
5440
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5441
-            $value = $cols_n_values[ $regular_column ];
5442
-        } elseif (! empty($this->foreign_key_aliases)) {
5443
-            // no PK?  ok check if there is a foreign key alias set for this table
5444
-            // then check if that alias exists in the incoming data
5445
-            // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446
-            foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
-                    $value = $cols_n_values[ $FK_alias ];
5449
-                    list($pk_class) = explode('.', $PK_column);
5450
-                    $pk_model_name = "EEM_{$pk_class}";
5451
-                    /** @var EEM_Base $pk_model */
5452
-                    $pk_model = EE_Registry::instance()->load_model($pk_model_name);
5453
-                    if ($pk_model instanceof EEM_Base) {
5454
-                        // make sure object is pulled from db and added to entity map
5455
-                        $pk_model->get_one_by_ID($value);
5456
-                    }
5457
-                    break;
5458
-                }
5459
-            }
5460
-        }
5461
-        return $value;
5462
-    }
5463
-
5464
-
5465
-
5466
-    /**
5467
-     * refresh_entity_map_from_db
5468
-     * Makes sure the model object in the entity map at $id assumes the values
5469
-     * of the database (opposite of EE_base_Class::save())
5470
-     *
5471
-     * @param int|string $id
5472
-     * @return EE_Base_Class
5473
-     * @throws EE_Error
5474
-     */
5475
-    public function refresh_entity_map_from_db($id)
5476
-    {
5477
-        $obj_in_map = $this->get_from_entity_map($id);
5478
-        if ($obj_in_map) {
5479
-            $wpdb_results = $this->_get_all_wpdb_results(
5480
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5481
-            );
5482
-            if ($wpdb_results && is_array($wpdb_results)) {
5483
-                $one_row = reset($wpdb_results);
5484
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5485
-                    $obj_in_map->set_from_db($field_name, $db_value);
5486
-                }
5487
-                // clear the cache of related model objects
5488
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5489
-                    $obj_in_map->clear_cache($relation_name, null, true);
5490
-                }
5491
-            }
5492
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5493
-            return $obj_in_map;
5494
-        }
5495
-        return $this->get_one_by_ID($id);
5496
-    }
5497
-
5498
-
5499
-
5500
-    /**
5501
-     * refresh_entity_map_with
5502
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5503
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5504
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5505
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5506
-     *
5507
-     * @param int|string    $id
5508
-     * @param EE_Base_Class $replacing_model_obj
5509
-     * @return \EE_Base_Class
5510
-     * @throws EE_Error
5511
-     */
5512
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5513
-    {
5514
-        $obj_in_map = $this->get_from_entity_map($id);
5515
-        if ($obj_in_map) {
5516
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5517
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5518
-                    $obj_in_map->set($field_name, $value);
5519
-                }
5520
-                // make the model object in the entity map's cache match the $replacing_model_obj
5521
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5522
-                    $obj_in_map->clear_cache($relation_name, null, true);
5523
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5524
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5525
-                    }
5526
-                }
5527
-            }
5528
-            return $obj_in_map;
5529
-        }
5530
-        $this->add_to_entity_map($replacing_model_obj);
5531
-        return $replacing_model_obj;
5532
-    }
5533
-
5534
-
5535
-
5536
-    /**
5537
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5538
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5539
-     * require_once($this->_getClassName().".class.php");
5540
-     *
5541
-     * @return string
5542
-     */
5543
-    private function _get_class_name()
5544
-    {
5545
-        return "EE_" . $this->get_this_model_name();
5546
-    }
5547
-
5548
-
5549
-
5550
-    /**
5551
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5552
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5553
-     * it would be 'Events'.
5554
-     *
5555
-     * @param int $quantity
5556
-     * @return string
5557
-     */
5558
-    public function item_name($quantity = 1)
5559
-    {
5560
-        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5561
-    }
5562
-
5563
-
5564
-
5565
-    /**
5566
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5567
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5568
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5569
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5570
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5571
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5572
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5573
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5574
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5575
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5576
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5577
-     *        return $previousReturnValue.$returnString;
5578
-     * }
5579
-     * require('EEM_Answer.model.php');
5580
-     * $answer=EEM_Answer::instance();
5581
-     * echo $answer->my_callback('monkeys',100);
5582
-     * //will output "you called my_callback! and passed args:monkeys,100"
5583
-     *
5584
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5585
-     * @param array  $args       array of original arguments passed to the function
5586
-     * @throws EE_Error
5587
-     * @return mixed whatever the plugin which calls add_filter decides
5588
-     */
5589
-    public function __call($methodName, $args)
5590
-    {
5591
-        $className = get_class($this);
5592
-        $tagName = "FHEE__{$className}__{$methodName}";
5593
-        if (! has_filter($tagName)) {
5594
-            throw new EE_Error(
5595
-                sprintf(
5596
-                    __(
5597
-                        '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 );',
5598
-                        'event_espresso'
5599
-                    ),
5600
-                    $methodName,
5601
-                    $className,
5602
-                    $tagName,
5603
-                    '<br />'
5604
-                )
5605
-            );
5606
-        }
5607
-        return apply_filters($tagName, null, $this, $args);
5608
-    }
5609
-
5610
-
5611
-
5612
-    /**
5613
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5614
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5615
-     *
5616
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5617
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5618
-     *                                                       the object's class name
5619
-     *                                                       or object's ID
5620
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5621
-     *                                                       exists in the database. If it does not, we add it
5622
-     * @throws EE_Error
5623
-     * @return EE_Base_Class
5624
-     */
5625
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5626
-    {
5627
-        $className = $this->_get_class_name();
5628
-        if ($base_class_obj_or_id instanceof $className) {
5629
-            $model_object = $base_class_obj_or_id;
5630
-        } else {
5631
-            $primary_key_field = $this->get_primary_key_field();
5632
-            if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5633
-                && (
5634
-                    is_int($base_class_obj_or_id)
5635
-                    || is_string($base_class_obj_or_id)
5636
-                )
5637
-            ) {
5638
-                // assume it's an ID.
5639
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5640
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
-            } elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5642
-                && is_string($base_class_obj_or_id)
5643
-            ) {
5644
-                // assume its a string representation of the object
5645
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5646
-            } else {
5647
-                throw new EE_Error(
5648
-                    sprintf(
5649
-                        __(
5650
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5651
-                            'event_espresso'
5652
-                        ),
5653
-                        $base_class_obj_or_id,
5654
-                        $this->_get_class_name(),
5655
-                        print_r($base_class_obj_or_id, true)
5656
-                    )
5657
-                );
5658
-            }
5659
-        }
5660
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5661
-            $model_object->save();
5662
-        }
5663
-        return $model_object;
5664
-    }
5665
-
5666
-
5667
-
5668
-    /**
5669
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5670
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5671
-     * returns it ID.
5672
-     *
5673
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5674
-     * @return int|string depending on the type of this model object's ID
5675
-     * @throws EE_Error
5676
-     */
5677
-    public function ensure_is_ID($base_class_obj_or_id)
5678
-    {
5679
-        $className = $this->_get_class_name();
5680
-        if ($base_class_obj_or_id instanceof $className) {
5681
-            /** @var $base_class_obj_or_id EE_Base_Class */
5682
-            $id = $base_class_obj_or_id->ID();
5683
-        } elseif (is_int($base_class_obj_or_id)) {
5684
-            // assume it's an ID
5685
-            $id = $base_class_obj_or_id;
5686
-        } elseif (is_string($base_class_obj_or_id)) {
5687
-            // assume its a string representation of the object
5688
-            $id = $base_class_obj_or_id;
5689
-        } else {
5690
-            throw new EE_Error(sprintf(
5691
-                __(
5692
-                    "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5693
-                    'event_espresso'
5694
-                ),
5695
-                $base_class_obj_or_id,
5696
-                $this->_get_class_name(),
5697
-                print_r($base_class_obj_or_id, true)
5698
-            ));
5699
-        }
5700
-        return $id;
5701
-    }
5702
-
5703
-
5704
-
5705
-    /**
5706
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5707
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5708
-     * been sanitized and converted into the appropriate domain.
5709
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5710
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5711
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5712
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5713
-     * $EVT = EEM_Event::instance(); $old_setting =
5714
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5715
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5716
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5717
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5718
-     *
5719
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5720
-     * @return void
5721
-     */
5722
-    public function assume_values_already_prepared_by_model_object(
5723
-        $values_already_prepared = self::not_prepared_by_model_object
5724
-    ) {
5725
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5726
-    }
5727
-
5728
-
5729
-
5730
-    /**
5731
-     * Read comments for assume_values_already_prepared_by_model_object()
5732
-     *
5733
-     * @return int
5734
-     */
5735
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5736
-    {
5737
-        return $this->_values_already_prepared_by_model_object;
5738
-    }
5739
-
5740
-
5741
-
5742
-    /**
5743
-     * Gets all the indexes on this model
5744
-     *
5745
-     * @return EE_Index[]
5746
-     */
5747
-    public function indexes()
5748
-    {
5749
-        return $this->_indexes;
5750
-    }
5751
-
5752
-
5753
-
5754
-    /**
5755
-     * Gets all the Unique Indexes on this model
5756
-     *
5757
-     * @return EE_Unique_Index[]
5758
-     */
5759
-    public function unique_indexes()
5760
-    {
5761
-        $unique_indexes = array();
5762
-        foreach ($this->_indexes as $name => $index) {
5763
-            if ($index instanceof EE_Unique_Index) {
5764
-                $unique_indexes [ $name ] = $index;
5765
-            }
5766
-        }
5767
-        return $unique_indexes;
5768
-    }
5769
-
5770
-
5771
-
5772
-    /**
5773
-     * Gets all the fields which, when combined, make the primary key.
5774
-     * This is usually just an array with 1 element (the primary key), but in cases
5775
-     * where there is no primary key, it's a combination of fields as defined
5776
-     * on a primary index
5777
-     *
5778
-     * @return EE_Model_Field_Base[] indexed by the field's name
5779
-     * @throws EE_Error
5780
-     */
5781
-    public function get_combined_primary_key_fields()
5782
-    {
5783
-        foreach ($this->indexes() as $index) {
5784
-            if ($index instanceof EE_Primary_Key_Index) {
5785
-                return $index->fields();
5786
-            }
5787
-        }
5788
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5789
-    }
5790
-
5791
-
5792
-
5793
-    /**
5794
-     * Used to build a primary key string (when the model has no primary key),
5795
-     * which can be used a unique string to identify this model object.
5796
-     *
5797
-     * @param array $fields_n_values keys are field names, values are their values.
5798
-     *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5799
-     *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5800
-     *                               before passing it to this function (that will convert it from columns-n-values
5801
-     *                               to field-names-n-values).
5802
-     * @return string
5803
-     * @throws EE_Error
5804
-     */
5805
-    public function get_index_primary_key_string($fields_n_values)
5806
-    {
5807
-        $cols_n_values_for_primary_key_index = array_intersect_key(
5808
-            $fields_n_values,
5809
-            $this->get_combined_primary_key_fields()
5810
-        );
5811
-        return http_build_query($cols_n_values_for_primary_key_index);
5812
-    }
5813
-
5814
-
5815
-
5816
-    /**
5817
-     * Gets the field values from the primary key string
5818
-     *
5819
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5820
-     * @param string $index_primary_key_string
5821
-     * @return null|array
5822
-     * @throws EE_Error
5823
-     */
5824
-    public function parse_index_primary_key_string($index_primary_key_string)
5825
-    {
5826
-        $key_fields = $this->get_combined_primary_key_fields();
5827
-        // check all of them are in the $id
5828
-        $key_vals_in_combined_pk = array();
5829
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830
-        foreach ($key_fields as $key_field_name => $field_obj) {
5831
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5832
-                return null;
5833
-            }
5834
-        }
5835
-        return $key_vals_in_combined_pk;
5836
-    }
5837
-
5838
-
5839
-
5840
-    /**
5841
-     * verifies that an array of key-value pairs for model fields has a key
5842
-     * for each field comprising the primary key index
5843
-     *
5844
-     * @param array $key_vals
5845
-     * @return boolean
5846
-     * @throws EE_Error
5847
-     */
5848
-    public function has_all_combined_primary_key_fields($key_vals)
5849
-    {
5850
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851
-        foreach ($keys_it_should_have as $key) {
5852
-            if (! isset($key_vals[ $key ])) {
5853
-                return false;
5854
-            }
5855
-        }
5856
-        return true;
5857
-    }
5858
-
5859
-
5860
-
5861
-    /**
5862
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5863
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5864
-     *
5865
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5866
-     * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5867
-     * @throws EE_Error
5868
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5869
-     *                                                              indexed)
5870
-     */
5871
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5872
-    {
5873
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5874
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5875
-        } elseif (is_array($model_object_or_attributes_array)) {
5876
-            $attributes_array = $model_object_or_attributes_array;
5877
-        } else {
5878
-            throw new EE_Error(sprintf(__(
5879
-                "get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5880
-                "event_espresso"
5881
-            ), $model_object_or_attributes_array));
5882
-        }
5883
-        // even copies obviously won't have the same ID, so remove the primary key
5884
-        // from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
-            unset($attributes_array[ $this->primary_key_name() ]);
5887
-        }
5888
-        if (isset($query_params[0])) {
5889
-            $query_params[0] = array_merge($attributes_array, $query_params);
5890
-        } else {
5891
-            $query_params[0] = $attributes_array;
5892
-        }
5893
-        return $this->get_all($query_params);
5894
-    }
5895
-
5896
-
5897
-
5898
-    /**
5899
-     * Gets the first copy we find. See get_all_copies for more details
5900
-     *
5901
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5902
-     * @param array $query_params
5903
-     * @return EE_Base_Class
5904
-     * @throws EE_Error
5905
-     */
5906
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907
-    {
5908
-        if (! is_array($query_params)) {
5909
-            EE_Error::doing_it_wrong(
5910
-                'EEM_Base::get_one_copy',
5911
-                sprintf(
5912
-                    __('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5913
-                    gettype($query_params)
5914
-                ),
5915
-                '4.6.0'
5916
-            );
5917
-            $query_params = array();
5918
-        }
5919
-        $query_params['limit'] = 1;
5920
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5921
-        if (is_array($copies)) {
5922
-            return array_shift($copies);
5923
-        }
5924
-        return null;
5925
-    }
5926
-
5927
-
5928
-
5929
-    /**
5930
-     * Updates the item with the specified id. Ignores default query parameters because
5931
-     * we have specified the ID, and its assumed we KNOW what we're doing
5932
-     *
5933
-     * @param array      $fields_n_values keys are field names, values are their new values
5934
-     * @param int|string $id              the value of the primary key to update
5935
-     * @return int number of rows updated
5936
-     * @throws EE_Error
5937
-     */
5938
-    public function update_by_ID($fields_n_values, $id)
5939
-    {
5940
-        $query_params = array(
5941
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5942
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5943
-        );
5944
-        return $this->update($fields_n_values, $query_params);
5945
-    }
5946
-
5947
-
5948
-
5949
-    /**
5950
-     * Changes an operator which was supplied to the models into one usable in SQL
5951
-     *
5952
-     * @param string $operator_supplied
5953
-     * @return string an operator which can be used in SQL
5954
-     * @throws EE_Error
5955
-     */
5956
-    private function _prepare_operator_for_sql($operator_supplied)
5957
-    {
5958
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5959
-            : null;
5960
-        if ($sql_operator) {
5961
-            return $sql_operator;
5962
-        }
5963
-        throw new EE_Error(
5964
-            sprintf(
5965
-                __(
5966
-                    "The operator '%s' is not in the list of valid operators: %s",
5967
-                    "event_espresso"
5968
-                ),
5969
-                $operator_supplied,
5970
-                implode(",", array_keys($this->_valid_operators))
5971
-            )
5972
-        );
5973
-    }
5974
-
5975
-
5976
-
5977
-    /**
5978
-     * Gets the valid operators
5979
-     * @return array keys are accepted strings, values are the SQL they are converted to
5980
-     */
5981
-    public function valid_operators()
5982
-    {
5983
-        return $this->_valid_operators;
5984
-    }
5985
-
5986
-
5987
-
5988
-    /**
5989
-     * Gets the between-style operators (take 2 arguments).
5990
-     * @return array keys are accepted strings, values are the SQL they are converted to
5991
-     */
5992
-    public function valid_between_style_operators()
5993
-    {
5994
-        return array_intersect(
5995
-            $this->valid_operators(),
5996
-            $this->_between_style_operators
5997
-        );
5998
-    }
5999
-
6000
-    /**
6001
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6002
-     * @return array keys are accepted strings, values are the SQL they are converted to
6003
-     */
6004
-    public function valid_like_style_operators()
6005
-    {
6006
-        return array_intersect(
6007
-            $this->valid_operators(),
6008
-            $this->_like_style_operators
6009
-        );
6010
-    }
6011
-
6012
-    /**
6013
-     * Gets the "in"-style operators
6014
-     * @return array keys are accepted strings, values are the SQL they are converted to
6015
-     */
6016
-    public function valid_in_style_operators()
6017
-    {
6018
-        return array_intersect(
6019
-            $this->valid_operators(),
6020
-            $this->_in_style_operators
6021
-        );
6022
-    }
6023
-
6024
-    /**
6025
-     * Gets the "null"-style operators (accept no arguments)
6026
-     * @return array keys are accepted strings, values are the SQL they are converted to
6027
-     */
6028
-    public function valid_null_style_operators()
6029
-    {
6030
-        return array_intersect(
6031
-            $this->valid_operators(),
6032
-            $this->_null_style_operators
6033
-        );
6034
-    }
6035
-
6036
-    /**
6037
-     * Gets an array where keys are the primary keys and values are their 'names'
6038
-     * (as determined by the model object's name() function, which is often overridden)
6039
-     *
6040
-     * @param array $query_params like get_all's
6041
-     * @return string[]
6042
-     * @throws EE_Error
6043
-     */
6044
-    public function get_all_names($query_params = array())
6045
-    {
6046
-        $objs = $this->get_all($query_params);
6047
-        $names = array();
6048
-        foreach ($objs as $obj) {
6049
-            $names[ $obj->ID() ] = $obj->name();
6050
-        }
6051
-        return $names;
6052
-    }
6053
-
6054
-
6055
-
6056
-    /**
6057
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
6058
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6059
-     * this is duplicated effort and reduces efficiency) you would be better to use
6060
-     * array_keys() on $model_objects.
6061
-     *
6062
-     * @param \EE_Base_Class[] $model_objects
6063
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6064
-     *                                               in the returned array
6065
-     * @return array
6066
-     * @throws EE_Error
6067
-     */
6068
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069
-    {
6070
-        if (! $this->has_primary_key_field()) {
6071
-            if (WP_DEBUG) {
6072
-                EE_Error::add_error(
6073
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6074
-                    __FILE__,
6075
-                    __FUNCTION__,
6076
-                    __LINE__
6077
-                );
6078
-            }
6079
-        }
6080
-        $IDs = array();
6081
-        foreach ($model_objects as $model_object) {
6082
-            $id = $model_object->ID();
6083
-            if (! $id) {
6084
-                if ($filter_out_empty_ids) {
6085
-                    continue;
6086
-                }
6087
-                if (WP_DEBUG) {
6088
-                    EE_Error::add_error(
6089
-                        __(
6090
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6091
-                            'event_espresso'
6092
-                        ),
6093
-                        __FILE__,
6094
-                        __FUNCTION__,
6095
-                        __LINE__
6096
-                    );
6097
-                }
6098
-            }
6099
-            $IDs[] = $id;
6100
-        }
6101
-        return $IDs;
6102
-    }
6103
-
6104
-
6105
-
6106
-    /**
6107
-     * Returns the string used in capabilities relating to this model. If there
6108
-     * are no capabilities that relate to this model returns false
6109
-     *
6110
-     * @return string|false
6111
-     */
6112
-    public function cap_slug()
6113
-    {
6114
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6115
-    }
6116
-
6117
-
6118
-
6119
-    /**
6120
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6121
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6122
-     * only returns the cap restrictions array in that context (ie, the array
6123
-     * at that key)
6124
-     *
6125
-     * @param string $context
6126
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
6127
-     * @throws EE_Error
6128
-     */
6129
-    public function cap_restrictions($context = EEM_Base::caps_read)
6130
-    {
6131
-        EEM_Base::verify_is_valid_cap_context($context);
6132
-        // check if we ought to run the restriction generator first
6133
-        if (isset($this->_cap_restriction_generators[ $context ])
6134
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6136
-        ) {
6137
-            $this->_cap_restrictions[ $context ] = array_merge(
6138
-                $this->_cap_restrictions[ $context ],
6139
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6140
-            );
6141
-        }
6142
-        // and make sure we've finalized the construction of each restriction
6143
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6144
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145
-                $where_conditions_obj->_finalize_construct($this);
6146
-            }
6147
-        }
6148
-        return $this->_cap_restrictions[ $context ];
6149
-    }
6150
-
6151
-
6152
-
6153
-    /**
6154
-     * Indicating whether or not this model thinks its a wp core model
6155
-     *
6156
-     * @return boolean
6157
-     */
6158
-    public function is_wp_core_model()
6159
-    {
6160
-        return $this->_wp_core_model;
6161
-    }
6162
-
6163
-
6164
-
6165
-    /**
6166
-     * Gets all the caps that are missing which impose a restriction on
6167
-     * queries made in this context
6168
-     *
6169
-     * @param string $context one of EEM_Base::caps_ constants
6170
-     * @return EE_Default_Where_Conditions[] indexed by capability name
6171
-     * @throws EE_Error
6172
-     */
6173
-    public function caps_missing($context = EEM_Base::caps_read)
6174
-    {
6175
-        $missing_caps = array();
6176
-        $cap_restrictions = $this->cap_restrictions($context);
6177
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
-            if (! EE_Capabilities::instance()
6179
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6180
-            ) {
6181
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6182
-            }
6183
-        }
6184
-        return $missing_caps;
6185
-    }
6186
-
6187
-
6188
-
6189
-    /**
6190
-     * Gets the mapping from capability contexts to action strings used in capability names
6191
-     *
6192
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6193
-     * one of 'read', 'edit', or 'delete'
6194
-     */
6195
-    public function cap_contexts_to_cap_action_map()
6196
-    {
6197
-        return apply_filters(
6198
-            'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6199
-            $this->_cap_contexts_to_cap_action_map,
6200
-            $this
6201
-        );
6202
-    }
6203
-
6204
-
6205
-
6206
-    /**
6207
-     * Gets the action string for the specified capability context
6208
-     *
6209
-     * @param string $context
6210
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6211
-     * @throws EE_Error
6212
-     */
6213
-    public function cap_action_for_context($context)
6214
-    {
6215
-        $mapping = $this->cap_contexts_to_cap_action_map();
6216
-        if (isset($mapping[ $context ])) {
6217
-            return $mapping[ $context ];
6218
-        }
6219
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220
-            return $action;
6221
-        }
6222
-        throw new EE_Error(
6223
-            sprintf(
6224
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6225
-                $context,
6226
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6227
-            )
6228
-        );
6229
-    }
6230
-
6231
-
6232
-
6233
-    /**
6234
-     * Returns all the capability contexts which are valid when querying models
6235
-     *
6236
-     * @return array
6237
-     */
6238
-    public static function valid_cap_contexts()
6239
-    {
6240
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6241
-            self::caps_read,
6242
-            self::caps_read_admin,
6243
-            self::caps_edit,
6244
-            self::caps_delete,
6245
-        ));
6246
-    }
6247
-
6248
-
6249
-
6250
-    /**
6251
-     * Returns all valid options for 'default_where_conditions'
6252
-     *
6253
-     * @return array
6254
-     */
6255
-    public static function valid_default_where_conditions()
6256
-    {
6257
-        return array(
6258
-            EEM_Base::default_where_conditions_all,
6259
-            EEM_Base::default_where_conditions_this_only,
6260
-            EEM_Base::default_where_conditions_others_only,
6261
-            EEM_Base::default_where_conditions_minimum_all,
6262
-            EEM_Base::default_where_conditions_minimum_others,
6263
-            EEM_Base::default_where_conditions_none
6264
-        );
6265
-    }
6266
-
6267
-    // public static function default_where_conditions_full
6268
-    /**
6269
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6270
-     *
6271
-     * @param string $context
6272
-     * @return bool
6273
-     * @throws EE_Error
6274
-     */
6275
-    public static function verify_is_valid_cap_context($context)
6276
-    {
6277
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
6278
-        if (in_array($context, $valid_cap_contexts)) {
6279
-            return true;
6280
-        }
6281
-        throw new EE_Error(
6282
-            sprintf(
6283
-                __(
6284
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6285
-                    'event_espresso'
6286
-                ),
6287
-                $context,
6288
-                'EEM_Base',
6289
-                implode(',', $valid_cap_contexts)
6290
-            )
6291
-        );
6292
-    }
6293
-
6294
-
6295
-
6296
-    /**
6297
-     * Clears all the models field caches. This is only useful when a sub-class
6298
-     * might have added a field or something and these caches might be invalidated
6299
-     */
6300
-    protected function _invalidate_field_caches()
6301
-    {
6302
-        $this->_cache_foreign_key_to_fields = array();
6303
-        $this->_cached_fields = null;
6304
-        $this->_cached_fields_non_db_only = null;
6305
-    }
6306
-
6307
-
6308
-
6309
-    /**
6310
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6311
-     * (eg "and", "or", "not").
6312
-     *
6313
-     * @return array
6314
-     */
6315
-    public function logic_query_param_keys()
6316
-    {
6317
-        return $this->_logic_query_param_keys;
6318
-    }
6319
-
6320
-
6321
-
6322
-    /**
6323
-     * Determines whether or not the where query param array key is for a logic query param.
6324
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6325
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6326
-     *
6327
-     * @param $query_param_key
6328
-     * @return bool
6329
-     */
6330
-    public function is_logic_query_param_key($query_param_key)
6331
-    {
6332
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333
-            if ($query_param_key === $logic_query_param_key
6334
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6335
-            ) {
6336
-                return true;
6337
-            }
6338
-        }
6339
-        return false;
6340
-    }
6341
-
6342
-    /**
6343
-     * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6344
-     * @since 4.9.74.p
6345
-     * @return boolean
6346
-     */
6347
-    public function hasPassword()
6348
-    {
6349
-        // if we don't yet know if there's a password field, find out and remember it for next time.
6350
-        if ($this->has_password_field === null) {
6351
-            $password_field = $this->getPasswordField();
6352
-            $this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6353
-        }
6354
-        return $this->has_password_field;
6355
-    }
6356
-
6357
-    /**
6358
-     * Returns the password field on this model, if there is one
6359
-     * @since 4.9.74.p
6360
-     * @return EE_Password_Field|null
6361
-     */
6362
-    public function getPasswordField()
6363
-    {
6364
-        // if we definetely already know there is a password field or not (because has_password_field is true or false)
6365
-        // there's no need to search for it. If we don't know yet, then find out
6366
-        if ($this->has_password_field === null && $this->password_field === null) {
6367
-            $this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6368
-        }
6369
-        // don't bother setting has_password_field because that's hasPassword()'s job.
6370
-        return $this->password_field;
6371
-    }
6372
-
6373
-
6374
-    /**
6375
-     * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6376
-     * @since 4.9.74.p
6377
-     * @return EE_Model_Field_Base[]
6378
-     * @throws EE_Error
6379
-     */
6380
-    public function getPasswordProtectedFields()
6381
-    {
6382
-        $password_field = $this->getPasswordField();
6383
-        $fields = array();
6384
-        if ($password_field instanceof EE_Password_Field) {
6385
-            $field_names = $password_field->protectedFields();
6386
-            foreach ($field_names as $field_name) {
6387
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6388
-            }
6389
-        }
6390
-        return $fields;
6391
-    }
6392
-
6393
-
6394
-    /**
6395
-     * Checks if the current user can perform the requested action on this model
6396
-     * @since 4.9.74.p
6397
-     * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6398
-     * @param EE_Base_Class|array $model_obj_or_fields_n_values
6399
-     * @return bool
6400
-     * @throws EE_Error
6401
-     * @throws InvalidArgumentException
6402
-     * @throws InvalidDataTypeException
6403
-     * @throws InvalidInterfaceException
6404
-     * @throws ReflectionException
6405
-     * @throws UnexpectedEntityException
6406
-     */
6407
-    public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6408
-    {
6409
-        if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410
-            $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411
-        }
6412
-        if (!is_array($model_obj_or_fields_n_values)) {
6413
-            throw new UnexpectedEntityException(
6414
-                $model_obj_or_fields_n_values,
6415
-                'EE_Base_Class',
6416
-                sprintf(
6417
-                    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'),
6418
-                    __FUNCTION__
6419
-                )
6420
-            );
6421
-        }
6422
-        return $this->exists(
6423
-            $this->alter_query_params_to_restrict_by_ID(
6424
-                $this->get_index_primary_key_string($model_obj_or_fields_n_values),
6425
-                array(
6426
-                    'default_where_conditions' => 'none',
6427
-                    'caps'                     => $cap_to_check,
6428
-                )
6429
-            )
6430
-        );
6431
-    }
6432
-
6433
-    /**
6434
-     * Returns the query param where conditions key to the password affecting this model.
6435
-     * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6436
-     * @since 4.9.74.p
6437
-     * @return null|string
6438
-     * @throws EE_Error
6439
-     * @throws InvalidArgumentException
6440
-     * @throws InvalidDataTypeException
6441
-     * @throws InvalidInterfaceException
6442
-     * @throws ModelConfigurationException
6443
-     * @throws ReflectionException
6444
-     */
6445
-    public function modelChainAndPassword()
6446
-    {
6447
-        if ($this->model_chain_to_password === null) {
6448
-            throw new ModelConfigurationException(
6449
-                $this,
6450
-                esc_html_x(
6451
-                // @codingStandardsIgnoreStart
6452
-                    'Cannot exclude protected data because the model has not specified which model has the password.',
6453
-                    // @codingStandardsIgnoreEnd
6454
-                    '1: model name',
6455
-                    'event_espresso'
6456
-                )
6457
-            );
6458
-        }
6459
-        if ($this->model_chain_to_password === '') {
6460
-            $model_with_password = $this;
6461
-        } else {
6462
-            if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6463
-                $last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6464
-            } else {
6465
-                $last_model_in_chain = $this->model_chain_to_password;
6466
-            }
6467
-            $model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6468
-        }
6469
-
6470
-        $password_field = $model_with_password->getPasswordField();
6471
-        if ($password_field instanceof EE_Password_Field) {
6472
-            $password_field_name = $password_field->get_name();
6473
-        } else {
6474
-            throw new ModelConfigurationException(
6475
-                $this,
6476
-                sprintf(
6477
-                    esc_html_x(
6478
-                        '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"',
6479
-                        '1: model name, 2: special string',
6480
-                        'event_espresso'
6481
-                    ),
6482
-                    $model_with_password->get_this_model_name(),
6483
-                    $this->model_chain_to_password
6484
-                )
6485
-            );
6486
-        }
6487
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6488
-    }
6489
-
6490
-    /**
6491
-     * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6492
-     * or if this model itself has a password affecting access to some of its other fields.
6493
-     * @since 4.9.74.p
6494
-     * @return boolean
6495
-     */
6496
-    public function restrictedByRelatedModelPassword()
6497
-    {
6498
-        return $this->model_chain_to_password !== null;
6499
-    }
3804
+		}
3805
+		return $null_friendly_where_conditions;
3806
+	}
3807
+
3808
+
3809
+
3810
+	/**
3811
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3812
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3813
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3814
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3815
+	 *
3816
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3817
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3818
+	 */
3819
+	private function _get_default_where_conditions($model_relation_path = null)
3820
+	{
3821
+		if ($this->_ignore_where_strategy) {
3822
+			return array();
3823
+		}
3824
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3825
+	}
3826
+
3827
+
3828
+
3829
+	/**
3830
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3831
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3832
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3833
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3834
+	 * Similar to _get_default_where_conditions
3835
+	 *
3836
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3837
+	 * @return array @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md#0-where-conditions
3838
+	 */
3839
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3840
+	{
3841
+		if ($this->_ignore_where_strategy) {
3842
+			return array();
3843
+		}
3844
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3845
+	}
3846
+
3847
+
3848
+
3849
+	/**
3850
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3851
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3852
+	 *
3853
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3854
+	 * @return string
3855
+	 * @throws EE_Error
3856
+	 */
3857
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3858
+	{
3859
+		$selects = $this->_get_columns_to_select_for_this_model();
3860
+		foreach ($model_query_info->get_model_names_included() as $model_relation_chain =>
3861
+			$name_of_other_model_included) {
3862
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3863
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3864
+			foreach ($other_model_selects as $key => $value) {
3865
+				$selects[] = $value;
3866
+			}
3867
+		}
3868
+		return implode(", ", $selects);
3869
+	}
3870
+
3871
+
3872
+
3873
+	/**
3874
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3875
+	 * So that's going to be the columns for all the fields on the model
3876
+	 *
3877
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3878
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3879
+	 */
3880
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3881
+	{
3882
+		$fields = $this->field_settings();
3883
+		$selects = array();
3884
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix(
3885
+			$model_relation_chain,
3886
+			$this->get_this_model_name()
3887
+		);
3888
+		foreach ($fields as $field_obj) {
3889
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3890
+						 . $field_obj->get_table_alias()
3891
+						 . "."
3892
+						 . $field_obj->get_table_column()
3893
+						 . " AS '"
3894
+						 . $table_alias_with_model_relation_chain_prefix
3895
+						 . $field_obj->get_table_alias()
3896
+						 . "."
3897
+						 . $field_obj->get_table_column()
3898
+						 . "'";
3899
+		}
3900
+		// make sure we are also getting the PKs of each table
3901
+		$tables = $this->get_tables();
3902
+		if (count($tables) > 1) {
3903
+			foreach ($tables as $table_obj) {
3904
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905
+									   . $table_obj->get_fully_qualified_pk_column();
3906
+				if (! in_array($qualified_pk_column, $selects)) {
3907
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908
+				}
3909
+			}
3910
+		}
3911
+		return $selects;
3912
+	}
3913
+
3914
+
3915
+
3916
+	/**
3917
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3918
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3919
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3920
+	 * SQL for joining, and the data types
3921
+	 *
3922
+	 * @param null|string                 $original_query_param
3923
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3924
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3925
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3926
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3927
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3928
+	 *                                                          or 'Registration's
3929
+	 * @param string                      $original_query_param what it originally was (eg
3930
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3931
+	 *                                                          matches $query_param
3932
+	 * @throws EE_Error
3933
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3934
+	 */
3935
+	private function _extract_related_model_info_from_query_param(
3936
+		$query_param,
3937
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3938
+		$query_param_type,
3939
+		$original_query_param = null
3940
+	) {
3941
+		if ($original_query_param === null) {
3942
+			$original_query_param = $query_param;
3943
+		}
3944
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3945
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3946
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having', 0, 'custom_selects'), true);
3947
+		$allow_fields = in_array(
3948
+			$query_param_type,
3949
+			array('where', 'having', 'order_by', 'group_by', 'order', 'custom_selects', 0),
3950
+			true
3951
+		);
3952
+		// check to see if we have a field on this model
3953
+		$this_model_fields = $this->field_settings(true);
3954
+		if (array_key_exists($query_param, $this_model_fields)) {
3955
+			if ($allow_fields) {
3956
+				return;
3957
+			}
3958
+			throw new EE_Error(
3959
+				sprintf(
3960
+					__(
3961
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3962
+						"event_espresso"
3963
+					),
3964
+					$query_param,
3965
+					get_class($this),
3966
+					$query_param_type,
3967
+					$original_query_param
3968
+				)
3969
+			);
3970
+		}
3971
+		// check if this is a special logic query param
3972
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3973
+			if ($allow_logic_query_params) {
3974
+				return;
3975
+			}
3976
+			throw new EE_Error(
3977
+				sprintf(
3978
+					__(
3979
+						'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',
3980
+						'event_espresso'
3981
+					),
3982
+					implode('", "', $this->_logic_query_param_keys),
3983
+					$query_param,
3984
+					get_class($this),
3985
+					'<br />',
3986
+					"\t"
3987
+					. ' $passed_in_query_info = <pre>'
3988
+					. print_r($passed_in_query_info, true)
3989
+					. '</pre>'
3990
+					. "\n\t"
3991
+					. ' $query_param_type = '
3992
+					. $query_param_type
3993
+					. "\n\t"
3994
+					. ' $original_query_param = '
3995
+					. $original_query_param
3996
+				)
3997
+			);
3998
+		}
3999
+		// check if it's a custom selection
4000
+		if ($this->_custom_selections instanceof CustomSelects
4001
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4002
+		) {
4003
+			return;
4004
+		}
4005
+		// check if has a model name at the beginning
4006
+		// and
4007
+		// check if it's a field on a related model
4008
+		if ($this->extractJoinModelFromQueryParams(
4009
+			$passed_in_query_info,
4010
+			$query_param,
4011
+			$original_query_param,
4012
+			$query_param_type
4013
+		)) {
4014
+			return;
4015
+		}
4016
+
4017
+		// ok so $query_param didn't start with a model name
4018
+		// and we previously confirmed it wasn't a logic query param or field on the current model
4019
+		// it's wack, that's what it is
4020
+		throw new EE_Error(
4021
+			sprintf(
4022
+				esc_html__(
4023
+					"There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
4024
+					"event_espresso"
4025
+				),
4026
+				$query_param,
4027
+				get_class($this),
4028
+				$query_param_type,
4029
+				$original_query_param
4030
+			)
4031
+		);
4032
+	}
4033
+
4034
+
4035
+	/**
4036
+	 * Extracts any possible join model information from the provided possible_join_string.
4037
+	 * This method will read the provided $possible_join_string value and determine if there are any possible model join
4038
+	 * parts that should be added to the query.
4039
+	 *
4040
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4041
+	 * @param string                      $possible_join_string  Such as Registration.REG_ID, or Registration
4042
+	 * @param null|string                 $original_query_param
4043
+	 * @param string                      $query_parameter_type  The type for the source of the $possible_join_string
4044
+	 *                                                           ('where', 'order_by', 'group_by', 'custom_selects' etc.)
4045
+	 * @return bool  returns true if a join was added and false if not.
4046
+	 * @throws EE_Error
4047
+	 */
4048
+	private function extractJoinModelFromQueryParams(
4049
+		EE_Model_Query_Info_Carrier $query_info_carrier,
4050
+		$possible_join_string,
4051
+		$original_query_param,
4052
+		$query_parameter_type
4053
+	) {
4054
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
+			if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4056
+				$this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
+				$possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4058
+				if ($possible_join_string === '') {
4059
+					// nothing left to $query_param
4060
+					// we should actually end in a field name, not a model like this!
4061
+					throw new EE_Error(
4062
+						sprintf(
4063
+							esc_html__(
4064
+								"Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
4065
+								"event_espresso"
4066
+							),
4067
+							$possible_join_string,
4068
+							$query_parameter_type,
4069
+							get_class($this),
4070
+							$valid_related_model_name
4071
+						)
4072
+					);
4073
+				}
4074
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
4075
+				$related_model_obj->_extract_related_model_info_from_query_param(
4076
+					$possible_join_string,
4077
+					$query_info_carrier,
4078
+					$query_parameter_type,
4079
+					$original_query_param
4080
+				);
4081
+				return true;
4082
+			}
4083
+			if ($possible_join_string === $valid_related_model_name) {
4084
+				$this->_add_join_to_model(
4085
+					$valid_related_model_name,
4086
+					$query_info_carrier,
4087
+					$original_query_param
4088
+				);
4089
+				return true;
4090
+			}
4091
+		}
4092
+		return false;
4093
+	}
4094
+
4095
+
4096
+	/**
4097
+	 * Extracts related models from Custom Selects and sets up any joins for those related models.
4098
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
4099
+	 * @throws EE_Error
4100
+	 */
4101
+	private function extractRelatedModelsFromCustomSelects(EE_Model_Query_Info_Carrier $query_info_carrier)
4102
+	{
4103
+		if ($this->_custom_selections instanceof CustomSelects
4104
+			&& ($this->_custom_selections->type() === CustomSelects::TYPE_STRUCTURED
4105
+				|| $this->_custom_selections->type() == CustomSelects::TYPE_COMPLEX
4106
+			)
4107
+		) {
4108
+			$original_selects = $this->_custom_selections->originalSelects();
4109
+			foreach ($original_selects as $alias => $select_configuration) {
4110
+				$this->extractJoinModelFromQueryParams(
4111
+					$query_info_carrier,
4112
+					$select_configuration[0],
4113
+					$select_configuration[0],
4114
+					'custom_selects'
4115
+				);
4116
+			}
4117
+		}
4118
+	}
4119
+
4120
+
4121
+
4122
+	/**
4123
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
4124
+	 * and store it on $passed_in_query_info
4125
+	 *
4126
+	 * @param string                      $model_name
4127
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
4128
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
4129
+	 *                                                          model and $model_name. Eg, if we are querying Event,
4130
+	 *                                                          and are adding a join to 'Payment' with the original
4131
+	 *                                                          query param key
4132
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
4133
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
4134
+	 *                                                          Payment wants to add default query params so that it
4135
+	 *                                                          will know what models to prepend onto its default query
4136
+	 *                                                          params or in case it wants to rename tables (in case
4137
+	 *                                                          there are multiple joins to the same table)
4138
+	 * @return void
4139
+	 * @throws EE_Error
4140
+	 */
4141
+	private function _add_join_to_model(
4142
+		$model_name,
4143
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
4144
+		$original_query_param
4145
+	) {
4146
+		$relation_obj = $this->related_settings_for($model_name);
4147
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
4148
+		// check if the relation is HABTM, because then we're essentially doing two joins
4149
+		// If so, join first to the JOIN table, and add its data types, and then continue as normal
4150
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4151
+			$join_model_obj = $relation_obj->get_join_model();
4152
+			// replace the model specified with the join model for this relation chain, whi
4153
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain(
4154
+				$model_name,
4155
+				$join_model_obj->get_this_model_name(),
4156
+				$model_relation_chain
4157
+			);
4158
+			$passed_in_query_info->merge(
4159
+				new EE_Model_Query_Info_Carrier(
4160
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4161
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4162
+				)
4163
+			);
4164
+		}
4165
+		// now just join to the other table pointed to by the relation object, and add its data types
4166
+		$passed_in_query_info->merge(
4167
+			new EE_Model_Query_Info_Carrier(
4168
+				array($model_relation_chain => $model_name),
4169
+				$relation_obj->get_join_statement($model_relation_chain)
4170
+			)
4171
+		);
4172
+	}
4173
+
4174
+
4175
+
4176
+	/**
4177
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4178
+	 *
4179
+	 * @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
4180
+	 * @return string of SQL
4181
+	 * @throws EE_Error
4182
+	 */
4183
+	private function _construct_where_clause($where_params)
4184
+	{
4185
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186
+		if ($SQL) {
4187
+			return " WHERE " . $SQL;
4188
+		}
4189
+		return '';
4190
+	}
4191
+
4192
+
4193
+
4194
+	/**
4195
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4196
+	 * and should be passed HAVING parameters, not WHERE parameters
4197
+	 *
4198
+	 * @param array $having_params
4199
+	 * @return string
4200
+	 * @throws EE_Error
4201
+	 */
4202
+	private function _construct_having_clause($having_params)
4203
+	{
4204
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205
+		if ($SQL) {
4206
+			return " HAVING " . $SQL;
4207
+		}
4208
+		return '';
4209
+	}
4210
+
4211
+
4212
+	/**
4213
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4214
+	 * Event_Meta.meta_value = 'foo'))"
4215
+	 *
4216
+	 * @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
4217
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4218
+	 * @throws EE_Error
4219
+	 * @return string of SQL
4220
+	 */
4221
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4222
+	{
4223
+		$where_clauses = array();
4224
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4226
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4227
+				switch ($query_param) {
4228
+					case 'not':
4229
+					case 'NOT':
4230
+						$where_clauses[] = "! ("
4231
+										   . $this->_construct_condition_clause_recursive(
4232
+											   $op_and_value_or_sub_condition,
4233
+											   $glue
4234
+										   )
4235
+										   . ")";
4236
+						break;
4237
+					case 'and':
4238
+					case 'AND':
4239
+						$where_clauses[] = " ("
4240
+										   . $this->_construct_condition_clause_recursive(
4241
+											   $op_and_value_or_sub_condition,
4242
+											   ' AND '
4243
+										   )
4244
+										   . ")";
4245
+						break;
4246
+					case 'or':
4247
+					case 'OR':
4248
+						$where_clauses[] = " ("
4249
+										   . $this->_construct_condition_clause_recursive(
4250
+											   $op_and_value_or_sub_condition,
4251
+											   ' OR '
4252
+										   )
4253
+										   . ")";
4254
+						break;
4255
+				}
4256
+			} else {
4257
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4258
+				// if it's not a normal field, maybe it's a custom selection?
4259
+				if (! $field_obj) {
4260
+					if ($this->_custom_selections instanceof CustomSelects) {
4261
+						$field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262
+					} else {
4263
+						throw new EE_Error(sprintf(__(
4264
+							"%s is neither a valid model field name, nor a custom selection",
4265
+							"event_espresso"
4266
+						), $query_param));
4267
+					}
4268
+				}
4269
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4271
+			}
4272
+		}
4273
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4274
+	}
4275
+
4276
+
4277
+
4278
+	/**
4279
+	 * Takes the input parameter and extract the table name (alias) and column name
4280
+	 *
4281
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4282
+	 * @throws EE_Error
4283
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4284
+	 */
4285
+	private function _deduce_column_name_from_query_param($query_param)
4286
+	{
4287
+		$field = $this->_deduce_field_from_query_param($query_param);
4288
+		if ($field) {
4289
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param(
4290
+				$field->get_model_name(),
4291
+				$query_param
4292
+			);
4293
+			return $table_alias_prefix . $field->get_qualified_column();
4294
+		}
4295
+		if ($this->_custom_selections instanceof CustomSelects
4296
+			&& in_array($query_param, $this->_custom_selections->columnAliases(), true)
4297
+		) {
4298
+			// maybe it's custom selection item?
4299
+			// if so, just use it as the "column name"
4300
+			return $query_param;
4301
+		}
4302
+		$custom_select_aliases = $this->_custom_selections instanceof CustomSelects
4303
+			? implode(',', $this->_custom_selections->columnAliases())
4304
+			: '';
4305
+		throw new EE_Error(
4306
+			sprintf(
4307
+				__(
4308
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4309
+					"event_espresso"
4310
+				),
4311
+				$query_param,
4312
+				$custom_select_aliases
4313
+			)
4314
+		);
4315
+	}
4316
+
4317
+
4318
+
4319
+	/**
4320
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4321
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4322
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4323
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4324
+	 *
4325
+	 * @param string $condition_query_param_key
4326
+	 * @return string
4327
+	 */
4328
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4329
+	{
4330
+		$pos_of_star = strpos($condition_query_param_key, '*');
4331
+		if ($pos_of_star === false) {
4332
+			return $condition_query_param_key;
4333
+		}
4334
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4335
+		return $condition_query_param_sans_star;
4336
+	}
4337
+
4338
+
4339
+
4340
+	/**
4341
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4342
+	 *
4343
+	 * @param                            mixed      array | string    $op_and_value
4344
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4345
+	 * @throws EE_Error
4346
+	 * @return string
4347
+	 */
4348
+	private function _construct_op_and_value($op_and_value, $field_obj)
4349
+	{
4350
+		if (is_array($op_and_value)) {
4351
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
+			if (! $operator) {
4353
+				$php_array_like_string = array();
4354
+				foreach ($op_and_value as $key => $value) {
4355
+					$php_array_like_string[] = "$key=>$value";
4356
+				}
4357
+				throw new EE_Error(
4358
+					sprintf(
4359
+						__(
4360
+							"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))",
4361
+							"event_espresso"
4362
+						),
4363
+						implode(",", $php_array_like_string)
4364
+					)
4365
+				);
4366
+			}
4367
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4368
+		} else {
4369
+			$operator = '=';
4370
+			$value = $op_and_value;
4371
+		}
4372
+		// check to see if the value is actually another field
4373
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4375
+		}
4376
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377
+			// in this case, the value should be an array, or at least a comma-separated list
4378
+			// it will need to handle a little differently
4379
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4380
+			// note: $cleaned_value has already been run through $wpdb->prepare()
4381
+			return $operator . SP . $cleaned_value;
4382
+		}
4383
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384
+			// the value should be an array with count of two.
4385
+			if (count($value) !== 2) {
4386
+				throw new EE_Error(
4387
+					sprintf(
4388
+						__(
4389
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4390
+							'event_espresso'
4391
+						),
4392
+						"BETWEEN"
4393
+					)
4394
+				);
4395
+			}
4396
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
+			return $operator . SP . $cleaned_value;
4398
+		}
4399
+		if (in_array($operator, $this->valid_null_style_operators())) {
4400
+			if ($value !== null) {
4401
+				throw new EE_Error(
4402
+					sprintf(
4403
+						__(
4404
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4405
+							"event_espresso"
4406
+						),
4407
+						$value,
4408
+						$operator
4409
+					)
4410
+				);
4411
+			}
4412
+			return $operator;
4413
+		}
4414
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415
+			// if the operator is 'LIKE', we want to allow percent signs (%) and not
4416
+			// remove other junk. So just treat it as a string.
4417
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4418
+		}
4419
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4421
+		}
4422
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423
+			throw new EE_Error(
4424
+				sprintf(
4425
+					__(
4426
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4427
+						'event_espresso'
4428
+					),
4429
+					$operator,
4430
+					$operator
4431
+				)
4432
+			);
4433
+		}
4434
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435
+			throw new EE_Error(
4436
+				sprintf(
4437
+					__(
4438
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4439
+						'event_espresso'
4440
+					),
4441
+					$operator,
4442
+					$operator
4443
+				)
4444
+			);
4445
+		}
4446
+		throw new EE_Error(
4447
+			sprintf(
4448
+				__(
4449
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4450
+					"event_espresso"
4451
+				),
4452
+				http_build_query($op_and_value)
4453
+			)
4454
+		);
4455
+	}
4456
+
4457
+
4458
+
4459
+	/**
4460
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4461
+	 *
4462
+	 * @param array                      $values
4463
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4464
+	 *                                              '%s'
4465
+	 * @return string
4466
+	 * @throws EE_Error
4467
+	 */
4468
+	public function _construct_between_value($values, $field_obj)
4469
+	{
4470
+		$cleaned_values = array();
4471
+		foreach ($values as $value) {
4472
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473
+		}
4474
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4475
+	}
4476
+
4477
+
4478
+
4479
+	/**
4480
+	 * Takes an array or a comma-separated list of $values and cleans them
4481
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4482
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4483
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4484
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4485
+	 *
4486
+	 * @param mixed                      $values    array or comma-separated string
4487
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4488
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4489
+	 * @throws EE_Error
4490
+	 */
4491
+	public function _construct_in_value($values, $field_obj)
4492
+	{
4493
+		// check if the value is a CSV list
4494
+		if (is_string($values)) {
4495
+			// in which case, turn it into an array
4496
+			$values = explode(",", $values);
4497
+		}
4498
+		$cleaned_values = array();
4499
+		foreach ($values as $value) {
4500
+			$cleaned_values[] = $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($cleaned_values)) {
4506
+			$all_fields = $this->field_settings();
4507
+			$a_field = array_shift($all_fields);
4508
+			$main_table = $this->_get_main_table();
4509
+			$cleaned_values[] = "SELECT "
4510
+								. $a_field->get_table_column()
4511
+								. " FROM "
4512
+								. $main_table->get_table_name()
4513
+								. " WHERE FALSE";
4514
+		}
4515
+		return "(" . implode(",", $cleaned_values) . ")";
4516
+	}
4517
+
4518
+
4519
+
4520
+	/**
4521
+	 * @param mixed                      $value
4522
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4523
+	 * @throws EE_Error
4524
+	 * @return false|null|string
4525
+	 */
4526
+	private function _wpdb_prepare_using_field($value, $field_obj)
4527
+	{
4528
+		/** @type WPDB $wpdb */
4529
+		global $wpdb;
4530
+		if ($field_obj instanceof EE_Model_Field_Base) {
4531
+			return $wpdb->prepare(
4532
+				$field_obj->get_wpdb_data_type(),
4533
+				$this->_prepare_value_for_use_in_db($value, $field_obj)
4534
+			);
4535
+		} //$field_obj should really just be a data type
4536
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537
+			throw new EE_Error(
4538
+				sprintf(
4539
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4540
+					$field_obj,
4541
+					implode(",", $this->_valid_wpdb_data_types)
4542
+				)
4543
+			);
4544
+		}
4545
+		return $wpdb->prepare($field_obj, $value);
4546
+	}
4547
+
4548
+
4549
+
4550
+	/**
4551
+	 * Takes the input parameter and finds the model field that it indicates.
4552
+	 *
4553
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4554
+	 * @throws EE_Error
4555
+	 * @return EE_Model_Field_Base
4556
+	 */
4557
+	protected function _deduce_field_from_query_param($query_param_name)
4558
+	{
4559
+		// ok, now proceed with deducing which part is the model's name, and which is the field's name
4560
+		// which will help us find the database table and column
4561
+		$query_param_parts = explode(".", $query_param_name);
4562
+		if (empty($query_param_parts)) {
4563
+			throw new EE_Error(sprintf(__(
4564
+				"_extract_column_name is empty when trying to extract column and table name from %s",
4565
+				'event_espresso'
4566
+			), $query_param_name));
4567
+		}
4568
+		$number_of_parts = count($query_param_parts);
4569
+		$last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4570
+		if ($number_of_parts === 1) {
4571
+			$field_name = $last_query_param_part;
4572
+			$model_obj = $this;
4573
+		} else {// $number_of_parts >= 2
4574
+			// the last part is the column name, and there are only 2parts. therefore...
4575
+			$field_name = $last_query_param_part;
4576
+			$model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4577
+		}
4578
+		try {
4579
+			return $model_obj->field_settings_for($field_name);
4580
+		} catch (EE_Error $e) {
4581
+			return null;
4582
+		}
4583
+	}
4584
+
4585
+
4586
+
4587
+	/**
4588
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4589
+	 * alias and column which corresponds to it
4590
+	 *
4591
+	 * @param string $field_name
4592
+	 * @throws EE_Error
4593
+	 * @return string
4594
+	 */
4595
+	public function _get_qualified_column_for_field($field_name)
4596
+	{
4597
+		$all_fields = $this->field_settings();
4598
+		$field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4599
+		if ($field) {
4600
+			return $field->get_qualified_column();
4601
+		}
4602
+		throw new EE_Error(
4603
+			sprintf(
4604
+				__(
4605
+					"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.",
4606
+					'event_espresso'
4607
+				),
4608
+				$field_name,
4609
+				get_class($this)
4610
+			)
4611
+		);
4612
+	}
4613
+
4614
+
4615
+
4616
+	/**
4617
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4618
+	 * Example usage:
4619
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4620
+	 *      array(),
4621
+	 *      ARRAY_A,
4622
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4623
+	 *  );
4624
+	 * is equivalent to
4625
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4626
+	 * and
4627
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4628
+	 *      array(
4629
+	 *          array(
4630
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4631
+	 *          ),
4632
+	 *          ARRAY_A,
4633
+	 *          implode(
4634
+	 *              ', ',
4635
+	 *              array_merge(
4636
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4637
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4638
+	 *              )
4639
+	 *          )
4640
+	 *      )
4641
+	 *  );
4642
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4643
+	 *
4644
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4645
+	 *                                            and the one whose fields you are selecting for example: when querying
4646
+	 *                                            tickets model and selecting fields from the tickets model you would
4647
+	 *                                            leave this parameter empty, because no models are needed to join
4648
+	 *                                            between the queried model and the selected one. Likewise when
4649
+	 *                                            querying the datetime model and selecting fields from the tickets
4650
+	 *                                            model, it would also be left empty, because there is a direct
4651
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4652
+	 *                                            them together. However, when querying from the event model and
4653
+	 *                                            selecting fields from the ticket model, you should provide the string
4654
+	 *                                            'Datetime', indicating that the event model must first join to the
4655
+	 *                                            datetime model in order to find its relation to ticket model.
4656
+	 *                                            Also, when querying from the venue model and selecting fields from
4657
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4658
+	 *                                            indicating you need to join the venue model to the event model,
4659
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4660
+	 *                                            This string is used to deduce the prefix that gets added onto the
4661
+	 *                                            models' tables qualified columns
4662
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4663
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4664
+	 *                                            qualified column names
4665
+	 * @return array|string
4666
+	 */
4667
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668
+	{
4669
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4670
+		$qualified_columns = array();
4671
+		foreach ($this->field_settings() as $field_name => $field) {
4672
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4673
+		}
4674
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675
+	}
4676
+
4677
+
4678
+
4679
+	/**
4680
+	 * constructs the select use on special limit joins
4681
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4682
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4683
+	 * (as that is typically where the limits would be set).
4684
+	 *
4685
+	 * @param  string       $table_alias The table the select is being built for
4686
+	 * @param  mixed|string $limit       The limit for this select
4687
+	 * @return string                The final select join element for the query.
4688
+	 */
4689
+	public function _construct_limit_join_select($table_alias, $limit)
4690
+	{
4691
+		$SQL = '';
4692
+		foreach ($this->_tables as $table_obj) {
4693
+			if ($table_obj instanceof EE_Primary_Table) {
4694
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4695
+					? $table_obj->get_select_join_limit($limit)
4696
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4697
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4698
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4699
+					? $table_obj->get_select_join_limit_join($limit)
4700
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4701
+			}
4702
+		}
4703
+		return $SQL;
4704
+	}
4705
+
4706
+
4707
+
4708
+	/**
4709
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4710
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4711
+	 *
4712
+	 * @return string SQL
4713
+	 * @throws EE_Error
4714
+	 */
4715
+	public function _construct_internal_join()
4716
+	{
4717
+		$SQL = $this->_get_main_table()->get_table_sql();
4718
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4719
+		return $SQL;
4720
+	}
4721
+
4722
+
4723
+
4724
+	/**
4725
+	 * Constructs the SQL for joining all the tables on this model.
4726
+	 * Normally $alias should be the primary table's alias, but in cases where
4727
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4728
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4729
+	 * alias, this will construct SQL like:
4730
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4731
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4732
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4733
+	 *
4734
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4735
+	 * @return string
4736
+	 */
4737
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4738
+	{
4739
+		$SQL = '';
4740
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4741
+		foreach ($this->_tables as $table_obj) {
4742
+			if ($table_obj instanceof EE_Secondary_Table) {// table is secondary table
4743
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4744
+					// so we're joining to this table, meaning the table is already in
4745
+					// the FROM statement, BUT the primary table isn't. So we want
4746
+					// to add the inverse join sql
4747
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4748
+				} else {
4749
+					// just add a regular JOIN to this table from the primary table
4750
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4751
+				}
4752
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4753
+		}
4754
+		return $SQL;
4755
+	}
4756
+
4757
+
4758
+
4759
+	/**
4760
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4761
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4762
+	 * their data type (eg, '%s', '%d', etc)
4763
+	 *
4764
+	 * @return array
4765
+	 */
4766
+	public function _get_data_types()
4767
+	{
4768
+		$data_types = array();
4769
+		foreach ($this->field_settings() as $field_obj) {
4770
+			// $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771
+			/** @var $field_obj EE_Model_Field_Base */
4772
+			$data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4773
+		}
4774
+		return $data_types;
4775
+	}
4776
+
4777
+
4778
+
4779
+	/**
4780
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4781
+	 *
4782
+	 * @param string $model_name
4783
+	 * @throws EE_Error
4784
+	 * @return EEM_Base
4785
+	 */
4786
+	public function get_related_model_obj($model_name)
4787
+	{
4788
+		$model_classname = "EEM_" . $model_name;
4789
+		if (! class_exists($model_classname)) {
4790
+			throw new EE_Error(sprintf(__(
4791
+				"You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792
+				'event_espresso'
4793
+			), $model_name, $model_classname));
4794
+		}
4795
+		return call_user_func($model_classname . "::instance");
4796
+	}
4797
+
4798
+
4799
+
4800
+	/**
4801
+	 * Returns the array of EE_ModelRelations for this model.
4802
+	 *
4803
+	 * @return EE_Model_Relation_Base[]
4804
+	 */
4805
+	public function relation_settings()
4806
+	{
4807
+		return $this->_model_relations;
4808
+	}
4809
+
4810
+
4811
+
4812
+	/**
4813
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4814
+	 * because without THOSE models, this model probably doesn't have much purpose.
4815
+	 * (Eg, without an event, datetimes have little purpose.)
4816
+	 *
4817
+	 * @return EE_Belongs_To_Relation[]
4818
+	 */
4819
+	public function belongs_to_relations()
4820
+	{
4821
+		$belongs_to_relations = array();
4822
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
+				$belongs_to_relations[ $model_name ] = $relation_obj;
4825
+			}
4826
+		}
4827
+		return $belongs_to_relations;
4828
+	}
4829
+
4830
+
4831
+
4832
+	/**
4833
+	 * Returns the specified EE_Model_Relation, or throws an exception
4834
+	 *
4835
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4836
+	 * @throws EE_Error
4837
+	 * @return EE_Model_Relation_Base
4838
+	 */
4839
+	public function related_settings_for($relation_name)
4840
+	{
4841
+		$relatedModels = $this->relation_settings();
4842
+		if (! array_key_exists($relation_name, $relatedModels)) {
4843
+			throw new EE_Error(
4844
+				sprintf(
4845
+					__(
4846
+						'Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4847
+						'event_espresso'
4848
+					),
4849
+					$relation_name,
4850
+					$this->_get_class_name(),
4851
+					implode(', ', array_keys($relatedModels))
4852
+				)
4853
+			);
4854
+		}
4855
+		return $relatedModels[ $relation_name ];
4856
+	}
4857
+
4858
+
4859
+
4860
+	/**
4861
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4862
+	 * fields
4863
+	 *
4864
+	 * @param string $fieldName
4865
+	 * @param boolean $include_db_only_fields
4866
+	 * @throws EE_Error
4867
+	 * @return EE_Model_Field_Base
4868
+	 */
4869
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4870
+	{
4871
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4872
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4873
+			throw new EE_Error(sprintf(
4874
+				__("There is no field/column '%s' on '%s'", 'event_espresso'),
4875
+				$fieldName,
4876
+				get_class($this)
4877
+			));
4878
+		}
4879
+		return $fieldSettings[ $fieldName ];
4880
+	}
4881
+
4882
+
4883
+
4884
+	/**
4885
+	 * Checks if this field exists on this model
4886
+	 *
4887
+	 * @param string $fieldName a key in the model's _field_settings array
4888
+	 * @return boolean
4889
+	 */
4890
+	public function has_field($fieldName)
4891
+	{
4892
+		$fieldSettings = $this->field_settings(true);
4893
+		if (isset($fieldSettings[ $fieldName ])) {
4894
+			return true;
4895
+		}
4896
+		return false;
4897
+	}
4898
+
4899
+
4900
+
4901
+	/**
4902
+	 * Returns whether or not this model has a relation to the specified model
4903
+	 *
4904
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4905
+	 * @return boolean
4906
+	 */
4907
+	public function has_relation($relation_name)
4908
+	{
4909
+		$relations = $this->relation_settings();
4910
+		if (isset($relations[ $relation_name ])) {
4911
+			return true;
4912
+		}
4913
+		return false;
4914
+	}
4915
+
4916
+
4917
+
4918
+	/**
4919
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4920
+	 * Eg, on EE_Answer that would be ANS_ID field object
4921
+	 *
4922
+	 * @param $field_obj
4923
+	 * @return boolean
4924
+	 */
4925
+	public function is_primary_key_field($field_obj)
4926
+	{
4927
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4928
+	}
4929
+
4930
+
4931
+
4932
+	/**
4933
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4934
+	 * Eg, on EE_Answer that would be ANS_ID field object
4935
+	 *
4936
+	 * @return EE_Model_Field_Base
4937
+	 * @throws EE_Error
4938
+	 */
4939
+	public function get_primary_key_field()
4940
+	{
4941
+		if ($this->_primary_key_field === null) {
4942
+			foreach ($this->field_settings(true) as $field_obj) {
4943
+				if ($this->is_primary_key_field($field_obj)) {
4944
+					$this->_primary_key_field = $field_obj;
4945
+					break;
4946
+				}
4947
+			}
4948
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949
+				throw new EE_Error(sprintf(
4950
+					__("There is no Primary Key defined on model %s", 'event_espresso'),
4951
+					get_class($this)
4952
+				));
4953
+			}
4954
+		}
4955
+		return $this->_primary_key_field;
4956
+	}
4957
+
4958
+
4959
+
4960
+	/**
4961
+	 * Returns whether or not not there is a primary key on this model.
4962
+	 * Internally does some caching.
4963
+	 *
4964
+	 * @return boolean
4965
+	 */
4966
+	public function has_primary_key_field()
4967
+	{
4968
+		if ($this->_has_primary_key_field === null) {
4969
+			try {
4970
+				$this->get_primary_key_field();
4971
+				$this->_has_primary_key_field = true;
4972
+			} catch (EE_Error $e) {
4973
+				$this->_has_primary_key_field = false;
4974
+			}
4975
+		}
4976
+		return $this->_has_primary_key_field;
4977
+	}
4978
+
4979
+
4980
+
4981
+	/**
4982
+	 * Finds the first field of type $field_class_name.
4983
+	 *
4984
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4985
+	 *                                 EE_Foreign_Key_Field, etc
4986
+	 * @return EE_Model_Field_Base or null if none is found
4987
+	 */
4988
+	public function get_a_field_of_type($field_class_name)
4989
+	{
4990
+		foreach ($this->field_settings() as $field) {
4991
+			if ($field instanceof $field_class_name) {
4992
+				return $field;
4993
+			}
4994
+		}
4995
+		return null;
4996
+	}
4997
+
4998
+
4999
+
5000
+	/**
5001
+	 * Gets a foreign key field pointing to model.
5002
+	 *
5003
+	 * @param string $model_name eg Event, Registration, not EEM_Event
5004
+	 * @return EE_Foreign_Key_Field_Base
5005
+	 * @throws EE_Error
5006
+	 */
5007
+	public function get_foreign_key_to($model_name)
5008
+	{
5009
+		if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5010
+			foreach ($this->field_settings() as $field) {
5011
+				if ($field instanceof EE_Foreign_Key_Field_Base
5012
+					&& in_array($model_name, $field->get_model_names_pointed_to())
5013
+				) {
5014
+					$this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5015
+					break;
5016
+				}
5017
+			}
5018
+			if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5019
+				throw new EE_Error(sprintf(__(
5020
+					"There is no foreign key field pointing to model %s on model %s",
5021
+					'event_espresso'
5022
+				), $model_name, get_class($this)));
5023
+			}
5024
+		}
5025
+		return $this->_cache_foreign_key_to_fields[ $model_name ];
5026
+	}
5027
+
5028
+
5029
+
5030
+	/**
5031
+	 * Gets the table name (including $wpdb->prefix) for the table alias
5032
+	 *
5033
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
5034
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
5035
+	 *                            Either one works
5036
+	 * @return string
5037
+	 */
5038
+	public function get_table_for_alias($table_alias)
5039
+	{
5040
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
+		return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5042
+	}
5043
+
5044
+
5045
+
5046
+	/**
5047
+	 * Returns a flat array of all field son this model, instead of organizing them
5048
+	 * by table_alias as they are in the constructor.
5049
+	 *
5050
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
5051
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
5052
+	 */
5053
+	public function field_settings($include_db_only_fields = false)
5054
+	{
5055
+		if ($include_db_only_fields) {
5056
+			if ($this->_cached_fields === null) {
5057
+				$this->_cached_fields = array();
5058
+				foreach ($this->_fields as $fields_corresponding_to_table) {
5059
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
+						$this->_cached_fields[ $field_name ] = $field_obj;
5061
+					}
5062
+				}
5063
+			}
5064
+			return $this->_cached_fields;
5065
+		}
5066
+		if ($this->_cached_fields_non_db_only === null) {
5067
+			$this->_cached_fields_non_db_only = array();
5068
+			foreach ($this->_fields as $fields_corresponding_to_table) {
5069
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070
+					/** @var $field_obj EE_Model_Field_Base */
5071
+					if (! $field_obj->is_db_only_field()) {
5072
+						$this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5073
+					}
5074
+				}
5075
+			}
5076
+		}
5077
+		return $this->_cached_fields_non_db_only;
5078
+	}
5079
+
5080
+
5081
+
5082
+	/**
5083
+	 *        cycle though array of attendees and create objects out of each item
5084
+	 *
5085
+	 * @access        private
5086
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
5087
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
5088
+	 *                           numerically indexed)
5089
+	 * @throws EE_Error
5090
+	 */
5091
+	protected function _create_objects($rows = array())
5092
+	{
5093
+		$array_of_objects = array();
5094
+		if (empty($rows)) {
5095
+			return array();
5096
+		}
5097
+		$count_if_model_has_no_primary_key = 0;
5098
+		$has_primary_key = $this->has_primary_key_field();
5099
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
5100
+		foreach ((array) $rows as $row) {
5101
+			if (empty($row)) {
5102
+				// wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
5103
+				return array();
5104
+			}
5105
+			// check if we've already set this object in the results array,
5106
+			// in which case there's no need to process it further (again)
5107
+			if ($has_primary_key) {
5108
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5109
+					$row,
5110
+					$primary_key_field->get_qualified_column(),
5111
+					$primary_key_field->get_table_column()
5112
+				);
5113
+				if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5114
+					continue;
5115
+				}
5116
+			}
5117
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
5118
+			if (! $classInstance) {
5119
+				throw new EE_Error(
5120
+					sprintf(
5121
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
5122
+						$this->get_this_model_name(),
5123
+						http_build_query($row)
5124
+					)
5125
+				);
5126
+			}
5127
+			// set the timezone on the instantiated objects
5128
+			$classInstance->set_timezone($this->_timezone);
5129
+			// make sure if there is any timezone setting present that we set the timezone for the object
5130
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
+			$array_of_objects[ $key ] = $classInstance;
5132
+			// also, for all the relations of type BelongsTo, see if we can cache
5133
+			// those related models
5134
+			// (we could do this for other relations too, but if there are conditions
5135
+			// that filtered out some fo the results, then we'd be caching an incomplete set
5136
+			// so it requires a little more thought than just caching them immediately...)
5137
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
5138
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
5139
+					// check if this model's INFO is present. If so, cache it on the model
5140
+					$other_model = $relation_obj->get_other_model();
5141
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
5142
+					// if we managed to make a model object from the results, cache it on the main model object
5143
+					if ($other_model_obj_maybe) {
5144
+						// set timezone on these other model objects if they are present
5145
+						$other_model_obj_maybe->set_timezone($this->_timezone);
5146
+						$classInstance->cache($modelName, $other_model_obj_maybe);
5147
+					}
5148
+				}
5149
+			}
5150
+			// also, if this was a custom select query, let's see if there are any results for the custom select fields
5151
+			// and add them to the object as well.  We'll convert according to the set data_type if there's any set for
5152
+			// the field in the CustomSelects object
5153
+			if ($this->_custom_selections instanceof CustomSelects) {
5154
+				$classInstance->setCustomSelectsValues(
5155
+					$this->getValuesForCustomSelectAliasesFromResults($row)
5156
+				);
5157
+			}
5158
+		}
5159
+		return $array_of_objects;
5160
+	}
5161
+
5162
+
5163
+	/**
5164
+	 * This will parse a given row of results from the db and see if any keys in the results match an alias within the
5165
+	 * current CustomSelects object. This will be used to build an array of values indexed by those keys.
5166
+	 *
5167
+	 * @param array $db_results_row
5168
+	 * @return array
5169
+	 */
5170
+	protected function getValuesForCustomSelectAliasesFromResults(array $db_results_row)
5171
+	{
5172
+		$results = array();
5173
+		if ($this->_custom_selections instanceof CustomSelects) {
5174
+			foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
+				if (isset($db_results_row[ $alias ])) {
5176
+					$results[ $alias ] = $this->convertValueToDataType(
5177
+						$db_results_row[ $alias ],
5178
+						$this->_custom_selections->getDataTypeForAlias($alias)
5179
+					);
5180
+				}
5181
+			}
5182
+		}
5183
+		return $results;
5184
+	}
5185
+
5186
+
5187
+	/**
5188
+	 * This will set the value for the given alias
5189
+	 * @param string $value
5190
+	 * @param string $datatype (one of %d, %s, %f)
5191
+	 * @return int|string|float (int for %d, string for %s, float for %f)
5192
+	 */
5193
+	protected function convertValueToDataType($value, $datatype)
5194
+	{
5195
+		switch ($datatype) {
5196
+			case '%f':
5197
+				return (float) $value;
5198
+			case '%d':
5199
+				return (int) $value;
5200
+			default:
5201
+				return (string) $value;
5202
+		}
5203
+	}
5204
+
5205
+
5206
+	/**
5207
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
5208
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
5209
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
5210
+	 * object (as set in the model_field!).
5211
+	 *
5212
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
5213
+	 */
5214
+	public function create_default_object()
5215
+	{
5216
+		$this_model_fields_and_values = array();
5217
+		// setup the row using default values;
5218
+		foreach ($this->field_settings() as $field_name => $field_obj) {
5219
+			$this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5220
+		}
5221
+		$className = $this->_get_class_name();
5222
+		$classInstance = EE_Registry::instance()
5223
+									->load_class($className, array($this_model_fields_and_values), false, false);
5224
+		return $classInstance;
5225
+	}
5226
+
5227
+
5228
+
5229
+	/**
5230
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
5231
+	 *                             or an stdClass where each property is the name of a column,
5232
+	 * @return EE_Base_Class
5233
+	 * @throws EE_Error
5234
+	 */
5235
+	public function instantiate_class_from_array_or_object($cols_n_values)
5236
+	{
5237
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5238
+			$cols_n_values = get_object_vars($cols_n_values);
5239
+		}
5240
+		$primary_key = null;
5241
+		// make sure the array only has keys that are fields/columns on this model
5242
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
+			$primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5245
+		}
5246
+		$className = $this->_get_class_name();
5247
+		// check we actually found results that we can use to build our model object
5248
+		// if not, return null
5249
+		if ($this->has_primary_key_field()) {
5250
+			if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5251
+				return null;
5252
+			}
5253
+		} elseif ($this->unique_indexes()) {
5254
+			$first_column = reset($this_model_fields_n_values);
5255
+			if (empty($first_column)) {
5256
+				return null;
5257
+			}
5258
+		}
5259
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260
+		if ($primary_key) {
5261
+			$classInstance = $this->get_from_entity_map($primary_key);
5262
+			if (! $classInstance) {
5263
+				$classInstance = EE_Registry::instance()
5264
+											->load_class(
5265
+												$className,
5266
+												array($this_model_fields_n_values, $this->_timezone),
5267
+												true,
5268
+												false
5269
+											);
5270
+				// add this new object to the entity map
5271
+				$classInstance = $this->add_to_entity_map($classInstance);
5272
+			}
5273
+		} else {
5274
+			$classInstance = EE_Registry::instance()
5275
+										->load_class(
5276
+											$className,
5277
+											array($this_model_fields_n_values, $this->_timezone),
5278
+											true,
5279
+											false
5280
+										);
5281
+		}
5282
+		return $classInstance;
5283
+	}
5284
+
5285
+
5286
+
5287
+	/**
5288
+	 * Gets the model object from the  entity map if it exists
5289
+	 *
5290
+	 * @param int|string $id the ID of the model object
5291
+	 * @return EE_Base_Class
5292
+	 */
5293
+	public function get_from_entity_map($id)
5294
+	{
5295
+		return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
+			? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5297
+	}
5298
+
5299
+
5300
+
5301
+	/**
5302
+	 * add_to_entity_map
5303
+	 * Adds the object to the model's entity mappings
5304
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5305
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5306
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5307
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5308
+	 *        then this method should be called immediately after the update query
5309
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5310
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5311
+	 *
5312
+	 * @param    EE_Base_Class $object
5313
+	 * @throws EE_Error
5314
+	 * @return \EE_Base_Class
5315
+	 */
5316
+	public function add_to_entity_map(EE_Base_Class $object)
5317
+	{
5318
+		$className = $this->_get_class_name();
5319
+		if (! $object instanceof $className) {
5320
+			throw new EE_Error(sprintf(
5321
+				__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322
+				is_object($object) ? get_class($object) : $object,
5323
+				$className
5324
+			));
5325
+		}
5326
+		/** @var $object EE_Base_Class */
5327
+		if (! $object->ID()) {
5328
+			throw new EE_Error(sprintf(__(
5329
+				"You tried storing a model object with NO ID in the %s entity mapper.",
5330
+				"event_espresso"
5331
+			), get_class($this)));
5332
+		}
5333
+		// double check it's not already there
5334
+		$classInstance = $this->get_from_entity_map($object->ID());
5335
+		if ($classInstance) {
5336
+			return $classInstance;
5337
+		}
5338
+		$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5339
+		return $object;
5340
+	}
5341
+
5342
+
5343
+
5344
+	/**
5345
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5346
+	 * if no identifier is provided, then the entire entity map is emptied
5347
+	 *
5348
+	 * @param int|string $id the ID of the model object
5349
+	 * @return boolean
5350
+	 */
5351
+	public function clear_entity_map($id = null)
5352
+	{
5353
+		if (empty($id)) {
5354
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5355
+			return true;
5356
+		}
5357
+		if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
+			unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5359
+			return true;
5360
+		}
5361
+		return false;
5362
+	}
5363
+
5364
+
5365
+
5366
+	/**
5367
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5368
+	 * Given an array where keys are column (or column alias) names and values,
5369
+	 * returns an array of their corresponding field names and database values
5370
+	 *
5371
+	 * @param array $cols_n_values
5372
+	 * @return array
5373
+	 */
5374
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5375
+	{
5376
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5377
+	}
5378
+
5379
+
5380
+
5381
+	/**
5382
+	 * _deduce_fields_n_values_from_cols_n_values
5383
+	 * Given an array where keys are column (or column alias) names and values,
5384
+	 * returns an array of their corresponding field names and database values
5385
+	 *
5386
+	 * @param string $cols_n_values
5387
+	 * @return array
5388
+	 */
5389
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5390
+	{
5391
+		$this_model_fields_n_values = array();
5392
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5393
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
5394
+				$cols_n_values,
5395
+				$table_obj->get_fully_qualified_pk_column(),
5396
+				$table_obj->get_pk_column()
5397
+			);
5398
+			// there is a primary key on this table and its not set. Use defaults for all its columns
5399
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
+					if (! $field_obj->is_db_only_field()) {
5402
+						// prepare field as if its coming from db
5403
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
+						$this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5405
+					}
5406
+				}
5407
+			} else {
5408
+				// the table's rows existed. Use their values
5409
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
+					if (! $field_obj->is_db_only_field()) {
5411
+						$this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5412
+							$cols_n_values,
5413
+							$field_obj->get_qualified_column(),
5414
+							$field_obj->get_table_column()
5415
+						);
5416
+					}
5417
+				}
5418
+			}
5419
+		}
5420
+		return $this_model_fields_n_values;
5421
+	}
5422
+
5423
+
5424
+	/**
5425
+	 * @param $cols_n_values
5426
+	 * @param $qualified_column
5427
+	 * @param $regular_column
5428
+	 * @return null
5429
+	 * @throws EE_Error
5430
+	 * @throws ReflectionException
5431
+	 */
5432
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5433
+	{
5434
+		$value = null;
5435
+		// ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436
+		// does the field on the model relate to this column retrieved from the db?
5437
+		// or is it a db-only field? (not relating to the model)
5438
+		if (isset($cols_n_values[ $qualified_column ])) {
5439
+			$value = $cols_n_values[ $qualified_column ];
5440
+		} elseif (isset($cols_n_values[ $regular_column ])) {
5441
+			$value = $cols_n_values[ $regular_column ];
5442
+		} elseif (! empty($this->foreign_key_aliases)) {
5443
+			// no PK?  ok check if there is a foreign key alias set for this table
5444
+			// then check if that alias exists in the incoming data
5445
+			// AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446
+			foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
+				if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
+					$value = $cols_n_values[ $FK_alias ];
5449
+					list($pk_class) = explode('.', $PK_column);
5450
+					$pk_model_name = "EEM_{$pk_class}";
5451
+					/** @var EEM_Base $pk_model */
5452
+					$pk_model = EE_Registry::instance()->load_model($pk_model_name);
5453
+					if ($pk_model instanceof EEM_Base) {
5454
+						// make sure object is pulled from db and added to entity map
5455
+						$pk_model->get_one_by_ID($value);
5456
+					}
5457
+					break;
5458
+				}
5459
+			}
5460
+		}
5461
+		return $value;
5462
+	}
5463
+
5464
+
5465
+
5466
+	/**
5467
+	 * refresh_entity_map_from_db
5468
+	 * Makes sure the model object in the entity map at $id assumes the values
5469
+	 * of the database (opposite of EE_base_Class::save())
5470
+	 *
5471
+	 * @param int|string $id
5472
+	 * @return EE_Base_Class
5473
+	 * @throws EE_Error
5474
+	 */
5475
+	public function refresh_entity_map_from_db($id)
5476
+	{
5477
+		$obj_in_map = $this->get_from_entity_map($id);
5478
+		if ($obj_in_map) {
5479
+			$wpdb_results = $this->_get_all_wpdb_results(
5480
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5481
+			);
5482
+			if ($wpdb_results && is_array($wpdb_results)) {
5483
+				$one_row = reset($wpdb_results);
5484
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5485
+					$obj_in_map->set_from_db($field_name, $db_value);
5486
+				}
5487
+				// clear the cache of related model objects
5488
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5489
+					$obj_in_map->clear_cache($relation_name, null, true);
5490
+				}
5491
+			}
5492
+			$this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5493
+			return $obj_in_map;
5494
+		}
5495
+		return $this->get_one_by_ID($id);
5496
+	}
5497
+
5498
+
5499
+
5500
+	/**
5501
+	 * refresh_entity_map_with
5502
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5503
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5504
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5505
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5506
+	 *
5507
+	 * @param int|string    $id
5508
+	 * @param EE_Base_Class $replacing_model_obj
5509
+	 * @return \EE_Base_Class
5510
+	 * @throws EE_Error
5511
+	 */
5512
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5513
+	{
5514
+		$obj_in_map = $this->get_from_entity_map($id);
5515
+		if ($obj_in_map) {
5516
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5517
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5518
+					$obj_in_map->set($field_name, $value);
5519
+				}
5520
+				// make the model object in the entity map's cache match the $replacing_model_obj
5521
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5522
+					$obj_in_map->clear_cache($relation_name, null, true);
5523
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5524
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5525
+					}
5526
+				}
5527
+			}
5528
+			return $obj_in_map;
5529
+		}
5530
+		$this->add_to_entity_map($replacing_model_obj);
5531
+		return $replacing_model_obj;
5532
+	}
5533
+
5534
+
5535
+
5536
+	/**
5537
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5538
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5539
+	 * require_once($this->_getClassName().".class.php");
5540
+	 *
5541
+	 * @return string
5542
+	 */
5543
+	private function _get_class_name()
5544
+	{
5545
+		return "EE_" . $this->get_this_model_name();
5546
+	}
5547
+
5548
+
5549
+
5550
+	/**
5551
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5552
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5553
+	 * it would be 'Events'.
5554
+	 *
5555
+	 * @param int $quantity
5556
+	 * @return string
5557
+	 */
5558
+	public function item_name($quantity = 1)
5559
+	{
5560
+		return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5561
+	}
5562
+
5563
+
5564
+
5565
+	/**
5566
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5567
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5568
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5569
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5570
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5571
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5572
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5573
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5574
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5575
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5576
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5577
+	 *        return $previousReturnValue.$returnString;
5578
+	 * }
5579
+	 * require('EEM_Answer.model.php');
5580
+	 * $answer=EEM_Answer::instance();
5581
+	 * echo $answer->my_callback('monkeys',100);
5582
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5583
+	 *
5584
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5585
+	 * @param array  $args       array of original arguments passed to the function
5586
+	 * @throws EE_Error
5587
+	 * @return mixed whatever the plugin which calls add_filter decides
5588
+	 */
5589
+	public function __call($methodName, $args)
5590
+	{
5591
+		$className = get_class($this);
5592
+		$tagName = "FHEE__{$className}__{$methodName}";
5593
+		if (! has_filter($tagName)) {
5594
+			throw new EE_Error(
5595
+				sprintf(
5596
+					__(
5597
+						'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 );',
5598
+						'event_espresso'
5599
+					),
5600
+					$methodName,
5601
+					$className,
5602
+					$tagName,
5603
+					'<br />'
5604
+				)
5605
+			);
5606
+		}
5607
+		return apply_filters($tagName, null, $this, $args);
5608
+	}
5609
+
5610
+
5611
+
5612
+	/**
5613
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5614
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5615
+	 *
5616
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5617
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5618
+	 *                                                       the object's class name
5619
+	 *                                                       or object's ID
5620
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5621
+	 *                                                       exists in the database. If it does not, we add it
5622
+	 * @throws EE_Error
5623
+	 * @return EE_Base_Class
5624
+	 */
5625
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5626
+	{
5627
+		$className = $this->_get_class_name();
5628
+		if ($base_class_obj_or_id instanceof $className) {
5629
+			$model_object = $base_class_obj_or_id;
5630
+		} else {
5631
+			$primary_key_field = $this->get_primary_key_field();
5632
+			if ($primary_key_field instanceof EE_Primary_Key_Int_Field
5633
+				&& (
5634
+					is_int($base_class_obj_or_id)
5635
+					|| is_string($base_class_obj_or_id)
5636
+				)
5637
+			) {
5638
+				// assume it's an ID.
5639
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5640
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5641
+			} elseif ($primary_key_field instanceof EE_Primary_Key_String_Field
5642
+				&& is_string($base_class_obj_or_id)
5643
+			) {
5644
+				// assume its a string representation of the object
5645
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5646
+			} else {
5647
+				throw new EE_Error(
5648
+					sprintf(
5649
+						__(
5650
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5651
+							'event_espresso'
5652
+						),
5653
+						$base_class_obj_or_id,
5654
+						$this->_get_class_name(),
5655
+						print_r($base_class_obj_or_id, true)
5656
+					)
5657
+				);
5658
+			}
5659
+		}
5660
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5661
+			$model_object->save();
5662
+		}
5663
+		return $model_object;
5664
+	}
5665
+
5666
+
5667
+
5668
+	/**
5669
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5670
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5671
+	 * returns it ID.
5672
+	 *
5673
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5674
+	 * @return int|string depending on the type of this model object's ID
5675
+	 * @throws EE_Error
5676
+	 */
5677
+	public function ensure_is_ID($base_class_obj_or_id)
5678
+	{
5679
+		$className = $this->_get_class_name();
5680
+		if ($base_class_obj_or_id instanceof $className) {
5681
+			/** @var $base_class_obj_or_id EE_Base_Class */
5682
+			$id = $base_class_obj_or_id->ID();
5683
+		} elseif (is_int($base_class_obj_or_id)) {
5684
+			// assume it's an ID
5685
+			$id = $base_class_obj_or_id;
5686
+		} elseif (is_string($base_class_obj_or_id)) {
5687
+			// assume its a string representation of the object
5688
+			$id = $base_class_obj_or_id;
5689
+		} else {
5690
+			throw new EE_Error(sprintf(
5691
+				__(
5692
+					"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5693
+					'event_espresso'
5694
+				),
5695
+				$base_class_obj_or_id,
5696
+				$this->_get_class_name(),
5697
+				print_r($base_class_obj_or_id, true)
5698
+			));
5699
+		}
5700
+		return $id;
5701
+	}
5702
+
5703
+
5704
+
5705
+	/**
5706
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5707
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5708
+	 * been sanitized and converted into the appropriate domain.
5709
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5710
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5711
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5712
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5713
+	 * $EVT = EEM_Event::instance(); $old_setting =
5714
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5715
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5716
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5717
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5718
+	 *
5719
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5720
+	 * @return void
5721
+	 */
5722
+	public function assume_values_already_prepared_by_model_object(
5723
+		$values_already_prepared = self::not_prepared_by_model_object
5724
+	) {
5725
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5726
+	}
5727
+
5728
+
5729
+
5730
+	/**
5731
+	 * Read comments for assume_values_already_prepared_by_model_object()
5732
+	 *
5733
+	 * @return int
5734
+	 */
5735
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5736
+	{
5737
+		return $this->_values_already_prepared_by_model_object;
5738
+	}
5739
+
5740
+
5741
+
5742
+	/**
5743
+	 * Gets all the indexes on this model
5744
+	 *
5745
+	 * @return EE_Index[]
5746
+	 */
5747
+	public function indexes()
5748
+	{
5749
+		return $this->_indexes;
5750
+	}
5751
+
5752
+
5753
+
5754
+	/**
5755
+	 * Gets all the Unique Indexes on this model
5756
+	 *
5757
+	 * @return EE_Unique_Index[]
5758
+	 */
5759
+	public function unique_indexes()
5760
+	{
5761
+		$unique_indexes = array();
5762
+		foreach ($this->_indexes as $name => $index) {
5763
+			if ($index instanceof EE_Unique_Index) {
5764
+				$unique_indexes [ $name ] = $index;
5765
+			}
5766
+		}
5767
+		return $unique_indexes;
5768
+	}
5769
+
5770
+
5771
+
5772
+	/**
5773
+	 * Gets all the fields which, when combined, make the primary key.
5774
+	 * This is usually just an array with 1 element (the primary key), but in cases
5775
+	 * where there is no primary key, it's a combination of fields as defined
5776
+	 * on a primary index
5777
+	 *
5778
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5779
+	 * @throws EE_Error
5780
+	 */
5781
+	public function get_combined_primary_key_fields()
5782
+	{
5783
+		foreach ($this->indexes() as $index) {
5784
+			if ($index instanceof EE_Primary_Key_Index) {
5785
+				return $index->fields();
5786
+			}
5787
+		}
5788
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5789
+	}
5790
+
5791
+
5792
+
5793
+	/**
5794
+	 * Used to build a primary key string (when the model has no primary key),
5795
+	 * which can be used a unique string to identify this model object.
5796
+	 *
5797
+	 * @param array $fields_n_values keys are field names, values are their values.
5798
+	 *                               Note: if you have results from `EEM_Base::get_all_wpdb_results()`, you need to
5799
+	 *                               run it through `EEM_Base::deduce_fields_n_values_from_cols_n_values()`
5800
+	 *                               before passing it to this function (that will convert it from columns-n-values
5801
+	 *                               to field-names-n-values).
5802
+	 * @return string
5803
+	 * @throws EE_Error
5804
+	 */
5805
+	public function get_index_primary_key_string($fields_n_values)
5806
+	{
5807
+		$cols_n_values_for_primary_key_index = array_intersect_key(
5808
+			$fields_n_values,
5809
+			$this->get_combined_primary_key_fields()
5810
+		);
5811
+		return http_build_query($cols_n_values_for_primary_key_index);
5812
+	}
5813
+
5814
+
5815
+
5816
+	/**
5817
+	 * Gets the field values from the primary key string
5818
+	 *
5819
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5820
+	 * @param string $index_primary_key_string
5821
+	 * @return null|array
5822
+	 * @throws EE_Error
5823
+	 */
5824
+	public function parse_index_primary_key_string($index_primary_key_string)
5825
+	{
5826
+		$key_fields = $this->get_combined_primary_key_fields();
5827
+		// check all of them are in the $id
5828
+		$key_vals_in_combined_pk = array();
5829
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830
+		foreach ($key_fields as $key_field_name => $field_obj) {
5831
+			if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5832
+				return null;
5833
+			}
5834
+		}
5835
+		return $key_vals_in_combined_pk;
5836
+	}
5837
+
5838
+
5839
+
5840
+	/**
5841
+	 * verifies that an array of key-value pairs for model fields has a key
5842
+	 * for each field comprising the primary key index
5843
+	 *
5844
+	 * @param array $key_vals
5845
+	 * @return boolean
5846
+	 * @throws EE_Error
5847
+	 */
5848
+	public function has_all_combined_primary_key_fields($key_vals)
5849
+	{
5850
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851
+		foreach ($keys_it_should_have as $key) {
5852
+			if (! isset($key_vals[ $key ])) {
5853
+				return false;
5854
+			}
5855
+		}
5856
+		return true;
5857
+	}
5858
+
5859
+
5860
+
5861
+	/**
5862
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5863
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5864
+	 *
5865
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5866
+	 * @param array               $query_params @see https://github.com/eventespresso/event-espresso-core/tree/master/docs/G--Model-System/model-query-params.md
5867
+	 * @throws EE_Error
5868
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5869
+	 *                                                              indexed)
5870
+	 */
5871
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5872
+	{
5873
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5874
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5875
+		} elseif (is_array($model_object_or_attributes_array)) {
5876
+			$attributes_array = $model_object_or_attributes_array;
5877
+		} else {
5878
+			throw new EE_Error(sprintf(__(
5879
+				"get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5880
+				"event_espresso"
5881
+			), $model_object_or_attributes_array));
5882
+		}
5883
+		// even copies obviously won't have the same ID, so remove the primary key
5884
+		// from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
+		if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
+			unset($attributes_array[ $this->primary_key_name() ]);
5887
+		}
5888
+		if (isset($query_params[0])) {
5889
+			$query_params[0] = array_merge($attributes_array, $query_params);
5890
+		} else {
5891
+			$query_params[0] = $attributes_array;
5892
+		}
5893
+		return $this->get_all($query_params);
5894
+	}
5895
+
5896
+
5897
+
5898
+	/**
5899
+	 * Gets the first copy we find. See get_all_copies for more details
5900
+	 *
5901
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5902
+	 * @param array $query_params
5903
+	 * @return EE_Base_Class
5904
+	 * @throws EE_Error
5905
+	 */
5906
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907
+	{
5908
+		if (! is_array($query_params)) {
5909
+			EE_Error::doing_it_wrong(
5910
+				'EEM_Base::get_one_copy',
5911
+				sprintf(
5912
+					__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5913
+					gettype($query_params)
5914
+				),
5915
+				'4.6.0'
5916
+			);
5917
+			$query_params = array();
5918
+		}
5919
+		$query_params['limit'] = 1;
5920
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5921
+		if (is_array($copies)) {
5922
+			return array_shift($copies);
5923
+		}
5924
+		return null;
5925
+	}
5926
+
5927
+
5928
+
5929
+	/**
5930
+	 * Updates the item with the specified id. Ignores default query parameters because
5931
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5932
+	 *
5933
+	 * @param array      $fields_n_values keys are field names, values are their new values
5934
+	 * @param int|string $id              the value of the primary key to update
5935
+	 * @return int number of rows updated
5936
+	 * @throws EE_Error
5937
+	 */
5938
+	public function update_by_ID($fields_n_values, $id)
5939
+	{
5940
+		$query_params = array(
5941
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5942
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5943
+		);
5944
+		return $this->update($fields_n_values, $query_params);
5945
+	}
5946
+
5947
+
5948
+
5949
+	/**
5950
+	 * Changes an operator which was supplied to the models into one usable in SQL
5951
+	 *
5952
+	 * @param string $operator_supplied
5953
+	 * @return string an operator which can be used in SQL
5954
+	 * @throws EE_Error
5955
+	 */
5956
+	private function _prepare_operator_for_sql($operator_supplied)
5957
+	{
5958
+		$sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5959
+			: null;
5960
+		if ($sql_operator) {
5961
+			return $sql_operator;
5962
+		}
5963
+		throw new EE_Error(
5964
+			sprintf(
5965
+				__(
5966
+					"The operator '%s' is not in the list of valid operators: %s",
5967
+					"event_espresso"
5968
+				),
5969
+				$operator_supplied,
5970
+				implode(",", array_keys($this->_valid_operators))
5971
+			)
5972
+		);
5973
+	}
5974
+
5975
+
5976
+
5977
+	/**
5978
+	 * Gets the valid operators
5979
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5980
+	 */
5981
+	public function valid_operators()
5982
+	{
5983
+		return $this->_valid_operators;
5984
+	}
5985
+
5986
+
5987
+
5988
+	/**
5989
+	 * Gets the between-style operators (take 2 arguments).
5990
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5991
+	 */
5992
+	public function valid_between_style_operators()
5993
+	{
5994
+		return array_intersect(
5995
+			$this->valid_operators(),
5996
+			$this->_between_style_operators
5997
+		);
5998
+	}
5999
+
6000
+	/**
6001
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
6002
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6003
+	 */
6004
+	public function valid_like_style_operators()
6005
+	{
6006
+		return array_intersect(
6007
+			$this->valid_operators(),
6008
+			$this->_like_style_operators
6009
+		);
6010
+	}
6011
+
6012
+	/**
6013
+	 * Gets the "in"-style operators
6014
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6015
+	 */
6016
+	public function valid_in_style_operators()
6017
+	{
6018
+		return array_intersect(
6019
+			$this->valid_operators(),
6020
+			$this->_in_style_operators
6021
+		);
6022
+	}
6023
+
6024
+	/**
6025
+	 * Gets the "null"-style operators (accept no arguments)
6026
+	 * @return array keys are accepted strings, values are the SQL they are converted to
6027
+	 */
6028
+	public function valid_null_style_operators()
6029
+	{
6030
+		return array_intersect(
6031
+			$this->valid_operators(),
6032
+			$this->_null_style_operators
6033
+		);
6034
+	}
6035
+
6036
+	/**
6037
+	 * Gets an array where keys are the primary keys and values are their 'names'
6038
+	 * (as determined by the model object's name() function, which is often overridden)
6039
+	 *
6040
+	 * @param array $query_params like get_all's
6041
+	 * @return string[]
6042
+	 * @throws EE_Error
6043
+	 */
6044
+	public function get_all_names($query_params = array())
6045
+	{
6046
+		$objs = $this->get_all($query_params);
6047
+		$names = array();
6048
+		foreach ($objs as $obj) {
6049
+			$names[ $obj->ID() ] = $obj->name();
6050
+		}
6051
+		return $names;
6052
+	}
6053
+
6054
+
6055
+
6056
+	/**
6057
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
6058
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
6059
+	 * this is duplicated effort and reduces efficiency) you would be better to use
6060
+	 * array_keys() on $model_objects.
6061
+	 *
6062
+	 * @param \EE_Base_Class[] $model_objects
6063
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
6064
+	 *                                               in the returned array
6065
+	 * @return array
6066
+	 * @throws EE_Error
6067
+	 */
6068
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069
+	{
6070
+		if (! $this->has_primary_key_field()) {
6071
+			if (WP_DEBUG) {
6072
+				EE_Error::add_error(
6073
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
6074
+					__FILE__,
6075
+					__FUNCTION__,
6076
+					__LINE__
6077
+				);
6078
+			}
6079
+		}
6080
+		$IDs = array();
6081
+		foreach ($model_objects as $model_object) {
6082
+			$id = $model_object->ID();
6083
+			if (! $id) {
6084
+				if ($filter_out_empty_ids) {
6085
+					continue;
6086
+				}
6087
+				if (WP_DEBUG) {
6088
+					EE_Error::add_error(
6089
+						__(
6090
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
6091
+							'event_espresso'
6092
+						),
6093
+						__FILE__,
6094
+						__FUNCTION__,
6095
+						__LINE__
6096
+					);
6097
+				}
6098
+			}
6099
+			$IDs[] = $id;
6100
+		}
6101
+		return $IDs;
6102
+	}
6103
+
6104
+
6105
+
6106
+	/**
6107
+	 * Returns the string used in capabilities relating to this model. If there
6108
+	 * are no capabilities that relate to this model returns false
6109
+	 *
6110
+	 * @return string|false
6111
+	 */
6112
+	public function cap_slug()
6113
+	{
6114
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
6115
+	}
6116
+
6117
+
6118
+
6119
+	/**
6120
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
6121
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
6122
+	 * only returns the cap restrictions array in that context (ie, the array
6123
+	 * at that key)
6124
+	 *
6125
+	 * @param string $context
6126
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
6127
+	 * @throws EE_Error
6128
+	 */
6129
+	public function cap_restrictions($context = EEM_Base::caps_read)
6130
+	{
6131
+		EEM_Base::verify_is_valid_cap_context($context);
6132
+		// check if we ought to run the restriction generator first
6133
+		if (isset($this->_cap_restriction_generators[ $context ])
6134
+			&& $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
+			&& ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6136
+		) {
6137
+			$this->_cap_restrictions[ $context ] = array_merge(
6138
+				$this->_cap_restrictions[ $context ],
6139
+				$this->_cap_restriction_generators[ $context ]->generate_restrictions()
6140
+			);
6141
+		}
6142
+		// and make sure we've finalized the construction of each restriction
6143
+		foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6144
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145
+				$where_conditions_obj->_finalize_construct($this);
6146
+			}
6147
+		}
6148
+		return $this->_cap_restrictions[ $context ];
6149
+	}
6150
+
6151
+
6152
+
6153
+	/**
6154
+	 * Indicating whether or not this model thinks its a wp core model
6155
+	 *
6156
+	 * @return boolean
6157
+	 */
6158
+	public function is_wp_core_model()
6159
+	{
6160
+		return $this->_wp_core_model;
6161
+	}
6162
+
6163
+
6164
+
6165
+	/**
6166
+	 * Gets all the caps that are missing which impose a restriction on
6167
+	 * queries made in this context
6168
+	 *
6169
+	 * @param string $context one of EEM_Base::caps_ constants
6170
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
6171
+	 * @throws EE_Error
6172
+	 */
6173
+	public function caps_missing($context = EEM_Base::caps_read)
6174
+	{
6175
+		$missing_caps = array();
6176
+		$cap_restrictions = $this->cap_restrictions($context);
6177
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
+			if (! EE_Capabilities::instance()
6179
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6180
+			) {
6181
+				$missing_caps[ $cap ] = $restriction_if_no_cap;
6182
+			}
6183
+		}
6184
+		return $missing_caps;
6185
+	}
6186
+
6187
+
6188
+
6189
+	/**
6190
+	 * Gets the mapping from capability contexts to action strings used in capability names
6191
+	 *
6192
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
6193
+	 * one of 'read', 'edit', or 'delete'
6194
+	 */
6195
+	public function cap_contexts_to_cap_action_map()
6196
+	{
6197
+		return apply_filters(
6198
+			'FHEE__EEM_Base__cap_contexts_to_cap_action_map',
6199
+			$this->_cap_contexts_to_cap_action_map,
6200
+			$this
6201
+		);
6202
+	}
6203
+
6204
+
6205
+
6206
+	/**
6207
+	 * Gets the action string for the specified capability context
6208
+	 *
6209
+	 * @param string $context
6210
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
6211
+	 * @throws EE_Error
6212
+	 */
6213
+	public function cap_action_for_context($context)
6214
+	{
6215
+		$mapping = $this->cap_contexts_to_cap_action_map();
6216
+		if (isset($mapping[ $context ])) {
6217
+			return $mapping[ $context ];
6218
+		}
6219
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220
+			return $action;
6221
+		}
6222
+		throw new EE_Error(
6223
+			sprintf(
6224
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
6225
+				$context,
6226
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
6227
+			)
6228
+		);
6229
+	}
6230
+
6231
+
6232
+
6233
+	/**
6234
+	 * Returns all the capability contexts which are valid when querying models
6235
+	 *
6236
+	 * @return array
6237
+	 */
6238
+	public static function valid_cap_contexts()
6239
+	{
6240
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
6241
+			self::caps_read,
6242
+			self::caps_read_admin,
6243
+			self::caps_edit,
6244
+			self::caps_delete,
6245
+		));
6246
+	}
6247
+
6248
+
6249
+
6250
+	/**
6251
+	 * Returns all valid options for 'default_where_conditions'
6252
+	 *
6253
+	 * @return array
6254
+	 */
6255
+	public static function valid_default_where_conditions()
6256
+	{
6257
+		return array(
6258
+			EEM_Base::default_where_conditions_all,
6259
+			EEM_Base::default_where_conditions_this_only,
6260
+			EEM_Base::default_where_conditions_others_only,
6261
+			EEM_Base::default_where_conditions_minimum_all,
6262
+			EEM_Base::default_where_conditions_minimum_others,
6263
+			EEM_Base::default_where_conditions_none
6264
+		);
6265
+	}
6266
+
6267
+	// public static function default_where_conditions_full
6268
+	/**
6269
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
6270
+	 *
6271
+	 * @param string $context
6272
+	 * @return bool
6273
+	 * @throws EE_Error
6274
+	 */
6275
+	public static function verify_is_valid_cap_context($context)
6276
+	{
6277
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
6278
+		if (in_array($context, $valid_cap_contexts)) {
6279
+			return true;
6280
+		}
6281
+		throw new EE_Error(
6282
+			sprintf(
6283
+				__(
6284
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
6285
+					'event_espresso'
6286
+				),
6287
+				$context,
6288
+				'EEM_Base',
6289
+				implode(',', $valid_cap_contexts)
6290
+			)
6291
+		);
6292
+	}
6293
+
6294
+
6295
+
6296
+	/**
6297
+	 * Clears all the models field caches. This is only useful when a sub-class
6298
+	 * might have added a field or something and these caches might be invalidated
6299
+	 */
6300
+	protected function _invalidate_field_caches()
6301
+	{
6302
+		$this->_cache_foreign_key_to_fields = array();
6303
+		$this->_cached_fields = null;
6304
+		$this->_cached_fields_non_db_only = null;
6305
+	}
6306
+
6307
+
6308
+
6309
+	/**
6310
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6311
+	 * (eg "and", "or", "not").
6312
+	 *
6313
+	 * @return array
6314
+	 */
6315
+	public function logic_query_param_keys()
6316
+	{
6317
+		return $this->_logic_query_param_keys;
6318
+	}
6319
+
6320
+
6321
+
6322
+	/**
6323
+	 * Determines whether or not the where query param array key is for a logic query param.
6324
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6325
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6326
+	 *
6327
+	 * @param $query_param_key
6328
+	 * @return bool
6329
+	 */
6330
+	public function is_logic_query_param_key($query_param_key)
6331
+	{
6332
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333
+			if ($query_param_key === $logic_query_param_key
6334
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6335
+			) {
6336
+				return true;
6337
+			}
6338
+		}
6339
+		return false;
6340
+	}
6341
+
6342
+	/**
6343
+	 * Returns true if this model has a password field on it (regardless of whether that password field has any content)
6344
+	 * @since 4.9.74.p
6345
+	 * @return boolean
6346
+	 */
6347
+	public function hasPassword()
6348
+	{
6349
+		// if we don't yet know if there's a password field, find out and remember it for next time.
6350
+		if ($this->has_password_field === null) {
6351
+			$password_field = $this->getPasswordField();
6352
+			$this->has_password_field = $password_field instanceof EE_Password_Field ? true : false;
6353
+		}
6354
+		return $this->has_password_field;
6355
+	}
6356
+
6357
+	/**
6358
+	 * Returns the password field on this model, if there is one
6359
+	 * @since 4.9.74.p
6360
+	 * @return EE_Password_Field|null
6361
+	 */
6362
+	public function getPasswordField()
6363
+	{
6364
+		// if we definetely already know there is a password field or not (because has_password_field is true or false)
6365
+		// there's no need to search for it. If we don't know yet, then find out
6366
+		if ($this->has_password_field === null && $this->password_field === null) {
6367
+			$this->password_field = $this->get_a_field_of_type('EE_Password_Field');
6368
+		}
6369
+		// don't bother setting has_password_field because that's hasPassword()'s job.
6370
+		return $this->password_field;
6371
+	}
6372
+
6373
+
6374
+	/**
6375
+	 * Returns the list of field (as EE_Model_Field_Bases) that are protected by the password
6376
+	 * @since 4.9.74.p
6377
+	 * @return EE_Model_Field_Base[]
6378
+	 * @throws EE_Error
6379
+	 */
6380
+	public function getPasswordProtectedFields()
6381
+	{
6382
+		$password_field = $this->getPasswordField();
6383
+		$fields = array();
6384
+		if ($password_field instanceof EE_Password_Field) {
6385
+			$field_names = $password_field->protectedFields();
6386
+			foreach ($field_names as $field_name) {
6387
+				$fields[ $field_name ] = $this->field_settings_for($field_name);
6388
+			}
6389
+		}
6390
+		return $fields;
6391
+	}
6392
+
6393
+
6394
+	/**
6395
+	 * Checks if the current user can perform the requested action on this model
6396
+	 * @since 4.9.74.p
6397
+	 * @param string $cap_to_check one of the array keys from _cap_contexts_to_cap_action_map
6398
+	 * @param EE_Base_Class|array $model_obj_or_fields_n_values
6399
+	 * @return bool
6400
+	 * @throws EE_Error
6401
+	 * @throws InvalidArgumentException
6402
+	 * @throws InvalidDataTypeException
6403
+	 * @throws InvalidInterfaceException
6404
+	 * @throws ReflectionException
6405
+	 * @throws UnexpectedEntityException
6406
+	 */
6407
+	public function currentUserCan($cap_to_check, $model_obj_or_fields_n_values)
6408
+	{
6409
+		if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410
+			$model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411
+		}
6412
+		if (!is_array($model_obj_or_fields_n_values)) {
6413
+			throw new UnexpectedEntityException(
6414
+				$model_obj_or_fields_n_values,
6415
+				'EE_Base_Class',
6416
+				sprintf(
6417
+					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'),
6418
+					__FUNCTION__
6419
+				)
6420
+			);
6421
+		}
6422
+		return $this->exists(
6423
+			$this->alter_query_params_to_restrict_by_ID(
6424
+				$this->get_index_primary_key_string($model_obj_or_fields_n_values),
6425
+				array(
6426
+					'default_where_conditions' => 'none',
6427
+					'caps'                     => $cap_to_check,
6428
+				)
6429
+			)
6430
+		);
6431
+	}
6432
+
6433
+	/**
6434
+	 * Returns the query param where conditions key to the password affecting this model.
6435
+	 * Eg on EEM_Event this would just be "password", on EEM_Datetime this would be "Event.password", etc.
6436
+	 * @since 4.9.74.p
6437
+	 * @return null|string
6438
+	 * @throws EE_Error
6439
+	 * @throws InvalidArgumentException
6440
+	 * @throws InvalidDataTypeException
6441
+	 * @throws InvalidInterfaceException
6442
+	 * @throws ModelConfigurationException
6443
+	 * @throws ReflectionException
6444
+	 */
6445
+	public function modelChainAndPassword()
6446
+	{
6447
+		if ($this->model_chain_to_password === null) {
6448
+			throw new ModelConfigurationException(
6449
+				$this,
6450
+				esc_html_x(
6451
+				// @codingStandardsIgnoreStart
6452
+					'Cannot exclude protected data because the model has not specified which model has the password.',
6453
+					// @codingStandardsIgnoreEnd
6454
+					'1: model name',
6455
+					'event_espresso'
6456
+				)
6457
+			);
6458
+		}
6459
+		if ($this->model_chain_to_password === '') {
6460
+			$model_with_password = $this;
6461
+		} else {
6462
+			if ($pos_of_period = strrpos($this->model_chain_to_password, '.')) {
6463
+				$last_model_in_chain = substr($this->model_chain_to_password, $pos_of_period + 1);
6464
+			} else {
6465
+				$last_model_in_chain = $this->model_chain_to_password;
6466
+			}
6467
+			$model_with_password = EE_Registry::instance()->load_model($last_model_in_chain);
6468
+		}
6469
+
6470
+		$password_field = $model_with_password->getPasswordField();
6471
+		if ($password_field instanceof EE_Password_Field) {
6472
+			$password_field_name = $password_field->get_name();
6473
+		} else {
6474
+			throw new ModelConfigurationException(
6475
+				$this,
6476
+				sprintf(
6477
+					esc_html_x(
6478
+						'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"',
6479
+						'1: model name, 2: special string',
6480
+						'event_espresso'
6481
+					),
6482
+					$model_with_password->get_this_model_name(),
6483
+					$this->model_chain_to_password
6484
+				)
6485
+			);
6486
+		}
6487
+		return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6488
+	}
6489
+
6490
+	/**
6491
+	 * Returns true if there is a password on a related model which restricts access to some of this model's rows,
6492
+	 * or if this model itself has a password affecting access to some of its other fields.
6493
+	 * @since 4.9.74.p
6494
+	 * @return boolean
6495
+	 */
6496
+	public function restrictedByRelatedModelPassword()
6497
+	{
6498
+		return $this->model_chain_to_password !== null;
6499
+	}
6500 6500
 }
Please login to merge, or discard this patch.
Spacing   +230 added lines, -230 removed lines patch added patch discarded remove patch
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     protected function __construct($timezone = null)
555 555
     {
556 556
         // check that the model has not been loaded too soon
557
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
557
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
558 558
             throw new EE_Error(
559 559
                 sprintf(
560 560
                     __(
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
          *
578 578
          * @var EE_Table_Base[] $_tables
579 579
          */
580
-        $this->_tables = (array) apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
580
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
581 581
         foreach ($this->_tables as $table_alias => $table_obj) {
582 582
             /** @var $table_obj EE_Table_Base */
583 583
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -592,10 +592,10 @@  discard block
 block discarded – undo
592 592
          *
593 593
          * @param EE_Model_Field_Base[] $_fields
594 594
          */
595
-        $this->_fields = (array) apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
595
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
596 596
         $this->_invalidate_field_caches();
597 597
         foreach ($this->_fields as $table_alias => $fields_for_table) {
598
-            if (! array_key_exists($table_alias, $this->_tables)) {
598
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
599 599
                 throw new EE_Error(sprintf(__(
600 600
                     "Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
601 601
                     'event_espresso'
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
          * @param EE_Model_Relation_Base[] $_model_relations
627 627
          */
628 628
         $this->_model_relations = (array) apply_filters(
629
-            'FHEE__' . get_class($this) . '__construct__model_relations',
629
+            'FHEE__'.get_class($this).'__construct__model_relations',
630 630
             $this->_model_relations
631 631
         );
632 632
         foreach ($this->_model_relations as $model_name => $relation_obj) {
@@ -639,12 +639,12 @@  discard block
 block discarded – undo
639 639
         }
640 640
         $this->set_timezone($timezone);
641 641
         // finalize default where condition strategy, or set default
642
-        if (! $this->_default_where_conditions_strategy) {
642
+        if ( ! $this->_default_where_conditions_strategy) {
643 643
             // nothing was set during child constructor, so set default
644 644
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
645 645
         }
646 646
         $this->_default_where_conditions_strategy->_finalize_construct($this);
647
-        if (! $this->_minimum_where_conditions_strategy) {
647
+        if ( ! $this->_minimum_where_conditions_strategy) {
648 648
             // nothing was set during child constructor, so set default
649 649
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
650 650
         }
@@ -657,8 +657,8 @@  discard block
 block discarded – undo
657 657
         // initialize the standard cap restriction generators if none were specified by the child constructor
658 658
         if ($this->_cap_restriction_generators !== false) {
659 659
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
660
-                if (! isset($this->_cap_restriction_generators[ $cap_context ])) {
661
-                    $this->_cap_restriction_generators[ $cap_context ] = apply_filters(
660
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
661
+                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
662 662
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
663 663
                         new EE_Restriction_Generator_Protected(),
664 664
                         $cap_context,
@@ -670,10 +670,10 @@  discard block
 block discarded – undo
670 670
         // if there are cap restriction generators, use them to make the default cap restrictions
671 671
         if ($this->_cap_restriction_generators !== false) {
672 672
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
673
-                if (! $generator_object) {
673
+                if ( ! $generator_object) {
674 674
                     continue;
675 675
                 }
676
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
676
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
677 677
                     throw new EE_Error(
678 678
                         sprintf(
679 679
                             __(
@@ -686,12 +686,12 @@  discard block
 block discarded – undo
686 686
                     );
687 687
                 }
688 688
                 $action = $this->cap_action_for_context($context);
689
-                if (! $generator_object->construction_finalized()) {
689
+                if ( ! $generator_object->construction_finalized()) {
690 690
                     $generator_object->_construct_finalize($this, $action);
691 691
                 }
692 692
             }
693 693
         }
694
-        do_action('AHEE__' . get_class($this) . '__construct__end');
694
+        do_action('AHEE__'.get_class($this).'__construct__end');
695 695
     }
696 696
 
697 697
 
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
     public static function instance($timezone = null)
739 739
     {
740 740
         // check if instance of Espresso_model already exists
741
-        if (! static::$_instance instanceof static) {
741
+        if ( ! static::$_instance instanceof static) {
742 742
             // instantiate Espresso_model
743 743
             static::$_instance = new static(
744 744
                 $timezone,
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach ($r->getDefaultProperties() as $property => $value) {
778 778
                 // don't set instance to null like it was originally,
779 779
                 // but it's static anyways, and we're ignoring static properties (for now at least)
780
-                if (! isset($static_properties[ $property ])) {
780
+                if ( ! isset($static_properties[$property])) {
781 781
                     static::$_instance->{$property} = $value;
782 782
                 }
783 783
             }
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
      */
802 802
     private static function getLoader()
803 803
     {
804
-        if (! EEM_Base::$loader instanceof LoaderInterface) {
804
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
805 805
             EEM_Base::$loader = LoaderFactory::getLoader();
806 806
         }
807 807
         return EEM_Base::$loader;
@@ -821,7 +821,7 @@  discard block
 block discarded – undo
821 821
      */
822 822
     public function status_array($translated = false)
823 823
     {
824
-        if (! array_key_exists('Status', $this->_model_relations)) {
824
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
825 825
             return array();
826 826
         }
827 827
         $model_name = $this->get_this_model_name();
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
         $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
830 830
         $status_array = array();
831 831
         foreach ($stati as $status) {
832
-            $status_array[ $status->ID() ] = $status->get('STS_code');
832
+            $status_array[$status->ID()] = $status->get('STS_code');
833 833
         }
834 834
         return $translated
835 835
             ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
     {
890 890
         $wp_user_field_name = $this->wp_user_field_name();
891 891
         if ($wp_user_field_name) {
892
-            $query_params[0][ $wp_user_field_name ] = get_current_user_id();
892
+            $query_params[0][$wp_user_field_name] = get_current_user_id();
893 893
         }
894 894
         return $query_params;
895 895
     }
@@ -907,17 +907,17 @@  discard block
 block discarded – undo
907 907
     public function wp_user_field_name()
908 908
     {
909 909
         try {
910
-            if (! empty($this->_model_chain_to_wp_user)) {
910
+            if ( ! empty($this->_model_chain_to_wp_user)) {
911 911
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
912 912
                 $last_model_name = end($models_to_follow_to_wp_users);
913 913
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
914
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
914
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
915 915
             } else {
916 916
                 $model_with_fk_to_wp_users = $this;
917 917
                 $model_chain_to_wp_user = '';
918 918
             }
919 919
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
920
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
920
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
921 921
         } catch (EE_Error $e) {
922 922
             return false;
923 923
         }
@@ -994,11 +994,11 @@  discard block
 block discarded – undo
994 994
         if ($this->_custom_selections instanceof CustomSelects) {
995 995
             $custom_expressions = $this->_custom_selections->columnsToSelectExpression();
996 996
             $select_expressions .= $select_expressions
997
-                ? ', ' . $custom_expressions
997
+                ? ', '.$custom_expressions
998 998
                 : $custom_expressions;
999 999
         }
1000 1000
 
1001
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1001
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1002 1002
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1003 1003
     }
1004 1004
 
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
      */
1016 1016
     protected function getCustomSelection(array $query_params, $columns_to_select = null)
1017 1017
     {
1018
-        if (! isset($query_params['extra_selects']) && $columns_to_select === null) {
1018
+        if ( ! isset($query_params['extra_selects']) && $columns_to_select === null) {
1019 1019
             return null;
1020 1020
         }
1021 1021
         $selects = isset($query_params['extra_selects']) ? $query_params['extra_selects'] : $columns_to_select;
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
         if (is_array($columns_to_select)) {
1065 1065
             $select_sql_array = array();
1066 1066
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1067
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1067
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1068 1068
                     throw new EE_Error(
1069 1069
                         sprintf(
1070 1070
                             __(
@@ -1076,7 +1076,7 @@  discard block
 block discarded – undo
1076 1076
                         )
1077 1077
                     );
1078 1078
                 }
1079
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1079
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1080 1080
                     throw new EE_Error(
1081 1081
                         sprintf(
1082 1082
                             esc_html__(
@@ -1155,12 +1155,12 @@  discard block
 block discarded – undo
1155 1155
      */
1156 1156
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1157 1157
     {
1158
-        if (! isset($query_params[0])) {
1158
+        if ( ! isset($query_params[0])) {
1159 1159
             $query_params[0] = array();
1160 1160
         }
1161 1161
         $conditions_from_id = $this->parse_index_primary_key_string($id);
1162 1162
         if ($conditions_from_id === null) {
1163
-            $query_params[0][ $this->primary_key_name() ] = $id;
1163
+            $query_params[0][$this->primary_key_name()] = $id;
1164 1164
         } else {
1165 1165
             // no primary key, so the $id must be from the get_index_primary_key_string()
1166 1166
             $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
@@ -1180,7 +1180,7 @@  discard block
 block discarded – undo
1180 1180
      */
1181 1181
     public function get_one($query_params = array())
1182 1182
     {
1183
-        if (! is_array($query_params)) {
1183
+        if ( ! is_array($query_params)) {
1184 1184
             EE_Error::doing_it_wrong(
1185 1185
                 'EEM_Base::get_one',
1186 1186
                 sprintf(
@@ -1378,7 +1378,7 @@  discard block
 block discarded – undo
1378 1378
                 return array();
1379 1379
             }
1380 1380
         }
1381
-        if (! is_array($query_params)) {
1381
+        if ( ! is_array($query_params)) {
1382 1382
             EE_Error::doing_it_wrong(
1383 1383
                 'EEM_Base::_get_consecutive',
1384 1384
                 sprintf(
@@ -1390,7 +1390,7 @@  discard block
 block discarded – undo
1390 1390
             $query_params = array();
1391 1391
         }
1392 1392
         // let's add the where query param for consecutive look up.
1393
-        $query_params[0][ $field_to_order_by ] = array($operand, $current_field_value);
1393
+        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1394 1394
         $query_params['limit'] = $limit;
1395 1395
         // set direction
1396 1396
         $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
@@ -1471,7 +1471,7 @@  discard block
 block discarded – undo
1471 1471
     {
1472 1472
         $field_settings = $this->field_settings_for($field_name);
1473 1473
         // if not a valid EE_Datetime_Field then throw error
1474
-        if (! $field_settings instanceof EE_Datetime_Field) {
1474
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1475 1475
             throw new EE_Error(sprintf(__(
1476 1476
                 '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.',
1477 1477
                 'event_espresso'
@@ -1620,7 +1620,7 @@  discard block
 block discarded – undo
1620 1620
      */
1621 1621
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1622 1622
     {
1623
-        if (! is_array($query_params)) {
1623
+        if ( ! is_array($query_params)) {
1624 1624
             EE_Error::doing_it_wrong(
1625 1625
                 'EEM_Base::update',
1626 1626
                 sprintf(
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
             $wpdb_result = (array) $wpdb_result;
1669 1669
             // get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1670 1670
             if ($this->has_primary_key_field()) {
1671
-                $main_table_pk_value = $wpdb_result[ $this->get_primary_key_field()->get_qualified_column() ];
1671
+                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1672 1672
             } else {
1673 1673
                 // 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)
1674 1674
                 $main_table_pk_value = null;
@@ -1682,8 +1682,8 @@  discard block
 block discarded – undo
1682 1682
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1683 1683
                     // if there is no private key for this table on the results, it means there's no entry
1684 1684
                     // in this table, right? so insert a row in the current table, using any fields available
1685
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
-                           && $wpdb_result[ $this_table_pk_column ])
1685
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1686
+                           && $wpdb_result[$this_table_pk_column])
1687 1687
                     ) {
1688 1688
                         $success = $this->_insert_into_specific_table(
1689 1689
                             $table_obj,
@@ -1691,7 +1691,7 @@  discard block
 block discarded – undo
1691 1691
                             $main_table_pk_value
1692 1692
                         );
1693 1693
                         // if we died here, report the error
1694
-                        if (! $success) {
1694
+                        if ( ! $success) {
1695 1695
                             return false;
1696 1696
                         }
1697 1697
                     }
@@ -1719,10 +1719,10 @@  discard block
 block discarded – undo
1719 1719
                 $model_objs_affected_ids = array();
1720 1720
                 foreach ($models_affected_key_columns as $row) {
1721 1721
                     $combined_index_key = $this->get_index_primary_key_string($row);
1722
-                    $model_objs_affected_ids[ $combined_index_key ] = $combined_index_key;
1722
+                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1723 1723
                 }
1724 1724
             }
1725
-            if (! $model_objs_affected_ids) {
1725
+            if ( ! $model_objs_affected_ids) {
1726 1726
                 // wait wait wait- if nothing was affected let's stop here
1727 1727
                 return 0;
1728 1728
             }
@@ -1749,7 +1749,7 @@  discard block
 block discarded – undo
1749 1749
                . $model_query_info->get_full_join_sql()
1750 1750
                . " SET "
1751 1751
                . $this->_construct_update_sql($fields_n_values)
1752
-               . $model_query_info->get_where_sql();// note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1752
+               . $model_query_info->get_where_sql(); // note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1753 1753
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1754 1754
         /**
1755 1755
          * Action called after a model update call has been made.
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
          * @param int      $rows_affected
1761 1761
          */
1762 1762
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1763
-        return $rows_affected;// how many supposedly got updated
1763
+        return $rows_affected; // how many supposedly got updated
1764 1764
     }
1765 1765
 
1766 1766
 
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
         }
1789 1789
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1790 1790
         $select_expressions = $field->get_qualified_column();
1791
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1791
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1792 1792
         return $this->_do_wpdb_query('get_col', array($SQL));
1793 1793
     }
1794 1794
 
@@ -1806,7 +1806,7 @@  discard block
 block discarded – undo
1806 1806
     {
1807 1807
         $query_params['limit'] = 1;
1808 1808
         $col = $this->get_col($query_params, $field_to_select);
1809
-        if (! empty($col)) {
1809
+        if ( ! empty($col)) {
1810 1810
             return reset($col);
1811 1811
         }
1812 1812
         return null;
@@ -1837,7 +1837,7 @@  discard block
 block discarded – undo
1837 1837
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1838 1838
             $value_sql = $prepared_value === null ? 'NULL'
1839 1839
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1840
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1840
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1841 1841
         }
1842 1842
         return implode(",", $cols_n_values);
1843 1843
     }
@@ -1980,12 +1980,12 @@  discard block
 block discarded – undo
1980 1980
         // there was no error with the delete query.
1981 1981
         if ($this->has_primary_key_field()
1982 1982
             && $rows_deleted !== false
1983
-            && isset($columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ])
1983
+            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1984 1984
         ) {
1985
-            $ids_for_removal = $columns_and_ids_for_deleting[ $this->get_primary_key_field()->get_qualified_column() ];
1985
+            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1986 1986
             foreach ($ids_for_removal as $id) {
1987
-                if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
1988
-                    unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
1987
+                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1988
+                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1989 1989
                 }
1990 1990
             }
1991 1991
 
@@ -2020,7 +2020,7 @@  discard block
 block discarded – undo
2020 2020
          * @param int      $rows_deleted
2021 2021
          */
2022 2022
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2023
-        return $rows_deleted;// how many supposedly got deleted
2023
+        return $rows_deleted; // how many supposedly got deleted
2024 2024
     }
2025 2025
 
2026 2026
 
@@ -2113,15 +2113,15 @@  discard block
 block discarded – undo
2113 2113
                 // make sure there's no related entities blocking its deletion (if we're checking)
2114 2114
                 if ($allow_blocking
2115 2115
                     && $this->delete_is_blocked_by_related_models(
2116
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ]
2116
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2117 2117
                     )
2118 2118
                 ) {
2119 2119
                     continue;
2120 2120
                 }
2121 2121
                 // primary table deletes
2122
-                if (isset($item_to_delete[ $primary_table->get_fully_qualified_pk_column() ])) {
2123
-                    $ids_to_delete_indexed_by_column[ $primary_table->get_fully_qualified_pk_column() ][] =
2124
-                        $item_to_delete[ $primary_table->get_fully_qualified_pk_column() ];
2122
+                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2123
+                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2124
+                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2125 2125
                 }
2126 2126
             }
2127 2127
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2130,8 +2130,8 @@  discard block
 block discarded – undo
2130 2130
                 $ids_to_delete_indexed_by_column_for_row = array();
2131 2131
                 foreach ($fields as $cpk_field) {
2132 2132
                     if ($cpk_field instanceof EE_Model_Field_Base) {
2133
-                        $ids_to_delete_indexed_by_column_for_row[ $cpk_field->get_qualified_column() ] =
2134
-                            $item_to_delete[ $cpk_field->get_qualified_column() ];
2133
+                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2134
+                            $item_to_delete[$cpk_field->get_qualified_column()];
2135 2135
                     }
2136 2136
                 }
2137 2137
                 $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2172 2172
                 // make sure we have unique $ids
2173 2173
                 $ids = array_unique($ids);
2174
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2174
+                $query[] = $column.' IN('.implode(',', $ids).')';
2175 2175
             }
2176 2176
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2177 2177
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2179,7 +2179,7 @@  discard block
 block discarded – undo
2179 2179
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2180 2180
                 $values_for_each_combined_primary_key_for_a_row = array();
2181 2181
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2182
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2182
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2183 2183
                 }
2184 2184
                 $ways_to_identify_a_row[] = '('
2185 2185
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2251,8 +2251,8 @@  discard block
 block discarded – undo
2251 2251
                 $column_to_count = '*';
2252 2252
             }
2253 2253
         }
2254
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2255
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2254
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2255
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2256 2256
         return (int) $this->_do_wpdb_query('get_var', array($SQL));
2257 2257
     }
2258 2258
 
@@ -2275,7 +2275,7 @@  discard block
 block discarded – undo
2275 2275
             $field_obj = $this->get_primary_key_field();
2276 2276
         }
2277 2277
         $column_to_count = $field_obj->get_qualified_column();
2278
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2278
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2279 2279
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2280 2280
         $data_type = $field_obj->get_wpdb_data_type();
2281 2281
         if ($data_type === '%d' || $data_type === '%s') {
@@ -2302,7 +2302,7 @@  discard block
 block discarded – undo
2302 2302
         // if we're in maintenance mode level 2, DON'T run any queries
2303 2303
         // because level 2 indicates the database needs updating and
2304 2304
         // is probably out of sync with the code
2305
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2305
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2306 2306
             throw new EE_Error(sprintf(__(
2307 2307
                 "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.",
2308 2308
                 "event_espresso"
@@ -2310,7 +2310,7 @@  discard block
 block discarded – undo
2310 2310
         }
2311 2311
         /** @type WPDB $wpdb */
2312 2312
         global $wpdb;
2313
-        if (! method_exists($wpdb, $wpdb_method)) {
2313
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2314 2314
             throw new EE_Error(sprintf(__(
2315 2315
                 'There is no method named "%s" on Wordpress\' $wpdb object',
2316 2316
                 'event_espresso'
@@ -2324,7 +2324,7 @@  discard block
 block discarded – undo
2324 2324
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2325 2325
         if (WP_DEBUG) {
2326 2326
             $wpdb->show_errors($old_show_errors_value);
2327
-            if (! empty($wpdb->last_error)) {
2327
+            if ( ! empty($wpdb->last_error)) {
2328 2328
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2329 2329
             }
2330 2330
             if ($result === false) {
@@ -2389,7 +2389,7 @@  discard block
 block discarded – undo
2389 2389
                     return $result;
2390 2390
                     break;
2391 2391
             }
2392
-            if (! empty($error_message)) {
2392
+            if ( ! empty($error_message)) {
2393 2393
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2394 2394
                 trigger_error($error_message);
2395 2395
             }
@@ -2469,11 +2469,11 @@  discard block
 block discarded – undo
2469 2469
      */
2470 2470
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2471 2471
     {
2472
-        return " FROM " . $model_query_info->get_full_join_sql() .
2473
-               $model_query_info->get_where_sql() .
2474
-               $model_query_info->get_group_by_sql() .
2475
-               $model_query_info->get_having_sql() .
2476
-               $model_query_info->get_order_by_sql() .
2472
+        return " FROM ".$model_query_info->get_full_join_sql().
2473
+               $model_query_info->get_where_sql().
2474
+               $model_query_info->get_group_by_sql().
2475
+               $model_query_info->get_having_sql().
2476
+               $model_query_info->get_order_by_sql().
2477 2477
                $model_query_info->get_limit_sql();
2478 2478
     }
2479 2479
 
@@ -2669,12 +2669,12 @@  discard block
 block discarded – undo
2669 2669
         $related_model = $this->get_related_model_obj($model_name);
2670 2670
         // we're just going to use the query params on the related model's normal get_all query,
2671 2671
         // except add a condition to say to match the current mod
2672
-        if (! isset($query_params['default_where_conditions'])) {
2672
+        if ( ! isset($query_params['default_where_conditions'])) {
2673 2673
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2674 2674
         }
2675 2675
         $this_model_name = $this->get_this_model_name();
2676 2676
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2677
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2677
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2678 2678
         return $related_model->count($query_params, $field_to_count, $distinct);
2679 2679
     }
2680 2680
 
@@ -2694,7 +2694,7 @@  discard block
 block discarded – undo
2694 2694
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2695 2695
     {
2696 2696
         $related_model = $this->get_related_model_obj($model_name);
2697
-        if (! is_array($query_params)) {
2697
+        if ( ! is_array($query_params)) {
2698 2698
             EE_Error::doing_it_wrong(
2699 2699
                 'EEM_Base::sum_related',
2700 2700
                 sprintf(
@@ -2707,12 +2707,12 @@  discard block
 block discarded – undo
2707 2707
         }
2708 2708
         // we're just going to use the query params on the related model's normal get_all query,
2709 2709
         // except add a condition to say to match the current mod
2710
-        if (! isset($query_params['default_where_conditions'])) {
2710
+        if ( ! isset($query_params['default_where_conditions'])) {
2711 2711
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2712 2712
         }
2713 2713
         $this_model_name = $this->get_this_model_name();
2714 2714
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2715
-        $query_params[0][ $this_model_name . "." . $this_pk_field_name ] = $id_or_obj;
2715
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2716 2716
         return $related_model->sum($query_params, $field_to_sum);
2717 2717
     }
2718 2718
 
@@ -2765,7 +2765,7 @@  discard block
 block discarded – undo
2765 2765
                 $field_with_model_name = $field;
2766 2766
             }
2767 2767
         }
2768
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2768
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2769 2769
             throw new EE_Error(sprintf(
2770 2770
                 __("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2771 2771
                 $this->get_this_model_name()
@@ -2901,13 +2901,13 @@  discard block
 block discarded – undo
2901 2901
                 || $this->get_primary_key_field()
2902 2902
                    instanceof
2903 2903
                    EE_Primary_Key_String_Field)
2904
-            && isset($fields_n_values[ $this->primary_key_name() ])
2904
+            && isset($fields_n_values[$this->primary_key_name()])
2905 2905
         ) {
2906
-            $query_params[0]['OR'][ $this->primary_key_name() ] = $fields_n_values[ $this->primary_key_name() ];
2906
+            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2907 2907
         }
2908 2908
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2909 2909
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2910
-            $query_params[0]['OR'][ 'AND*' . $unique_index_name ] = $uniqueness_where_params;
2910
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2911 2911
         }
2912 2912
         // if there is nothing to base this search on, then we shouldn't find anything
2913 2913
         if (empty($query_params)) {
@@ -2985,15 +2985,15 @@  discard block
 block discarded – undo
2985 2985
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2986 2986
             // if the value we want to assign it to is NULL, just don't mention it for the insertion
2987 2987
             if ($prepared_value !== null) {
2988
-                $insertion_col_n_values[ $field_obj->get_table_column() ] = $prepared_value;
2988
+                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2989 2989
                 $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2990 2990
             }
2991 2991
         }
2992 2992
         if ($table instanceof EE_Secondary_Table && $new_id) {
2993 2993
             // its not the main table, so we should have already saved the main table's PK which we just inserted
2994 2994
             // so add the fk to the main table as a column
2995
-            $insertion_col_n_values[ $table->get_fk_on_table() ] = $new_id;
2996
-            $format_for_insertion[] = '%d';// yes right now we're only allowing these foreign keys to be INTs
2995
+            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2996
+            $format_for_insertion[] = '%d'; // yes right now we're only allowing these foreign keys to be INTs
2997 2997
         }
2998 2998
         // insert the new entry
2999 2999
         $result = $this->_do_wpdb_query(
@@ -3010,7 +3010,7 @@  discard block
 block discarded – undo
3010 3010
             }
3011 3011
             // it's not an auto-increment primary key, so
3012 3012
             // it must have been supplied
3013
-            return $fields_n_values[ $this->get_primary_key_field()->get_name() ];
3013
+            return $fields_n_values[$this->get_primary_key_field()->get_name()];
3014 3014
         }
3015 3015
         // we can't return a  primary key because there is none. instead return
3016 3016
         // a unique string indicating this model
@@ -3032,16 +3032,16 @@  discard block
 block discarded – undo
3032 3032
     protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3033 3033
     {
3034 3034
         // if this field doesn't allow nullable, don't allow it
3035
-        if (! $field_obj->is_nullable()
3035
+        if ( ! $field_obj->is_nullable()
3036 3036
             && (
3037
-                ! isset($fields_n_values[ $field_obj->get_name() ])
3038
-                || $fields_n_values[ $field_obj->get_name() ] === null
3037
+                ! isset($fields_n_values[$field_obj->get_name()])
3038
+                || $fields_n_values[$field_obj->get_name()] === null
3039 3039
             )
3040 3040
         ) {
3041
-            $fields_n_values[ $field_obj->get_name() ] = $field_obj->get_default_value();
3041
+            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3042 3042
         }
3043
-        $unprepared_value = isset($fields_n_values[ $field_obj->get_name() ])
3044
-            ? $fields_n_values[ $field_obj->get_name() ]
3043
+        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3044
+            ? $fields_n_values[$field_obj->get_name()]
3045 3045
             : null;
3046 3046
         return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3047 3047
     }
@@ -3142,7 +3142,7 @@  discard block
 block discarded – undo
3142 3142
      */
3143 3143
     public function get_table_obj_by_alias($table_alias = '')
3144 3144
     {
3145
-        return isset($this->_tables[ $table_alias ]) ? $this->_tables[ $table_alias ] : null;
3145
+        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3146 3146
     }
3147 3147
 
3148 3148
 
@@ -3157,7 +3157,7 @@  discard block
 block discarded – undo
3157 3157
         $other_tables = array();
3158 3158
         foreach ($this->_tables as $table_alias => $table) {
3159 3159
             if ($table instanceof EE_Secondary_Table) {
3160
-                $other_tables[ $table_alias ] = $table;
3160
+                $other_tables[$table_alias] = $table;
3161 3161
             }
3162 3162
         }
3163 3163
         return $other_tables;
@@ -3173,7 +3173,7 @@  discard block
 block discarded – undo
3173 3173
      */
3174 3174
     public function _get_fields_for_table($table_alias)
3175 3175
     {
3176
-        return $this->_fields[ $table_alias ];
3176
+        return $this->_fields[$table_alias];
3177 3177
     }
3178 3178
 
3179 3179
 
@@ -3202,7 +3202,7 @@  discard block
 block discarded – undo
3202 3202
                     $query_info_carrier,
3203 3203
                     'group_by'
3204 3204
                 );
3205
-            } elseif (! empty($query_params['group_by'])) {
3205
+            } elseif ( ! empty($query_params['group_by'])) {
3206 3206
                 $this->_extract_related_model_info_from_query_param(
3207 3207
                     $query_params['group_by'],
3208 3208
                     $query_info_carrier,
@@ -3224,7 +3224,7 @@  discard block
 block discarded – undo
3224 3224
                     $query_info_carrier,
3225 3225
                     'order_by'
3226 3226
                 );
3227
-            } elseif (! empty($query_params['order_by'])) {
3227
+            } elseif ( ! empty($query_params['order_by'])) {
3228 3228
                 $this->_extract_related_model_info_from_query_param(
3229 3229
                     $query_params['order_by'],
3230 3230
                     $query_info_carrier,
@@ -3259,7 +3259,7 @@  discard block
 block discarded – undo
3259 3259
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3260 3260
         $query_param_type
3261 3261
     ) {
3262
-        if (! empty($sub_query_params)) {
3262
+        if ( ! empty($sub_query_params)) {
3263 3263
             $sub_query_params = (array) $sub_query_params;
3264 3264
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3265 3265
                 // $param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
@@ -3274,7 +3274,7 @@  discard block
 block discarded – undo
3274 3274
                 // of array('Registration.TXN_ID'=>23)
3275 3275
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3276 3276
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3277
-                    if (! is_array($possibly_array_of_params)) {
3277
+                    if ( ! is_array($possibly_array_of_params)) {
3278 3278
                         throw new EE_Error(sprintf(
3279 3279
                             __(
3280 3280
                                 "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'))",
@@ -3297,7 +3297,7 @@  discard block
 block discarded – undo
3297 3297
                     // then $possible_array_of_params looks something like array('<','DTT_sold',true)
3298 3298
                     // indicating that $possible_array_of_params[1] is actually a field name,
3299 3299
                     // from which we should extract query parameters!
3300
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3300
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3301 3301
                         throw new EE_Error(sprintf(__(
3302 3302
                             "Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3303 3303
                             "event_espresso"
@@ -3331,8 +3331,8 @@  discard block
 block discarded – undo
3331 3331
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3332 3332
         $query_param_type
3333 3333
     ) {
3334
-        if (! empty($sub_query_params)) {
3335
-            if (! is_array($sub_query_params)) {
3334
+        if ( ! empty($sub_query_params)) {
3335
+            if ( ! is_array($sub_query_params)) {
3336 3336
                 throw new EE_Error(sprintf(
3337 3337
                     __("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3338 3338
                     $sub_query_params
@@ -3366,7 +3366,7 @@  discard block
 block discarded – undo
3366 3366
      */
3367 3367
     public function _create_model_query_info_carrier($query_params)
3368 3368
     {
3369
-        if (! is_array($query_params)) {
3369
+        if ( ! is_array($query_params)) {
3370 3370
             EE_Error::doing_it_wrong(
3371 3371
                 'EEM_Base::_create_model_query_info_carrier',
3372 3372
                 sprintf(
@@ -3399,7 +3399,7 @@  discard block
 block discarded – undo
3399 3399
             // only include if related to a cpt where no password has been set
3400 3400
             $query_params[0]['OR*nopassword'] = array(
3401 3401
                 $where_param_key_for_password => '',
3402
-                $where_param_key_for_password . '*' => array('IS_NULL')
3402
+                $where_param_key_for_password.'*' => array('IS_NULL')
3403 3403
             );
3404 3404
         }
3405 3405
         $query_object = $this->_extract_related_models_from_query($query_params);
@@ -3452,7 +3452,7 @@  discard block
 block discarded – undo
3452 3452
         // set limit
3453 3453
         if (array_key_exists('limit', $query_params)) {
3454 3454
             if (is_array($query_params['limit'])) {
3455
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3455
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3456 3456
                     $e = sprintf(
3457 3457
                         __(
3458 3458
                             "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)",
@@ -3460,12 +3460,12 @@  discard block
 block discarded – undo
3460 3460
                         ),
3461 3461
                         http_build_query($query_params['limit'])
3462 3462
                     );
3463
-                    throw new EE_Error($e . "|" . $e);
3463
+                    throw new EE_Error($e."|".$e);
3464 3464
                 }
3465 3465
                 // they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3466
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3467
-            } elseif (! empty($query_params['limit'])) {
3468
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3466
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3467
+            } elseif ( ! empty($query_params['limit'])) {
3468
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3469 3469
             }
3470 3470
         }
3471 3471
         // set order by
@@ -3497,10 +3497,10 @@  discard block
 block discarded – undo
3497 3497
                 $order_array = array();
3498 3498
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3499 3499
                     $order = $this->_extract_order($order);
3500
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3500
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3501 3501
                 }
3502
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3503
-            } elseif (! empty($query_params['order_by'])) {
3502
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3503
+            } elseif ( ! empty($query_params['order_by'])) {
3504 3504
                 $this->_extract_related_model_info_from_query_param(
3505 3505
                     $query_params['order_by'],
3506 3506
                     $query_object,
@@ -3511,18 +3511,18 @@  discard block
 block discarded – undo
3511 3511
                     ? $this->_extract_order($query_params['order'])
3512 3512
                     : 'DESC';
3513 3513
                 $query_object->set_order_by_sql(
3514
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3514
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3515 3515
                 );
3516 3516
             }
3517 3517
         }
3518 3518
         // if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3519
-        if (! array_key_exists('order_by', $query_params)
3519
+        if ( ! array_key_exists('order_by', $query_params)
3520 3520
             && array_key_exists('order', $query_params)
3521 3521
             && ! empty($query_params['order'])
3522 3522
         ) {
3523 3523
             $pk_field = $this->get_primary_key_field();
3524 3524
             $order = $this->_extract_order($query_params['order']);
3525
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3525
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3526 3526
         }
3527 3527
         // set group by
3528 3528
         if (array_key_exists('group_by', $query_params)) {
@@ -3532,10 +3532,10 @@  discard block
 block discarded – undo
3532 3532
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3533 3533
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3534 3534
                 }
3535
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3536
-            } elseif (! empty($query_params['group_by'])) {
3535
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3536
+            } elseif ( ! empty($query_params['group_by'])) {
3537 3537
                 $query_object->set_group_by_sql(
3538
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3538
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3539 3539
                 );
3540 3540
             }
3541 3541
         }
@@ -3545,7 +3545,7 @@  discard block
 block discarded – undo
3545 3545
         }
3546 3546
         // now, just verify they didn't pass anything wack
3547 3547
         foreach ($query_params as $query_key => $query_value) {
3548
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3548
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3549 3549
                 throw new EE_Error(
3550 3550
                     sprintf(
3551 3551
                         __(
@@ -3653,7 +3653,7 @@  discard block
 block discarded – undo
3653 3653
         $where_query_params = array()
3654 3654
     ) {
3655 3655
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3656
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3656
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3657 3657
             throw new EE_Error(sprintf(
3658 3658
                 __(
3659 3659
                     "You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
@@ -3785,19 +3785,19 @@  discard block
 block discarded – undo
3785 3785
     ) {
3786 3786
         $null_friendly_where_conditions = array();
3787 3787
         $none_overridden = true;
3788
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3788
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3789 3789
         foreach ($default_where_conditions as $key => $val) {
3790
-            if (isset($provided_where_conditions[ $key ])) {
3790
+            if (isset($provided_where_conditions[$key])) {
3791 3791
                 $none_overridden = false;
3792 3792
             } else {
3793
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ]['AND'][ $key ] = $val;
3793
+                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3794 3794
             }
3795 3795
         }
3796 3796
         if ($none_overridden && $default_where_conditions) {
3797 3797
             if ($model->has_primary_key_field()) {
3798
-                $null_friendly_where_conditions[ $or_condition_key_for_defaults ][ $model_relation_path
3798
+                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3799 3799
                                                                                 . "."
3800
-                                                                                . $model->primary_key_name() ] = array('IS NULL');
3800
+                                                                                . $model->primary_key_name()] = array('IS NULL');
3801 3801
             }/*else{
3802 3802
                 //@todo NO PK, use other defaults
3803 3803
             }*/
@@ -3903,7 +3903,7 @@  discard block
 block discarded – undo
3903 3903
             foreach ($tables as $table_obj) {
3904 3904
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3905 3905
                                        . $table_obj->get_fully_qualified_pk_column();
3906
-                if (! in_array($qualified_pk_column, $selects)) {
3906
+                if ( ! in_array($qualified_pk_column, $selects)) {
3907 3907
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3908 3908
                 }
3909 3909
             }
@@ -4052,9 +4052,9 @@  discard block
 block discarded – undo
4052 4052
         $query_parameter_type
4053 4053
     ) {
4054 4054
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
4055
-            if (strpos($possible_join_string, $valid_related_model_name . ".") === 0) {
4055
+            if (strpos($possible_join_string, $valid_related_model_name.".") === 0) {
4056 4056
                 $this->_add_join_to_model($valid_related_model_name, $query_info_carrier, $original_query_param);
4057
-                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name . "."));
4057
+                $possible_join_string = substr($possible_join_string, strlen($valid_related_model_name."."));
4058 4058
                 if ($possible_join_string === '') {
4059 4059
                     // nothing left to $query_param
4060 4060
                     // we should actually end in a field name, not a model like this!
@@ -4184,7 +4184,7 @@  discard block
 block discarded – undo
4184 4184
     {
4185 4185
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4186 4186
         if ($SQL) {
4187
-            return " WHERE " . $SQL;
4187
+            return " WHERE ".$SQL;
4188 4188
         }
4189 4189
         return '';
4190 4190
     }
@@ -4203,7 +4203,7 @@  discard block
 block discarded – undo
4203 4203
     {
4204 4204
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4205 4205
         if ($SQL) {
4206
-            return " HAVING " . $SQL;
4206
+            return " HAVING ".$SQL;
4207 4207
         }
4208 4208
         return '';
4209 4209
     }
@@ -4222,7 +4222,7 @@  discard block
 block discarded – undo
4222 4222
     {
4223 4223
         $where_clauses = array();
4224 4224
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4225
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);// str_replace("*",'',$query_param);
4225
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); // str_replace("*",'',$query_param);
4226 4226
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4227 4227
                 switch ($query_param) {
4228 4228
                     case 'not':
@@ -4256,7 +4256,7 @@  discard block
 block discarded – undo
4256 4256
             } else {
4257 4257
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4258 4258
                 // if it's not a normal field, maybe it's a custom selection?
4259
-                if (! $field_obj) {
4259
+                if ( ! $field_obj) {
4260 4260
                     if ($this->_custom_selections instanceof CustomSelects) {
4261 4261
                         $field_obj = $this->_custom_selections->getDataTypeForAlias($query_param);
4262 4262
                     } else {
@@ -4267,7 +4267,7 @@  discard block
 block discarded – undo
4267 4267
                     }
4268 4268
                 }
4269 4269
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4270
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4270
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4271 4271
             }
4272 4272
         }
4273 4273
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4290,7 +4290,7 @@  discard block
 block discarded – undo
4290 4290
                 $field->get_model_name(),
4291 4291
                 $query_param
4292 4292
             );
4293
-            return $table_alias_prefix . $field->get_qualified_column();
4293
+            return $table_alias_prefix.$field->get_qualified_column();
4294 4294
         }
4295 4295
         if ($this->_custom_selections instanceof CustomSelects
4296 4296
             && in_array($query_param, $this->_custom_selections->columnAliases(), true)
@@ -4349,7 +4349,7 @@  discard block
 block discarded – undo
4349 4349
     {
4350 4350
         if (is_array($op_and_value)) {
4351 4351
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4352
-            if (! $operator) {
4352
+            if ( ! $operator) {
4353 4353
                 $php_array_like_string = array();
4354 4354
                 foreach ($op_and_value as $key => $value) {
4355 4355
                     $php_array_like_string[] = "$key=>$value";
@@ -4371,14 +4371,14 @@  discard block
 block discarded – undo
4371 4371
         }
4372 4372
         // check to see if the value is actually another field
4373 4373
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4374
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4374
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4375 4375
         }
4376 4376
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4377 4377
             // in this case, the value should be an array, or at least a comma-separated list
4378 4378
             // it will need to handle a little differently
4379 4379
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4380 4380
             // note: $cleaned_value has already been run through $wpdb->prepare()
4381
-            return $operator . SP . $cleaned_value;
4381
+            return $operator.SP.$cleaned_value;
4382 4382
         }
4383 4383
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4384 4384
             // the value should be an array with count of two.
@@ -4394,7 +4394,7 @@  discard block
 block discarded – undo
4394 4394
                 );
4395 4395
             }
4396 4396
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4397
-            return $operator . SP . $cleaned_value;
4397
+            return $operator.SP.$cleaned_value;
4398 4398
         }
4399 4399
         if (in_array($operator, $this->valid_null_style_operators())) {
4400 4400
             if ($value !== null) {
@@ -4414,10 +4414,10 @@  discard block
 block discarded – undo
4414 4414
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4415 4415
             // if the operator is 'LIKE', we want to allow percent signs (%) and not
4416 4416
             // remove other junk. So just treat it as a string.
4417
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4417
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4418 4418
         }
4419
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4419
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4420
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4421 4421
         }
4422 4422
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4423 4423
             throw new EE_Error(
@@ -4431,7 +4431,7 @@  discard block
 block discarded – undo
4431 4431
                 )
4432 4432
             );
4433 4433
         }
4434
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4434
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4435 4435
             throw new EE_Error(
4436 4436
                 sprintf(
4437 4437
                     __(
@@ -4471,7 +4471,7 @@  discard block
 block discarded – undo
4471 4471
         foreach ($values as $value) {
4472 4472
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4473 4473
         }
4474
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4474
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4475 4475
     }
4476 4476
 
4477 4477
 
@@ -4512,7 +4512,7 @@  discard block
 block discarded – undo
4512 4512
                                 . $main_table->get_table_name()
4513 4513
                                 . " WHERE FALSE";
4514 4514
         }
4515
-        return "(" . implode(",", $cleaned_values) . ")";
4515
+        return "(".implode(",", $cleaned_values).")";
4516 4516
     }
4517 4517
 
4518 4518
 
@@ -4533,7 +4533,7 @@  discard block
 block discarded – undo
4533 4533
                 $this->_prepare_value_for_use_in_db($value, $field_obj)
4534 4534
             );
4535 4535
         } //$field_obj should really just be a data type
4536
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4536
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4537 4537
             throw new EE_Error(
4538 4538
                 sprintf(
4539 4539
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4566,14 +4566,14 @@  discard block
 block discarded – undo
4566 4566
             ), $query_param_name));
4567 4567
         }
4568 4568
         $number_of_parts = count($query_param_parts);
4569
-        $last_query_param_part = $query_param_parts[ count($query_param_parts) - 1 ];
4569
+        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4570 4570
         if ($number_of_parts === 1) {
4571 4571
             $field_name = $last_query_param_part;
4572 4572
             $model_obj = $this;
4573 4573
         } else {// $number_of_parts >= 2
4574 4574
             // the last part is the column name, and there are only 2parts. therefore...
4575 4575
             $field_name = $last_query_param_part;
4576
-            $model_obj = $this->get_related_model_obj($query_param_parts[ $number_of_parts - 2 ]);
4576
+            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4577 4577
         }
4578 4578
         try {
4579 4579
             return $model_obj->field_settings_for($field_name);
@@ -4595,7 +4595,7 @@  discard block
 block discarded – undo
4595 4595
     public function _get_qualified_column_for_field($field_name)
4596 4596
     {
4597 4597
         $all_fields = $this->field_settings();
4598
-        $field = isset($all_fields[ $field_name ]) ? $all_fields[ $field_name ] : false;
4598
+        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4599 4599
         if ($field) {
4600 4600
             return $field->get_qualified_column();
4601 4601
         }
@@ -4666,10 +4666,10 @@  discard block
 block discarded – undo
4666 4666
      */
4667 4667
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4668 4668
     {
4669
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4669
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4670 4670
         $qualified_columns = array();
4671 4671
         foreach ($this->field_settings() as $field_name => $field) {
4672
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4672
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4673 4673
         }
4674 4674
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4675 4675
     }
@@ -4693,11 +4693,11 @@  discard block
 block discarded – undo
4693 4693
             if ($table_obj instanceof EE_Primary_Table) {
4694 4694
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4695 4695
                     ? $table_obj->get_select_join_limit($limit)
4696
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4696
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4697 4697
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4698 4698
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4699 4699
                     ? $table_obj->get_select_join_limit_join($limit)
4700
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4700
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4701 4701
             }
4702 4702
         }
4703 4703
         return $SQL;
@@ -4769,7 +4769,7 @@  discard block
 block discarded – undo
4769 4769
         foreach ($this->field_settings() as $field_obj) {
4770 4770
             // $data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4771 4771
             /** @var $field_obj EE_Model_Field_Base */
4772
-            $data_types[ $field_obj->get_qualified_column() ] = $field_obj->get_wpdb_data_type();
4772
+            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4773 4773
         }
4774 4774
         return $data_types;
4775 4775
     }
@@ -4785,14 +4785,14 @@  discard block
 block discarded – undo
4785 4785
      */
4786 4786
     public function get_related_model_obj($model_name)
4787 4787
     {
4788
-        $model_classname = "EEM_" . $model_name;
4789
-        if (! class_exists($model_classname)) {
4788
+        $model_classname = "EEM_".$model_name;
4789
+        if ( ! class_exists($model_classname)) {
4790 4790
             throw new EE_Error(sprintf(__(
4791 4791
                 "You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4792 4792
                 'event_espresso'
4793 4793
             ), $model_name, $model_classname));
4794 4794
         }
4795
-        return call_user_func($model_classname . "::instance");
4795
+        return call_user_func($model_classname."::instance");
4796 4796
     }
4797 4797
 
4798 4798
 
@@ -4821,7 +4821,7 @@  discard block
 block discarded – undo
4821 4821
         $belongs_to_relations = array();
4822 4822
         foreach ($this->relation_settings() as $model_name => $relation_obj) {
4823 4823
             if ($relation_obj instanceof EE_Belongs_To_Relation) {
4824
-                $belongs_to_relations[ $model_name ] = $relation_obj;
4824
+                $belongs_to_relations[$model_name] = $relation_obj;
4825 4825
             }
4826 4826
         }
4827 4827
         return $belongs_to_relations;
@@ -4839,7 +4839,7 @@  discard block
 block discarded – undo
4839 4839
     public function related_settings_for($relation_name)
4840 4840
     {
4841 4841
         $relatedModels = $this->relation_settings();
4842
-        if (! array_key_exists($relation_name, $relatedModels)) {
4842
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4843 4843
             throw new EE_Error(
4844 4844
                 sprintf(
4845 4845
                     __(
@@ -4852,7 +4852,7 @@  discard block
 block discarded – undo
4852 4852
                 )
4853 4853
             );
4854 4854
         }
4855
-        return $relatedModels[ $relation_name ];
4855
+        return $relatedModels[$relation_name];
4856 4856
     }
4857 4857
 
4858 4858
 
@@ -4869,14 +4869,14 @@  discard block
 block discarded – undo
4869 4869
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4870 4870
     {
4871 4871
         $fieldSettings = $this->field_settings($include_db_only_fields);
4872
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4872
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4873 4873
             throw new EE_Error(sprintf(
4874 4874
                 __("There is no field/column '%s' on '%s'", 'event_espresso'),
4875 4875
                 $fieldName,
4876 4876
                 get_class($this)
4877 4877
             ));
4878 4878
         }
4879
-        return $fieldSettings[ $fieldName ];
4879
+        return $fieldSettings[$fieldName];
4880 4880
     }
4881 4881
 
4882 4882
 
@@ -4890,7 +4890,7 @@  discard block
 block discarded – undo
4890 4890
     public function has_field($fieldName)
4891 4891
     {
4892 4892
         $fieldSettings = $this->field_settings(true);
4893
-        if (isset($fieldSettings[ $fieldName ])) {
4893
+        if (isset($fieldSettings[$fieldName])) {
4894 4894
             return true;
4895 4895
         }
4896 4896
         return false;
@@ -4907,7 +4907,7 @@  discard block
 block discarded – undo
4907 4907
     public function has_relation($relation_name)
4908 4908
     {
4909 4909
         $relations = $this->relation_settings();
4910
-        if (isset($relations[ $relation_name ])) {
4910
+        if (isset($relations[$relation_name])) {
4911 4911
             return true;
4912 4912
         }
4913 4913
         return false;
@@ -4945,7 +4945,7 @@  discard block
 block discarded – undo
4945 4945
                     break;
4946 4946
                 }
4947 4947
             }
4948
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4948
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4949 4949
                 throw new EE_Error(sprintf(
4950 4950
                     __("There is no Primary Key defined on model %s", 'event_espresso'),
4951 4951
                     get_class($this)
@@ -5006,23 +5006,23 @@  discard block
 block discarded – undo
5006 5006
      */
5007 5007
     public function get_foreign_key_to($model_name)
5008 5008
     {
5009
-        if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5009
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5010 5010
             foreach ($this->field_settings() as $field) {
5011 5011
                 if ($field instanceof EE_Foreign_Key_Field_Base
5012 5012
                     && in_array($model_name, $field->get_model_names_pointed_to())
5013 5013
                 ) {
5014
-                    $this->_cache_foreign_key_to_fields[ $model_name ] = $field;
5014
+                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
5015 5015
                     break;
5016 5016
                 }
5017 5017
             }
5018
-            if (! isset($this->_cache_foreign_key_to_fields[ $model_name ])) {
5018
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
5019 5019
                 throw new EE_Error(sprintf(__(
5020 5020
                     "There is no foreign key field pointing to model %s on model %s",
5021 5021
                     'event_espresso'
5022 5022
                 ), $model_name, get_class($this)));
5023 5023
             }
5024 5024
         }
5025
-        return $this->_cache_foreign_key_to_fields[ $model_name ];
5025
+        return $this->_cache_foreign_key_to_fields[$model_name];
5026 5026
     }
5027 5027
 
5028 5028
 
@@ -5038,7 +5038,7 @@  discard block
 block discarded – undo
5038 5038
     public function get_table_for_alias($table_alias)
5039 5039
     {
5040 5040
         $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
5041
-        return $this->_tables[ $table_alias_sans_model_relation_chain_prefix ]->get_table_name();
5041
+        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
5042 5042
     }
5043 5043
 
5044 5044
 
@@ -5057,7 +5057,7 @@  discard block
 block discarded – undo
5057 5057
                 $this->_cached_fields = array();
5058 5058
                 foreach ($this->_fields as $fields_corresponding_to_table) {
5059 5059
                     foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5060
-                        $this->_cached_fields[ $field_name ] = $field_obj;
5060
+                        $this->_cached_fields[$field_name] = $field_obj;
5061 5061
                     }
5062 5062
                 }
5063 5063
             }
@@ -5068,8 +5068,8 @@  discard block
 block discarded – undo
5068 5068
             foreach ($this->_fields as $fields_corresponding_to_table) {
5069 5069
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
5070 5070
                     /** @var $field_obj EE_Model_Field_Base */
5071
-                    if (! $field_obj->is_db_only_field()) {
5072
-                        $this->_cached_fields_non_db_only[ $field_name ] = $field_obj;
5071
+                    if ( ! $field_obj->is_db_only_field()) {
5072
+                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
5073 5073
                     }
5074 5074
                 }
5075 5075
             }
@@ -5110,12 +5110,12 @@  discard block
 block discarded – undo
5110 5110
                     $primary_key_field->get_qualified_column(),
5111 5111
                     $primary_key_field->get_table_column()
5112 5112
                 );
5113
-                if ($table_pk_value && isset($array_of_objects[ $table_pk_value ])) {
5113
+                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
5114 5114
                     continue;
5115 5115
                 }
5116 5116
             }
5117 5117
             $classInstance = $this->instantiate_class_from_array_or_object($row);
5118
-            if (! $classInstance) {
5118
+            if ( ! $classInstance) {
5119 5119
                 throw new EE_Error(
5120 5120
                     sprintf(
5121 5121
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -5128,7 +5128,7 @@  discard block
 block discarded – undo
5128 5128
             $classInstance->set_timezone($this->_timezone);
5129 5129
             // make sure if there is any timezone setting present that we set the timezone for the object
5130 5130
             $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
5131
-            $array_of_objects[ $key ] = $classInstance;
5131
+            $array_of_objects[$key] = $classInstance;
5132 5132
             // also, for all the relations of type BelongsTo, see if we can cache
5133 5133
             // those related models
5134 5134
             // (we could do this for other relations too, but if there are conditions
@@ -5172,9 +5172,9 @@  discard block
 block discarded – undo
5172 5172
         $results = array();
5173 5173
         if ($this->_custom_selections instanceof CustomSelects) {
5174 5174
             foreach ($this->_custom_selections->columnAliases() as $alias) {
5175
-                if (isset($db_results_row[ $alias ])) {
5176
-                    $results[ $alias ] = $this->convertValueToDataType(
5177
-                        $db_results_row[ $alias ],
5175
+                if (isset($db_results_row[$alias])) {
5176
+                    $results[$alias] = $this->convertValueToDataType(
5177
+                        $db_results_row[$alias],
5178 5178
                         $this->_custom_selections->getDataTypeForAlias($alias)
5179 5179
                     );
5180 5180
                 }
@@ -5216,7 +5216,7 @@  discard block
 block discarded – undo
5216 5216
         $this_model_fields_and_values = array();
5217 5217
         // setup the row using default values;
5218 5218
         foreach ($this->field_settings() as $field_name => $field_obj) {
5219
-            $this_model_fields_and_values[ $field_name ] = $field_obj->get_default_value();
5219
+            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
5220 5220
         }
5221 5221
         $className = $this->_get_class_name();
5222 5222
         $classInstance = EE_Registry::instance()
@@ -5234,20 +5234,20 @@  discard block
 block discarded – undo
5234 5234
      */
5235 5235
     public function instantiate_class_from_array_or_object($cols_n_values)
5236 5236
     {
5237
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5237
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5238 5238
             $cols_n_values = get_object_vars($cols_n_values);
5239 5239
         }
5240 5240
         $primary_key = null;
5241 5241
         // make sure the array only has keys that are fields/columns on this model
5242 5242
         $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5243
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[ $this->primary_key_name() ])) {
5244
-            $primary_key = $this_model_fields_n_values[ $this->primary_key_name() ];
5243
+        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5244
+            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5245 5245
         }
5246 5246
         $className = $this->_get_class_name();
5247 5247
         // check we actually found results that we can use to build our model object
5248 5248
         // if not, return null
5249 5249
         if ($this->has_primary_key_field()) {
5250
-            if (empty($this_model_fields_n_values[ $this->primary_key_name() ])) {
5250
+            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5251 5251
                 return null;
5252 5252
             }
5253 5253
         } elseif ($this->unique_indexes()) {
@@ -5259,7 +5259,7 @@  discard block
 block discarded – undo
5259 5259
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5260 5260
         if ($primary_key) {
5261 5261
             $classInstance = $this->get_from_entity_map($primary_key);
5262
-            if (! $classInstance) {
5262
+            if ( ! $classInstance) {
5263 5263
                 $classInstance = EE_Registry::instance()
5264 5264
                                             ->load_class(
5265 5265
                                                 $className,
@@ -5292,8 +5292,8 @@  discard block
 block discarded – undo
5292 5292
      */
5293 5293
     public function get_from_entity_map($id)
5294 5294
     {
5295
-        return isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])
5296
-            ? $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] : null;
5295
+        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5296
+            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5297 5297
     }
5298 5298
 
5299 5299
 
@@ -5316,7 +5316,7 @@  discard block
 block discarded – undo
5316 5316
     public function add_to_entity_map(EE_Base_Class $object)
5317 5317
     {
5318 5318
         $className = $this->_get_class_name();
5319
-        if (! $object instanceof $className) {
5319
+        if ( ! $object instanceof $className) {
5320 5320
             throw new EE_Error(sprintf(
5321 5321
                 __("You tried adding a %s to a mapping of %ss", "event_espresso"),
5322 5322
                 is_object($object) ? get_class($object) : $object,
@@ -5324,7 +5324,7 @@  discard block
 block discarded – undo
5324 5324
             ));
5325 5325
         }
5326 5326
         /** @var $object EE_Base_Class */
5327
-        if (! $object->ID()) {
5327
+        if ( ! $object->ID()) {
5328 5328
             throw new EE_Error(sprintf(__(
5329 5329
                 "You tried storing a model object with NO ID in the %s entity mapper.",
5330 5330
                 "event_espresso"
@@ -5335,7 +5335,7 @@  discard block
 block discarded – undo
5335 5335
         if ($classInstance) {
5336 5336
             return $classInstance;
5337 5337
         }
5338
-        $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $object->ID() ] = $object;
5338
+        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5339 5339
         return $object;
5340 5340
     }
5341 5341
 
@@ -5351,11 +5351,11 @@  discard block
 block discarded – undo
5351 5351
     public function clear_entity_map($id = null)
5352 5352
     {
5353 5353
         if (empty($id)) {
5354
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ] = array();
5354
+            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5355 5355
             return true;
5356 5356
         }
5357
-        if (isset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ])) {
5358
-            unset($this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ]);
5357
+        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5358
+            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5359 5359
             return true;
5360 5360
         }
5361 5361
         return false;
@@ -5398,17 +5398,17 @@  discard block
 block discarded – undo
5398 5398
             // there is a primary key on this table and its not set. Use defaults for all its columns
5399 5399
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5400 5400
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5401
-                    if (! $field_obj->is_db_only_field()) {
5401
+                    if ( ! $field_obj->is_db_only_field()) {
5402 5402
                         // prepare field as if its coming from db
5403 5403
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5404
-                        $this_model_fields_n_values[ $field_name ] = $field_obj->prepare_for_use_in_db($prepared_value);
5404
+                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5405 5405
                     }
5406 5406
                 }
5407 5407
             } else {
5408 5408
                 // the table's rows existed. Use their values
5409 5409
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5410
-                    if (! $field_obj->is_db_only_field()) {
5411
-                        $this_model_fields_n_values[ $field_name ] = $this->_get_column_value_with_table_alias_or_not(
5410
+                    if ( ! $field_obj->is_db_only_field()) {
5411
+                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5412 5412
                             $cols_n_values,
5413 5413
                             $field_obj->get_qualified_column(),
5414 5414
                             $field_obj->get_table_column()
@@ -5435,17 +5435,17 @@  discard block
 block discarded – undo
5435 5435
         // ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5436 5436
         // does the field on the model relate to this column retrieved from the db?
5437 5437
         // or is it a db-only field? (not relating to the model)
5438
-        if (isset($cols_n_values[ $qualified_column ])) {
5439
-            $value = $cols_n_values[ $qualified_column ];
5440
-        } elseif (isset($cols_n_values[ $regular_column ])) {
5441
-            $value = $cols_n_values[ $regular_column ];
5442
-        } elseif (! empty($this->foreign_key_aliases)) {
5438
+        if (isset($cols_n_values[$qualified_column])) {
5439
+            $value = $cols_n_values[$qualified_column];
5440
+        } elseif (isset($cols_n_values[$regular_column])) {
5441
+            $value = $cols_n_values[$regular_column];
5442
+        } elseif ( ! empty($this->foreign_key_aliases)) {
5443 5443
             // no PK?  ok check if there is a foreign key alias set for this table
5444 5444
             // then check if that alias exists in the incoming data
5445 5445
             // AND that the actual PK the $FK_alias represents matches the $qualified_column (full PK)
5446 5446
             foreach ($this->foreign_key_aliases as $FK_alias => $PK_column) {
5447
-                if ($PK_column === $qualified_column && isset($cols_n_values[ $FK_alias ])) {
5448
-                    $value = $cols_n_values[ $FK_alias ];
5447
+                if ($PK_column === $qualified_column && isset($cols_n_values[$FK_alias])) {
5448
+                    $value = $cols_n_values[$FK_alias];
5449 5449
                     list($pk_class) = explode('.', $PK_column);
5450 5450
                     $pk_model_name = "EEM_{$pk_class}";
5451 5451
                     /** @var EEM_Base $pk_model */
@@ -5489,7 +5489,7 @@  discard block
 block discarded – undo
5489 5489
                     $obj_in_map->clear_cache($relation_name, null, true);
5490 5490
                 }
5491 5491
             }
5492
-            $this->_entity_map[ EEM_Base::$_model_query_blog_id ][ $id ] = $obj_in_map;
5492
+            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5493 5493
             return $obj_in_map;
5494 5494
         }
5495 5495
         return $this->get_one_by_ID($id);
@@ -5542,7 +5542,7 @@  discard block
 block discarded – undo
5542 5542
      */
5543 5543
     private function _get_class_name()
5544 5544
     {
5545
-        return "EE_" . $this->get_this_model_name();
5545
+        return "EE_".$this->get_this_model_name();
5546 5546
     }
5547 5547
 
5548 5548
 
@@ -5590,7 +5590,7 @@  discard block
 block discarded – undo
5590 5590
     {
5591 5591
         $className = get_class($this);
5592 5592
         $tagName = "FHEE__{$className}__{$methodName}";
5593
-        if (! has_filter($tagName)) {
5593
+        if ( ! has_filter($tagName)) {
5594 5594
             throw new EE_Error(
5595 5595
                 sprintf(
5596 5596
                     __(
@@ -5761,7 +5761,7 @@  discard block
 block discarded – undo
5761 5761
         $unique_indexes = array();
5762 5762
         foreach ($this->_indexes as $name => $index) {
5763 5763
             if ($index instanceof EE_Unique_Index) {
5764
-                $unique_indexes [ $name ] = $index;
5764
+                $unique_indexes [$name] = $index;
5765 5765
             }
5766 5766
         }
5767 5767
         return $unique_indexes;
@@ -5828,7 +5828,7 @@  discard block
 block discarded – undo
5828 5828
         $key_vals_in_combined_pk = array();
5829 5829
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5830 5830
         foreach ($key_fields as $key_field_name => $field_obj) {
5831
-            if (! isset($key_vals_in_combined_pk[ $key_field_name ])) {
5831
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5832 5832
                 return null;
5833 5833
             }
5834 5834
         }
@@ -5849,7 +5849,7 @@  discard block
 block discarded – undo
5849 5849
     {
5850 5850
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5851 5851
         foreach ($keys_it_should_have as $key) {
5852
-            if (! isset($key_vals[ $key ])) {
5852
+            if ( ! isset($key_vals[$key])) {
5853 5853
                 return false;
5854 5854
             }
5855 5855
         }
@@ -5882,8 +5882,8 @@  discard block
 block discarded – undo
5882 5882
         }
5883 5883
         // even copies obviously won't have the same ID, so remove the primary key
5884 5884
         // from the WHERE conditions for finding copies (if there is a primary key, of course)
5885
-        if ($this->has_primary_key_field() && isset($attributes_array[ $this->primary_key_name() ])) {
5886
-            unset($attributes_array[ $this->primary_key_name() ]);
5885
+        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5886
+            unset($attributes_array[$this->primary_key_name()]);
5887 5887
         }
5888 5888
         if (isset($query_params[0])) {
5889 5889
             $query_params[0] = array_merge($attributes_array, $query_params);
@@ -5905,7 +5905,7 @@  discard block
 block discarded – undo
5905 5905
      */
5906 5906
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5907 5907
     {
5908
-        if (! is_array($query_params)) {
5908
+        if ( ! is_array($query_params)) {
5909 5909
             EE_Error::doing_it_wrong(
5910 5910
                 'EEM_Base::get_one_copy',
5911 5911
                 sprintf(
@@ -5955,7 +5955,7 @@  discard block
 block discarded – undo
5955 5955
      */
5956 5956
     private function _prepare_operator_for_sql($operator_supplied)
5957 5957
     {
5958
-        $sql_operator = isset($this->_valid_operators[ $operator_supplied ]) ? $this->_valid_operators[ $operator_supplied ]
5958
+        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5959 5959
             : null;
5960 5960
         if ($sql_operator) {
5961 5961
             return $sql_operator;
@@ -6046,7 +6046,7 @@  discard block
 block discarded – undo
6046 6046
         $objs = $this->get_all($query_params);
6047 6047
         $names = array();
6048 6048
         foreach ($objs as $obj) {
6049
-            $names[ $obj->ID() ] = $obj->name();
6049
+            $names[$obj->ID()] = $obj->name();
6050 6050
         }
6051 6051
         return $names;
6052 6052
     }
@@ -6067,7 +6067,7 @@  discard block
 block discarded – undo
6067 6067
      */
6068 6068
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
6069 6069
     {
6070
-        if (! $this->has_primary_key_field()) {
6070
+        if ( ! $this->has_primary_key_field()) {
6071 6071
             if (WP_DEBUG) {
6072 6072
                 EE_Error::add_error(
6073 6073
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -6080,7 +6080,7 @@  discard block
 block discarded – undo
6080 6080
         $IDs = array();
6081 6081
         foreach ($model_objects as $model_object) {
6082 6082
             $id = $model_object->ID();
6083
-            if (! $id) {
6083
+            if ( ! $id) {
6084 6084
                 if ($filter_out_empty_ids) {
6085 6085
                     continue;
6086 6086
                 }
@@ -6130,22 +6130,22 @@  discard block
 block discarded – undo
6130 6130
     {
6131 6131
         EEM_Base::verify_is_valid_cap_context($context);
6132 6132
         // check if we ought to run the restriction generator first
6133
-        if (isset($this->_cap_restriction_generators[ $context ])
6134
-            && $this->_cap_restriction_generators[ $context ] instanceof EE_Restriction_Generator_Base
6135
-            && ! $this->_cap_restriction_generators[ $context ]->has_generated_cap_restrictions()
6133
+        if (isset($this->_cap_restriction_generators[$context])
6134
+            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
6135
+            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
6136 6136
         ) {
6137
-            $this->_cap_restrictions[ $context ] = array_merge(
6138
-                $this->_cap_restrictions[ $context ],
6139
-                $this->_cap_restriction_generators[ $context ]->generate_restrictions()
6137
+            $this->_cap_restrictions[$context] = array_merge(
6138
+                $this->_cap_restrictions[$context],
6139
+                $this->_cap_restriction_generators[$context]->generate_restrictions()
6140 6140
             );
6141 6141
         }
6142 6142
         // and make sure we've finalized the construction of each restriction
6143
-        foreach ($this->_cap_restrictions[ $context ] as $where_conditions_obj) {
6143
+        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
6144 6144
             if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
6145 6145
                 $where_conditions_obj->_finalize_construct($this);
6146 6146
             }
6147 6147
         }
6148
-        return $this->_cap_restrictions[ $context ];
6148
+        return $this->_cap_restrictions[$context];
6149 6149
     }
6150 6150
 
6151 6151
 
@@ -6175,10 +6175,10 @@  discard block
 block discarded – undo
6175 6175
         $missing_caps = array();
6176 6176
         $cap_restrictions = $this->cap_restrictions($context);
6177 6177
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
6178
-            if (! EE_Capabilities::instance()
6179
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
6178
+            if ( ! EE_Capabilities::instance()
6179
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
6180 6180
             ) {
6181
-                $missing_caps[ $cap ] = $restriction_if_no_cap;
6181
+                $missing_caps[$cap] = $restriction_if_no_cap;
6182 6182
             }
6183 6183
         }
6184 6184
         return $missing_caps;
@@ -6213,8 +6213,8 @@  discard block
 block discarded – undo
6213 6213
     public function cap_action_for_context($context)
6214 6214
     {
6215 6215
         $mapping = $this->cap_contexts_to_cap_action_map();
6216
-        if (isset($mapping[ $context ])) {
6217
-            return $mapping[ $context ];
6216
+        if (isset($mapping[$context])) {
6217
+            return $mapping[$context];
6218 6218
         }
6219 6219
         if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
6220 6220
             return $action;
@@ -6331,7 +6331,7 @@  discard block
 block discarded – undo
6331 6331
     {
6332 6332
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6333 6333
             if ($query_param_key === $logic_query_param_key
6334
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6334
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6335 6335
             ) {
6336 6336
                 return true;
6337 6337
             }
@@ -6384,7 +6384,7 @@  discard block
 block discarded – undo
6384 6384
         if ($password_field instanceof EE_Password_Field) {
6385 6385
             $field_names = $password_field->protectedFields();
6386 6386
             foreach ($field_names as $field_name) {
6387
-                $fields[ $field_name ] = $this->field_settings_for($field_name);
6387
+                $fields[$field_name] = $this->field_settings_for($field_name);
6388 6388
             }
6389 6389
         }
6390 6390
         return $fields;
@@ -6409,7 +6409,7 @@  discard block
 block discarded – undo
6409 6409
         if ($model_obj_or_fields_n_values instanceof EE_Base_Class) {
6410 6410
             $model_obj_or_fields_n_values = $model_obj_or_fields_n_values->model_field_array();
6411 6411
         }
6412
-        if (!is_array($model_obj_or_fields_n_values)) {
6412
+        if ( ! is_array($model_obj_or_fields_n_values)) {
6413 6413
             throw new UnexpectedEntityException(
6414 6414
                 $model_obj_or_fields_n_values,
6415 6415
                 'EE_Base_Class',
@@ -6484,7 +6484,7 @@  discard block
 block discarded – undo
6484 6484
                 )
6485 6485
             );
6486 6486
         }
6487
-        return ($this->model_chain_to_password ? $this->model_chain_to_password . '.' : '') . $password_field_name;
6487
+        return ($this->model_chain_to_password ? $this->model_chain_to_password.'.' : '').$password_field_name;
6488 6488
     }
6489 6489
 
6490 6490
     /**
Please login to merge, or discard this patch.
core/libraries/form_sections/base/EE_Model_Form_Section.form.php 1 patch
Indentation   +455 added lines, -455 removed lines patch added patch discarded remove patch
@@ -14,459 +14,459 @@
 block discarded – undo
14 14
 class EE_Model_Form_Section extends EE_Form_Section_Proper
15 15
 {
16 16
 
17
-    /**
18
-     * @var EEM_Base
19
-     */
20
-    protected $_model = null;
21
-
22
-    /**
23
-     * @var EE_Base_Class
24
-     */
25
-    protected $_model_object = null;
26
-
27
-
28
-
29
-    /**
30
-     * @param array        $options_array   keys: {
31
-     * @type EEM_Base      $model
32
-     * @type EE_Base_Class $model_object
33
-     * @type array         $subsection_args array keys should be subsection names (that either do or will exist), and
34
-     *       values are the arrays as you would pass them to that subsection
35
-     *                                      }
36
-     * @throws EE_Error
37
-     */
38
-    public function __construct($options_array = array())
39
-    {
40
-        if (isset($options_array['model']) && $options_array['model'] instanceof EEM_Base) {
41
-            $this->_model = $options_array['model'];
42
-        }
43
-        if (! $this->_model || ! $this->_model instanceof EEM_Base) {
44
-            throw new EE_Error(sprintf(__(
45
-                "Model Form Sections must first specify the _model property to be a subclass of EEM_Base",
46
-                "event_espresso"
47
-            )));
48
-        }
49
-        if (isset($options_array['subsection_args'])) {
50
-            $subsection_args = $options_array['subsection_args'];
51
-        } else {
52
-            $subsection_args = array();
53
-        }
54
-        // gather fields and relations to convert to inputs
55
-        // but if they're just going to exclude a field anyways, don't bother converting it to an input
56
-        $exclude = $this->_subsections;
57
-        if (isset($options_array['exclude'])) {
58
-            $exclude = array_merge($exclude, array_flip($options_array['exclude']));
59
-        }
60
-        $model_fields = array_diff_key($this->_model->field_settings(), $exclude);
61
-        $model_relations = array_diff_key($this->_model->relation_settings(), $exclude);
62
-        // convert fields and relations to inputs
63
-        $this->_subsections = array_merge(
64
-            $this->_convert_model_fields_to_inputs($model_fields),
65
-            $this->_convert_model_relations_to_inputs($model_relations, $subsection_args),
66
-            $this->_subsections
67
-        );
68
-        parent::__construct($options_array);
69
-        if (isset($options_array['model_object']) && $options_array['model_object'] instanceof EE_Base_Class) {
70
-            $this->populate_model_obj($options_array['model_object']);
71
-        }
72
-    }
73
-
74
-
75
-
76
-    /**
77
-     * For now, just makes inputs for only HABTM relations
78
-     *
79
-     * @param EE_Model_Relation_Base[] $relations
80
-     * @param array                    $subsection_args keys should be existing or soon-to-be-existing input names, and
81
-     *                                                  their values are {
82
-     * @type array {
83
-     * @type EE_Base_Class[]           $model_objects   if the subsection is an EE_Select_Multi_Model_Input
84
-     *                                                  }
85
-     *                                                  }
86
-     * @return array
87
-     */
88
-    protected function _convert_model_relations_to_inputs($relations, $subsection_args = array())
89
-    {
90
-        $inputs = array();
91
-        foreach ($relations as $relation_name => $relation_obj) {
92
-            $input_constructor_args = array(
93
-                array_merge(
94
-                    array(
95
-                        'required'        => $relation_obj instanceof EE_Belongs_To_Relation,
96
-                        'html_label_text' => $relation_obj instanceof EE_Belongs_To_Relation
97
-                            ? $relation_obj->get_other_model()->item_name(1)
98
-                            : $relation_obj->get_other_model()
99
-                                           ->item_name(2),
100
-                    ),
101
-                    $subsection_args
102
-                ),
103
-            );
104
-            $input = null;
105
-            switch (get_class($relation_obj)) {
106
-                case 'EE_HABTM_Relation':
107
-                    if (isset($subsection_args[ $relation_name ])
108
-                        && isset($subsection_args[ $relation_name ]['model_objects'])
109
-                    ) {
110
-                        $model_objects = $subsection_args[ $relation_name ]['model_objects'];
111
-                    } else {
112
-                        $model_objects = $relation_obj->get_other_model()->get_all();
113
-                    }
114
-                    $input = new EE_Select_Multi_Model_Input($model_objects, $input_constructor_args);
115
-                    break;
116
-                default:
117
-            }
118
-            if ($input) {
119
-                $inputs[ $relation_name ] = $input;
120
-            }
121
-        }
122
-        return $inputs;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * Changes model fields into form section inputs
129
-     *
130
-     * @param EE_Model_Field_Base[] $model_fields keys are the model's name
131
-     * @throws EE_Error
132
-     * @return EE_Form_Input_Base[]
133
-     */
134
-    protected function _convert_model_fields_to_inputs($model_fields = array())
135
-    {
136
-        $inputs = array();
137
-        foreach ($model_fields as $field_name => $model_field) {
138
-            if ($model_field instanceof EE_Model_Field_Base) {
139
-                $input_constructor_args = array(
140
-                    array(
141
-                        'required'        => ! $model_field->is_nullable()
142
-                                             && $model_field->get_default_value()
143
-                                                === null,
144
-                        'html_label_text' => $model_field->get_nicename(),
145
-                        'default'         => $model_field->get_default_value(),
146
-                    ),
147
-                );
148
-                switch (get_class($model_field)) {
149
-                    case 'EE_All_Caps_Text_Field':
150
-                    case 'EE_Any_Foreign_Model_Name_Field':
151
-                        $input_class = 'EE_Text_Input';
152
-                        break;
153
-                    case 'EE_Boolean_Field':
154
-                        $input_class = 'EE_Yes_No_Input';
155
-                        break;
156
-                    case 'EE_Datetime_Field':
157
-                        throw new EE_Error(sprintf(__(
158
-                            "Model field '%s' does not yet have a known conversion to form input",
159
-                            "event_espresso"
160
-                        ), get_class($model_field)));
161
-                        break;
162
-                    case 'EE_Email_Field':
163
-                        $input_class = 'EE_Email_Input';
164
-                        break;
165
-                    case 'EE_Enum_Integer_Field':
166
-                        throw new EE_Error(sprintf(__(
167
-                            "Model field '%s' does not yet have a known conversion to form input",
168
-                            "event_espresso"
169
-                        ), get_class($model_field)));
170
-                        break;
171
-                    case 'EE_Enum_Text_Field':
172
-                        throw new EE_Error(sprintf(__(
173
-                            "Model field '%s' does not yet have a known conversion to form input",
174
-                            "event_espresso"
175
-                        ), get_class($model_field)));
176
-                        break;
177
-                    case 'EE_Float_Field':
178
-                        $input_class = 'EE_Float_Input';
179
-                        break;
180
-                    case 'EE_Foreign_Key_Int_Field':
181
-                    case 'EE_Foreign_Key_String_Field':
182
-                    case 'EE_WP_User_Field':
183
-                        $models_pointed_to = $model_field instanceof EE_Field_With_Model_Name
184
-                            ? $model_field->get_model_class_names_pointed_to() : array();
185
-                        if (true || is_array($models_pointed_to) && count($models_pointed_to) > 1) {
186
-                            $input_class = 'EE_Text_Input';
187
-                        } else {
188
-                            // so its just one model
189
-                            $model_name = is_array($models_pointed_to) ? reset($models_pointed_to) : $models_pointed_to;
190
-                            $model = EE_Registry::instance()->load_model($model_name);
191
-                            $model_names = $model->get_all_names(array('limit' => 10));
192
-                            if ($model_field->is_nullable()) {
193
-                                array_unshift($model_names, __("Please Select", 'event_espresso'));
194
-                            }
195
-                            $input_constructor_args[1] = $input_constructor_args[0];
196
-                            $input_constructor_args[0] = $model_names;
197
-                            $input_class = 'EE_Select_Input';
198
-                        }
199
-                        break;
200
-                    case 'EE_Full_HTML_Field':
201
-                        $input_class = 'EE_Text_Area_Input';
202
-                        $input_constructor_args[0]['validation_strategies'] = array(new EE_Full_HTML_Validation_Strategy());
203
-                        break;
204
-                    case 'EE_Infinite_Integer':
205
-                        throw new EE_Error(sprintf(__(
206
-                            "Model field '%s' does not yet have a known conversion to form input",
207
-                            "event_espresso"
208
-                        ), get_class($model_field)));
209
-                        break;
210
-                    case 'EE_Integer_Field':
211
-                        $input_class = 'EE_Text_Input';
212
-                        break;
213
-                    case 'EE_Maybe_Serialized_Text_Field':
214
-                        $input_class = 'EE_Text_Area_Input';
215
-                        break;
216
-                    case 'EE_Money_Field':
217
-                        throw new EE_Error(sprintf(__(
218
-                            "Model field '%s' does not yet have a known conversion to form input",
219
-                            "event_espresso"
220
-                        ), get_class($model_field)));
221
-                        break;
222
-                    case 'EE_Post_Content_Field':
223
-                        $input_class = 'EE_Text_Area_Input';
224
-                        $input_constructor_args[0]['validation_strategies'] = array(new EE_Full_HTML_Validation_Strategy());
225
-                        break;
226
-                    case 'EE_Plain_Text_Field':
227
-                        $input_class = 'EE_Text_Input';
228
-                        break;
229
-                    case 'EE_Primary_Key_Int_Field':
230
-                        $input_class = 'EE_Hidden_Input';
231
-                        $input_constructor_args[0]['normalization_strategy'] = new EE_Int_Normalization();
232
-                        break;
233
-                    case 'EE_Primary_Key_String_Field':
234
-                        $input_class = 'EE_Hidden_Input';
235
-                        break;
236
-                    case 'EE_Serialized_Text_Field':
237
-                        $input_class = 'EE_Text_Area_Input';
238
-                        break;
239
-                    case 'EE_Simple_HTML_Field':
240
-                        $input_class = 'EE_Text_Area_Input';
241
-                        $input_constructor_args[0]['validation_strategies'] = array(new EE_Simple_HTML_Validation_Strategy());
242
-                        break;
243
-                    case 'EE_Slug_Field':
244
-                        $input_class = 'EE_Text_Input';
245
-                        break;
246
-                    case 'EE_Trashed_Flag_Field':
247
-                        $input_class = 'EE_Yes_No_Input';
248
-                        break;
249
-                    case 'EE_WP_Post_Status_Field':
250
-                        throw new EE_Error(sprintf(__(
251
-                            "Model field '%s' does not yet have a known conversion to form input",
252
-                            "event_espresso"
253
-                        ), get_class($model_field)));
254
-                        break;
255
-                    case 'EE_WP_Post_Type_Field':
256
-                        throw new EE_Error(sprintf(__(
257
-                            "Model field '%s' does not yet have a known conversion to form input",
258
-                            "event_espresso"
259
-                        ), get_class($model_field)));
260
-                        break;
261
-                    default:
262
-                        throw new EE_Error(sprintf(__(
263
-                            "Model field of type '%s' does not convert to any known Form Input. Please add a case to EE_Model_Form_section's _convert_model_fields_to_inputs switch statement",
264
-                            "event_espresso"
265
-                        ), get_class($model_field)));
266
-                }
267
-                $reflection = new ReflectionClass($input_class);
268
-                $input = $reflection->newInstanceArgs($input_constructor_args);
269
-                $inputs[ $field_name ] = $input;
270
-            }
271
-        }
272
-        return $inputs;
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * Mostly the same as populate_defaults , except takes a model object as input, not an array,
279
-     * and also sets the form's _model_object
280
-     *
281
-     * @param EE_Base_Class $model_obj
282
-     * @return void
283
-     */
284
-    public function populate_model_obj($model_obj)
285
-    {
286
-        $model_obj = $this->_model->ensure_is_obj($model_obj);
287
-        $this->_model_object = $model_obj;
288
-        $defaults = $model_obj->model_field_array();
289
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
290
-            $subsection = $this->get_subsection($relation_name, false);
291
-            if ($subsection instanceof EE_Form_Input_Base) {
292
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
293
-                    // then we only expect there to be one
294
-                    $related_item = $this->_model_object->get_first_related($relation_name);
295
-                    $defaults[ $relation_name ] = $related_item->ID();
296
-                } else {
297
-                    $related_items = $this->_model_object->get_many_related($relation_name);
298
-                    $ids = array();
299
-                    foreach ($related_items as $related_item) {
300
-                        $ids[] = $related_item->ID();
301
-                    }
302
-                    $defaults[ $relation_name ] = $ids;
303
-                }
304
-            }
305
-        }
306
-        $defaults = apply_filters(
307
-            'FHEE__EE_Model_Form_Section__populate_model_obj',
308
-            $defaults,
309
-            $this
310
-        );
311
-        $this->populate_defaults($defaults);
312
-    }
313
-
314
-
315
-
316
-    /**
317
-     * Gets all the input values that correspond to model fields. Keys are the input/field names,
318
-     * values are their normalized values
319
-     *
320
-     * @return array
321
-     */
322
-    public function inputs_values_corresponding_to_model_fields()
323
-    {
324
-        return array_intersect_key($this->input_values(), $this->_model->field_settings());
325
-    }
326
-
327
-
328
-
329
-    /**
330
-     * After we've normalized the data as normal, set the corresponding model object
331
-     * on the form.
332
-     *
333
-     * @param array $req_data should usually be $_REQUEST (the default).
334
-     * @return void
335
-     */
336
-    public function _normalize($req_data)
337
-    {
338
-        parent::_normalize($req_data);
339
-        // create or set the model object, if it isn't already
340
-        if (! $this->_model_object) {
341
-            // check to see if the form indicates a PK, in which case we want to only retrieve it and update it
342
-            $pk_name = $this->_model->primary_key_name();
343
-            $model_obj = $this->_model->get_one_by_ID($this->get_input_value($pk_name));
344
-            if ($model_obj) {
345
-                $this->_model_object = $model_obj;
346
-            } else {
347
-                $this->_model_object = EE_Registry::instance()->load_class($this->_model->get_this_model_name());
348
-            }
349
-        }
350
-    }
351
-
352
-
353
-
354
-    /**
355
-     * After this form has been initialized and is verified to be valid,
356
-     * either creates a model object from its data and saves it, or updates
357
-     * the model object its data represents
358
-     *
359
-     * @throws EE_Error
360
-     * @return int, 1 on a successful update, the ID of
361
-     *                    the new entry on insert; 0 on failure
362
-     */
363
-    public function save()
364
-    {
365
-        if (! $this->_model_object) {
366
-            throw new EE_Error(sprintf(__(
367
-                "Cannot save the model form's model object (model is '%s') because there is no model object set. You must either set it, or call receive_form_submission where it is set automatically",
368
-                "event_espresso"
369
-            ), get_class($this->_model)));
370
-        }
371
-        // ok so the model object is set. Just set it with the submitted form data
372
-        foreach ($this->inputs_values_corresponding_to_model_fields() as $field_name => $field_value) {
373
-            // only set the non-primary key
374
-            if ($field_name != $this->_model->primary_key_name()) {
375
-                $this->_model_object->set($field_name, $field_value);
376
-            }
377
-        }
378
-        $success = $this->_model_object->save();
379
-        foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
380
-            if (isset($this->_subsections[ $relation_name ])) {
381
-                $success = $this->_save_related_info($relation_name);
382
-            }
383
-        }
384
-        do_action('AHEE__EE_Model_Form_Section__save__done', $this, $success);
385
-        return $success;
386
-    }
387
-
388
-
389
-
390
-    /**
391
-     * Automatically finds the related model info from the form, if present, and
392
-     * save the relations indicated
393
-     *
394
-     * @type string $relation_name
395
-     * @return bool
396
-     * @throws EE_Error
397
-     */
398
-    protected function _save_related_info($relation_name)
399
-    {
400
-        $relation_obj = $this->_model->related_settings_for($relation_name);
401
-        if ($relation_obj instanceof EE_Belongs_To_Relation) {
402
-            // there is just a foreign key on this model pointing to that one
403
-            $this->_model_object->_add_relation_to($this->get_input_value($relation_name), $relation_name);
404
-        } elseif ($relation_obj instanceof EE_Has_Many_Relation) {
405
-            // then we want to consider all of its currently-related things.
406
-            // if they're in this list, keep them
407
-            // if they're not in this list, remove them
408
-            // and lastly add all the new items
409
-            throw new EE_Error(sprintf(__(
410
-                'Automatic saving of related info across a "has many" relation is not yet supported',
411
-                "event_espresso"
412
-            )));
413
-        } elseif ($relation_obj instanceof EE_HABTM_Relation) {
414
-            // delete everything NOT in this list
415
-            $normalized_input_value = $this->get_input_value($relation_name);
416
-            if ($normalized_input_value && is_array($normalized_input_value)) {
417
-                $where_query_params = array(
418
-                    $relation_obj->get_other_model()->primary_key_name() => array('NOT_IN', $normalized_input_value),
419
-                );
420
-            } else {
421
-                $where_query_params = array();
422
-            }
423
-            $this->_model_object->_remove_relations($relation_name, $where_query_params);
424
-            foreach ($normalized_input_value as $id) {
425
-                $this->_model_object->_add_relation_to($id, $relation_name);
426
-            }
427
-        }
428
-        return true;
429
-    }
430
-
431
-
432
-
433
-    /**
434
-     * Gets the model of this model form
435
-     *
436
-     * @return EEM_Base
437
-     */
438
-    public function get_model()
439
-    {
440
-        return $this->_model;
441
-    }
442
-
443
-
444
-
445
-    /**
446
-     * Gets the model object for this model form, which was either set
447
-     * upon construction (using the $options_array arg 'model_object'), by using
448
-     * set_model_object($model_obj), or implicitly
449
-     * when receive_form_submission($req_data) was called.
450
-     *
451
-     * @return EE_Base_Class
452
-     */
453
-    public function get_model_object()
454
-    {
455
-        return $this->_model_object;
456
-    }
457
-
458
-
459
-
460
-    /**
461
-     * gets teh default name of this form section if none is specified
462
-     *
463
-     * @return string
464
-     */
465
-    protected function _set_default_name_if_empty()
466
-    {
467
-        if (! $this->_name) {
468
-            $default_name = str_replace("EEM_", "", get_class($this->_model)) . "_Model_Form";
469
-            $this->_name = $default_name;
470
-        }
471
-    }
17
+	/**
18
+	 * @var EEM_Base
19
+	 */
20
+	protected $_model = null;
21
+
22
+	/**
23
+	 * @var EE_Base_Class
24
+	 */
25
+	protected $_model_object = null;
26
+
27
+
28
+
29
+	/**
30
+	 * @param array        $options_array   keys: {
31
+	 * @type EEM_Base      $model
32
+	 * @type EE_Base_Class $model_object
33
+	 * @type array         $subsection_args array keys should be subsection names (that either do or will exist), and
34
+	 *       values are the arrays as you would pass them to that subsection
35
+	 *                                      }
36
+	 * @throws EE_Error
37
+	 */
38
+	public function __construct($options_array = array())
39
+	{
40
+		if (isset($options_array['model']) && $options_array['model'] instanceof EEM_Base) {
41
+			$this->_model = $options_array['model'];
42
+		}
43
+		if (! $this->_model || ! $this->_model instanceof EEM_Base) {
44
+			throw new EE_Error(sprintf(__(
45
+				"Model Form Sections must first specify the _model property to be a subclass of EEM_Base",
46
+				"event_espresso"
47
+			)));
48
+		}
49
+		if (isset($options_array['subsection_args'])) {
50
+			$subsection_args = $options_array['subsection_args'];
51
+		} else {
52
+			$subsection_args = array();
53
+		}
54
+		// gather fields and relations to convert to inputs
55
+		// but if they're just going to exclude a field anyways, don't bother converting it to an input
56
+		$exclude = $this->_subsections;
57
+		if (isset($options_array['exclude'])) {
58
+			$exclude = array_merge($exclude, array_flip($options_array['exclude']));
59
+		}
60
+		$model_fields = array_diff_key($this->_model->field_settings(), $exclude);
61
+		$model_relations = array_diff_key($this->_model->relation_settings(), $exclude);
62
+		// convert fields and relations to inputs
63
+		$this->_subsections = array_merge(
64
+			$this->_convert_model_fields_to_inputs($model_fields),
65
+			$this->_convert_model_relations_to_inputs($model_relations, $subsection_args),
66
+			$this->_subsections
67
+		);
68
+		parent::__construct($options_array);
69
+		if (isset($options_array['model_object']) && $options_array['model_object'] instanceof EE_Base_Class) {
70
+			$this->populate_model_obj($options_array['model_object']);
71
+		}
72
+	}
73
+
74
+
75
+
76
+	/**
77
+	 * For now, just makes inputs for only HABTM relations
78
+	 *
79
+	 * @param EE_Model_Relation_Base[] $relations
80
+	 * @param array                    $subsection_args keys should be existing or soon-to-be-existing input names, and
81
+	 *                                                  their values are {
82
+	 * @type array {
83
+	 * @type EE_Base_Class[]           $model_objects   if the subsection is an EE_Select_Multi_Model_Input
84
+	 *                                                  }
85
+	 *                                                  }
86
+	 * @return array
87
+	 */
88
+	protected function _convert_model_relations_to_inputs($relations, $subsection_args = array())
89
+	{
90
+		$inputs = array();
91
+		foreach ($relations as $relation_name => $relation_obj) {
92
+			$input_constructor_args = array(
93
+				array_merge(
94
+					array(
95
+						'required'        => $relation_obj instanceof EE_Belongs_To_Relation,
96
+						'html_label_text' => $relation_obj instanceof EE_Belongs_To_Relation
97
+							? $relation_obj->get_other_model()->item_name(1)
98
+							: $relation_obj->get_other_model()
99
+										   ->item_name(2),
100
+					),
101
+					$subsection_args
102
+				),
103
+			);
104
+			$input = null;
105
+			switch (get_class($relation_obj)) {
106
+				case 'EE_HABTM_Relation':
107
+					if (isset($subsection_args[ $relation_name ])
108
+						&& isset($subsection_args[ $relation_name ]['model_objects'])
109
+					) {
110
+						$model_objects = $subsection_args[ $relation_name ]['model_objects'];
111
+					} else {
112
+						$model_objects = $relation_obj->get_other_model()->get_all();
113
+					}
114
+					$input = new EE_Select_Multi_Model_Input($model_objects, $input_constructor_args);
115
+					break;
116
+				default:
117
+			}
118
+			if ($input) {
119
+				$inputs[ $relation_name ] = $input;
120
+			}
121
+		}
122
+		return $inputs;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * Changes model fields into form section inputs
129
+	 *
130
+	 * @param EE_Model_Field_Base[] $model_fields keys are the model's name
131
+	 * @throws EE_Error
132
+	 * @return EE_Form_Input_Base[]
133
+	 */
134
+	protected function _convert_model_fields_to_inputs($model_fields = array())
135
+	{
136
+		$inputs = array();
137
+		foreach ($model_fields as $field_name => $model_field) {
138
+			if ($model_field instanceof EE_Model_Field_Base) {
139
+				$input_constructor_args = array(
140
+					array(
141
+						'required'        => ! $model_field->is_nullable()
142
+											 && $model_field->get_default_value()
143
+												=== null,
144
+						'html_label_text' => $model_field->get_nicename(),
145
+						'default'         => $model_field->get_default_value(),
146
+					),
147
+				);
148
+				switch (get_class($model_field)) {
149
+					case 'EE_All_Caps_Text_Field':
150
+					case 'EE_Any_Foreign_Model_Name_Field':
151
+						$input_class = 'EE_Text_Input';
152
+						break;
153
+					case 'EE_Boolean_Field':
154
+						$input_class = 'EE_Yes_No_Input';
155
+						break;
156
+					case 'EE_Datetime_Field':
157
+						throw new EE_Error(sprintf(__(
158
+							"Model field '%s' does not yet have a known conversion to form input",
159
+							"event_espresso"
160
+						), get_class($model_field)));
161
+						break;
162
+					case 'EE_Email_Field':
163
+						$input_class = 'EE_Email_Input';
164
+						break;
165
+					case 'EE_Enum_Integer_Field':
166
+						throw new EE_Error(sprintf(__(
167
+							"Model field '%s' does not yet have a known conversion to form input",
168
+							"event_espresso"
169
+						), get_class($model_field)));
170
+						break;
171
+					case 'EE_Enum_Text_Field':
172
+						throw new EE_Error(sprintf(__(
173
+							"Model field '%s' does not yet have a known conversion to form input",
174
+							"event_espresso"
175
+						), get_class($model_field)));
176
+						break;
177
+					case 'EE_Float_Field':
178
+						$input_class = 'EE_Float_Input';
179
+						break;
180
+					case 'EE_Foreign_Key_Int_Field':
181
+					case 'EE_Foreign_Key_String_Field':
182
+					case 'EE_WP_User_Field':
183
+						$models_pointed_to = $model_field instanceof EE_Field_With_Model_Name
184
+							? $model_field->get_model_class_names_pointed_to() : array();
185
+						if (true || is_array($models_pointed_to) && count($models_pointed_to) > 1) {
186
+							$input_class = 'EE_Text_Input';
187
+						} else {
188
+							// so its just one model
189
+							$model_name = is_array($models_pointed_to) ? reset($models_pointed_to) : $models_pointed_to;
190
+							$model = EE_Registry::instance()->load_model($model_name);
191
+							$model_names = $model->get_all_names(array('limit' => 10));
192
+							if ($model_field->is_nullable()) {
193
+								array_unshift($model_names, __("Please Select", 'event_espresso'));
194
+							}
195
+							$input_constructor_args[1] = $input_constructor_args[0];
196
+							$input_constructor_args[0] = $model_names;
197
+							$input_class = 'EE_Select_Input';
198
+						}
199
+						break;
200
+					case 'EE_Full_HTML_Field':
201
+						$input_class = 'EE_Text_Area_Input';
202
+						$input_constructor_args[0]['validation_strategies'] = array(new EE_Full_HTML_Validation_Strategy());
203
+						break;
204
+					case 'EE_Infinite_Integer':
205
+						throw new EE_Error(sprintf(__(
206
+							"Model field '%s' does not yet have a known conversion to form input",
207
+							"event_espresso"
208
+						), get_class($model_field)));
209
+						break;
210
+					case 'EE_Integer_Field':
211
+						$input_class = 'EE_Text_Input';
212
+						break;
213
+					case 'EE_Maybe_Serialized_Text_Field':
214
+						$input_class = 'EE_Text_Area_Input';
215
+						break;
216
+					case 'EE_Money_Field':
217
+						throw new EE_Error(sprintf(__(
218
+							"Model field '%s' does not yet have a known conversion to form input",
219
+							"event_espresso"
220
+						), get_class($model_field)));
221
+						break;
222
+					case 'EE_Post_Content_Field':
223
+						$input_class = 'EE_Text_Area_Input';
224
+						$input_constructor_args[0]['validation_strategies'] = array(new EE_Full_HTML_Validation_Strategy());
225
+						break;
226
+					case 'EE_Plain_Text_Field':
227
+						$input_class = 'EE_Text_Input';
228
+						break;
229
+					case 'EE_Primary_Key_Int_Field':
230
+						$input_class = 'EE_Hidden_Input';
231
+						$input_constructor_args[0]['normalization_strategy'] = new EE_Int_Normalization();
232
+						break;
233
+					case 'EE_Primary_Key_String_Field':
234
+						$input_class = 'EE_Hidden_Input';
235
+						break;
236
+					case 'EE_Serialized_Text_Field':
237
+						$input_class = 'EE_Text_Area_Input';
238
+						break;
239
+					case 'EE_Simple_HTML_Field':
240
+						$input_class = 'EE_Text_Area_Input';
241
+						$input_constructor_args[0]['validation_strategies'] = array(new EE_Simple_HTML_Validation_Strategy());
242
+						break;
243
+					case 'EE_Slug_Field':
244
+						$input_class = 'EE_Text_Input';
245
+						break;
246
+					case 'EE_Trashed_Flag_Field':
247
+						$input_class = 'EE_Yes_No_Input';
248
+						break;
249
+					case 'EE_WP_Post_Status_Field':
250
+						throw new EE_Error(sprintf(__(
251
+							"Model field '%s' does not yet have a known conversion to form input",
252
+							"event_espresso"
253
+						), get_class($model_field)));
254
+						break;
255
+					case 'EE_WP_Post_Type_Field':
256
+						throw new EE_Error(sprintf(__(
257
+							"Model field '%s' does not yet have a known conversion to form input",
258
+							"event_espresso"
259
+						), get_class($model_field)));
260
+						break;
261
+					default:
262
+						throw new EE_Error(sprintf(__(
263
+							"Model field of type '%s' does not convert to any known Form Input. Please add a case to EE_Model_Form_section's _convert_model_fields_to_inputs switch statement",
264
+							"event_espresso"
265
+						), get_class($model_field)));
266
+				}
267
+				$reflection = new ReflectionClass($input_class);
268
+				$input = $reflection->newInstanceArgs($input_constructor_args);
269
+				$inputs[ $field_name ] = $input;
270
+			}
271
+		}
272
+		return $inputs;
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * Mostly the same as populate_defaults , except takes a model object as input, not an array,
279
+	 * and also sets the form's _model_object
280
+	 *
281
+	 * @param EE_Base_Class $model_obj
282
+	 * @return void
283
+	 */
284
+	public function populate_model_obj($model_obj)
285
+	{
286
+		$model_obj = $this->_model->ensure_is_obj($model_obj);
287
+		$this->_model_object = $model_obj;
288
+		$defaults = $model_obj->model_field_array();
289
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
290
+			$subsection = $this->get_subsection($relation_name, false);
291
+			if ($subsection instanceof EE_Form_Input_Base) {
292
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
293
+					// then we only expect there to be one
294
+					$related_item = $this->_model_object->get_first_related($relation_name);
295
+					$defaults[ $relation_name ] = $related_item->ID();
296
+				} else {
297
+					$related_items = $this->_model_object->get_many_related($relation_name);
298
+					$ids = array();
299
+					foreach ($related_items as $related_item) {
300
+						$ids[] = $related_item->ID();
301
+					}
302
+					$defaults[ $relation_name ] = $ids;
303
+				}
304
+			}
305
+		}
306
+		$defaults = apply_filters(
307
+			'FHEE__EE_Model_Form_Section__populate_model_obj',
308
+			$defaults,
309
+			$this
310
+		);
311
+		$this->populate_defaults($defaults);
312
+	}
313
+
314
+
315
+
316
+	/**
317
+	 * Gets all the input values that correspond to model fields. Keys are the input/field names,
318
+	 * values are their normalized values
319
+	 *
320
+	 * @return array
321
+	 */
322
+	public function inputs_values_corresponding_to_model_fields()
323
+	{
324
+		return array_intersect_key($this->input_values(), $this->_model->field_settings());
325
+	}
326
+
327
+
328
+
329
+	/**
330
+	 * After we've normalized the data as normal, set the corresponding model object
331
+	 * on the form.
332
+	 *
333
+	 * @param array $req_data should usually be $_REQUEST (the default).
334
+	 * @return void
335
+	 */
336
+	public function _normalize($req_data)
337
+	{
338
+		parent::_normalize($req_data);
339
+		// create or set the model object, if it isn't already
340
+		if (! $this->_model_object) {
341
+			// check to see if the form indicates a PK, in which case we want to only retrieve it and update it
342
+			$pk_name = $this->_model->primary_key_name();
343
+			$model_obj = $this->_model->get_one_by_ID($this->get_input_value($pk_name));
344
+			if ($model_obj) {
345
+				$this->_model_object = $model_obj;
346
+			} else {
347
+				$this->_model_object = EE_Registry::instance()->load_class($this->_model->get_this_model_name());
348
+			}
349
+		}
350
+	}
351
+
352
+
353
+
354
+	/**
355
+	 * After this form has been initialized and is verified to be valid,
356
+	 * either creates a model object from its data and saves it, or updates
357
+	 * the model object its data represents
358
+	 *
359
+	 * @throws EE_Error
360
+	 * @return int, 1 on a successful update, the ID of
361
+	 *                    the new entry on insert; 0 on failure
362
+	 */
363
+	public function save()
364
+	{
365
+		if (! $this->_model_object) {
366
+			throw new EE_Error(sprintf(__(
367
+				"Cannot save the model form's model object (model is '%s') because there is no model object set. You must either set it, or call receive_form_submission where it is set automatically",
368
+				"event_espresso"
369
+			), get_class($this->_model)));
370
+		}
371
+		// ok so the model object is set. Just set it with the submitted form data
372
+		foreach ($this->inputs_values_corresponding_to_model_fields() as $field_name => $field_value) {
373
+			// only set the non-primary key
374
+			if ($field_name != $this->_model->primary_key_name()) {
375
+				$this->_model_object->set($field_name, $field_value);
376
+			}
377
+		}
378
+		$success = $this->_model_object->save();
379
+		foreach ($this->_model->relation_settings() as $relation_name => $relation_obj) {
380
+			if (isset($this->_subsections[ $relation_name ])) {
381
+				$success = $this->_save_related_info($relation_name);
382
+			}
383
+		}
384
+		do_action('AHEE__EE_Model_Form_Section__save__done', $this, $success);
385
+		return $success;
386
+	}
387
+
388
+
389
+
390
+	/**
391
+	 * Automatically finds the related model info from the form, if present, and
392
+	 * save the relations indicated
393
+	 *
394
+	 * @type string $relation_name
395
+	 * @return bool
396
+	 * @throws EE_Error
397
+	 */
398
+	protected function _save_related_info($relation_name)
399
+	{
400
+		$relation_obj = $this->_model->related_settings_for($relation_name);
401
+		if ($relation_obj instanceof EE_Belongs_To_Relation) {
402
+			// there is just a foreign key on this model pointing to that one
403
+			$this->_model_object->_add_relation_to($this->get_input_value($relation_name), $relation_name);
404
+		} elseif ($relation_obj instanceof EE_Has_Many_Relation) {
405
+			// then we want to consider all of its currently-related things.
406
+			// if they're in this list, keep them
407
+			// if they're not in this list, remove them
408
+			// and lastly add all the new items
409
+			throw new EE_Error(sprintf(__(
410
+				'Automatic saving of related info across a "has many" relation is not yet supported',
411
+				"event_espresso"
412
+			)));
413
+		} elseif ($relation_obj instanceof EE_HABTM_Relation) {
414
+			// delete everything NOT in this list
415
+			$normalized_input_value = $this->get_input_value($relation_name);
416
+			if ($normalized_input_value && is_array($normalized_input_value)) {
417
+				$where_query_params = array(
418
+					$relation_obj->get_other_model()->primary_key_name() => array('NOT_IN', $normalized_input_value),
419
+				);
420
+			} else {
421
+				$where_query_params = array();
422
+			}
423
+			$this->_model_object->_remove_relations($relation_name, $where_query_params);
424
+			foreach ($normalized_input_value as $id) {
425
+				$this->_model_object->_add_relation_to($id, $relation_name);
426
+			}
427
+		}
428
+		return true;
429
+	}
430
+
431
+
432
+
433
+	/**
434
+	 * Gets the model of this model form
435
+	 *
436
+	 * @return EEM_Base
437
+	 */
438
+	public function get_model()
439
+	{
440
+		return $this->_model;
441
+	}
442
+
443
+
444
+
445
+	/**
446
+	 * Gets the model object for this model form, which was either set
447
+	 * upon construction (using the $options_array arg 'model_object'), by using
448
+	 * set_model_object($model_obj), or implicitly
449
+	 * when receive_form_submission($req_data) was called.
450
+	 *
451
+	 * @return EE_Base_Class
452
+	 */
453
+	public function get_model_object()
454
+	{
455
+		return $this->_model_object;
456
+	}
457
+
458
+
459
+
460
+	/**
461
+	 * gets teh default name of this form section if none is specified
462
+	 *
463
+	 * @return string
464
+	 */
465
+	protected function _set_default_name_if_empty()
466
+	{
467
+		if (! $this->_name) {
468
+			$default_name = str_replace("EEM_", "", get_class($this->_model)) . "_Model_Form";
469
+			$this->_name = $default_name;
470
+		}
471
+	}
472 472
 }
Please login to merge, or discard this patch.
pricing/templates/event_tickets_datetime_attached_tickets_row.template.php 1 patch
Indentation   +26 added lines, -26 removed lines patch added patch discarded remove patch
@@ -8,10 +8,10 @@  discard block
 block discarded – undo
8 8
                           placeholder="Datetime Description (optional)"><?php echo $DTT_description; ?></textarea>
9 9
             </div>
10 10
             <?php do_action(
11
-                'AHEE__event_tickets_datetime_attached_tickets_row_template__advanced_details_after_dtt_description',
12
-                $dtt_row,
13
-                $DTT_ID
14
-            ); ?>
11
+				'AHEE__event_tickets_datetime_attached_tickets_row_template__advanced_details_after_dtt_description',
12
+				$dtt_row,
13
+				$DTT_ID
14
+			); ?>
15 15
             <h4 class="datetime-tickets-heading"><?php esc_html_e('Assigned Tickets', 'event_espresso'); ?></h4>
16 16
 
17 17
             <ul class="datetime-tickets-list">
@@ -21,28 +21,28 @@  discard block
 block discarded – undo
21 21
 
22 22
             <div class="add-datetime-ticket-container">
23 23
                 <h4 class="datetime-tickets-heading"><?php
24
-                    esc_html_e(
25
-                        'Add New Ticket',
26
-                        'event_espresso'
27
-                    ); ?></h4><?php echo $add_new_datetime_ticket_help_link; ?><br>
24
+					esc_html_e(
25
+						'Add New Ticket',
26
+						'event_espresso'
27
+					); ?></h4><?php echo $add_new_datetime_ticket_help_link; ?><br>
28 28
                 <table class="add-new-ticket-table">
29 29
                     <thead>
30 30
                     <tr valign="top">
31 31
                         <td><span class="ANT_TKT_name_label"><?php
32
-                                esc_html_e(
33
-                                    'Ticket Name',
34
-                                    'event_espresso'
35
-                                ); ?></span></td>
32
+								esc_html_e(
33
+									'Ticket Name',
34
+									'event_espresso'
35
+								); ?></span></td>
36 36
                         <td><span class="ANT_TKT_goes_on_sale_label"><?php
37
-                                esc_html_e(
38
-                                    'Sale Starts',
39
-                                    'event_espresso'
40
-                                ); ?></span></td>
37
+								esc_html_e(
38
+									'Sale Starts',
39
+									'event_espresso'
40
+								); ?></span></td>
41 41
                         <td><span class="ANT_TKT_sell_until_label"><?php
42
-                                esc_html_e(
43
-                                    'Sell Until',
44
-                                    'event_espresso'
45
-                                ); ?></span></td>
42
+								esc_html_e(
43
+									'Sell Until',
44
+									'event_espresso'
45
+								); ?></span></td>
46 46
                         <td><span class="ANT_TKT_price_label"><?php esc_html_e('Price', 'event_espresso'); ?></span>
47 47
                         </td>
48 48
                         <td><span class="ANT_TKT_qty_label"><?php esc_html_e('Qty', 'event_espresso'); ?></span></td>
@@ -92,12 +92,12 @@  discard block
 block discarded – undo
92 92
                 <div class="ee-editor-footer-container">
93 93
                     <div class="ee-editor-id-container">
94 94
                         <span class="ee-item-id"><?php
95
-                            echo $DTT_ID
96
-                                ? sprintf(
97
-                                    esc_html__('Datetime ID: %d', 'event_espresso'),
98
-                                    $DTT_ID
99
-                                )
100
-                                : ''; ?></span>
95
+							echo $DTT_ID
96
+								? sprintf(
97
+									esc_html__('Datetime ID: %d', 'event_espresso'),
98
+									$DTT_ID
99
+								)
100
+								: ''; ?></span>
101 101
                     </div>
102 102
                     <div class="save-cancel-button-container">
103 103
                         <button data-context="short-ticket" data-datetime-row="<?php echo $dtt_row; ?>"
Please login to merge, or discard this patch.
caffeinated/admin/new/pricing/espresso_events_Pricing_Hooks.class.php 1 patch
Indentation   +2141 added lines, -2141 removed lines patch added patch discarded remove patch
@@ -15,2201 +15,2201 @@
 block discarded – undo
15 15
 class espresso_events_Pricing_Hooks extends EE_Admin_Hooks
16 16
 {
17 17
 
18
-    /**
19
-     * This property is just used to hold the status of whether an event is currently being
20
-     * created (true) or edited (false)
21
-     *
22
-     * @access protected
23
-     * @var bool
24
-     */
25
-    protected $_is_creating_event;
18
+	/**
19
+	 * This property is just used to hold the status of whether an event is currently being
20
+	 * created (true) or edited (false)
21
+	 *
22
+	 * @access protected
23
+	 * @var bool
24
+	 */
25
+	protected $_is_creating_event;
26 26
 
27
-    /**
28
-     * Used to contain the format strings for date and time that will be used for php date and
29
-     * time.
30
-     * Is set in the _set_hooks_properties() method.
31
-     *
32
-     * @var array
33
-     */
34
-    protected $_date_format_strings;
27
+	/**
28
+	 * Used to contain the format strings for date and time that will be used for php date and
29
+	 * time.
30
+	 * Is set in the _set_hooks_properties() method.
31
+	 *
32
+	 * @var array
33
+	 */
34
+	protected $_date_format_strings;
35 35
 
36
-    /**
37
-     * @var string $_date_time_format
38
-     */
39
-    protected $_date_time_format;
36
+	/**
37
+	 * @var string $_date_time_format
38
+	 */
39
+	protected $_date_time_format;
40 40
 
41 41
 
42
-    /**
43
-     * @throws InvalidArgumentException
44
-     * @throws InvalidInterfaceException
45
-     * @throws InvalidDataTypeException
46
-     */
47
-    protected function _set_hooks_properties()
48
-    {
49
-        $this->_name = 'pricing';
50
-        // capability check
51
-        if (! EE_Registry::instance()->CAP->current_user_can(
52
-            'ee_read_default_prices',
53
-            'advanced_ticket_datetime_metabox'
54
-        )) {
55
-            return;
56
-        }
57
-        $this->_setup_metaboxes();
58
-        $this->_set_date_time_formats();
59
-        $this->_validate_format_strings();
60
-        $this->_set_scripts_styles();
61
-        // commented out temporarily until logic is implemented in callback
62
-        // add_action(
63
-        //     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
64
-        //     array($this, 'autosave_handling')
65
-        // );
66
-        add_filter(
67
-            'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
68
-            array($this, 'caf_updates')
69
-        );
70
-    }
42
+	/**
43
+	 * @throws InvalidArgumentException
44
+	 * @throws InvalidInterfaceException
45
+	 * @throws InvalidDataTypeException
46
+	 */
47
+	protected function _set_hooks_properties()
48
+	{
49
+		$this->_name = 'pricing';
50
+		// capability check
51
+		if (! EE_Registry::instance()->CAP->current_user_can(
52
+			'ee_read_default_prices',
53
+			'advanced_ticket_datetime_metabox'
54
+		)) {
55
+			return;
56
+		}
57
+		$this->_setup_metaboxes();
58
+		$this->_set_date_time_formats();
59
+		$this->_validate_format_strings();
60
+		$this->_set_scripts_styles();
61
+		// commented out temporarily until logic is implemented in callback
62
+		// add_action(
63
+		//     'AHEE__EE_Admin_Page_CPT__do_extra_autosave_stuff__after_Extend_Events_Admin_Page',
64
+		//     array($this, 'autosave_handling')
65
+		// );
66
+		add_filter(
67
+			'FHEE__Events_Admin_Page___insert_update_cpt_item__event_update_callbacks',
68
+			array($this, 'caf_updates')
69
+		);
70
+	}
71 71
 
72 72
 
73
-    /**
74
-     * @return void
75
-     */
76
-    protected function _setup_metaboxes()
77
-    {
78
-        // if we were going to add our own metaboxes we'd use the below.
79
-        $this->_metaboxes = array(
80
-            0 => array(
81
-                'page_route' => array('edit', 'create_new'),
82
-                'func'       => 'pricing_metabox',
83
-                'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
84
-                'priority'   => 'high',
85
-                'context'    => 'normal',
86
-            ),
87
-        );
88
-        $this->_remove_metaboxes = array(
89
-            0 => array(
90
-                'page_route' => array('edit', 'create_new'),
91
-                'id'         => 'espresso_event_editor_tickets',
92
-                'context'    => 'normal',
93
-            ),
94
-        );
95
-    }
73
+	/**
74
+	 * @return void
75
+	 */
76
+	protected function _setup_metaboxes()
77
+	{
78
+		// if we were going to add our own metaboxes we'd use the below.
79
+		$this->_metaboxes = array(
80
+			0 => array(
81
+				'page_route' => array('edit', 'create_new'),
82
+				'func'       => 'pricing_metabox',
83
+				'label'      => esc_html__('Event Tickets & Datetimes', 'event_espresso'),
84
+				'priority'   => 'high',
85
+				'context'    => 'normal',
86
+			),
87
+		);
88
+		$this->_remove_metaboxes = array(
89
+			0 => array(
90
+				'page_route' => array('edit', 'create_new'),
91
+				'id'         => 'espresso_event_editor_tickets',
92
+				'context'    => 'normal',
93
+			),
94
+		);
95
+	}
96 96
 
97 97
 
98
-    /**
99
-     * @return void
100
-     */
101
-    protected function _set_date_time_formats()
102
-    {
103
-        /**
104
-         * Format strings for date and time.  Defaults are existing behaviour from 4.1.
105
-         * Note, that if you return null as the value for 'date', and 'time' in the array, then
106
-         * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
107
-         *
108
-         * @since 4.6.7
109
-         * @var array  Expected an array returned with 'date' and 'time' keys.
110
-         */
111
-        $this->_date_format_strings = apply_filters(
112
-            'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
113
-            array(
114
-                'date' => 'Y-m-d',
115
-                'time' => 'h:i a',
116
-            )
117
-        );
118
-        // validate
119
-        $this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
120
-            ? $this->_date_format_strings['date']
121
-            : null;
122
-        $this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
123
-            ? $this->_date_format_strings['time']
124
-            : null;
125
-        $this->_date_time_format = $this->_date_format_strings['date']
126
-                                   . ' '
127
-                                   . $this->_date_format_strings['time'];
128
-    }
98
+	/**
99
+	 * @return void
100
+	 */
101
+	protected function _set_date_time_formats()
102
+	{
103
+		/**
104
+		 * Format strings for date and time.  Defaults are existing behaviour from 4.1.
105
+		 * Note, that if you return null as the value for 'date', and 'time' in the array, then
106
+		 * EE will automatically use the set wp_options, 'date_format', and 'time_format'.
107
+		 *
108
+		 * @since 4.6.7
109
+		 * @var array  Expected an array returned with 'date' and 'time' keys.
110
+		 */
111
+		$this->_date_format_strings = apply_filters(
112
+			'FHEE__espresso_events_Pricing_Hooks___set_hooks_properties__date_format_strings',
113
+			array(
114
+				'date' => 'Y-m-d',
115
+				'time' => 'h:i a',
116
+			)
117
+		);
118
+		// validate
119
+		$this->_date_format_strings['date'] = isset($this->_date_format_strings['date'])
120
+			? $this->_date_format_strings['date']
121
+			: null;
122
+		$this->_date_format_strings['time'] = isset($this->_date_format_strings['time'])
123
+			? $this->_date_format_strings['time']
124
+			: null;
125
+		$this->_date_time_format = $this->_date_format_strings['date']
126
+								   . ' '
127
+								   . $this->_date_format_strings['time'];
128
+	}
129 129
 
130 130
 
131
-    /**
132
-     * @return void
133
-     */
134
-    protected function _validate_format_strings()
135
-    {
136
-        // validate format strings
137
-        $format_validation = EEH_DTT_Helper::validate_format_string(
138
-            $this->_date_time_format
139
-        );
140
-        if (is_array($format_validation)) {
141
-            $msg = '<p>';
142
-            $msg .= sprintf(
143
-                esc_html__(
144
-                    'The format "%s" was likely added via a filter and is invalid for the following reasons:',
145
-                    'event_espresso'
146
-                ),
147
-                $this->_date_time_format
148
-            );
149
-            $msg .= '</p><ul>';
150
-            foreach ($format_validation as $error) {
151
-                $msg .= '<li>' . $error . '</li>';
152
-            }
153
-            $msg .= '</ul><p>';
154
-            $msg .= sprintf(
155
-                esc_html__(
156
-                    '%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
157
-                    'event_espresso'
158
-                ),
159
-                '<span style="color:#D54E21;">',
160
-                '</span>'
161
-            );
162
-            $msg .= '</p>';
163
-            EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
164
-            $this->_date_format_strings = array(
165
-                'date' => 'Y-m-d',
166
-                'time' => 'h:i a',
167
-            );
168
-        }
169
-    }
131
+	/**
132
+	 * @return void
133
+	 */
134
+	protected function _validate_format_strings()
135
+	{
136
+		// validate format strings
137
+		$format_validation = EEH_DTT_Helper::validate_format_string(
138
+			$this->_date_time_format
139
+		);
140
+		if (is_array($format_validation)) {
141
+			$msg = '<p>';
142
+			$msg .= sprintf(
143
+				esc_html__(
144
+					'The format "%s" was likely added via a filter and is invalid for the following reasons:',
145
+					'event_espresso'
146
+				),
147
+				$this->_date_time_format
148
+			);
149
+			$msg .= '</p><ul>';
150
+			foreach ($format_validation as $error) {
151
+				$msg .= '<li>' . $error . '</li>';
152
+			}
153
+			$msg .= '</ul><p>';
154
+			$msg .= sprintf(
155
+				esc_html__(
156
+					'%sPlease note that your date and time formats have been reset to "Y-m-d" and "h:i a" respectively.%s',
157
+					'event_espresso'
158
+				),
159
+				'<span style="color:#D54E21;">',
160
+				'</span>'
161
+			);
162
+			$msg .= '</p>';
163
+			EE_Error::add_attention($msg, __FILE__, __FUNCTION__, __LINE__);
164
+			$this->_date_format_strings = array(
165
+				'date' => 'Y-m-d',
166
+				'time' => 'h:i a',
167
+			);
168
+		}
169
+	}
170 170
 
171 171
 
172
-    /**
173
-     * @return void
174
-     */
175
-    protected function _set_scripts_styles()
176
-    {
177
-        $this->_scripts_styles = array(
178
-            'registers'   => array(
179
-                'ee-tickets-datetimes-css' => array(
180
-                    'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
181
-                    'type' => 'css',
182
-                ),
183
-                'ee-dtt-ticket-metabox'    => array(
184
-                    'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
185
-                    'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
186
-                ),
187
-            ),
188
-            'deregisters' => array(
189
-                'event-editor-css'       => array('type' => 'css'),
190
-                'event-datetime-metabox' => array('type' => 'js'),
191
-            ),
192
-            'enqueues'    => array(
193
-                'ee-tickets-datetimes-css' => array('edit', 'create_new'),
194
-                'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
195
-            ),
196
-            'localize'    => array(
197
-                'ee-dtt-ticket-metabox' => array(
198
-                    'DTT_TRASH_BLOCK'       => array(
199
-                        'main_warning'            => esc_html__(
200
-                            'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
201
-                            'event_espresso'
202
-                        ),
203
-                        'after_warning'           => esc_html__(
204
-                            'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
205
-                            'event_espresso'
206
-                        ),
207
-                        'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
208
-                                                     . esc_html__('Cancel', 'event_espresso') . '</button>',
209
-                        'close_button'            => '<button class="button-secondary ee-modal-cancel">'
210
-                                                     . esc_html__('Close', 'event_espresso') . '</button>',
211
-                        'single_warning_from_tkt' => esc_html__(
212
-                            'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
213
-                            'event_espresso'
214
-                        ),
215
-                        'single_warning_from_dtt' => esc_html__(
216
-                            'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
217
-                            'event_espresso'
218
-                        ),
219
-                        'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
220
-                                                     . esc_html__('Dismiss', 'event_espresso') . '</button>',
221
-                    ),
222
-                    'DTT_ERROR_MSG'         => array(
223
-                        'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
224
-                        'dismiss_button' => '<div class="save-cancel-button-container">'
225
-                                            . '<button class="button-secondary ee-modal-cancel">'
226
-                                            . esc_html__('Dismiss', 'event_espresso')
227
-                                            . '</button></div>',
228
-                    ),
229
-                    'DTT_OVERSELL_WARNING'  => array(
230
-                        'datetime_ticket' => esc_html__(
231
-                            'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
232
-                            'event_espresso'
233
-                        ),
234
-                        'ticket_datetime' => esc_html__(
235
-                            'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
236
-                            'event_espresso'
237
-                        ),
238
-                    ),
239
-                    'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
240
-                        $this->_date_format_strings['date'],
241
-                        $this->_date_format_strings['time']
242
-                    ),
243
-                    'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
244
-                ),
245
-            ),
246
-        );
247
-    }
172
+	/**
173
+	 * @return void
174
+	 */
175
+	protected function _set_scripts_styles()
176
+	{
177
+		$this->_scripts_styles = array(
178
+			'registers'   => array(
179
+				'ee-tickets-datetimes-css' => array(
180
+					'url'  => PRICING_ASSETS_URL . 'event-tickets-datetimes.css',
181
+					'type' => 'css',
182
+				),
183
+				'ee-dtt-ticket-metabox'    => array(
184
+					'url'     => PRICING_ASSETS_URL . 'ee-datetime-ticket-metabox.js',
185
+					'depends' => array('ee-datepicker', 'ee-dialog', 'underscore'),
186
+				),
187
+			),
188
+			'deregisters' => array(
189
+				'event-editor-css'       => array('type' => 'css'),
190
+				'event-datetime-metabox' => array('type' => 'js'),
191
+			),
192
+			'enqueues'    => array(
193
+				'ee-tickets-datetimes-css' => array('edit', 'create_new'),
194
+				'ee-dtt-ticket-metabox'    => array('edit', 'create_new'),
195
+			),
196
+			'localize'    => array(
197
+				'ee-dtt-ticket-metabox' => array(
198
+					'DTT_TRASH_BLOCK'       => array(
199
+						'main_warning'            => esc_html__(
200
+							'The Datetime you are attempting to trash is the only datetime selected for the following ticket(s):',
201
+							'event_espresso'
202
+						),
203
+						'after_warning'           => esc_html__(
204
+							'In order to trash this datetime you must first make sure the above ticket(s) are assigned to other datetimes.',
205
+							'event_espresso'
206
+						),
207
+						'cancel_button'           => '<button class="button-secondary ee-modal-cancel">'
208
+													 . esc_html__('Cancel', 'event_espresso') . '</button>',
209
+						'close_button'            => '<button class="button-secondary ee-modal-cancel">'
210
+													 . esc_html__('Close', 'event_espresso') . '</button>',
211
+						'single_warning_from_tkt' => esc_html__(
212
+							'The Datetime you are attempting to unassign from this ticket is the only remaining datetime for this ticket. Tickets must always have at least one datetime assigned to them.',
213
+							'event_espresso'
214
+						),
215
+						'single_warning_from_dtt' => esc_html__(
216
+							'The ticket you are attempting to unassign from this datetime cannot be unassigned because the datetime is the only remaining datetime for the ticket.  Tickets must always have at least one datetime assigned to them.',
217
+							'event_espresso'
218
+						),
219
+						'dismiss_button'          => '<button class="button-secondary ee-modal-cancel">'
220
+													 . esc_html__('Dismiss', 'event_espresso') . '</button>',
221
+					),
222
+					'DTT_ERROR_MSG'         => array(
223
+						'no_ticket_name' => esc_html__('General Admission', 'event_espresso'),
224
+						'dismiss_button' => '<div class="save-cancel-button-container">'
225
+											. '<button class="button-secondary ee-modal-cancel">'
226
+											. esc_html__('Dismiss', 'event_espresso')
227
+											. '</button></div>',
228
+					),
229
+					'DTT_OVERSELL_WARNING'  => array(
230
+						'datetime_ticket' => esc_html__(
231
+							'You cannot add this ticket to this datetime because it has a sold amount that is greater than the amount of spots remaining for this datetime.',
232
+							'event_espresso'
233
+						),
234
+						'ticket_datetime' => esc_html__(
235
+							'You cannot add this datetime to this ticket because the ticket has a sold amount that is greater than the amount of spots remaining on the datetime.',
236
+							'event_espresso'
237
+						),
238
+					),
239
+					'DTT_CONVERTED_FORMATS' => EEH_DTT_Helper::convert_php_to_js_and_moment_date_formats(
240
+						$this->_date_format_strings['date'],
241
+						$this->_date_format_strings['time']
242
+					),
243
+					'DTT_START_OF_WEEK'     => array('dayValue' => (int) get_option('start_of_week')),
244
+				),
245
+			),
246
+		);
247
+	}
248 248
 
249 249
 
250
-    /**
251
-     * @param array $update_callbacks
252
-     * @return array
253
-     */
254
-    public function caf_updates(array $update_callbacks)
255
-    {
256
-        foreach ($update_callbacks as $key => $callback) {
257
-            if ($callback[1] === '_default_tickets_update') {
258
-                unset($update_callbacks[ $key ]);
259
-            }
260
-        }
261
-        $update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
262
-        return $update_callbacks;
263
-    }
250
+	/**
251
+	 * @param array $update_callbacks
252
+	 * @return array
253
+	 */
254
+	public function caf_updates(array $update_callbacks)
255
+	{
256
+		foreach ($update_callbacks as $key => $callback) {
257
+			if ($callback[1] === '_default_tickets_update') {
258
+				unset($update_callbacks[ $key ]);
259
+			}
260
+		}
261
+		$update_callbacks[] = array($this, 'datetime_and_tickets_caf_update');
262
+		return $update_callbacks;
263
+	}
264 264
 
265 265
 
266
-    /**
267
-     * Handles saving everything related to Tickets (datetimes, tickets, prices)
268
-     *
269
-     * @param  EE_Event $event The Event object we're attaching data to
270
-     * @param  array    $data  The request data from the form
271
-     * @throws ReflectionException
272
-     * @throws Exception
273
-     * @throws InvalidInterfaceException
274
-     * @throws InvalidDataTypeException
275
-     * @throws EE_Error
276
-     * @throws InvalidArgumentException
277
-     */
278
-    public function datetime_and_tickets_caf_update($event, $data)
279
-    {
280
-        // first we need to start with datetimes cause they are the "root" items attached to events.
281
-        $saved_datetimes = $this->_update_datetimes($event, $data);
282
-        // next tackle the tickets (and prices?)
283
-        $this->_update_tickets($event, $saved_datetimes, $data);
284
-    }
266
+	/**
267
+	 * Handles saving everything related to Tickets (datetimes, tickets, prices)
268
+	 *
269
+	 * @param  EE_Event $event The Event object we're attaching data to
270
+	 * @param  array    $data  The request data from the form
271
+	 * @throws ReflectionException
272
+	 * @throws Exception
273
+	 * @throws InvalidInterfaceException
274
+	 * @throws InvalidDataTypeException
275
+	 * @throws EE_Error
276
+	 * @throws InvalidArgumentException
277
+	 */
278
+	public function datetime_and_tickets_caf_update($event, $data)
279
+	{
280
+		// first we need to start with datetimes cause they are the "root" items attached to events.
281
+		$saved_datetimes = $this->_update_datetimes($event, $data);
282
+		// next tackle the tickets (and prices?)
283
+		$this->_update_tickets($event, $saved_datetimes, $data);
284
+	}
285 285
 
286 286
 
287
-    /**
288
-     * update event_datetimes
289
-     *
290
-     * @param  EE_Event $event Event being updated
291
-     * @param  array    $data  the request data from the form
292
-     * @return EE_Datetime[]
293
-     * @throws Exception
294
-     * @throws ReflectionException
295
-     * @throws InvalidInterfaceException
296
-     * @throws InvalidDataTypeException
297
-     * @throws InvalidArgumentException
298
-     * @throws EE_Error
299
-     */
300
-    protected function _update_datetimes($event, $data)
301
-    {
302
-        $timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
303
-        $saved_dtt_ids = array();
304
-        $saved_dtt_objs = array();
305
-        if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
306
-            throw new InvalidArgumentException(
307
-                esc_html__(
308
-                    'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
309
-                    'event_espresso'
310
-                )
311
-            );
312
-        }
313
-        foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
314
-            // trim all values to ensure any excess whitespace is removed.
315
-            $datetime_data = array_map(
316
-                function ($datetime_data) {
317
-                    return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
318
-                },
319
-                $datetime_data
320
-            );
321
-            $datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
322
-                                            && ! empty($datetime_data['DTT_EVT_end'])
323
-                ? $datetime_data['DTT_EVT_end']
324
-                : $datetime_data['DTT_EVT_start'];
325
-            $datetime_values = array(
326
-                'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
327
-                    ? $datetime_data['DTT_ID']
328
-                    : null,
329
-                'DTT_name'        => ! empty($datetime_data['DTT_name'])
330
-                    ? $datetime_data['DTT_name']
331
-                    : '',
332
-                'DTT_description' => ! empty($datetime_data['DTT_description'])
333
-                    ? $datetime_data['DTT_description']
334
-                    : '',
335
-                'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
336
-                'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
337
-                'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
338
-                    ? EE_INF
339
-                    : $datetime_data['DTT_reg_limit'],
340
-                'DTT_order'       => ! isset($datetime_data['DTT_order'])
341
-                    ? $row
342
-                    : $datetime_data['DTT_order'],
343
-            );
344
-            // if we have an id then let's get existing object first and then set the new values.
345
-            // Otherwise we instantiate a new object for save.
346
-            if (! empty($datetime_data['DTT_ID'])) {
347
-                $datetime = EE_Registry::instance()
348
-                                       ->load_model('Datetime', array($timezone))
349
-                                       ->get_one_by_ID($datetime_data['DTT_ID']);
350
-                // set date and time format according to what is set in this class.
351
-                $datetime->set_date_format($this->_date_format_strings['date']);
352
-                $datetime->set_time_format($this->_date_format_strings['time']);
353
-                foreach ($datetime_values as $field => $value) {
354
-                    $datetime->set($field, $value);
355
-                }
356
-                // make sure the $dtt_id here is saved just in case
357
-                // after the add_relation_to() the autosave replaces it.
358
-                // We need to do this so we dont' TRASH the parent DTT.
359
-                // (save the ID for both key and value to avoid duplications)
360
-                $saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
361
-            } else {
362
-                $datetime = EE_Registry::instance()->load_class(
363
-                    'Datetime',
364
-                    array(
365
-                        $datetime_values,
366
-                        $timezone,
367
-                        array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
368
-                    ),
369
-                    false,
370
-                    false
371
-                );
372
-                foreach ($datetime_values as $field => $value) {
373
-                    $datetime->set($field, $value);
374
-                }
375
-            }
376
-            $datetime->save();
377
-            do_action(
378
-                'AHEE__espresso_events_Pricing_Hooks___update_datetimes_after_save',
379
-                $datetime,
380
-                $row,
381
-                $datetime_data,
382
-                $data
383
-            );
384
-            $datetime = $event->_add_relation_to($datetime, 'Datetime');
385
-            // before going any further make sure our dates are setup correctly
386
-            // so that the end date is always equal or greater than the start date.
387
-            if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
388
-                $datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
389
-                $datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
390
-                $datetime->save();
391
-            }
392
-            // now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
393
-            // because it is possible there was a new one created for the autosave.
394
-            // (save the ID for both key and value to avoid duplications)
395
-            $DTT_ID = $datetime->ID();
396
-            $saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
397
-            $saved_dtt_objs[ $row ] = $datetime;
398
-            // @todo if ANY of these updates fail then we want the appropriate global error message.
399
-        }
400
-        $event->save();
401
-        // now we need to REMOVE any datetimes that got deleted.
402
-        // Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
403
-        // So its safe to permanently delete at this point.
404
-        $old_datetimes = explode(',', $data['datetime_IDs']);
405
-        $old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
406
-        if (is_array($old_datetimes)) {
407
-            $datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
408
-            foreach ($datetimes_to_delete as $id) {
409
-                $id = absint($id);
410
-                if (empty($id)) {
411
-                    continue;
412
-                }
413
-                $dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
414
-                // remove tkt relationships.
415
-                $related_tickets = $dtt_to_remove->get_many_related('Ticket');
416
-                foreach ($related_tickets as $tkt) {
417
-                    $dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
418
-                }
419
-                $event->_remove_relation_to($id, 'Datetime');
420
-                $dtt_to_remove->refresh_cache_of_related_objects();
421
-            }
422
-        }
423
-        return $saved_dtt_objs;
424
-    }
287
+	/**
288
+	 * update event_datetimes
289
+	 *
290
+	 * @param  EE_Event $event Event being updated
291
+	 * @param  array    $data  the request data from the form
292
+	 * @return EE_Datetime[]
293
+	 * @throws Exception
294
+	 * @throws ReflectionException
295
+	 * @throws InvalidInterfaceException
296
+	 * @throws InvalidDataTypeException
297
+	 * @throws InvalidArgumentException
298
+	 * @throws EE_Error
299
+	 */
300
+	protected function _update_datetimes($event, $data)
301
+	{
302
+		$timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
303
+		$saved_dtt_ids = array();
304
+		$saved_dtt_objs = array();
305
+		if (empty($data['edit_event_datetimes']) || ! is_array($data['edit_event_datetimes'])) {
306
+			throw new InvalidArgumentException(
307
+				esc_html__(
308
+					'The "edit_event_datetimes" array is invalid therefore the event can not be updated.',
309
+					'event_espresso'
310
+				)
311
+			);
312
+		}
313
+		foreach ($data['edit_event_datetimes'] as $row => $datetime_data) {
314
+			// trim all values to ensure any excess whitespace is removed.
315
+			$datetime_data = array_map(
316
+				function ($datetime_data) {
317
+					return is_array($datetime_data) ? $datetime_data : trim($datetime_data);
318
+				},
319
+				$datetime_data
320
+			);
321
+			$datetime_data['DTT_EVT_end'] = isset($datetime_data['DTT_EVT_end'])
322
+											&& ! empty($datetime_data['DTT_EVT_end'])
323
+				? $datetime_data['DTT_EVT_end']
324
+				: $datetime_data['DTT_EVT_start'];
325
+			$datetime_values = array(
326
+				'DTT_ID'          => ! empty($datetime_data['DTT_ID'])
327
+					? $datetime_data['DTT_ID']
328
+					: null,
329
+				'DTT_name'        => ! empty($datetime_data['DTT_name'])
330
+					? $datetime_data['DTT_name']
331
+					: '',
332
+				'DTT_description' => ! empty($datetime_data['DTT_description'])
333
+					? $datetime_data['DTT_description']
334
+					: '',
335
+				'DTT_EVT_start'   => $datetime_data['DTT_EVT_start'],
336
+				'DTT_EVT_end'     => $datetime_data['DTT_EVT_end'],
337
+				'DTT_reg_limit'   => empty($datetime_data['DTT_reg_limit'])
338
+					? EE_INF
339
+					: $datetime_data['DTT_reg_limit'],
340
+				'DTT_order'       => ! isset($datetime_data['DTT_order'])
341
+					? $row
342
+					: $datetime_data['DTT_order'],
343
+			);
344
+			// if we have an id then let's get existing object first and then set the new values.
345
+			// Otherwise we instantiate a new object for save.
346
+			if (! empty($datetime_data['DTT_ID'])) {
347
+				$datetime = EE_Registry::instance()
348
+									   ->load_model('Datetime', array($timezone))
349
+									   ->get_one_by_ID($datetime_data['DTT_ID']);
350
+				// set date and time format according to what is set in this class.
351
+				$datetime->set_date_format($this->_date_format_strings['date']);
352
+				$datetime->set_time_format($this->_date_format_strings['time']);
353
+				foreach ($datetime_values as $field => $value) {
354
+					$datetime->set($field, $value);
355
+				}
356
+				// make sure the $dtt_id here is saved just in case
357
+				// after the add_relation_to() the autosave replaces it.
358
+				// We need to do this so we dont' TRASH the parent DTT.
359
+				// (save the ID for both key and value to avoid duplications)
360
+				$saved_dtt_ids[ $datetime->ID() ] = $datetime->ID();
361
+			} else {
362
+				$datetime = EE_Registry::instance()->load_class(
363
+					'Datetime',
364
+					array(
365
+						$datetime_values,
366
+						$timezone,
367
+						array($this->_date_format_strings['date'], $this->_date_format_strings['time']),
368
+					),
369
+					false,
370
+					false
371
+				);
372
+				foreach ($datetime_values as $field => $value) {
373
+					$datetime->set($field, $value);
374
+				}
375
+			}
376
+			$datetime->save();
377
+			do_action(
378
+				'AHEE__espresso_events_Pricing_Hooks___update_datetimes_after_save',
379
+				$datetime,
380
+				$row,
381
+				$datetime_data,
382
+				$data
383
+			);
384
+			$datetime = $event->_add_relation_to($datetime, 'Datetime');
385
+			// before going any further make sure our dates are setup correctly
386
+			// so that the end date is always equal or greater than the start date.
387
+			if ($datetime->get_raw('DTT_EVT_start') > $datetime->get_raw('DTT_EVT_end')) {
388
+				$datetime->set('DTT_EVT_end', $datetime->get('DTT_EVT_start'));
389
+				$datetime = EEH_DTT_Helper::date_time_add($datetime, 'DTT_EVT_end', 'days');
390
+				$datetime->save();
391
+			}
392
+			// now we have to make sure we add the new DTT_ID to the $saved_dtt_ids array
393
+			// because it is possible there was a new one created for the autosave.
394
+			// (save the ID for both key and value to avoid duplications)
395
+			$DTT_ID = $datetime->ID();
396
+			$saved_dtt_ids[ $DTT_ID ] = $DTT_ID;
397
+			$saved_dtt_objs[ $row ] = $datetime;
398
+			// @todo if ANY of these updates fail then we want the appropriate global error message.
399
+		}
400
+		$event->save();
401
+		// now we need to REMOVE any datetimes that got deleted.
402
+		// Keep in mind that this process will only kick in for datetimes that don't have any DTT_sold on them.
403
+		// So its safe to permanently delete at this point.
404
+		$old_datetimes = explode(',', $data['datetime_IDs']);
405
+		$old_datetimes = $old_datetimes[0] === '' ? array() : $old_datetimes;
406
+		if (is_array($old_datetimes)) {
407
+			$datetimes_to_delete = array_diff($old_datetimes, $saved_dtt_ids);
408
+			foreach ($datetimes_to_delete as $id) {
409
+				$id = absint($id);
410
+				if (empty($id)) {
411
+					continue;
412
+				}
413
+				$dtt_to_remove = EE_Registry::instance()->load_model('Datetime')->get_one_by_ID($id);
414
+				// remove tkt relationships.
415
+				$related_tickets = $dtt_to_remove->get_many_related('Ticket');
416
+				foreach ($related_tickets as $tkt) {
417
+					$dtt_to_remove->_remove_relation_to($tkt, 'Ticket');
418
+				}
419
+				$event->_remove_relation_to($id, 'Datetime');
420
+				$dtt_to_remove->refresh_cache_of_related_objects();
421
+			}
422
+		}
423
+		return $saved_dtt_objs;
424
+	}
425 425
 
426 426
 
427
-    /**
428
-     * update tickets
429
-     *
430
-     * @param  EE_Event      $event           Event object being updated
431
-     * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
432
-     * @param  array         $data            incoming request data
433
-     * @return EE_Ticket[]
434
-     * @throws Exception
435
-     * @throws ReflectionException
436
-     * @throws InvalidInterfaceException
437
-     * @throws InvalidDataTypeException
438
-     * @throws InvalidArgumentException
439
-     * @throws EE_Error
440
-     */
441
-    protected function _update_tickets($event, $saved_datetimes, $data)
442
-    {
443
-        $new_tkt = null;
444
-        $new_default = null;
445
-        // stripslashes because WP filtered the $_POST ($data) array to add slashes
446
-        $data = stripslashes_deep($data);
447
-        $timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
448
-        $saved_tickets = $datetimes_on_existing = array();
449
-        $old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
450
-        if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
451
-            throw new InvalidArgumentException(
452
-                esc_html__(
453
-                    'The "edit_tickets" array is invalid therefore the event can not be updated.',
454
-                    'event_espresso'
455
-                )
456
-            );
457
-        }
458
-        foreach ($data['edit_tickets'] as $row => $tkt) {
459
-            $update_prices = $create_new_TKT = false;
460
-            // figure out what datetimes were added to the ticket
461
-            // and what datetimes were removed from the ticket in the session.
462
-            $starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
463
-            $tkt_dtt_rows = explode(',', $data['ticket_datetime_rows'][ $row ]);
464
-            $datetimes_added = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
465
-            $datetimes_removed = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
466
-            // trim inputs to ensure any excess whitespace is removed.
467
-            $tkt = array_map(
468
-                function ($ticket_data) {
469
-                    return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
470
-                },
471
-                $tkt
472
-            );
473
-            // note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
474
-            // because we're doing calculations prior to using the models.
475
-            // note incoming ['TKT_price'] value is already in standard notation (via js).
476
-            $ticket_price = isset($tkt['TKT_price'])
477
-                ? round((float) $tkt['TKT_price'], 3)
478
-                : 0;
479
-            // note incoming base price needs converted from localized value.
480
-            $base_price = isset($tkt['TKT_base_price'])
481
-                ? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
482
-                : 0;
483
-            // if ticket price == 0 and $base_price != 0 then ticket price == base_price
484
-            $ticket_price = $ticket_price === 0 && $base_price !== 0
485
-                ? $base_price
486
-                : $ticket_price;
487
-            $base_price_id = isset($tkt['TKT_base_price_ID'])
488
-                ? $tkt['TKT_base_price_ID']
489
-                : 0;
490
-            $price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
491
-                ? $data['edit_prices'][ $row ]
492
-                : array();
493
-            $now = null;
494
-            if (empty($tkt['TKT_start_date'])) {
495
-                // lets' use now in the set timezone.
496
-                $now = new DateTime('now', new DateTimeZone($event->get_timezone()));
497
-                $tkt['TKT_start_date'] = $now->format($this->_date_time_format);
498
-            }
499
-            if (empty($tkt['TKT_end_date'])) {
500
-                /**
501
-                 * set the TKT_end_date to the first datetime attached to the ticket.
502
-                 */
503
-                $first_dtt = $saved_datetimes[ reset($tkt_dtt_rows) ];
504
-                $tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
505
-            }
506
-            $TKT_values = array(
507
-                'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
508
-                'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
509
-                'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
510
-                'TKT_description' => ! empty($tkt['TKT_description'])
511
-                                     && $tkt['TKT_description'] !== esc_html__(
512
-                                         'You can modify this description',
513
-                                         'event_espresso'
514
-                                     )
515
-                    ? $tkt['TKT_description']
516
-                    : '',
517
-                'TKT_start_date'  => $tkt['TKT_start_date'],
518
-                'TKT_end_date'    => $tkt['TKT_end_date'],
519
-                'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
520
-                    ? EE_INF
521
-                    : $tkt['TKT_qty'],
522
-                'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
523
-                    ? EE_INF
524
-                    : $tkt['TKT_uses'],
525
-                'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
526
-                'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
527
-                'TKT_row'         => $row,
528
-                'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
529
-                'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
530
-                'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
531
-                'TKT_price'       => $ticket_price,
532
-            );
533
-            // if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
534
-            // which means in turn that the prices will become new prices as well.
535
-            if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
536
-                $TKT_values['TKT_ID'] = 0;
537
-                $TKT_values['TKT_is_default'] = 0;
538
-                $update_prices = true;
539
-            }
540
-            // if we have a TKT_ID then we need to get that existing TKT_obj and update it
541
-            // we actually do our saves ahead of doing any add_relations to
542
-            // because its entirely possible that this ticket wasn't removed or added to any datetime in the session
543
-            // but DID have it's items modified.
544
-            // keep in mind that if the TKT has been sold (and we have changed pricing information),
545
-            // then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
546
-            if (absint($TKT_values['TKT_ID'])) {
547
-                $ticket = EE_Registry::instance()
548
-                                     ->load_model('Ticket', array($timezone))
549
-                                     ->get_one_by_ID($tkt['TKT_ID']);
550
-                if ($ticket instanceof EE_Ticket) {
551
-                    $ticket = $this->_update_ticket_datetimes(
552
-                        $ticket,
553
-                        $saved_datetimes,
554
-                        $datetimes_added,
555
-                        $datetimes_removed
556
-                    );
557
-                    // are there any registrations using this ticket ?
558
-                    $tickets_sold = $ticket->count_related(
559
-                        'Registration',
560
-                        array(
561
-                            array(
562
-                                'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
563
-                            ),
564
-                        )
565
-                    );
566
-                    // set ticket formats
567
-                    $ticket->set_date_format($this->_date_format_strings['date']);
568
-                    $ticket->set_time_format($this->_date_format_strings['time']);
569
-                    // let's just check the total price for the existing ticket
570
-                    // and determine if it matches the new total price.
571
-                    // if they are different then we create a new ticket (if tickets sold)
572
-                    // if they aren't different then we go ahead and modify existing ticket.
573
-                    $create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
574
-                    // set new values
575
-                    foreach ($TKT_values as $field => $value) {
576
-                        if ($field === 'TKT_qty') {
577
-                            $ticket->set_qty($value);
578
-                        } else {
579
-                            $ticket->set($field, $value);
580
-                        }
581
-                    }
582
-                    // if $create_new_TKT is false then we can safely update the existing ticket.
583
-                    // Otherwise we have to create a new ticket.
584
-                    if ($create_new_TKT) {
585
-                        $new_tkt = $this->_duplicate_ticket(
586
-                            $ticket,
587
-                            $price_rows,
588
-                            $ticket_price,
589
-                            $base_price,
590
-                            $base_price_id
591
-                        );
592
-                    }
593
-                }
594
-            } else {
595
-                // no TKT_id so a new TKT
596
-                $ticket = EE_Ticket::new_instance(
597
-                    $TKT_values,
598
-                    $timezone,
599
-                    array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
600
-                );
601
-                if ($ticket instanceof EE_Ticket) {
602
-                    // make sure ticket has an ID of setting relations won't work
603
-                    $ticket->save();
604
-                    $ticket = $this->_update_ticket_datetimes(
605
-                        $ticket,
606
-                        $saved_datetimes,
607
-                        $datetimes_added,
608
-                        $datetimes_removed
609
-                    );
610
-                    $update_prices = true;
611
-                }
612
-            }
613
-            // make sure any current values have been saved.
614
-            // $ticket->save();
615
-            // before going any further make sure our dates are setup correctly
616
-            // so that the end date is always equal or greater than the start date.
617
-            if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
618
-                $ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
619
-                $ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
620
-            }
621
-            // let's make sure the base price is handled
622
-            $ticket = ! $create_new_TKT
623
-                ? $this->_add_prices_to_ticket(
624
-                    array(),
625
-                    $ticket,
626
-                    $update_prices,
627
-                    $base_price,
628
-                    $base_price_id
629
-                )
630
-                : $ticket;
631
-            // add/update price_modifiers
632
-            $ticket = ! $create_new_TKT
633
-                ? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
634
-                : $ticket;
635
-            // need to make sue that the TKT_price is accurate after saving the prices.
636
-            $ticket->ensure_TKT_Price_correct();
637
-            // handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
638
-            if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
639
-                $update_prices = true;
640
-                $new_default = clone $ticket;
641
-                $new_default->set('TKT_ID', 0);
642
-                $new_default->set('TKT_is_default', 1);
643
-                $new_default->set('TKT_row', 1);
644
-                $new_default->set('TKT_price', $ticket_price);
645
-                // remove any dtt relations cause we DON'T want dtt relations attached
646
-                // (note this is just removing the cached relations in the object)
647
-                $new_default->_remove_relations('Datetime');
648
-                // @todo we need to add the current attached prices as new prices to the new default ticket.
649
-                $new_default = $this->_add_prices_to_ticket(
650
-                    $price_rows,
651
-                    $new_default,
652
-                    $update_prices
653
-                );
654
-                // don't forget the base price!
655
-                $new_default = $this->_add_prices_to_ticket(
656
-                    array(),
657
-                    $new_default,
658
-                    $update_prices,
659
-                    $base_price,
660
-                    $base_price_id
661
-                );
662
-                $new_default->save();
663
-                do_action(
664
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
665
-                    $new_default,
666
-                    $row,
667
-                    $ticket,
668
-                    $data
669
-                );
670
-            }
671
-            // DO ALL dtt relationships for both current tickets and any archived tickets
672
-            // for the given dtt that are related to the current ticket.
673
-            // TODO... not sure exactly how we're going to do this considering we don't know
674
-            // what current ticket the archived tickets are related to
675
-            // (and TKT_parent is used for autosaves so that's not a field we can reliably use).
676
-            // let's assign any tickets that have been setup to the saved_tickets tracker
677
-            // save existing TKT
678
-            $ticket->save();
679
-            if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
680
-                // save new TKT
681
-                $new_tkt->save();
682
-                // add new ticket to array
683
-                $saved_tickets[ $new_tkt->ID() ] = $new_tkt;
684
-                do_action(
685
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
686
-                    $new_tkt,
687
-                    $row,
688
-                    $tkt,
689
-                    $data
690
-                );
691
-            } else {
692
-                // add tkt to saved tkts
693
-                $saved_tickets[ $ticket->ID() ] = $ticket;
694
-                do_action(
695
-                    'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
696
-                    $ticket,
697
-                    $row,
698
-                    $tkt,
699
-                    $data
700
-                );
701
-            }
702
-        }
703
-        // now we need to handle tickets actually "deleted permanently".
704
-        // There are cases where we'd want this to happen
705
-        // (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
706
-        // Or a draft event was saved and in the process of editing a ticket is trashed.
707
-        // No sense in keeping all the related data in the db!
708
-        $old_tickets = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
709
-        $tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
710
-        foreach ($tickets_removed as $id) {
711
-            $id = absint($id);
712
-            // get the ticket for this id
713
-            $tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
714
-            // if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
715
-            if ($tkt_to_remove->get('TKT_is_default')) {
716
-                continue;
717
-            }
718
-            // if this tkt has any registrations attached so then we just ARCHIVE
719
-            // because we don't actually permanently delete these tickets.
720
-            if ($tkt_to_remove->count_related('Registration') > 0) {
721
-                $tkt_to_remove->delete();
722
-                continue;
723
-            }
724
-            // need to get all the related datetimes on this ticket and remove from every single one of them
725
-            // (remember this process can ONLY kick off if there are NO tkts_sold)
726
-            $datetimes = $tkt_to_remove->get_many_related('Datetime');
727
-            foreach ($datetimes as $datetime) {
728
-                $tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
729
-            }
730
-            // need to do the same for prices (except these prices can also be deleted because again,
731
-            // tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
732
-            $tkt_to_remove->delete_related_permanently('Price');
733
-            do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
734
-            // finally let's delete this ticket
735
-            // (which should not be blocked at this point b/c we've removed all our relationships)
736
-            $tkt_to_remove->delete_permanently();
737
-        }
738
-        return $saved_tickets;
739
-    }
427
+	/**
428
+	 * update tickets
429
+	 *
430
+	 * @param  EE_Event      $event           Event object being updated
431
+	 * @param  EE_Datetime[] $saved_datetimes an array of datetime ids being updated
432
+	 * @param  array         $data            incoming request data
433
+	 * @return EE_Ticket[]
434
+	 * @throws Exception
435
+	 * @throws ReflectionException
436
+	 * @throws InvalidInterfaceException
437
+	 * @throws InvalidDataTypeException
438
+	 * @throws InvalidArgumentException
439
+	 * @throws EE_Error
440
+	 */
441
+	protected function _update_tickets($event, $saved_datetimes, $data)
442
+	{
443
+		$new_tkt = null;
444
+		$new_default = null;
445
+		// stripslashes because WP filtered the $_POST ($data) array to add slashes
446
+		$data = stripslashes_deep($data);
447
+		$timezone = isset($data['timezone_string']) ? $data['timezone_string'] : null;
448
+		$saved_tickets = $datetimes_on_existing = array();
449
+		$old_tickets = isset($data['ticket_IDs']) ? explode(',', $data['ticket_IDs']) : array();
450
+		if (empty($data['edit_tickets']) || ! is_array($data['edit_tickets'])) {
451
+			throw new InvalidArgumentException(
452
+				esc_html__(
453
+					'The "edit_tickets" array is invalid therefore the event can not be updated.',
454
+					'event_espresso'
455
+				)
456
+			);
457
+		}
458
+		foreach ($data['edit_tickets'] as $row => $tkt) {
459
+			$update_prices = $create_new_TKT = false;
460
+			// figure out what datetimes were added to the ticket
461
+			// and what datetimes were removed from the ticket in the session.
462
+			$starting_tkt_dtt_rows = explode(',', $data['starting_ticket_datetime_rows'][ $row ]);
463
+			$tkt_dtt_rows = explode(',', $data['ticket_datetime_rows'][ $row ]);
464
+			$datetimes_added = array_diff($tkt_dtt_rows, $starting_tkt_dtt_rows);
465
+			$datetimes_removed = array_diff($starting_tkt_dtt_rows, $tkt_dtt_rows);
466
+			// trim inputs to ensure any excess whitespace is removed.
467
+			$tkt = array_map(
468
+				function ($ticket_data) {
469
+					return is_array($ticket_data) ? $ticket_data : trim($ticket_data);
470
+				},
471
+				$tkt
472
+			);
473
+			// note we are doing conversions to floats here instead of allowing EE_Money_Field to handle
474
+			// because we're doing calculations prior to using the models.
475
+			// note incoming ['TKT_price'] value is already in standard notation (via js).
476
+			$ticket_price = isset($tkt['TKT_price'])
477
+				? round((float) $tkt['TKT_price'], 3)
478
+				: 0;
479
+			// note incoming base price needs converted from localized value.
480
+			$base_price = isset($tkt['TKT_base_price'])
481
+				? EEH_Money::convert_to_float_from_localized_money($tkt['TKT_base_price'])
482
+				: 0;
483
+			// if ticket price == 0 and $base_price != 0 then ticket price == base_price
484
+			$ticket_price = $ticket_price === 0 && $base_price !== 0
485
+				? $base_price
486
+				: $ticket_price;
487
+			$base_price_id = isset($tkt['TKT_base_price_ID'])
488
+				? $tkt['TKT_base_price_ID']
489
+				: 0;
490
+			$price_rows = is_array($data['edit_prices']) && isset($data['edit_prices'][ $row ])
491
+				? $data['edit_prices'][ $row ]
492
+				: array();
493
+			$now = null;
494
+			if (empty($tkt['TKT_start_date'])) {
495
+				// lets' use now in the set timezone.
496
+				$now = new DateTime('now', new DateTimeZone($event->get_timezone()));
497
+				$tkt['TKT_start_date'] = $now->format($this->_date_time_format);
498
+			}
499
+			if (empty($tkt['TKT_end_date'])) {
500
+				/**
501
+				 * set the TKT_end_date to the first datetime attached to the ticket.
502
+				 */
503
+				$first_dtt = $saved_datetimes[ reset($tkt_dtt_rows) ];
504
+				$tkt['TKT_end_date'] = $first_dtt->start_date_and_time($this->_date_time_format);
505
+			}
506
+			$TKT_values = array(
507
+				'TKT_ID'          => ! empty($tkt['TKT_ID']) ? $tkt['TKT_ID'] : null,
508
+				'TTM_ID'          => ! empty($tkt['TTM_ID']) ? $tkt['TTM_ID'] : 0,
509
+				'TKT_name'        => ! empty($tkt['TKT_name']) ? $tkt['TKT_name'] : '',
510
+				'TKT_description' => ! empty($tkt['TKT_description'])
511
+									 && $tkt['TKT_description'] !== esc_html__(
512
+										 'You can modify this description',
513
+										 'event_espresso'
514
+									 )
515
+					? $tkt['TKT_description']
516
+					: '',
517
+				'TKT_start_date'  => $tkt['TKT_start_date'],
518
+				'TKT_end_date'    => $tkt['TKT_end_date'],
519
+				'TKT_qty'         => ! isset($tkt['TKT_qty']) || $tkt['TKT_qty'] === ''
520
+					? EE_INF
521
+					: $tkt['TKT_qty'],
522
+				'TKT_uses'        => ! isset($tkt['TKT_uses']) || $tkt['TKT_uses'] === ''
523
+					? EE_INF
524
+					: $tkt['TKT_uses'],
525
+				'TKT_min'         => empty($tkt['TKT_min']) ? 0 : $tkt['TKT_min'],
526
+				'TKT_max'         => empty($tkt['TKT_max']) ? EE_INF : $tkt['TKT_max'],
527
+				'TKT_row'         => $row,
528
+				'TKT_order'       => isset($tkt['TKT_order']) ? $tkt['TKT_order'] : 0,
529
+				'TKT_taxable'     => ! empty($tkt['TKT_taxable']) ? 1 : 0,
530
+				'TKT_required'    => ! empty($tkt['TKT_required']) ? 1 : 0,
531
+				'TKT_price'       => $ticket_price,
532
+			);
533
+			// if this is a default TKT, then we need to set the TKT_ID to 0 and update accordingly,
534
+			// which means in turn that the prices will become new prices as well.
535
+			if (isset($tkt['TKT_is_default']) && $tkt['TKT_is_default']) {
536
+				$TKT_values['TKT_ID'] = 0;
537
+				$TKT_values['TKT_is_default'] = 0;
538
+				$update_prices = true;
539
+			}
540
+			// if we have a TKT_ID then we need to get that existing TKT_obj and update it
541
+			// we actually do our saves ahead of doing any add_relations to
542
+			// because its entirely possible that this ticket wasn't removed or added to any datetime in the session
543
+			// but DID have it's items modified.
544
+			// keep in mind that if the TKT has been sold (and we have changed pricing information),
545
+			// then we won't be updating the tkt but instead a new tkt will be created and the old one archived.
546
+			if (absint($TKT_values['TKT_ID'])) {
547
+				$ticket = EE_Registry::instance()
548
+									 ->load_model('Ticket', array($timezone))
549
+									 ->get_one_by_ID($tkt['TKT_ID']);
550
+				if ($ticket instanceof EE_Ticket) {
551
+					$ticket = $this->_update_ticket_datetimes(
552
+						$ticket,
553
+						$saved_datetimes,
554
+						$datetimes_added,
555
+						$datetimes_removed
556
+					);
557
+					// are there any registrations using this ticket ?
558
+					$tickets_sold = $ticket->count_related(
559
+						'Registration',
560
+						array(
561
+							array(
562
+								'STS_ID' => array('NOT IN', array(EEM_Registration::status_id_incomplete)),
563
+							),
564
+						)
565
+					);
566
+					// set ticket formats
567
+					$ticket->set_date_format($this->_date_format_strings['date']);
568
+					$ticket->set_time_format($this->_date_format_strings['time']);
569
+					// let's just check the total price for the existing ticket
570
+					// and determine if it matches the new total price.
571
+					// if they are different then we create a new ticket (if tickets sold)
572
+					// if they aren't different then we go ahead and modify existing ticket.
573
+					$create_new_TKT = $tickets_sold > 0 && $ticket_price !== $ticket->price() && ! $ticket->deleted();
574
+					// set new values
575
+					foreach ($TKT_values as $field => $value) {
576
+						if ($field === 'TKT_qty') {
577
+							$ticket->set_qty($value);
578
+						} else {
579
+							$ticket->set($field, $value);
580
+						}
581
+					}
582
+					// if $create_new_TKT is false then we can safely update the existing ticket.
583
+					// Otherwise we have to create a new ticket.
584
+					if ($create_new_TKT) {
585
+						$new_tkt = $this->_duplicate_ticket(
586
+							$ticket,
587
+							$price_rows,
588
+							$ticket_price,
589
+							$base_price,
590
+							$base_price_id
591
+						);
592
+					}
593
+				}
594
+			} else {
595
+				// no TKT_id so a new TKT
596
+				$ticket = EE_Ticket::new_instance(
597
+					$TKT_values,
598
+					$timezone,
599
+					array($this->_date_format_strings['date'], $this->_date_format_strings['time'])
600
+				);
601
+				if ($ticket instanceof EE_Ticket) {
602
+					// make sure ticket has an ID of setting relations won't work
603
+					$ticket->save();
604
+					$ticket = $this->_update_ticket_datetimes(
605
+						$ticket,
606
+						$saved_datetimes,
607
+						$datetimes_added,
608
+						$datetimes_removed
609
+					);
610
+					$update_prices = true;
611
+				}
612
+			}
613
+			// make sure any current values have been saved.
614
+			// $ticket->save();
615
+			// before going any further make sure our dates are setup correctly
616
+			// so that the end date is always equal or greater than the start date.
617
+			if ($ticket->get_raw('TKT_start_date') > $ticket->get_raw('TKT_end_date')) {
618
+				$ticket->set('TKT_end_date', $ticket->get('TKT_start_date'));
619
+				$ticket = EEH_DTT_Helper::date_time_add($ticket, 'TKT_end_date', 'days');
620
+			}
621
+			// let's make sure the base price is handled
622
+			$ticket = ! $create_new_TKT
623
+				? $this->_add_prices_to_ticket(
624
+					array(),
625
+					$ticket,
626
+					$update_prices,
627
+					$base_price,
628
+					$base_price_id
629
+				)
630
+				: $ticket;
631
+			// add/update price_modifiers
632
+			$ticket = ! $create_new_TKT
633
+				? $this->_add_prices_to_ticket($price_rows, $ticket, $update_prices)
634
+				: $ticket;
635
+			// need to make sue that the TKT_price is accurate after saving the prices.
636
+			$ticket->ensure_TKT_Price_correct();
637
+			// handle CREATING a default tkt from the incoming tkt but ONLY if this isn't an autosave.
638
+			if (! defined('DOING_AUTOSAVE') && ! empty($tkt['TKT_is_default_selector'])) {
639
+				$update_prices = true;
640
+				$new_default = clone $ticket;
641
+				$new_default->set('TKT_ID', 0);
642
+				$new_default->set('TKT_is_default', 1);
643
+				$new_default->set('TKT_row', 1);
644
+				$new_default->set('TKT_price', $ticket_price);
645
+				// remove any dtt relations cause we DON'T want dtt relations attached
646
+				// (note this is just removing the cached relations in the object)
647
+				$new_default->_remove_relations('Datetime');
648
+				// @todo we need to add the current attached prices as new prices to the new default ticket.
649
+				$new_default = $this->_add_prices_to_ticket(
650
+					$price_rows,
651
+					$new_default,
652
+					$update_prices
653
+				);
654
+				// don't forget the base price!
655
+				$new_default = $this->_add_prices_to_ticket(
656
+					array(),
657
+					$new_default,
658
+					$update_prices,
659
+					$base_price,
660
+					$base_price_id
661
+				);
662
+				$new_default->save();
663
+				do_action(
664
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_default_ticket',
665
+					$new_default,
666
+					$row,
667
+					$ticket,
668
+					$data
669
+				);
670
+			}
671
+			// DO ALL dtt relationships for both current tickets and any archived tickets
672
+			// for the given dtt that are related to the current ticket.
673
+			// TODO... not sure exactly how we're going to do this considering we don't know
674
+			// what current ticket the archived tickets are related to
675
+			// (and TKT_parent is used for autosaves so that's not a field we can reliably use).
676
+			// let's assign any tickets that have been setup to the saved_tickets tracker
677
+			// save existing TKT
678
+			$ticket->save();
679
+			if ($create_new_TKT && $new_tkt instanceof EE_Ticket) {
680
+				// save new TKT
681
+				$new_tkt->save();
682
+				// add new ticket to array
683
+				$saved_tickets[ $new_tkt->ID() ] = $new_tkt;
684
+				do_action(
685
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_new_ticket',
686
+					$new_tkt,
687
+					$row,
688
+					$tkt,
689
+					$data
690
+				);
691
+			} else {
692
+				// add tkt to saved tkts
693
+				$saved_tickets[ $ticket->ID() ] = $ticket;
694
+				do_action(
695
+					'AHEE__espresso_events_Pricing_Hooks___update_tkts_update_ticket',
696
+					$ticket,
697
+					$row,
698
+					$tkt,
699
+					$data
700
+				);
701
+			}
702
+		}
703
+		// now we need to handle tickets actually "deleted permanently".
704
+		// There are cases where we'd want this to happen
705
+		// (i.e. autosaves are happening and then in between autosaves the user trashes a ticket).
706
+		// Or a draft event was saved and in the process of editing a ticket is trashed.
707
+		// No sense in keeping all the related data in the db!
708
+		$old_tickets = isset($old_tickets[0]) && $old_tickets[0] === '' ? array() : $old_tickets;
709
+		$tickets_removed = array_diff($old_tickets, array_keys($saved_tickets));
710
+		foreach ($tickets_removed as $id) {
711
+			$id = absint($id);
712
+			// get the ticket for this id
713
+			$tkt_to_remove = EE_Registry::instance()->load_model('Ticket')->get_one_by_ID($id);
714
+			// if this tkt is a default tkt we leave it alone cause it won't be attached to the datetime
715
+			if ($tkt_to_remove->get('TKT_is_default')) {
716
+				continue;
717
+			}
718
+			// if this tkt has any registrations attached so then we just ARCHIVE
719
+			// because we don't actually permanently delete these tickets.
720
+			if ($tkt_to_remove->count_related('Registration') > 0) {
721
+				$tkt_to_remove->delete();
722
+				continue;
723
+			}
724
+			// need to get all the related datetimes on this ticket and remove from every single one of them
725
+			// (remember this process can ONLY kick off if there are NO tkts_sold)
726
+			$datetimes = $tkt_to_remove->get_many_related('Datetime');
727
+			foreach ($datetimes as $datetime) {
728
+				$tkt_to_remove->_remove_relation_to($datetime, 'Datetime');
729
+			}
730
+			// need to do the same for prices (except these prices can also be deleted because again,
731
+			// tickets can only be trashed if they don't have any TKTs sold (otherwise they are just archived))
732
+			$tkt_to_remove->delete_related_permanently('Price');
733
+			do_action('AHEE__espresso_events_Pricing_Hooks___update_tkts_delete_ticket', $tkt_to_remove);
734
+			// finally let's delete this ticket
735
+			// (which should not be blocked at this point b/c we've removed all our relationships)
736
+			$tkt_to_remove->delete_permanently();
737
+		}
738
+		return $saved_tickets;
739
+	}
740 740
 
741 741
 
742
-    /**
743
-     * @access  protected
744
-     * @param EE_Ticket      $ticket
745
-     * @param \EE_Datetime[] $saved_datetimes
746
-     * @param \EE_Datetime[] $added_datetimes
747
-     * @param \EE_Datetime[] $removed_datetimes
748
-     * @return EE_Ticket
749
-     * @throws EE_Error
750
-     */
751
-    protected function _update_ticket_datetimes(
752
-        EE_Ticket $ticket,
753
-        $saved_datetimes = array(),
754
-        $added_datetimes = array(),
755
-        $removed_datetimes = array()
756
-    ) {
757
-        // to start we have to add the ticket to all the datetimes its supposed to be with,
758
-        // and removing the ticket from datetimes it got removed from.
759
-        // first let's add datetimes
760
-        if (! empty($added_datetimes) && is_array($added_datetimes)) {
761
-            foreach ($added_datetimes as $row_id) {
762
-                $row_id = (int) $row_id;
763
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
764
-                    $ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
765
-                    // Is this an existing ticket (has an ID) and does it have any sold?
766
-                    // If so, then we need to add that to the DTT sold because this DTT is getting added.
767
-                    if ($ticket->ID() && $ticket->sold() > 0) {
768
-                        $saved_datetimes[ $row_id ]->increaseSold($ticket->sold(), false);
769
-                    }
770
-                }
771
-            }
772
-        }
773
-        // then remove datetimes
774
-        if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
775
-            foreach ($removed_datetimes as $row_id) {
776
-                $row_id = (int) $row_id;
777
-                // its entirely possible that a datetime got deleted (instead of just removed from relationship.
778
-                // So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
779
-                if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
780
-                    $ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
781
-                    // Is this an existing ticket (has an ID) and does it have any sold?
782
-                    // If so, then we need to remove it's sold from the DTT_sold.
783
-                    if ($ticket->ID() && $ticket->sold() > 0) {
784
-                        $saved_datetimes[ $row_id ]->decreaseSold($ticket->sold());
785
-                    }
786
-                }
787
-            }
788
-        }
789
-        // cap ticket qty by datetime reg limits
790
-        $ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
791
-        return $ticket;
792
-    }
742
+	/**
743
+	 * @access  protected
744
+	 * @param EE_Ticket      $ticket
745
+	 * @param \EE_Datetime[] $saved_datetimes
746
+	 * @param \EE_Datetime[] $added_datetimes
747
+	 * @param \EE_Datetime[] $removed_datetimes
748
+	 * @return EE_Ticket
749
+	 * @throws EE_Error
750
+	 */
751
+	protected function _update_ticket_datetimes(
752
+		EE_Ticket $ticket,
753
+		$saved_datetimes = array(),
754
+		$added_datetimes = array(),
755
+		$removed_datetimes = array()
756
+	) {
757
+		// to start we have to add the ticket to all the datetimes its supposed to be with,
758
+		// and removing the ticket from datetimes it got removed from.
759
+		// first let's add datetimes
760
+		if (! empty($added_datetimes) && is_array($added_datetimes)) {
761
+			foreach ($added_datetimes as $row_id) {
762
+				$row_id = (int) $row_id;
763
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
764
+					$ticket->_add_relation_to($saved_datetimes[ $row_id ], 'Datetime');
765
+					// Is this an existing ticket (has an ID) and does it have any sold?
766
+					// If so, then we need to add that to the DTT sold because this DTT is getting added.
767
+					if ($ticket->ID() && $ticket->sold() > 0) {
768
+						$saved_datetimes[ $row_id ]->increaseSold($ticket->sold(), false);
769
+					}
770
+				}
771
+			}
772
+		}
773
+		// then remove datetimes
774
+		if (! empty($removed_datetimes) && is_array($removed_datetimes)) {
775
+			foreach ($removed_datetimes as $row_id) {
776
+				$row_id = (int) $row_id;
777
+				// its entirely possible that a datetime got deleted (instead of just removed from relationship.
778
+				// So make sure we skip over this if the dtt isn't in the $saved_datetimes array)
779
+				if (isset($saved_datetimes[ $row_id ]) && $saved_datetimes[ $row_id ] instanceof EE_Datetime) {
780
+					$ticket->_remove_relation_to($saved_datetimes[ $row_id ], 'Datetime');
781
+					// Is this an existing ticket (has an ID) and does it have any sold?
782
+					// If so, then we need to remove it's sold from the DTT_sold.
783
+					if ($ticket->ID() && $ticket->sold() > 0) {
784
+						$saved_datetimes[ $row_id ]->decreaseSold($ticket->sold());
785
+					}
786
+				}
787
+			}
788
+		}
789
+		// cap ticket qty by datetime reg limits
790
+		$ticket->set_qty(min($ticket->qty(), $ticket->qty('reg_limit')));
791
+		return $ticket;
792
+	}
793 793
 
794 794
 
795
-    /**
796
-     * @access  protected
797
-     * @param EE_Ticket $ticket
798
-     * @param array     $price_rows
799
-     * @param int       $ticket_price
800
-     * @param int       $base_price
801
-     * @param int       $base_price_id
802
-     * @return EE_Ticket
803
-     * @throws ReflectionException
804
-     * @throws InvalidArgumentException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidDataTypeException
807
-     * @throws EE_Error
808
-     */
809
-    protected function _duplicate_ticket(
810
-        EE_Ticket $ticket,
811
-        $price_rows = array(),
812
-        $ticket_price = 0,
813
-        $base_price = 0,
814
-        $base_price_id = 0
815
-    ) {
816
-        // create new ticket that's a copy of the existing
817
-        // except a new id of course (and not archived)
818
-        // AND has the new TKT_price associated with it.
819
-        $new_ticket = clone $ticket;
820
-        $new_ticket->set('TKT_ID', 0);
821
-        $new_ticket->set_deleted(0);
822
-        $new_ticket->set_price($ticket_price);
823
-        $new_ticket->set_sold(0);
824
-        // let's get a new ID for this ticket
825
-        $new_ticket->save();
826
-        // we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
827
-        $datetimes_on_existing = $ticket->datetimes();
828
-        $new_ticket = $this->_update_ticket_datetimes(
829
-            $new_ticket,
830
-            $datetimes_on_existing,
831
-            array_keys($datetimes_on_existing)
832
-        );
833
-        // $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
834
-        // if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
835
-        // available.
836
-        if ($ticket->sold() > 0) {
837
-            $new_qty = $ticket->qty() - $ticket->sold();
838
-            $new_ticket->set_qty($new_qty);
839
-        }
840
-        // now we update the prices just for this ticket
841
-        $new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
842
-        // and we update the base price
843
-        $new_ticket = $this->_add_prices_to_ticket(
844
-            array(),
845
-            $new_ticket,
846
-            true,
847
-            $base_price,
848
-            $base_price_id
849
-        );
850
-        return $new_ticket;
851
-    }
795
+	/**
796
+	 * @access  protected
797
+	 * @param EE_Ticket $ticket
798
+	 * @param array     $price_rows
799
+	 * @param int       $ticket_price
800
+	 * @param int       $base_price
801
+	 * @param int       $base_price_id
802
+	 * @return EE_Ticket
803
+	 * @throws ReflectionException
804
+	 * @throws InvalidArgumentException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidDataTypeException
807
+	 * @throws EE_Error
808
+	 */
809
+	protected function _duplicate_ticket(
810
+		EE_Ticket $ticket,
811
+		$price_rows = array(),
812
+		$ticket_price = 0,
813
+		$base_price = 0,
814
+		$base_price_id = 0
815
+	) {
816
+		// create new ticket that's a copy of the existing
817
+		// except a new id of course (and not archived)
818
+		// AND has the new TKT_price associated with it.
819
+		$new_ticket = clone $ticket;
820
+		$new_ticket->set('TKT_ID', 0);
821
+		$new_ticket->set_deleted(0);
822
+		$new_ticket->set_price($ticket_price);
823
+		$new_ticket->set_sold(0);
824
+		// let's get a new ID for this ticket
825
+		$new_ticket->save();
826
+		// we also need to make sure this new ticket gets the same datetime attachments as the archived ticket
827
+		$datetimes_on_existing = $ticket->datetimes();
828
+		$new_ticket = $this->_update_ticket_datetimes(
829
+			$new_ticket,
830
+			$datetimes_on_existing,
831
+			array_keys($datetimes_on_existing)
832
+		);
833
+		// $ticket will get archived later b/c we are NOT adding it to the saved_tickets array.
834
+		// if existing $ticket has sold amount, then we need to adjust the qty for the new TKT to = the remaining
835
+		// available.
836
+		if ($ticket->sold() > 0) {
837
+			$new_qty = $ticket->qty() - $ticket->sold();
838
+			$new_ticket->set_qty($new_qty);
839
+		}
840
+		// now we update the prices just for this ticket
841
+		$new_ticket = $this->_add_prices_to_ticket($price_rows, $new_ticket, true);
842
+		// and we update the base price
843
+		$new_ticket = $this->_add_prices_to_ticket(
844
+			array(),
845
+			$new_ticket,
846
+			true,
847
+			$base_price,
848
+			$base_price_id
849
+		);
850
+		return $new_ticket;
851
+	}
852 852
 
853 853
 
854
-    /**
855
-     * This attaches a list of given prices to a ticket.
856
-     * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
857
-     * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
858
-     * price info and prices are automatically "archived" via the ticket.
859
-     *
860
-     * @access  private
861
-     * @param array     $prices        Array of prices from the form.
862
-     * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
863
-     * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
864
-     * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
865
-     * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
866
-     * @return EE_Ticket
867
-     * @throws ReflectionException
868
-     * @throws InvalidArgumentException
869
-     * @throws InvalidInterfaceException
870
-     * @throws InvalidDataTypeException
871
-     * @throws EE_Error
872
-     */
873
-    protected function _add_prices_to_ticket(
874
-        $prices = array(),
875
-        EE_Ticket $ticket,
876
-        $new_prices = false,
877
-        $base_price = false,
878
-        $base_price_id = false
879
-    ) {
880
-        // let's just get any current prices that may exist on the given ticket
881
-        // so we can remove any prices that got trashed in this session.
882
-        $current_prices_on_ticket = $base_price !== false
883
-            ? $ticket->base_price(true)
884
-            : $ticket->price_modifiers();
885
-        $updated_prices = array();
886
-        // if $base_price ! FALSE then updating a base price.
887
-        if ($base_price !== false) {
888
-            $prices[1] = array(
889
-                'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
890
-                'PRT_ID'     => 1,
891
-                'PRC_amount' => $base_price,
892
-                'PRC_name'   => $ticket->get('TKT_name'),
893
-                'PRC_desc'   => $ticket->get('TKT_description'),
894
-            );
895
-        }
896
-        // possibly need to save tkt
897
-        if (! $ticket->ID()) {
898
-            $ticket->save();
899
-        }
900
-        foreach ($prices as $row => $prc) {
901
-            $prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
902
-            if (empty($prt_id)) {
903
-                continue;
904
-            } //prices MUST have a price type id.
905
-            $PRC_values = array(
906
-                'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
907
-                'PRT_ID'         => $prt_id,
908
-                'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
909
-                'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
910
-                'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
911
-                'PRC_is_default' => false,
912
-                // make sure we set PRC_is_default to false for all ticket saves from event_editor
913
-                'PRC_order'      => $row,
914
-            );
915
-            if ($new_prices || empty($PRC_values['PRC_ID'])) {
916
-                $PRC_values['PRC_ID'] = 0;
917
-                $price = EE_Registry::instance()->load_class(
918
-                    'Price',
919
-                    array($PRC_values),
920
-                    false,
921
-                    false
922
-                );
923
-            } else {
924
-                $price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
925
-                // update this price with new values
926
-                foreach ($PRC_values as $field => $value) {
927
-                    $price->set($field, $value);
928
-                }
929
-            }
930
-            $price->save();
931
-            $updated_prices[ $price->ID() ] = $price;
932
-            $ticket->_add_relation_to($price, 'Price');
933
-        }
934
-        // now let's remove any prices that got removed from the ticket
935
-        if (! empty($current_prices_on_ticket)) {
936
-            $current = array_keys($current_prices_on_ticket);
937
-            $updated = array_keys($updated_prices);
938
-            $prices_to_remove = array_diff($current, $updated);
939
-            if (! empty($prices_to_remove)) {
940
-                foreach ($prices_to_remove as $prc_id) {
941
-                    $p = $current_prices_on_ticket[ $prc_id ];
942
-                    $ticket->_remove_relation_to($p, 'Price');
943
-                    // delete permanently the price
944
-                    $p->delete_permanently();
945
-                }
946
-            }
947
-        }
948
-        return $ticket;
949
-    }
854
+	/**
855
+	 * This attaches a list of given prices to a ticket.
856
+	 * Note we dont' have to worry about ever removing relationships (or archiving prices) because if there is a change
857
+	 * in price information on a ticket, a new ticket is created anyways so the archived ticket will retain the old
858
+	 * price info and prices are automatically "archived" via the ticket.
859
+	 *
860
+	 * @access  private
861
+	 * @param array     $prices        Array of prices from the form.
862
+	 * @param EE_Ticket $ticket        EE_Ticket object that prices are being attached to.
863
+	 * @param bool      $new_prices    Whether attach existing incoming prices or create new ones.
864
+	 * @param int|bool  $base_price    if FALSE then NOT doing a base price add.
865
+	 * @param int|bool  $base_price_id if present then this is the base_price_id being updated.
866
+	 * @return EE_Ticket
867
+	 * @throws ReflectionException
868
+	 * @throws InvalidArgumentException
869
+	 * @throws InvalidInterfaceException
870
+	 * @throws InvalidDataTypeException
871
+	 * @throws EE_Error
872
+	 */
873
+	protected function _add_prices_to_ticket(
874
+		$prices = array(),
875
+		EE_Ticket $ticket,
876
+		$new_prices = false,
877
+		$base_price = false,
878
+		$base_price_id = false
879
+	) {
880
+		// let's just get any current prices that may exist on the given ticket
881
+		// so we can remove any prices that got trashed in this session.
882
+		$current_prices_on_ticket = $base_price !== false
883
+			? $ticket->base_price(true)
884
+			: $ticket->price_modifiers();
885
+		$updated_prices = array();
886
+		// if $base_price ! FALSE then updating a base price.
887
+		if ($base_price !== false) {
888
+			$prices[1] = array(
889
+				'PRC_ID'     => $new_prices || $base_price_id === 1 ? null : $base_price_id,
890
+				'PRT_ID'     => 1,
891
+				'PRC_amount' => $base_price,
892
+				'PRC_name'   => $ticket->get('TKT_name'),
893
+				'PRC_desc'   => $ticket->get('TKT_description'),
894
+			);
895
+		}
896
+		// possibly need to save tkt
897
+		if (! $ticket->ID()) {
898
+			$ticket->save();
899
+		}
900
+		foreach ($prices as $row => $prc) {
901
+			$prt_id = ! empty($prc['PRT_ID']) ? $prc['PRT_ID'] : null;
902
+			if (empty($prt_id)) {
903
+				continue;
904
+			} //prices MUST have a price type id.
905
+			$PRC_values = array(
906
+				'PRC_ID'         => ! empty($prc['PRC_ID']) ? $prc['PRC_ID'] : null,
907
+				'PRT_ID'         => $prt_id,
908
+				'PRC_amount'     => ! empty($prc['PRC_amount']) ? $prc['PRC_amount'] : 0,
909
+				'PRC_name'       => ! empty($prc['PRC_name']) ? $prc['PRC_name'] : '',
910
+				'PRC_desc'       => ! empty($prc['PRC_desc']) ? $prc['PRC_desc'] : '',
911
+				'PRC_is_default' => false,
912
+				// make sure we set PRC_is_default to false for all ticket saves from event_editor
913
+				'PRC_order'      => $row,
914
+			);
915
+			if ($new_prices || empty($PRC_values['PRC_ID'])) {
916
+				$PRC_values['PRC_ID'] = 0;
917
+				$price = EE_Registry::instance()->load_class(
918
+					'Price',
919
+					array($PRC_values),
920
+					false,
921
+					false
922
+				);
923
+			} else {
924
+				$price = EE_Registry::instance()->load_model('Price')->get_one_by_ID($prc['PRC_ID']);
925
+				// update this price with new values
926
+				foreach ($PRC_values as $field => $value) {
927
+					$price->set($field, $value);
928
+				}
929
+			}
930
+			$price->save();
931
+			$updated_prices[ $price->ID() ] = $price;
932
+			$ticket->_add_relation_to($price, 'Price');
933
+		}
934
+		// now let's remove any prices that got removed from the ticket
935
+		if (! empty($current_prices_on_ticket)) {
936
+			$current = array_keys($current_prices_on_ticket);
937
+			$updated = array_keys($updated_prices);
938
+			$prices_to_remove = array_diff($current, $updated);
939
+			if (! empty($prices_to_remove)) {
940
+				foreach ($prices_to_remove as $prc_id) {
941
+					$p = $current_prices_on_ticket[ $prc_id ];
942
+					$ticket->_remove_relation_to($p, 'Price');
943
+					// delete permanently the price
944
+					$p->delete_permanently();
945
+				}
946
+			}
947
+		}
948
+		return $ticket;
949
+	}
950 950
 
951 951
 
952
-    /**
953
-     * @param Events_Admin_Page $event_admin_obj
954
-     * @return Events_Admin_Page
955
-     */
956
-    public function autosave_handling(Events_Admin_Page $event_admin_obj)
957
-    {
958
-        return $event_admin_obj;
959
-        // doing nothing for the moment.
960
-        // todo when I get to this remember that I need to set the template args on the $event_admin_obj
961
-        // (use the set_template_args() method)
962
-        /**
963
-         * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
964
-         * 1. TKT_is_default_selector (visible)
965
-         * 2. TKT_is_default (hidden)
966
-         * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
967
-         * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
968
-         * this ticket to be saved as a default.
969
-         * The tricky part is, on an initial display on create or edit (or after manually updating),
970
-         * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
971
-         * if this is a create.  However, after an autosave, users will want some sort of indicator that
972
-         * the TKT HAS been saved as a default..
973
-         * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
974
-         * On Autosave:
975
-         * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
976
-         * then set the TKT_is_default to false.
977
-         * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
978
-         *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
979
-         * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
980
-         */
981
-    }
952
+	/**
953
+	 * @param Events_Admin_Page $event_admin_obj
954
+	 * @return Events_Admin_Page
955
+	 */
956
+	public function autosave_handling(Events_Admin_Page $event_admin_obj)
957
+	{
958
+		return $event_admin_obj;
959
+		// doing nothing for the moment.
960
+		// todo when I get to this remember that I need to set the template args on the $event_admin_obj
961
+		// (use the set_template_args() method)
962
+		/**
963
+		 * need to remember to handle TICKET DEFAULT saves correctly:  I've got two input fields in the dom:
964
+		 * 1. TKT_is_default_selector (visible)
965
+		 * 2. TKT_is_default (hidden)
966
+		 * I think we'll use the TKT_is_default for recording whether the ticket displayed IS a default ticket
967
+		 * (on new event creations). Whereas the TKT_is_default_selector is for the user to indicate they want
968
+		 * this ticket to be saved as a default.
969
+		 * The tricky part is, on an initial display on create or edit (or after manually updating),
970
+		 * the TKT_is_default_selector will always be unselected and the TKT_is_default will only be true
971
+		 * if this is a create.  However, after an autosave, users will want some sort of indicator that
972
+		 * the TKT HAS been saved as a default..
973
+		 * in other words we don't want to remove the check on TKT_is_default_selector. So here's what I'm thinking.
974
+		 * On Autosave:
975
+		 * 1. If TKT_is_default is true: we create a new TKT, send back the new id and add id to related elements,
976
+		 * then set the TKT_is_default to false.
977
+		 * 2. If TKT_is_default_selector is true: we create/edit existing ticket (following conditions above as well).
978
+		 *  We do NOT create a new default ticket.  The checkbox stays selected after autosave.
979
+		 * 3. only on MANUAL update do we check for the selection and if selected create the new default ticket.
980
+		 */
981
+	}
982 982
 
983 983
 
984
-    /**
985
-     * @throws ReflectionException
986
-     * @throws InvalidArgumentException
987
-     * @throws InvalidInterfaceException
988
-     * @throws InvalidDataTypeException
989
-     * @throws DomainException
990
-     * @throws EE_Error
991
-     */
992
-    public function pricing_metabox()
993
-    {
994
-        $existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
995
-        $event = $this->_adminpage_obj->get_cpt_model_obj();
996
-        // set is_creating_event property.
997
-        $EVT_ID = $event->ID();
998
-        $this->_is_creating_event = empty($this->_req_data['post']);
999
-        // default main template args
1000
-        $main_template_args = array(
1001
-            'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1002
-                'event_editor_event_datetimes_help_tab',
1003
-                $this->_adminpage_obj->page_slug,
1004
-                $this->_adminpage_obj->get_req_action(),
1005
-                false,
1006
-                false
1007
-            ),
1008
-            // todo need to add a filter to the template for the help text
1009
-            // in the Events_Admin_Page core file so we can add further help
1010
-            'existing_datetime_ids'    => '',
1011
-            'total_dtt_rows'           => 1,
1012
-            'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1013
-                'add_new_dtt_info',
1014
-                $this->_adminpage_obj->page_slug,
1015
-                $this->_adminpage_obj->get_req_action(),
1016
-                false,
1017
-                false
1018
-            ),
1019
-            // todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1020
-            'datetime_rows'            => '',
1021
-            'show_tickets_container'   => '',
1022
-            // $this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1023
-            'ticket_rows'              => '',
1024
-            'existing_ticket_ids'      => '',
1025
-            'total_ticket_rows'        => 1,
1026
-            'ticket_js_structure'      => '',
1027
-            'ee_collapsible_status'    => ' ee-collapsible-open'
1028
-            // $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1029
-        );
1030
-        $timezone = $event instanceof EE_Event ? $event->timezone_string() : null;
1031
-        do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1032
-        /**
1033
-         * 1. Start with retrieving Datetimes
1034
-         * 2. For each datetime get related tickets
1035
-         * 3. For each ticket get related prices
1036
-         */
1037
-        /** @var EEM_Datetime $datetime_model */
1038
-        $datetime_model = EE_Registry::instance()->load_model('Datetime', array($timezone));
1039
-        $datetimes = $datetime_model->get_all_event_dates($EVT_ID);
1040
-        $main_template_args['total_dtt_rows'] = count($datetimes);
1041
-        /**
1042
-         * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1043
-         * for why we are counting $datetime_row and then setting that on the Datetime object
1044
-         */
1045
-        $datetime_row = 1;
1046
-        foreach ($datetimes as $datetime) {
1047
-            $DTT_ID = $datetime->get('DTT_ID');
1048
-            $datetime->set('DTT_order', $datetime_row);
1049
-            $existing_datetime_ids[] = $DTT_ID;
1050
-            // tickets attached
1051
-            $related_tickets = $datetime->ID() > 0
1052
-                ? $datetime->get_many_related(
1053
-                    'Ticket',
1054
-                    array(
1055
-                        array(
1056
-                            'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1057
-                        ),
1058
-                        'default_where_conditions' => 'none',
1059
-                        'order_by'                 => array('TKT_order' => 'ASC'),
1060
-                    )
1061
-                )
1062
-                : array();
1063
-            // if there are no related tickets this is likely a new event OR autodraft
1064
-            // event so we need to generate the default tickets because datetimes
1065
-            // ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1066
-            // datetime on the event.
1067
-            if (empty($related_tickets) && count($datetimes) < 2) {
1068
-                /** @var EEM_Ticket $ticket_model */
1069
-                $ticket_model = EE_Registry::instance()->load_model('Ticket');
1070
-                $related_tickets = $ticket_model->get_all_default_tickets();
1071
-                // this should be ordered by TKT_ID, so let's grab the first default ticket
1072
-                // (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1073
-                $default_prices = EEM_Price::instance()->get_all_default_prices();
1074
-                $main_default_ticket = reset($related_tickets);
1075
-                if ($main_default_ticket instanceof EE_Ticket) {
1076
-                    foreach ($default_prices as $default_price) {
1077
-                        if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1078
-                            continue;
1079
-                        }
1080
-                        $main_default_ticket->cache('Price', $default_price);
1081
-                    }
1082
-                }
1083
-            }
1084
-            // we can't actually setup rows in this loop yet cause we don't know all
1085
-            // the unique tickets for this event yet (tickets are linked through all datetimes).
1086
-            // So we're going to temporarily cache some of that information.
1087
-            // loop through and setup the ticket rows and make sure the order is set.
1088
-            foreach ($related_tickets as $ticket) {
1089
-                $TKT_ID = $ticket->get('TKT_ID');
1090
-                $ticket_row = $ticket->get('TKT_row');
1091
-                // we only want unique tickets in our final display!!
1092
-                if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1093
-                    $existing_ticket_ids[] = $TKT_ID;
1094
-                    $all_tickets[] = $ticket;
1095
-                }
1096
-                // temporary cache of this ticket info for this datetime for later processing of datetime rows.
1097
-                $datetime_tickets[ $DTT_ID ][] = $ticket_row;
1098
-                // temporary cache of this datetime info for this ticket for later processing of ticket rows.
1099
-                if (! isset($ticket_datetimes[ $TKT_ID ])
1100
-                    || ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1101
-                ) {
1102
-                    $ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1103
-                }
1104
-            }
1105
-            $datetime_row++;
1106
-        }
1107
-        $main_template_args['total_ticket_rows'] = count($existing_ticket_ids);
1108
-        $main_template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1109
-        $main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1110
-        // sort $all_tickets by order
1111
-        usort(
1112
-            $all_tickets,
1113
-            function (EE_Ticket $a, EE_Ticket $b) {
1114
-                $a_order = (int) $a->get('TKT_order');
1115
-                $b_order = (int) $b->get('TKT_order');
1116
-                if ($a_order === $b_order) {
1117
-                    return 0;
1118
-                }
1119
-                return ($a_order < $b_order) ? -1 : 1;
1120
-            }
1121
-        );
1122
-        // k NOW we have all the data we need for setting up the dtt rows
1123
-        // and ticket rows so we start our dtt loop again.
1124
-        $datetime_row = 1;
1125
-        foreach ($datetimes as $datetime) {
1126
-            $main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1127
-                $datetime_row,
1128
-                $datetime,
1129
-                $datetime_tickets,
1130
-                $all_tickets,
1131
-                false,
1132
-                $datetimes
1133
-            );
1134
-            $datetime_row++;
1135
-        }
1136
-        // then loop through all tickets for the ticket rows.
1137
-        $ticket_row = 1;
1138
-        foreach ($all_tickets as $ticket) {
1139
-            $main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1140
-                $ticket_row,
1141
-                $ticket,
1142
-                $ticket_datetimes,
1143
-                $datetimes,
1144
-                false,
1145
-                $all_tickets
1146
-            );
1147
-            $ticket_row++;
1148
-        }
1149
-        $main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
1150
-        EEH_Template::display_template(
1151
-            PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1152
-            $main_template_args
1153
-        );
1154
-    }
984
+	/**
985
+	 * @throws ReflectionException
986
+	 * @throws InvalidArgumentException
987
+	 * @throws InvalidInterfaceException
988
+	 * @throws InvalidDataTypeException
989
+	 * @throws DomainException
990
+	 * @throws EE_Error
991
+	 */
992
+	public function pricing_metabox()
993
+	{
994
+		$existing_datetime_ids = $existing_ticket_ids = $datetime_tickets = $ticket_datetimes = array();
995
+		$event = $this->_adminpage_obj->get_cpt_model_obj();
996
+		// set is_creating_event property.
997
+		$EVT_ID = $event->ID();
998
+		$this->_is_creating_event = empty($this->_req_data['post']);
999
+		// default main template args
1000
+		$main_template_args = array(
1001
+			'event_datetime_help_link' => EEH_Template::get_help_tab_link(
1002
+				'event_editor_event_datetimes_help_tab',
1003
+				$this->_adminpage_obj->page_slug,
1004
+				$this->_adminpage_obj->get_req_action(),
1005
+				false,
1006
+				false
1007
+			),
1008
+			// todo need to add a filter to the template for the help text
1009
+			// in the Events_Admin_Page core file so we can add further help
1010
+			'existing_datetime_ids'    => '',
1011
+			'total_dtt_rows'           => 1,
1012
+			'add_new_dtt_help_link'    => EEH_Template::get_help_tab_link(
1013
+				'add_new_dtt_info',
1014
+				$this->_adminpage_obj->page_slug,
1015
+				$this->_adminpage_obj->get_req_action(),
1016
+				false,
1017
+				false
1018
+			),
1019
+			// todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1020
+			'datetime_rows'            => '',
1021
+			'show_tickets_container'   => '',
1022
+			// $this->_adminpage_obj->get_cpt_model_obj()->ID() > 1 ? ' style="display:none;"' : '',
1023
+			'ticket_rows'              => '',
1024
+			'existing_ticket_ids'      => '',
1025
+			'total_ticket_rows'        => 1,
1026
+			'ticket_js_structure'      => '',
1027
+			'ee_collapsible_status'    => ' ee-collapsible-open'
1028
+			// $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0 ? ' ee-collapsible-closed' : ' ee-collapsible-open'
1029
+		);
1030
+		$timezone = $event instanceof EE_Event ? $event->timezone_string() : null;
1031
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
1032
+		/**
1033
+		 * 1. Start with retrieving Datetimes
1034
+		 * 2. For each datetime get related tickets
1035
+		 * 3. For each ticket get related prices
1036
+		 */
1037
+		/** @var EEM_Datetime $datetime_model */
1038
+		$datetime_model = EE_Registry::instance()->load_model('Datetime', array($timezone));
1039
+		$datetimes = $datetime_model->get_all_event_dates($EVT_ID);
1040
+		$main_template_args['total_dtt_rows'] = count($datetimes);
1041
+		/**
1042
+		 * @see https://events.codebasehq.com/projects/event-espresso/tickets/9486
1043
+		 * for why we are counting $datetime_row and then setting that on the Datetime object
1044
+		 */
1045
+		$datetime_row = 1;
1046
+		foreach ($datetimes as $datetime) {
1047
+			$DTT_ID = $datetime->get('DTT_ID');
1048
+			$datetime->set('DTT_order', $datetime_row);
1049
+			$existing_datetime_ids[] = $DTT_ID;
1050
+			// tickets attached
1051
+			$related_tickets = $datetime->ID() > 0
1052
+				? $datetime->get_many_related(
1053
+					'Ticket',
1054
+					array(
1055
+						array(
1056
+							'OR' => array('TKT_deleted' => 1, 'TKT_deleted*' => 0),
1057
+						),
1058
+						'default_where_conditions' => 'none',
1059
+						'order_by'                 => array('TKT_order' => 'ASC'),
1060
+					)
1061
+				)
1062
+				: array();
1063
+			// if there are no related tickets this is likely a new event OR autodraft
1064
+			// event so we need to generate the default tickets because datetimes
1065
+			// ALWAYS have at least one related ticket!!.  EXCEPT, we dont' do this if there is already more than one
1066
+			// datetime on the event.
1067
+			if (empty($related_tickets) && count($datetimes) < 2) {
1068
+				/** @var EEM_Ticket $ticket_model */
1069
+				$ticket_model = EE_Registry::instance()->load_model('Ticket');
1070
+				$related_tickets = $ticket_model->get_all_default_tickets();
1071
+				// this should be ordered by TKT_ID, so let's grab the first default ticket
1072
+				// (which will be the main default) and ensure it has any default prices added to it (but do NOT save).
1073
+				$default_prices = EEM_Price::instance()->get_all_default_prices();
1074
+				$main_default_ticket = reset($related_tickets);
1075
+				if ($main_default_ticket instanceof EE_Ticket) {
1076
+					foreach ($default_prices as $default_price) {
1077
+						if ($default_price instanceof EE_Price && $default_price->is_base_price()) {
1078
+							continue;
1079
+						}
1080
+						$main_default_ticket->cache('Price', $default_price);
1081
+					}
1082
+				}
1083
+			}
1084
+			// we can't actually setup rows in this loop yet cause we don't know all
1085
+			// the unique tickets for this event yet (tickets are linked through all datetimes).
1086
+			// So we're going to temporarily cache some of that information.
1087
+			// loop through and setup the ticket rows and make sure the order is set.
1088
+			foreach ($related_tickets as $ticket) {
1089
+				$TKT_ID = $ticket->get('TKT_ID');
1090
+				$ticket_row = $ticket->get('TKT_row');
1091
+				// we only want unique tickets in our final display!!
1092
+				if (! in_array($TKT_ID, $existing_ticket_ids, true)) {
1093
+					$existing_ticket_ids[] = $TKT_ID;
1094
+					$all_tickets[] = $ticket;
1095
+				}
1096
+				// temporary cache of this ticket info for this datetime for later processing of datetime rows.
1097
+				$datetime_tickets[ $DTT_ID ][] = $ticket_row;
1098
+				// temporary cache of this datetime info for this ticket for later processing of ticket rows.
1099
+				if (! isset($ticket_datetimes[ $TKT_ID ])
1100
+					|| ! in_array($datetime_row, $ticket_datetimes[ $TKT_ID ], true)
1101
+				) {
1102
+					$ticket_datetimes[ $TKT_ID ][] = $datetime_row;
1103
+				}
1104
+			}
1105
+			$datetime_row++;
1106
+		}
1107
+		$main_template_args['total_ticket_rows'] = count($existing_ticket_ids);
1108
+		$main_template_args['existing_ticket_ids'] = implode(',', $existing_ticket_ids);
1109
+		$main_template_args['existing_datetime_ids'] = implode(',', $existing_datetime_ids);
1110
+		// sort $all_tickets by order
1111
+		usort(
1112
+			$all_tickets,
1113
+			function (EE_Ticket $a, EE_Ticket $b) {
1114
+				$a_order = (int) $a->get('TKT_order');
1115
+				$b_order = (int) $b->get('TKT_order');
1116
+				if ($a_order === $b_order) {
1117
+					return 0;
1118
+				}
1119
+				return ($a_order < $b_order) ? -1 : 1;
1120
+			}
1121
+		);
1122
+		// k NOW we have all the data we need for setting up the dtt rows
1123
+		// and ticket rows so we start our dtt loop again.
1124
+		$datetime_row = 1;
1125
+		foreach ($datetimes as $datetime) {
1126
+			$main_template_args['datetime_rows'] .= $this->_get_datetime_row(
1127
+				$datetime_row,
1128
+				$datetime,
1129
+				$datetime_tickets,
1130
+				$all_tickets,
1131
+				false,
1132
+				$datetimes
1133
+			);
1134
+			$datetime_row++;
1135
+		}
1136
+		// then loop through all tickets for the ticket rows.
1137
+		$ticket_row = 1;
1138
+		foreach ($all_tickets as $ticket) {
1139
+			$main_template_args['ticket_rows'] .= $this->_get_ticket_row(
1140
+				$ticket_row,
1141
+				$ticket,
1142
+				$ticket_datetimes,
1143
+				$datetimes,
1144
+				false,
1145
+				$all_tickets
1146
+			);
1147
+			$ticket_row++;
1148
+		}
1149
+		$main_template_args['ticket_js_structure'] = $this->_get_ticket_js_structure($datetimes, $all_tickets);
1150
+		EEH_Template::display_template(
1151
+			PRICING_TEMPLATE_PATH . 'event_tickets_metabox_main.template.php',
1152
+			$main_template_args
1153
+		);
1154
+	}
1155 1155
 
1156 1156
 
1157
-    /**
1158
-     * @param int         $datetime_row
1159
-     * @param EE_Datetime $datetime
1160
-     * @param array       $datetime_tickets
1161
-     * @param array       $all_tickets
1162
-     * @param bool        $default
1163
-     * @param array       $all_datetimes
1164
-     * @return mixed
1165
-     * @throws DomainException
1166
-     * @throws EE_Error
1167
-     */
1168
-    protected function _get_datetime_row(
1169
-        $datetime_row,
1170
-        EE_Datetime $datetime,
1171
-        $datetime_tickets = array(),
1172
-        $all_tickets = array(),
1173
-        $default = false,
1174
-        $all_datetimes = array()
1175
-    ) {
1176
-        $dtt_display_template_args = array(
1177
-            'dtt_edit_row'             => $this->_get_dtt_edit_row(
1178
-                $datetime_row,
1179
-                $datetime,
1180
-                $default,
1181
-                $all_datetimes
1182
-            ),
1183
-            'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1184
-                $datetime_row,
1185
-                $datetime,
1186
-                $datetime_tickets,
1187
-                $all_tickets,
1188
-                $default
1189
-            ),
1190
-            'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1191
-        );
1192
-        return EEH_Template::display_template(
1193
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1194
-            $dtt_display_template_args,
1195
-            true
1196
-        );
1197
-    }
1157
+	/**
1158
+	 * @param int         $datetime_row
1159
+	 * @param EE_Datetime $datetime
1160
+	 * @param array       $datetime_tickets
1161
+	 * @param array       $all_tickets
1162
+	 * @param bool        $default
1163
+	 * @param array       $all_datetimes
1164
+	 * @return mixed
1165
+	 * @throws DomainException
1166
+	 * @throws EE_Error
1167
+	 */
1168
+	protected function _get_datetime_row(
1169
+		$datetime_row,
1170
+		EE_Datetime $datetime,
1171
+		$datetime_tickets = array(),
1172
+		$all_tickets = array(),
1173
+		$default = false,
1174
+		$all_datetimes = array()
1175
+	) {
1176
+		$dtt_display_template_args = array(
1177
+			'dtt_edit_row'             => $this->_get_dtt_edit_row(
1178
+				$datetime_row,
1179
+				$datetime,
1180
+				$default,
1181
+				$all_datetimes
1182
+			),
1183
+			'dtt_attached_tickets_row' => $this->_get_dtt_attached_tickets_row(
1184
+				$datetime_row,
1185
+				$datetime,
1186
+				$datetime_tickets,
1187
+				$all_tickets,
1188
+				$default
1189
+			),
1190
+			'dtt_row'                  => $default ? 'DTTNUM' : $datetime_row,
1191
+		);
1192
+		return EEH_Template::display_template(
1193
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_row_wrapper.template.php',
1194
+			$dtt_display_template_args,
1195
+			true
1196
+		);
1197
+	}
1198 1198
 
1199 1199
 
1200
-    /**
1201
-     * This method is used to generate a dtt fields  edit row.
1202
-     * The same row is used to generate a row with valid DTT objects
1203
-     * and the default row that is used as the skeleton by the js.
1204
-     *
1205
-     * @param int           $datetime_row  The row number for the row being generated.
1206
-     * @param EE_Datetime   $datetime
1207
-     * @param bool          $default       Whether a default row is being generated or not.
1208
-     * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1209
-     * @return string
1210
-     * @throws DomainException
1211
-     * @throws EE_Error
1212
-     */
1213
-    protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1214
-    {
1215
-        // if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1216
-        $default = ! $datetime instanceof EE_Datetime ? true : $default;
1217
-        $template_args = array(
1218
-            'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1219
-            'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1220
-            'edit_dtt_expanded'    => '',
1221
-            'DTT_ID'               => $default ? '' : $datetime->ID(),
1222
-            'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1223
-            'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1224
-            'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1225
-            'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1226
-            'DTT_reg_limit'        => $default
1227
-                ? ''
1228
-                : $datetime->get_pretty(
1229
-                    'DTT_reg_limit',
1230
-                    'input'
1231
-                ),
1232
-            'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1233
-            'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1234
-            'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1235
-            'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1236
-                ? ''
1237
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1238
-            'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1239
-                ? 'ee-lock-icon'
1240
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1241
-            'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1242
-                ? ''
1243
-                : EE_Admin_Page::add_query_args_and_nonce(
1244
-                    array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1245
-                    REG_ADMIN_URL
1246
-                ),
1247
-        );
1248
-        $template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1249
-            ? ' style="display:none"'
1250
-            : '';
1251
-        // allow filtering of template args at this point.
1252
-        $template_args = apply_filters(
1253
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1254
-            $template_args,
1255
-            $datetime_row,
1256
-            $datetime,
1257
-            $default,
1258
-            $all_datetimes,
1259
-            $this->_is_creating_event
1260
-        );
1261
-        return EEH_Template::display_template(
1262
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1263
-            $template_args,
1264
-            true
1265
-        );
1266
-    }
1200
+	/**
1201
+	 * This method is used to generate a dtt fields  edit row.
1202
+	 * The same row is used to generate a row with valid DTT objects
1203
+	 * and the default row that is used as the skeleton by the js.
1204
+	 *
1205
+	 * @param int           $datetime_row  The row number for the row being generated.
1206
+	 * @param EE_Datetime   $datetime
1207
+	 * @param bool          $default       Whether a default row is being generated or not.
1208
+	 * @param EE_Datetime[] $all_datetimes This is the array of all datetimes used in the editor.
1209
+	 * @return string
1210
+	 * @throws DomainException
1211
+	 * @throws EE_Error
1212
+	 */
1213
+	protected function _get_dtt_edit_row($datetime_row, $datetime, $default, $all_datetimes)
1214
+	{
1215
+		// if the incoming $datetime object is NOT an instance of EE_Datetime then force default to true.
1216
+		$default = ! $datetime instanceof EE_Datetime ? true : $default;
1217
+		$template_args = array(
1218
+			'dtt_row'              => $default ? 'DTTNUM' : $datetime_row,
1219
+			'event_datetimes_name' => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1220
+			'edit_dtt_expanded'    => '',
1221
+			'DTT_ID'               => $default ? '' : $datetime->ID(),
1222
+			'DTT_name'             => $default ? '' : $datetime->get_f('DTT_name'),
1223
+			'DTT_description'      => $default ? '' : $datetime->get_f('DTT_description'),
1224
+			'DTT_EVT_start'        => $default ? '' : $datetime->start_date($this->_date_time_format),
1225
+			'DTT_EVT_end'          => $default ? '' : $datetime->end_date($this->_date_time_format),
1226
+			'DTT_reg_limit'        => $default
1227
+				? ''
1228
+				: $datetime->get_pretty(
1229
+					'DTT_reg_limit',
1230
+					'input'
1231
+				),
1232
+			'DTT_order'            => $default ? 'DTTNUM' : $datetime_row,
1233
+			'dtt_sold'             => $default ? '0' : $datetime->get('DTT_sold'),
1234
+			'dtt_reserved'         => $default ? '0' : $datetime->reserved(),
1235
+			'clone_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1236
+				? ''
1237
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1238
+			'trash_icon'           => ! empty($datetime) && $datetime->get('DTT_sold') > 0
1239
+				? 'ee-lock-icon'
1240
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1241
+			'reg_list_url'         => $default || ! $datetime->event() instanceof \EE_Event
1242
+				? ''
1243
+				: EE_Admin_Page::add_query_args_and_nonce(
1244
+					array('event_id' => $datetime->event()->ID(), 'datetime_id' => $datetime->ID()),
1245
+					REG_ADMIN_URL
1246
+				),
1247
+		);
1248
+		$template_args['show_trash'] = count($all_datetimes) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1249
+			? ' style="display:none"'
1250
+			: '';
1251
+		// allow filtering of template args at this point.
1252
+		$template_args = apply_filters(
1253
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_edit_row__template_args',
1254
+			$template_args,
1255
+			$datetime_row,
1256
+			$datetime,
1257
+			$default,
1258
+			$all_datetimes,
1259
+			$this->_is_creating_event
1260
+		);
1261
+		return EEH_Template::display_template(
1262
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_edit_row.template.php',
1263
+			$template_args,
1264
+			true
1265
+		);
1266
+	}
1267 1267
 
1268 1268
 
1269
-    /**
1270
-     * @param int         $datetime_row
1271
-     * @param EE_Datetime $datetime
1272
-     * @param array       $datetime_tickets
1273
-     * @param array       $all_tickets
1274
-     * @param bool        $default
1275
-     * @return mixed
1276
-     * @throws DomainException
1277
-     * @throws EE_Error
1278
-     */
1279
-    protected function _get_dtt_attached_tickets_row(
1280
-        $datetime_row,
1281
-        $datetime,
1282
-        $datetime_tickets = array(),
1283
-        $all_tickets = array(),
1284
-        $default
1285
-    ) {
1286
-        $template_args = array(
1287
-            'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1288
-            'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1289
-            'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1290
-            'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1291
-            'show_tickets_row'                  => ' style="display:none;"',
1292
-            'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1293
-                'add_new_ticket_via_datetime',
1294
-                $this->_adminpage_obj->page_slug,
1295
-                $this->_adminpage_obj->get_req_action(),
1296
-                false,
1297
-                false
1298
-            ),
1299
-            // todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1300
-            'DTT_ID'                            => $default ? '' : $datetime->ID(),
1301
-        );
1302
-        // need to setup the list items (but only if this isn't a default skeleton setup)
1303
-        if (! $default) {
1304
-            $ticket_row = 1;
1305
-            foreach ($all_tickets as $ticket) {
1306
-                $template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1307
-                    $datetime_row,
1308
-                    $ticket_row,
1309
-                    $datetime,
1310
-                    $ticket,
1311
-                    $datetime_tickets,
1312
-                    $default
1313
-                );
1314
-                $ticket_row++;
1315
-            }
1316
-        }
1317
-        // filter template args at this point
1318
-        $template_args = apply_filters(
1319
-            'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1320
-            $template_args,
1321
-            $datetime_row,
1322
-            $datetime,
1323
-            $datetime_tickets,
1324
-            $all_tickets,
1325
-            $default,
1326
-            $this->_is_creating_event
1327
-        );
1328
-        return EEH_Template::display_template(
1329
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1330
-            $template_args,
1331
-            true
1332
-        );
1333
-    }
1269
+	/**
1270
+	 * @param int         $datetime_row
1271
+	 * @param EE_Datetime $datetime
1272
+	 * @param array       $datetime_tickets
1273
+	 * @param array       $all_tickets
1274
+	 * @param bool        $default
1275
+	 * @return mixed
1276
+	 * @throws DomainException
1277
+	 * @throws EE_Error
1278
+	 */
1279
+	protected function _get_dtt_attached_tickets_row(
1280
+		$datetime_row,
1281
+		$datetime,
1282
+		$datetime_tickets = array(),
1283
+		$all_tickets = array(),
1284
+		$default
1285
+	) {
1286
+		$template_args = array(
1287
+			'dtt_row'                           => $default ? 'DTTNUM' : $datetime_row,
1288
+			'event_datetimes_name'              => $default ? 'DTTNAMEATTR' : 'edit_event_datetimes',
1289
+			'DTT_description'                   => $default ? '' : $datetime->get_f('DTT_description'),
1290
+			'datetime_tickets_list'             => $default ? '<li class="hidden"></li>' : '',
1291
+			'show_tickets_row'                  => ' style="display:none;"',
1292
+			'add_new_datetime_ticket_help_link' => EEH_Template::get_help_tab_link(
1293
+				'add_new_ticket_via_datetime',
1294
+				$this->_adminpage_obj->page_slug,
1295
+				$this->_adminpage_obj->get_req_action(),
1296
+				false,
1297
+				false
1298
+			),
1299
+			// todo need to add this help info id to the Events_Admin_Page core file so we can access it here.
1300
+			'DTT_ID'                            => $default ? '' : $datetime->ID(),
1301
+		);
1302
+		// need to setup the list items (but only if this isn't a default skeleton setup)
1303
+		if (! $default) {
1304
+			$ticket_row = 1;
1305
+			foreach ($all_tickets as $ticket) {
1306
+				$template_args['datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
1307
+					$datetime_row,
1308
+					$ticket_row,
1309
+					$datetime,
1310
+					$ticket,
1311
+					$datetime_tickets,
1312
+					$default
1313
+				);
1314
+				$ticket_row++;
1315
+			}
1316
+		}
1317
+		// filter template args at this point
1318
+		$template_args = apply_filters(
1319
+			'FHEE__espresso_events_Pricing_Hooks___get_dtt_attached_ticket_row__template_args',
1320
+			$template_args,
1321
+			$datetime_row,
1322
+			$datetime,
1323
+			$datetime_tickets,
1324
+			$all_tickets,
1325
+			$default,
1326
+			$this->_is_creating_event
1327
+		);
1328
+		return EEH_Template::display_template(
1329
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_attached_tickets_row.template.php',
1330
+			$template_args,
1331
+			true
1332
+		);
1333
+	}
1334 1334
 
1335 1335
 
1336
-    /**
1337
-     * @param int         $datetime_row
1338
-     * @param int         $ticket_row
1339
-     * @param EE_Datetime $datetime
1340
-     * @param EE_Ticket   $ticket
1341
-     * @param array       $datetime_tickets
1342
-     * @param bool        $default
1343
-     * @return mixed
1344
-     * @throws DomainException
1345
-     * @throws EE_Error
1346
-     */
1347
-    protected function _get_datetime_tickets_list_item(
1348
-        $datetime_row,
1349
-        $ticket_row,
1350
-        $datetime,
1351
-        $ticket,
1352
-        $datetime_tickets = array(),
1353
-        $default
1354
-    ) {
1355
-        $dtt_tkts = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1356
-            ? $datetime_tickets[ $datetime->ID() ]
1357
-            : array();
1358
-        $display_row = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1359
-        $no_ticket = $default && empty($ticket);
1360
-        $template_args = array(
1361
-            'dtt_row'                 => $default
1362
-                ? 'DTTNUM'
1363
-                : $datetime_row,
1364
-            'tkt_row'                 => $no_ticket
1365
-                ? 'TICKETNUM'
1366
-                : $ticket_row,
1367
-            'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1368
-                ? ' checked="checked"'
1369
-                : '',
1370
-            'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1371
-                ? ' ticket-selected'
1372
-                : '',
1373
-            'TKT_name'                => $no_ticket
1374
-                ? 'TKTNAME'
1375
-                : $ticket->get('TKT_name'),
1376
-            'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1377
-                ? ' tkt-status-' . EE_Ticket::onsale
1378
-                : ' tkt-status-' . $ticket->ticket_status(),
1379
-        );
1380
-        // filter template args
1381
-        $template_args = apply_filters(
1382
-            'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1383
-            $template_args,
1384
-            $datetime_row,
1385
-            $ticket_row,
1386
-            $datetime,
1387
-            $ticket,
1388
-            $datetime_tickets,
1389
-            $default,
1390
-            $this->_is_creating_event
1391
-        );
1392
-        return EEH_Template::display_template(
1393
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1394
-            $template_args,
1395
-            true
1396
-        );
1397
-    }
1336
+	/**
1337
+	 * @param int         $datetime_row
1338
+	 * @param int         $ticket_row
1339
+	 * @param EE_Datetime $datetime
1340
+	 * @param EE_Ticket   $ticket
1341
+	 * @param array       $datetime_tickets
1342
+	 * @param bool        $default
1343
+	 * @return mixed
1344
+	 * @throws DomainException
1345
+	 * @throws EE_Error
1346
+	 */
1347
+	protected function _get_datetime_tickets_list_item(
1348
+		$datetime_row,
1349
+		$ticket_row,
1350
+		$datetime,
1351
+		$ticket,
1352
+		$datetime_tickets = array(),
1353
+		$default
1354
+	) {
1355
+		$dtt_tkts = $datetime instanceof EE_Datetime && isset($datetime_tickets[ $datetime->ID() ])
1356
+			? $datetime_tickets[ $datetime->ID() ]
1357
+			: array();
1358
+		$display_row = $ticket instanceof EE_Ticket ? $ticket->get('TKT_row') : 0;
1359
+		$no_ticket = $default && empty($ticket);
1360
+		$template_args = array(
1361
+			'dtt_row'                 => $default
1362
+				? 'DTTNUM'
1363
+				: $datetime_row,
1364
+			'tkt_row'                 => $no_ticket
1365
+				? 'TICKETNUM'
1366
+				: $ticket_row,
1367
+			'datetime_ticket_checked' => in_array($display_row, $dtt_tkts, true)
1368
+				? ' checked="checked"'
1369
+				: '',
1370
+			'ticket_selected'         => in_array($display_row, $dtt_tkts, true)
1371
+				? ' ticket-selected'
1372
+				: '',
1373
+			'TKT_name'                => $no_ticket
1374
+				? 'TKTNAME'
1375
+				: $ticket->get('TKT_name'),
1376
+			'tkt_status_class'        => $no_ticket || $this->_is_creating_event
1377
+				? ' tkt-status-' . EE_Ticket::onsale
1378
+				: ' tkt-status-' . $ticket->ticket_status(),
1379
+		);
1380
+		// filter template args
1381
+		$template_args = apply_filters(
1382
+			'FHEE__espresso_events_Pricing_Hooks___get_datetime_tickets_list_item__template_args',
1383
+			$template_args,
1384
+			$datetime_row,
1385
+			$ticket_row,
1386
+			$datetime,
1387
+			$ticket,
1388
+			$datetime_tickets,
1389
+			$default,
1390
+			$this->_is_creating_event
1391
+		);
1392
+		return EEH_Template::display_template(
1393
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_dtt_tickets_list.template.php',
1394
+			$template_args,
1395
+			true
1396
+		);
1397
+	}
1398 1398
 
1399 1399
 
1400
-    /**
1401
-     * This generates the ticket row for tickets.
1402
-     * This same method is used to generate both the actual rows and the js skeleton row
1403
-     * (when default === true)
1404
-     *
1405
-     * @param int           $ticket_row       Represents the row number being generated.
1406
-     * @param               $ticket
1407
-     * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1408
-     *                                        or empty for default
1409
-     * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1410
-     * @param bool          $default          Whether default row being generated or not.
1411
-     * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1412
-     *                                        (or empty in the case of defaults)
1413
-     * @return mixed
1414
-     * @throws InvalidArgumentException
1415
-     * @throws InvalidInterfaceException
1416
-     * @throws InvalidDataTypeException
1417
-     * @throws DomainException
1418
-     * @throws EE_Error
1419
-     * @throws ReflectionException
1420
-     */
1421
-    protected function _get_ticket_row(
1422
-        $ticket_row,
1423
-        $ticket,
1424
-        $ticket_datetimes,
1425
-        $all_datetimes,
1426
-        $default = false,
1427
-        $all_tickets = array()
1428
-    ) {
1429
-        // if $ticket is not an instance of EE_Ticket then force default to true.
1430
-        $default = ! $ticket instanceof EE_Ticket ? true : $default;
1431
-        $prices = ! empty($ticket) && ! $default
1432
-            ? $ticket->get_many_related(
1433
-                'Price',
1434
-                array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))
1435
-            )
1436
-            : array();
1437
-        // if there is only one price (which would be the base price)
1438
-        // or NO prices and this ticket is a default ticket,
1439
-        // let's just make sure there are no cached default prices on the object.
1440
-        // This is done by not including any query_params.
1441
-        if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1442
-            $prices = $ticket->prices();
1443
-        }
1444
-        // check if we're dealing with a default ticket in which case
1445
-        // we don't want any starting_ticket_datetime_row values set
1446
-        // (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1447
-        // This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1448
-        $default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1449
-        $tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1450
-            ? $ticket_datetimes[ $ticket->ID() ]
1451
-            : array();
1452
-        $ticket_subtotal = $default ? 0 : $ticket->get_ticket_subtotal();
1453
-        $base_price = $default ? null : $ticket->base_price();
1454
-        $count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1455
-        // breaking out complicated condition for ticket_status
1456
-        if ($default) {
1457
-            $ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1458
-        } else {
1459
-            $ticket_status_class = $ticket->is_default()
1460
-                ? ' tkt-status-' . EE_Ticket::onsale
1461
-                : ' tkt-status-' . $ticket->ticket_status();
1462
-        }
1463
-        // breaking out complicated condition for TKT_taxable
1464
-        if ($default) {
1465
-            $TKT_taxable = '';
1466
-        } else {
1467
-            $TKT_taxable = $ticket->taxable()
1468
-                ? ' checked="checked"'
1469
-                : '';
1470
-        }
1471
-        if ($default) {
1472
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1473
-        } elseif ($ticket->is_default()) {
1474
-            $TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1475
-        } else {
1476
-            $TKT_status = $ticket->ticket_status(true);
1477
-        }
1478
-        if ($default) {
1479
-            $TKT_min = '';
1480
-        } else {
1481
-            $TKT_min = $ticket->min();
1482
-            if ($TKT_min === -1 || $TKT_min === 0) {
1483
-                $TKT_min = '';
1484
-            }
1485
-        }
1486
-        $template_args = array(
1487
-            'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1488
-            'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1489
-            // on initial page load this will always be the correct order.
1490
-            'tkt_status_class'              => $ticket_status_class,
1491
-            'display_edit_tkt_row'          => ' style="display:none;"',
1492
-            'edit_tkt_expanded'             => '',
1493
-            'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1494
-            'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1495
-            'TKT_start_date'                => $default
1496
-                ? ''
1497
-                : $ticket->get_date('TKT_start_date', $this->_date_time_format),
1498
-            'TKT_end_date'                  => $default
1499
-                ? ''
1500
-                : $ticket->get_date('TKT_end_date', $this->_date_time_format),
1501
-            'TKT_status'                    => $TKT_status,
1502
-            'TKT_price'                     => $default
1503
-                ? ''
1504
-                : EEH_Template::format_currency(
1505
-                    $ticket->get_ticket_total_with_taxes(),
1506
-                    false,
1507
-                    false
1508
-                ),
1509
-            'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1510
-            'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1511
-            'TKT_qty'                       => $default
1512
-                ? ''
1513
-                : $ticket->get_pretty('TKT_qty', 'symbol'),
1514
-            'TKT_qty_for_input'             => $default
1515
-                ? ''
1516
-                : $ticket->get_pretty('TKT_qty', 'input'),
1517
-            'TKT_uses'                      => $default
1518
-                ? ''
1519
-                : $ticket->get_pretty('TKT_uses', 'input'),
1520
-            'TKT_min'                       => $TKT_min,
1521
-            'TKT_max'                       => $default
1522
-                ? ''
1523
-                : $ticket->get_pretty('TKT_max', 'input'),
1524
-            'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1525
-            'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1526
-            'TKT_registrations'             => $default
1527
-                ? 0
1528
-                : $ticket->count_registrations(
1529
-                    array(
1530
-                        array(
1531
-                            'STS_ID' => array(
1532
-                                '!=',
1533
-                                EEM_Registration::status_id_incomplete,
1534
-                            ),
1535
-                        ),
1536
-                    )
1537
-                ),
1538
-            'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1539
-            'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1540
-            'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1541
-            'TKT_required'                  => $default ? 0 : $ticket->required(),
1542
-            'TKT_is_default_selector'       => '',
1543
-            'ticket_price_rows'             => '',
1544
-            'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1545
-                ? ''
1546
-                : $base_price->get_pretty('PRC_amount', 'localized_float'),
1547
-            'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1548
-            'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1549
-                ? ''
1550
-                : ' style="display:none;"',
1551
-            'show_price_mod_button'         => count($prices) > 1
1552
-                                               || ($default && $count_price_mods > 0)
1553
-                                               || (! $default && $ticket->deleted())
1554
-                ? ' style="display:none;"'
1555
-                : '',
1556
-            'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1557
-            'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1558
-            'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1559
-            'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1560
-            'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1561
-            'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1562
-            'TKT_taxable'                   => $TKT_taxable,
1563
-            'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1564
-                ? ''
1565
-                : ' style="display:none"',
1566
-            'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1567
-            'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1568
-                $ticket_subtotal,
1569
-                false,
1570
-                false
1571
-            ),
1572
-            'TKT_subtotal_amount'           => $ticket_subtotal,
1573
-            'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1574
-            'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1575
-            'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1576
-                ? ' ticket-archived'
1577
-                : '',
1578
-            'trash_icon'                    => $ticket instanceof EE_Ticket
1579
-                                               && $ticket->deleted()
1580
-                                               && ! $ticket->is_permanently_deleteable()
1581
-                ? 'ee-lock-icon '
1582
-                : 'trash-icon dashicons dashicons-post-trash clickable',
1583
-            'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1584
-                ? ''
1585
-                : 'clone-icon ee-icon ee-icon-clone clickable',
1586
-        );
1587
-        $template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1588
-            ? ' style="display:none"'
1589
-            : '';
1590
-        // handle rows that should NOT be empty
1591
-        if (empty($template_args['TKT_start_date'])) {
1592
-            // if empty then the start date will be now.
1593
-            $template_args['TKT_start_date'] = date(
1594
-                $this->_date_time_format,
1595
-                current_time('timestamp')
1596
-            );
1597
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1598
-        }
1599
-        if (empty($template_args['TKT_end_date'])) {
1600
-            // get the earliest datetime (if present);
1601
-            $earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1602
-                ? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1603
-                    'Datetime',
1604
-                    array('order_by' => array('DTT_EVT_start' => 'ASC'))
1605
-                )
1606
-                : null;
1607
-            if (! empty($earliest_dtt)) {
1608
-                $template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1609
-                    'DTT_EVT_start',
1610
-                    $this->_date_time_format
1611
-                );
1612
-            } else {
1613
-                // default so let's just use what's been set for the default date-time which is 30 days from now.
1614
-                $template_args['TKT_end_date'] = date(
1615
-                    $this->_date_time_format,
1616
-                    mktime(
1617
-                        24,
1618
-                        0,
1619
-                        0,
1620
-                        date('m'),
1621
-                        date('d') + 29,
1622
-                        date('Y')
1623
-                    )
1624
-                );
1625
-            }
1626
-            $template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1627
-        }
1628
-        // generate ticket_datetime items
1629
-        if (! $default) {
1630
-            $datetime_row = 1;
1631
-            foreach ($all_datetimes as $datetime) {
1632
-                $template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1633
-                    $datetime_row,
1634
-                    $ticket_row,
1635
-                    $datetime,
1636
-                    $ticket,
1637
-                    $ticket_datetimes,
1638
-                    $default
1639
-                );
1640
-                $datetime_row++;
1641
-            }
1642
-        }
1643
-        $price_row = 1;
1644
-        foreach ($prices as $price) {
1645
-            if (! $price instanceof EE_Price) {
1646
-                continue;
1647
-            }
1648
-            if ($price->is_base_price()) {
1649
-                $price_row++;
1650
-                continue;
1651
-            }
1652
-            $show_trash = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1653
-            $show_create = ! (count($prices) > 1 && count($prices) !== $price_row);
1654
-            $template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1655
-                $ticket_row,
1656
-                $price_row,
1657
-                $price,
1658
-                $default,
1659
-                $ticket,
1660
-                $show_trash,
1661
-                $show_create
1662
-            );
1663
-            $price_row++;
1664
-        }
1665
-        // filter $template_args
1666
-        $template_args = apply_filters(
1667
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1668
-            $template_args,
1669
-            $ticket_row,
1670
-            $ticket,
1671
-            $ticket_datetimes,
1672
-            $all_datetimes,
1673
-            $default,
1674
-            $all_tickets,
1675
-            $this->_is_creating_event
1676
-        );
1677
-        return EEH_Template::display_template(
1678
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1679
-            $template_args,
1680
-            true
1681
-        );
1682
-    }
1400
+	/**
1401
+	 * This generates the ticket row for tickets.
1402
+	 * This same method is used to generate both the actual rows and the js skeleton row
1403
+	 * (when default === true)
1404
+	 *
1405
+	 * @param int           $ticket_row       Represents the row number being generated.
1406
+	 * @param               $ticket
1407
+	 * @param EE_Datetime[] $ticket_datetimes Either an array of all datetimes on all tickets indexed by each ticket
1408
+	 *                                        or empty for default
1409
+	 * @param EE_Datetime[] $all_datetimes    All Datetimes on the event or empty for default.
1410
+	 * @param bool          $default          Whether default row being generated or not.
1411
+	 * @param EE_Ticket[]   $all_tickets      This is an array of all tickets attached to the event
1412
+	 *                                        (or empty in the case of defaults)
1413
+	 * @return mixed
1414
+	 * @throws InvalidArgumentException
1415
+	 * @throws InvalidInterfaceException
1416
+	 * @throws InvalidDataTypeException
1417
+	 * @throws DomainException
1418
+	 * @throws EE_Error
1419
+	 * @throws ReflectionException
1420
+	 */
1421
+	protected function _get_ticket_row(
1422
+		$ticket_row,
1423
+		$ticket,
1424
+		$ticket_datetimes,
1425
+		$all_datetimes,
1426
+		$default = false,
1427
+		$all_tickets = array()
1428
+	) {
1429
+		// if $ticket is not an instance of EE_Ticket then force default to true.
1430
+		$default = ! $ticket instanceof EE_Ticket ? true : $default;
1431
+		$prices = ! empty($ticket) && ! $default
1432
+			? $ticket->get_many_related(
1433
+				'Price',
1434
+				array('default_where_conditions' => 'none', 'order_by' => array('PRC_order' => 'ASC'))
1435
+			)
1436
+			: array();
1437
+		// if there is only one price (which would be the base price)
1438
+		// or NO prices and this ticket is a default ticket,
1439
+		// let's just make sure there are no cached default prices on the object.
1440
+		// This is done by not including any query_params.
1441
+		if ($ticket instanceof EE_Ticket && $ticket->is_default() && (count($prices) === 1 || empty($prices))) {
1442
+			$prices = $ticket->prices();
1443
+		}
1444
+		// check if we're dealing with a default ticket in which case
1445
+		// we don't want any starting_ticket_datetime_row values set
1446
+		// (otherwise there won't be any new relationships created for tickets based off of the default ticket).
1447
+		// This will future proof in case there is ever any behaviour change between what the primary_key defaults to.
1448
+		$default_dtt = $default || ($ticket instanceof EE_Ticket && $ticket->is_default());
1449
+		$tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
1450
+			? $ticket_datetimes[ $ticket->ID() ]
1451
+			: array();
1452
+		$ticket_subtotal = $default ? 0 : $ticket->get_ticket_subtotal();
1453
+		$base_price = $default ? null : $ticket->base_price();
1454
+		$count_price_mods = EEM_Price::instance()->get_all_default_prices(true);
1455
+		// breaking out complicated condition for ticket_status
1456
+		if ($default) {
1457
+			$ticket_status_class = ' tkt-status-' . EE_Ticket::onsale;
1458
+		} else {
1459
+			$ticket_status_class = $ticket->is_default()
1460
+				? ' tkt-status-' . EE_Ticket::onsale
1461
+				: ' tkt-status-' . $ticket->ticket_status();
1462
+		}
1463
+		// breaking out complicated condition for TKT_taxable
1464
+		if ($default) {
1465
+			$TKT_taxable = '';
1466
+		} else {
1467
+			$TKT_taxable = $ticket->taxable()
1468
+				? ' checked="checked"'
1469
+				: '';
1470
+		}
1471
+		if ($default) {
1472
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1473
+		} elseif ($ticket->is_default()) {
1474
+			$TKT_status = EEH_Template::pretty_status(EE_Ticket::onsale, false, 'sentence');
1475
+		} else {
1476
+			$TKT_status = $ticket->ticket_status(true);
1477
+		}
1478
+		if ($default) {
1479
+			$TKT_min = '';
1480
+		} else {
1481
+			$TKT_min = $ticket->min();
1482
+			if ($TKT_min === -1 || $TKT_min === 0) {
1483
+				$TKT_min = '';
1484
+			}
1485
+		}
1486
+		$template_args = array(
1487
+			'tkt_row'                       => $default ? 'TICKETNUM' : $ticket_row,
1488
+			'TKT_order'                     => $default ? 'TICKETNUM' : $ticket_row,
1489
+			// on initial page load this will always be the correct order.
1490
+			'tkt_status_class'              => $ticket_status_class,
1491
+			'display_edit_tkt_row'          => ' style="display:none;"',
1492
+			'edit_tkt_expanded'             => '',
1493
+			'edit_tickets_name'             => $default ? 'TICKETNAMEATTR' : 'edit_tickets',
1494
+			'TKT_name'                      => $default ? '' : $ticket->get_f('TKT_name'),
1495
+			'TKT_start_date'                => $default
1496
+				? ''
1497
+				: $ticket->get_date('TKT_start_date', $this->_date_time_format),
1498
+			'TKT_end_date'                  => $default
1499
+				? ''
1500
+				: $ticket->get_date('TKT_end_date', $this->_date_time_format),
1501
+			'TKT_status'                    => $TKT_status,
1502
+			'TKT_price'                     => $default
1503
+				? ''
1504
+				: EEH_Template::format_currency(
1505
+					$ticket->get_ticket_total_with_taxes(),
1506
+					false,
1507
+					false
1508
+				),
1509
+			'TKT_price_code'                => EE_Registry::instance()->CFG->currency->code,
1510
+			'TKT_price_amount'              => $default ? 0 : $ticket_subtotal,
1511
+			'TKT_qty'                       => $default
1512
+				? ''
1513
+				: $ticket->get_pretty('TKT_qty', 'symbol'),
1514
+			'TKT_qty_for_input'             => $default
1515
+				? ''
1516
+				: $ticket->get_pretty('TKT_qty', 'input'),
1517
+			'TKT_uses'                      => $default
1518
+				? ''
1519
+				: $ticket->get_pretty('TKT_uses', 'input'),
1520
+			'TKT_min'                       => $TKT_min,
1521
+			'TKT_max'                       => $default
1522
+				? ''
1523
+				: $ticket->get_pretty('TKT_max', 'input'),
1524
+			'TKT_sold'                      => $default ? 0 : $ticket->tickets_sold('ticket'),
1525
+			'TKT_reserved'                  => $default ? 0 : $ticket->reserved(),
1526
+			'TKT_registrations'             => $default
1527
+				? 0
1528
+				: $ticket->count_registrations(
1529
+					array(
1530
+						array(
1531
+							'STS_ID' => array(
1532
+								'!=',
1533
+								EEM_Registration::status_id_incomplete,
1534
+							),
1535
+						),
1536
+					)
1537
+				),
1538
+			'TKT_ID'                        => $default ? 0 : $ticket->ID(),
1539
+			'TKT_description'               => $default ? '' : $ticket->get_f('TKT_description'),
1540
+			'TKT_is_default'                => $default ? 0 : $ticket->is_default(),
1541
+			'TKT_required'                  => $default ? 0 : $ticket->required(),
1542
+			'TKT_is_default_selector'       => '',
1543
+			'ticket_price_rows'             => '',
1544
+			'TKT_base_price'                => $default || ! $base_price instanceof EE_Price
1545
+				? ''
1546
+				: $base_price->get_pretty('PRC_amount', 'localized_float'),
1547
+			'TKT_base_price_ID'             => $default || ! $base_price instanceof EE_Price ? 0 : $base_price->ID(),
1548
+			'show_price_modifier'           => count($prices) > 1 || ($default && $count_price_mods > 0)
1549
+				? ''
1550
+				: ' style="display:none;"',
1551
+			'show_price_mod_button'         => count($prices) > 1
1552
+											   || ($default && $count_price_mods > 0)
1553
+											   || (! $default && $ticket->deleted())
1554
+				? ' style="display:none;"'
1555
+				: '',
1556
+			'total_price_rows'              => count($prices) > 1 ? count($prices) : 1,
1557
+			'ticket_datetimes_list'         => $default ? '<li class="hidden"></li>' : '',
1558
+			'starting_ticket_datetime_rows' => $default || $default_dtt ? '' : implode(',', $tkt_datetimes),
1559
+			'ticket_datetime_rows'          => $default ? '' : implode(',', $tkt_datetimes),
1560
+			'existing_ticket_price_ids'     => $default ? '' : implode(',', array_keys($prices)),
1561
+			'ticket_template_id'            => $default ? 0 : $ticket->get('TTM_ID'),
1562
+			'TKT_taxable'                   => $TKT_taxable,
1563
+			'display_subtotal'              => $ticket instanceof EE_Ticket && $ticket->taxable()
1564
+				? ''
1565
+				: ' style="display:none"',
1566
+			'price_currency_symbol'         => EE_Registry::instance()->CFG->currency->sign,
1567
+			'TKT_subtotal_amount_display'   => EEH_Template::format_currency(
1568
+				$ticket_subtotal,
1569
+				false,
1570
+				false
1571
+			),
1572
+			'TKT_subtotal_amount'           => $ticket_subtotal,
1573
+			'tax_rows'                      => $this->_get_tax_rows($ticket_row, $ticket),
1574
+			'disabled'                      => $ticket instanceof EE_Ticket && $ticket->deleted(),
1575
+			'ticket_archive_class'          => $ticket instanceof EE_Ticket && $ticket->deleted()
1576
+				? ' ticket-archived'
1577
+				: '',
1578
+			'trash_icon'                    => $ticket instanceof EE_Ticket
1579
+											   && $ticket->deleted()
1580
+											   && ! $ticket->is_permanently_deleteable()
1581
+				? 'ee-lock-icon '
1582
+				: 'trash-icon dashicons dashicons-post-trash clickable',
1583
+			'clone_icon'                    => $ticket instanceof EE_Ticket && $ticket->deleted()
1584
+				? ''
1585
+				: 'clone-icon ee-icon ee-icon-clone clickable',
1586
+		);
1587
+		$template_args['trash_hidden'] = count($all_tickets) === 1 && $template_args['trash_icon'] !== 'ee-lock-icon'
1588
+			? ' style="display:none"'
1589
+			: '';
1590
+		// handle rows that should NOT be empty
1591
+		if (empty($template_args['TKT_start_date'])) {
1592
+			// if empty then the start date will be now.
1593
+			$template_args['TKT_start_date'] = date(
1594
+				$this->_date_time_format,
1595
+				current_time('timestamp')
1596
+			);
1597
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1598
+		}
1599
+		if (empty($template_args['TKT_end_date'])) {
1600
+			// get the earliest datetime (if present);
1601
+			$earliest_dtt = $this->_adminpage_obj->get_cpt_model_obj()->ID() > 0
1602
+				? $this->_adminpage_obj->get_cpt_model_obj()->get_first_related(
1603
+					'Datetime',
1604
+					array('order_by' => array('DTT_EVT_start' => 'ASC'))
1605
+				)
1606
+				: null;
1607
+			if (! empty($earliest_dtt)) {
1608
+				$template_args['TKT_end_date'] = $earliest_dtt->get_datetime(
1609
+					'DTT_EVT_start',
1610
+					$this->_date_time_format
1611
+				);
1612
+			} else {
1613
+				// default so let's just use what's been set for the default date-time which is 30 days from now.
1614
+				$template_args['TKT_end_date'] = date(
1615
+					$this->_date_time_format,
1616
+					mktime(
1617
+						24,
1618
+						0,
1619
+						0,
1620
+						date('m'),
1621
+						date('d') + 29,
1622
+						date('Y')
1623
+					)
1624
+				);
1625
+			}
1626
+			$template_args['tkt_status_class'] = ' tkt-status-' . EE_Ticket::onsale;
1627
+		}
1628
+		// generate ticket_datetime items
1629
+		if (! $default) {
1630
+			$datetime_row = 1;
1631
+			foreach ($all_datetimes as $datetime) {
1632
+				$template_args['ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
1633
+					$datetime_row,
1634
+					$ticket_row,
1635
+					$datetime,
1636
+					$ticket,
1637
+					$ticket_datetimes,
1638
+					$default
1639
+				);
1640
+				$datetime_row++;
1641
+			}
1642
+		}
1643
+		$price_row = 1;
1644
+		foreach ($prices as $price) {
1645
+			if (! $price instanceof EE_Price) {
1646
+				continue;
1647
+			}
1648
+			if ($price->is_base_price()) {
1649
+				$price_row++;
1650
+				continue;
1651
+			}
1652
+			$show_trash = ! ((count($prices) > 1 && $price_row === 1) || count($prices) === 1);
1653
+			$show_create = ! (count($prices) > 1 && count($prices) !== $price_row);
1654
+			$template_args['ticket_price_rows'] .= $this->_get_ticket_price_row(
1655
+				$ticket_row,
1656
+				$price_row,
1657
+				$price,
1658
+				$default,
1659
+				$ticket,
1660
+				$show_trash,
1661
+				$show_create
1662
+			);
1663
+			$price_row++;
1664
+		}
1665
+		// filter $template_args
1666
+		$template_args = apply_filters(
1667
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_row__template_args',
1668
+			$template_args,
1669
+			$ticket_row,
1670
+			$ticket,
1671
+			$ticket_datetimes,
1672
+			$all_datetimes,
1673
+			$default,
1674
+			$all_tickets,
1675
+			$this->_is_creating_event
1676
+		);
1677
+		return EEH_Template::display_template(
1678
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_row.template.php',
1679
+			$template_args,
1680
+			true
1681
+		);
1682
+	}
1683 1683
 
1684 1684
 
1685
-    /**
1686
-     * @param int            $ticket_row
1687
-     * @param EE_Ticket|null $ticket
1688
-     * @return string
1689
-     * @throws DomainException
1690
-     * @throws EE_Error
1691
-     */
1692
-    protected function _get_tax_rows($ticket_row, $ticket)
1693
-    {
1694
-        $tax_rows = '';
1695
-        /** @var EE_Price[] $taxes */
1696
-        $taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1697
-        foreach ($taxes as $tax) {
1698
-            $tax_added = $this->_get_tax_added($tax, $ticket);
1699
-            $template_args = array(
1700
-                'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1701
-                    ? ''
1702
-                    : ' style="display:none;"',
1703
-                'tax_id'            => $tax->ID(),
1704
-                'tkt_row'           => $ticket_row,
1705
-                'tax_label'         => $tax->get('PRC_name'),
1706
-                'tax_added'         => $tax_added,
1707
-                'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1708
-                'tax_amount'        => $tax->get('PRC_amount'),
1709
-            );
1710
-            $template_args = apply_filters(
1711
-                'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1712
-                $template_args,
1713
-                $ticket_row,
1714
-                $ticket,
1715
-                $this->_is_creating_event
1716
-            );
1717
-            $tax_rows .= EEH_Template::display_template(
1718
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1719
-                $template_args,
1720
-                true
1721
-            );
1722
-        }
1723
-        return $tax_rows;
1724
-    }
1685
+	/**
1686
+	 * @param int            $ticket_row
1687
+	 * @param EE_Ticket|null $ticket
1688
+	 * @return string
1689
+	 * @throws DomainException
1690
+	 * @throws EE_Error
1691
+	 */
1692
+	protected function _get_tax_rows($ticket_row, $ticket)
1693
+	{
1694
+		$tax_rows = '';
1695
+		/** @var EE_Price[] $taxes */
1696
+		$taxes = empty($ticket) ? EE_Taxes::get_taxes_for_admin() : $ticket->get_ticket_taxes_for_admin();
1697
+		foreach ($taxes as $tax) {
1698
+			$tax_added = $this->_get_tax_added($tax, $ticket);
1699
+			$template_args = array(
1700
+				'display_tax'       => ! empty($ticket) && $ticket->get('TKT_taxable')
1701
+					? ''
1702
+					: ' style="display:none;"',
1703
+				'tax_id'            => $tax->ID(),
1704
+				'tkt_row'           => $ticket_row,
1705
+				'tax_label'         => $tax->get('PRC_name'),
1706
+				'tax_added'         => $tax_added,
1707
+				'tax_added_display' => EEH_Template::format_currency($tax_added, false, false),
1708
+				'tax_amount'        => $tax->get('PRC_amount'),
1709
+			);
1710
+			$template_args = apply_filters(
1711
+				'FHEE__espresso_events_Pricing_Hooks___get_tax_rows__template_args',
1712
+				$template_args,
1713
+				$ticket_row,
1714
+				$ticket,
1715
+				$this->_is_creating_event
1716
+			);
1717
+			$tax_rows .= EEH_Template::display_template(
1718
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_tax_row.template.php',
1719
+				$template_args,
1720
+				true
1721
+			);
1722
+		}
1723
+		return $tax_rows;
1724
+	}
1725 1725
 
1726 1726
 
1727
-    /**
1728
-     * @param EE_Price       $tax
1729
-     * @param EE_Ticket|null $ticket
1730
-     * @return float|int
1731
-     * @throws EE_Error
1732
-     */
1733
-    protected function _get_tax_added(EE_Price $tax, $ticket)
1734
-    {
1735
-        $subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1736
-        return $subtotal * $tax->get('PRC_amount') / 100;
1737
-    }
1727
+	/**
1728
+	 * @param EE_Price       $tax
1729
+	 * @param EE_Ticket|null $ticket
1730
+	 * @return float|int
1731
+	 * @throws EE_Error
1732
+	 */
1733
+	protected function _get_tax_added(EE_Price $tax, $ticket)
1734
+	{
1735
+		$subtotal = empty($ticket) ? 0 : $ticket->get_ticket_subtotal();
1736
+		return $subtotal * $tax->get('PRC_amount') / 100;
1737
+	}
1738 1738
 
1739 1739
 
1740
-    /**
1741
-     * @param int            $ticket_row
1742
-     * @param int            $price_row
1743
-     * @param EE_Price|null  $price
1744
-     * @param bool           $default
1745
-     * @param EE_Ticket|null $ticket
1746
-     * @param bool           $show_trash
1747
-     * @param bool           $show_create
1748
-     * @return mixed
1749
-     * @throws InvalidArgumentException
1750
-     * @throws InvalidInterfaceException
1751
-     * @throws InvalidDataTypeException
1752
-     * @throws DomainException
1753
-     * @throws EE_Error
1754
-     * @throws ReflectionException
1755
-     */
1756
-    protected function _get_ticket_price_row(
1757
-        $ticket_row,
1758
-        $price_row,
1759
-        $price,
1760
-        $default,
1761
-        $ticket,
1762
-        $show_trash = true,
1763
-        $show_create = true
1764
-    ) {
1765
-        $send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1766
-        $template_args = array(
1767
-            'tkt_row'               => $default && empty($ticket)
1768
-                ? 'TICKETNUM'
1769
-                : $ticket_row,
1770
-            'PRC_order'             => $default && empty($price)
1771
-                ? 'PRICENUM'
1772
-                : $price_row,
1773
-            'edit_prices_name'      => $default && empty($price)
1774
-                ? 'PRICENAMEATTR'
1775
-                : 'edit_prices',
1776
-            'price_type_selector'   => $default && empty($price)
1777
-                ? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1778
-                : $this->_get_price_type_selector(
1779
-                    $ticket_row,
1780
-                    $price_row,
1781
-                    $price,
1782
-                    $default,
1783
-                    $send_disabled
1784
-                ),
1785
-            'PRC_ID'                => $default && empty($price)
1786
-                ? 0
1787
-                : $price->ID(),
1788
-            'PRC_is_default'        => $default && empty($price)
1789
-                ? 0
1790
-                : $price->get('PRC_is_default'),
1791
-            'PRC_name'              => $default && empty($price)
1792
-                ? ''
1793
-                : $price->get('PRC_name'),
1794
-            'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1795
-            'show_plus_or_minus'    => $default && empty($price)
1796
-                ? ''
1797
-                : ' style="display:none;"',
1798
-            'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1799
-                ? ' style="display:none;"'
1800
-                : '',
1801
-            'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1802
-                ? ' style="display:none;"'
1803
-                : '',
1804
-            'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1805
-                ? ' style="display:none"'
1806
-                : '',
1807
-            'PRC_amount'            => $default && empty($price)
1808
-                ? 0
1809
-                : $price->get_pretty('PRC_amount', 'localized_float'),
1810
-            'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1811
-                ? ' style="display:none;"'
1812
-                : '',
1813
-            'show_trash_icon'       => $show_trash
1814
-                ? ''
1815
-                : ' style="display:none;"',
1816
-            'show_create_button'    => $show_create
1817
-                ? ''
1818
-                : ' style="display:none;"',
1819
-            'PRC_desc'              => $default && empty($price)
1820
-                ? ''
1821
-                : $price->get('PRC_desc'),
1822
-            'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1823
-        );
1824
-        $template_args = apply_filters(
1825
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1826
-            $template_args,
1827
-            $ticket_row,
1828
-            $price_row,
1829
-            $price,
1830
-            $default,
1831
-            $ticket,
1832
-            $show_trash,
1833
-            $show_create,
1834
-            $this->_is_creating_event
1835
-        );
1836
-        return EEH_Template::display_template(
1837
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1838
-            $template_args,
1839
-            true
1840
-        );
1841
-    }
1740
+	/**
1741
+	 * @param int            $ticket_row
1742
+	 * @param int            $price_row
1743
+	 * @param EE_Price|null  $price
1744
+	 * @param bool           $default
1745
+	 * @param EE_Ticket|null $ticket
1746
+	 * @param bool           $show_trash
1747
+	 * @param bool           $show_create
1748
+	 * @return mixed
1749
+	 * @throws InvalidArgumentException
1750
+	 * @throws InvalidInterfaceException
1751
+	 * @throws InvalidDataTypeException
1752
+	 * @throws DomainException
1753
+	 * @throws EE_Error
1754
+	 * @throws ReflectionException
1755
+	 */
1756
+	protected function _get_ticket_price_row(
1757
+		$ticket_row,
1758
+		$price_row,
1759
+		$price,
1760
+		$default,
1761
+		$ticket,
1762
+		$show_trash = true,
1763
+		$show_create = true
1764
+	) {
1765
+		$send_disabled = ! empty($ticket) && $ticket->get('TKT_deleted');
1766
+		$template_args = array(
1767
+			'tkt_row'               => $default && empty($ticket)
1768
+				? 'TICKETNUM'
1769
+				: $ticket_row,
1770
+			'PRC_order'             => $default && empty($price)
1771
+				? 'PRICENUM'
1772
+				: $price_row,
1773
+			'edit_prices_name'      => $default && empty($price)
1774
+				? 'PRICENAMEATTR'
1775
+				: 'edit_prices',
1776
+			'price_type_selector'   => $default && empty($price)
1777
+				? $this->_get_base_price_template($ticket_row, $price_row, $price, $default)
1778
+				: $this->_get_price_type_selector(
1779
+					$ticket_row,
1780
+					$price_row,
1781
+					$price,
1782
+					$default,
1783
+					$send_disabled
1784
+				),
1785
+			'PRC_ID'                => $default && empty($price)
1786
+				? 0
1787
+				: $price->ID(),
1788
+			'PRC_is_default'        => $default && empty($price)
1789
+				? 0
1790
+				: $price->get('PRC_is_default'),
1791
+			'PRC_name'              => $default && empty($price)
1792
+				? ''
1793
+				: $price->get('PRC_name'),
1794
+			'price_currency_symbol' => EE_Registry::instance()->CFG->currency->sign,
1795
+			'show_plus_or_minus'    => $default && empty($price)
1796
+				? ''
1797
+				: ' style="display:none;"',
1798
+			'show_plus'             => ($default && empty($price)) || ($price->is_discount() || $price->is_base_price())
1799
+				? ' style="display:none;"'
1800
+				: '',
1801
+			'show_minus'            => ($default && empty($price)) || ! $price->is_discount()
1802
+				? ' style="display:none;"'
1803
+				: '',
1804
+			'show_currency_symbol'  => ($default && empty($price)) || $price->is_percent()
1805
+				? ' style="display:none"'
1806
+				: '',
1807
+			'PRC_amount'            => $default && empty($price)
1808
+				? 0
1809
+				: $price->get_pretty('PRC_amount', 'localized_float'),
1810
+			'show_percentage'       => ($default && empty($price)) || ! $price->is_percent()
1811
+				? ' style="display:none;"'
1812
+				: '',
1813
+			'show_trash_icon'       => $show_trash
1814
+				? ''
1815
+				: ' style="display:none;"',
1816
+			'show_create_button'    => $show_create
1817
+				? ''
1818
+				: ' style="display:none;"',
1819
+			'PRC_desc'              => $default && empty($price)
1820
+				? ''
1821
+				: $price->get('PRC_desc'),
1822
+			'disabled'              => ! empty($ticket) && $ticket->get('TKT_deleted'),
1823
+		);
1824
+		$template_args = apply_filters(
1825
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_price_row__template_args',
1826
+			$template_args,
1827
+			$ticket_row,
1828
+			$price_row,
1829
+			$price,
1830
+			$default,
1831
+			$ticket,
1832
+			$show_trash,
1833
+			$show_create,
1834
+			$this->_is_creating_event
1835
+		);
1836
+		return EEH_Template::display_template(
1837
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_price_row.template.php',
1838
+			$template_args,
1839
+			true
1840
+		);
1841
+	}
1842 1842
 
1843 1843
 
1844
-    /**
1845
-     * @param int      $ticket_row
1846
-     * @param int      $price_row
1847
-     * @param EE_Price $price
1848
-     * @param bool     $default
1849
-     * @param bool     $disabled
1850
-     * @return mixed
1851
-     * @throws ReflectionException
1852
-     * @throws InvalidArgumentException
1853
-     * @throws InvalidInterfaceException
1854
-     * @throws InvalidDataTypeException
1855
-     * @throws DomainException
1856
-     * @throws EE_Error
1857
-     */
1858
-    protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1859
-    {
1860
-        if ($price->is_base_price()) {
1861
-            return $this->_get_base_price_template(
1862
-                $ticket_row,
1863
-                $price_row,
1864
-                $price,
1865
-                $default
1866
-            );
1867
-        }
1868
-        return $this->_get_price_modifier_template(
1869
-            $ticket_row,
1870
-            $price_row,
1871
-            $price,
1872
-            $default,
1873
-            $disabled
1874
-        );
1875
-    }
1844
+	/**
1845
+	 * @param int      $ticket_row
1846
+	 * @param int      $price_row
1847
+	 * @param EE_Price $price
1848
+	 * @param bool     $default
1849
+	 * @param bool     $disabled
1850
+	 * @return mixed
1851
+	 * @throws ReflectionException
1852
+	 * @throws InvalidArgumentException
1853
+	 * @throws InvalidInterfaceException
1854
+	 * @throws InvalidDataTypeException
1855
+	 * @throws DomainException
1856
+	 * @throws EE_Error
1857
+	 */
1858
+	protected function _get_price_type_selector($ticket_row, $price_row, $price, $default, $disabled = false)
1859
+	{
1860
+		if ($price->is_base_price()) {
1861
+			return $this->_get_base_price_template(
1862
+				$ticket_row,
1863
+				$price_row,
1864
+				$price,
1865
+				$default
1866
+			);
1867
+		}
1868
+		return $this->_get_price_modifier_template(
1869
+			$ticket_row,
1870
+			$price_row,
1871
+			$price,
1872
+			$default,
1873
+			$disabled
1874
+		);
1875
+	}
1876 1876
 
1877 1877
 
1878
-    /**
1879
-     * @param int      $ticket_row
1880
-     * @param int      $price_row
1881
-     * @param EE_Price $price
1882
-     * @param bool     $default
1883
-     * @return mixed
1884
-     * @throws DomainException
1885
-     * @throws EE_Error
1886
-     */
1887
-    protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1888
-    {
1889
-        $template_args = array(
1890
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1891
-            'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1892
-            'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1893
-            'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1894
-            'price_selected_operator'   => '+',
1895
-            'price_selected_is_percent' => 0,
1896
-        );
1897
-        $template_args = apply_filters(
1898
-            'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1899
-            $template_args,
1900
-            $ticket_row,
1901
-            $price_row,
1902
-            $price,
1903
-            $default,
1904
-            $this->_is_creating_event
1905
-        );
1906
-        return EEH_Template::display_template(
1907
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1908
-            $template_args,
1909
-            true
1910
-        );
1911
-    }
1878
+	/**
1879
+	 * @param int      $ticket_row
1880
+	 * @param int      $price_row
1881
+	 * @param EE_Price $price
1882
+	 * @param bool     $default
1883
+	 * @return mixed
1884
+	 * @throws DomainException
1885
+	 * @throws EE_Error
1886
+	 */
1887
+	protected function _get_base_price_template($ticket_row, $price_row, $price, $default)
1888
+	{
1889
+		$template_args = array(
1890
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1891
+			'PRC_order'                 => $default && empty($price) ? 'PRICENUM' : $price_row,
1892
+			'PRT_ID'                    => $default && empty($price) ? 1 : $price->get('PRT_ID'),
1893
+			'PRT_name'                  => esc_html__('Price', 'event_espresso'),
1894
+			'price_selected_operator'   => '+',
1895
+			'price_selected_is_percent' => 0,
1896
+		);
1897
+		$template_args = apply_filters(
1898
+			'FHEE__espresso_events_Pricing_Hooks___get_base_price_template__template_args',
1899
+			$template_args,
1900
+			$ticket_row,
1901
+			$price_row,
1902
+			$price,
1903
+			$default,
1904
+			$this->_is_creating_event
1905
+		);
1906
+		return EEH_Template::display_template(
1907
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_type_base.template.php',
1908
+			$template_args,
1909
+			true
1910
+		);
1911
+	}
1912 1912
 
1913 1913
 
1914
-    /**
1915
-     * @param int      $ticket_row
1916
-     * @param int      $price_row
1917
-     * @param EE_Price $price
1918
-     * @param bool     $default
1919
-     * @param bool     $disabled
1920
-     * @return mixed
1921
-     * @throws ReflectionException
1922
-     * @throws InvalidArgumentException
1923
-     * @throws InvalidInterfaceException
1924
-     * @throws InvalidDataTypeException
1925
-     * @throws DomainException
1926
-     * @throws EE_Error
1927
-     */
1928
-    protected function _get_price_modifier_template(
1929
-        $ticket_row,
1930
-        $price_row,
1931
-        $price,
1932
-        $default,
1933
-        $disabled = false
1934
-    ) {
1935
-        $select_name = $default && ! $price instanceof EE_Price
1936
-            ? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1937
-            : 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1938
-        /** @var EEM_Price_Type $price_type_model */
1939
-        $price_type_model = EE_Registry::instance()->load_model('Price_Type');
1940
-        $price_types = $price_type_model->get_all(array(
1941
-            array(
1942
-                'OR' => array(
1943
-                    'PBT_ID'  => '2',
1944
-                    'PBT_ID*' => '3',
1945
-                ),
1946
-            ),
1947
-        ));
1948
-        $all_price_types = $default && ! $price instanceof EE_Price
1949
-            ? array(esc_html__('Select Modifier', 'event_espresso'))
1950
-            : array();
1951
-        $selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1952
-        $price_option_spans = '';
1953
-        // setup price types for selector
1954
-        foreach ($price_types as $price_type) {
1955
-            if (! $price_type instanceof EE_Price_Type) {
1956
-                continue;
1957
-            }
1958
-            $all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1959
-            // while we're in the loop let's setup the option spans used by js
1960
-            $span_args = array(
1961
-                'PRT_ID'         => $price_type->ID(),
1962
-                'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1963
-                'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1964
-            );
1965
-            $price_option_spans .= EEH_Template::display_template(
1966
-                PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1967
-                $span_args,
1968
-                true
1969
-            );
1970
-        }
1971
-        $select_name = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1972
-            : $select_name;
1973
-        $select_input = new EE_Select_Input(
1974
-            $all_price_types,
1975
-            array(
1976
-                'default'               => $selected_price_type_id,
1977
-                'html_name'             => $select_name,
1978
-                'html_class'            => 'edit-price-PRT_ID',
1979
-                'other_html_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1980
-            )
1981
-        );
1982
-        $price_selected_operator = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1983
-        $price_selected_operator = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
1984
-        $price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
1985
-        $price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
1986
-        $template_args = array(
1987
-            'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1988
-            'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
1989
-            'price_modifier_selector'   => $select_input->get_html_for_input(),
1990
-            'main_name'                 => $select_name,
1991
-            'selected_price_type_id'    => $selected_price_type_id,
1992
-            'price_option_spans'        => $price_option_spans,
1993
-            'price_selected_operator'   => $price_selected_operator,
1994
-            'price_selected_is_percent' => $price_selected_is_percent,
1995
-            'disabled'                  => $disabled,
1996
-        );
1997
-        $template_args = apply_filters(
1998
-            'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1999
-            $template_args,
2000
-            $ticket_row,
2001
-            $price_row,
2002
-            $price,
2003
-            $default,
2004
-            $disabled,
2005
-            $this->_is_creating_event
2006
-        );
2007
-        return EEH_Template::display_template(
2008
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2009
-            $template_args,
2010
-            true
2011
-        );
2012
-    }
1914
+	/**
1915
+	 * @param int      $ticket_row
1916
+	 * @param int      $price_row
1917
+	 * @param EE_Price $price
1918
+	 * @param bool     $default
1919
+	 * @param bool     $disabled
1920
+	 * @return mixed
1921
+	 * @throws ReflectionException
1922
+	 * @throws InvalidArgumentException
1923
+	 * @throws InvalidInterfaceException
1924
+	 * @throws InvalidDataTypeException
1925
+	 * @throws DomainException
1926
+	 * @throws EE_Error
1927
+	 */
1928
+	protected function _get_price_modifier_template(
1929
+		$ticket_row,
1930
+		$price_row,
1931
+		$price,
1932
+		$default,
1933
+		$disabled = false
1934
+	) {
1935
+		$select_name = $default && ! $price instanceof EE_Price
1936
+			? 'edit_prices[TICKETNUM][PRICENUM][PRT_ID]'
1937
+			: 'edit_prices[' . $ticket_row . '][' . $price_row . '][PRT_ID]';
1938
+		/** @var EEM_Price_Type $price_type_model */
1939
+		$price_type_model = EE_Registry::instance()->load_model('Price_Type');
1940
+		$price_types = $price_type_model->get_all(array(
1941
+			array(
1942
+				'OR' => array(
1943
+					'PBT_ID'  => '2',
1944
+					'PBT_ID*' => '3',
1945
+				),
1946
+			),
1947
+		));
1948
+		$all_price_types = $default && ! $price instanceof EE_Price
1949
+			? array(esc_html__('Select Modifier', 'event_espresso'))
1950
+			: array();
1951
+		$selected_price_type_id = $default && ! $price instanceof EE_Price ? 0 : $price->type();
1952
+		$price_option_spans = '';
1953
+		// setup price types for selector
1954
+		foreach ($price_types as $price_type) {
1955
+			if (! $price_type instanceof EE_Price_Type) {
1956
+				continue;
1957
+			}
1958
+			$all_price_types[ $price_type->ID() ] = $price_type->get('PRT_name');
1959
+			// while we're in the loop let's setup the option spans used by js
1960
+			$span_args = array(
1961
+				'PRT_ID'         => $price_type->ID(),
1962
+				'PRT_operator'   => $price_type->is_discount() ? '-' : '+',
1963
+				'PRT_is_percent' => $price_type->get('PRT_is_percent') ? 1 : 0,
1964
+			);
1965
+			$price_option_spans .= EEH_Template::display_template(
1966
+				PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_option_span.template.php',
1967
+				$span_args,
1968
+				true
1969
+			);
1970
+		}
1971
+		$select_name = $disabled ? 'archive_price[' . $ticket_row . '][' . $price_row . '][PRT_ID]'
1972
+			: $select_name;
1973
+		$select_input = new EE_Select_Input(
1974
+			$all_price_types,
1975
+			array(
1976
+				'default'               => $selected_price_type_id,
1977
+				'html_name'             => $select_name,
1978
+				'html_class'            => 'edit-price-PRT_ID',
1979
+				'other_html_attributes' => $disabled ? 'style="width:auto;" disabled' : 'style="width:auto;"',
1980
+			)
1981
+		);
1982
+		$price_selected_operator = $price instanceof EE_Price && $price->is_discount() ? '-' : '+';
1983
+		$price_selected_operator = $default && ! $price instanceof EE_Price ? '' : $price_selected_operator;
1984
+		$price_selected_is_percent = $price instanceof EE_Price && $price->is_percent() ? 1 : 0;
1985
+		$price_selected_is_percent = $default && ! $price instanceof EE_Price ? '' : $price_selected_is_percent;
1986
+		$template_args = array(
1987
+			'tkt_row'                   => $default ? 'TICKETNUM' : $ticket_row,
1988
+			'PRC_order'                 => $default && ! $price instanceof EE_Price ? 'PRICENUM' : $price_row,
1989
+			'price_modifier_selector'   => $select_input->get_html_for_input(),
1990
+			'main_name'                 => $select_name,
1991
+			'selected_price_type_id'    => $selected_price_type_id,
1992
+			'price_option_spans'        => $price_option_spans,
1993
+			'price_selected_operator'   => $price_selected_operator,
1994
+			'price_selected_is_percent' => $price_selected_is_percent,
1995
+			'disabled'                  => $disabled,
1996
+		);
1997
+		$template_args = apply_filters(
1998
+			'FHEE__espresso_events_Pricing_Hooks___get_price_modifier_template__template_args',
1999
+			$template_args,
2000
+			$ticket_row,
2001
+			$price_row,
2002
+			$price,
2003
+			$default,
2004
+			$disabled,
2005
+			$this->_is_creating_event
2006
+		);
2007
+		return EEH_Template::display_template(
2008
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_price_modifier_selector.template.php',
2009
+			$template_args,
2010
+			true
2011
+		);
2012
+	}
2013 2013
 
2014 2014
 
2015
-    /**
2016
-     * @param int              $datetime_row
2017
-     * @param int              $ticket_row
2018
-     * @param EE_Datetime|null $datetime
2019
-     * @param EE_Ticket|null   $ticket
2020
-     * @param array            $ticket_datetimes
2021
-     * @param bool             $default
2022
-     * @return mixed
2023
-     * @throws DomainException
2024
-     * @throws EE_Error
2025
-     */
2026
-    protected function _get_ticket_datetime_list_item(
2027
-        $datetime_row,
2028
-        $ticket_row,
2029
-        $datetime,
2030
-        $ticket,
2031
-        $ticket_datetimes = array(),
2032
-        $default
2033
-    ) {
2034
-        $tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2035
-            ? $ticket_datetimes[ $ticket->ID() ]
2036
-            : array();
2037
-        $template_args = array(
2038
-            'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2039
-                ? 'DTTNUM'
2040
-                : $datetime_row,
2041
-            'tkt_row'                  => $default
2042
-                ? 'TICKETNUM'
2043
-                : $ticket_row,
2044
-            'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2045
-                ? ' ticket-selected'
2046
-                : '',
2047
-            'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2048
-                ? ' checked="checked"'
2049
-                : '',
2050
-            'DTT_name'                 => $default && empty($datetime)
2051
-                ? 'DTTNAME'
2052
-                : $datetime->get_dtt_display_name(true),
2053
-            'tkt_status_class'         => '',
2054
-        );
2055
-        $template_args = apply_filters(
2056
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2057
-            $template_args,
2058
-            $datetime_row,
2059
-            $ticket_row,
2060
-            $datetime,
2061
-            $ticket,
2062
-            $ticket_datetimes,
2063
-            $default,
2064
-            $this->_is_creating_event
2065
-        );
2066
-        return EEH_Template::display_template(
2067
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2068
-            $template_args,
2069
-            true
2070
-        );
2071
-    }
2015
+	/**
2016
+	 * @param int              $datetime_row
2017
+	 * @param int              $ticket_row
2018
+	 * @param EE_Datetime|null $datetime
2019
+	 * @param EE_Ticket|null   $ticket
2020
+	 * @param array            $ticket_datetimes
2021
+	 * @param bool             $default
2022
+	 * @return mixed
2023
+	 * @throws DomainException
2024
+	 * @throws EE_Error
2025
+	 */
2026
+	protected function _get_ticket_datetime_list_item(
2027
+		$datetime_row,
2028
+		$ticket_row,
2029
+		$datetime,
2030
+		$ticket,
2031
+		$ticket_datetimes = array(),
2032
+		$default
2033
+	) {
2034
+		$tkt_datetimes = $ticket instanceof EE_Ticket && isset($ticket_datetimes[ $ticket->ID() ])
2035
+			? $ticket_datetimes[ $ticket->ID() ]
2036
+			: array();
2037
+		$template_args = array(
2038
+			'dtt_row'                  => $default && ! $datetime instanceof EE_Datetime
2039
+				? 'DTTNUM'
2040
+				: $datetime_row,
2041
+			'tkt_row'                  => $default
2042
+				? 'TICKETNUM'
2043
+				: $ticket_row,
2044
+			'ticket_datetime_selected' => in_array($datetime_row, $tkt_datetimes, true)
2045
+				? ' ticket-selected'
2046
+				: '',
2047
+			'ticket_datetime_checked'  => in_array($datetime_row, $tkt_datetimes, true)
2048
+				? ' checked="checked"'
2049
+				: '',
2050
+			'DTT_name'                 => $default && empty($datetime)
2051
+				? 'DTTNAME'
2052
+				: $datetime->get_dtt_display_name(true),
2053
+			'tkt_status_class'         => '',
2054
+		);
2055
+		$template_args = apply_filters(
2056
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_datetime_list_item__template_args',
2057
+			$template_args,
2058
+			$datetime_row,
2059
+			$ticket_row,
2060
+			$datetime,
2061
+			$ticket,
2062
+			$ticket_datetimes,
2063
+			$default,
2064
+			$this->_is_creating_event
2065
+		);
2066
+		return EEH_Template::display_template(
2067
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_datetimes_list_item.template.php',
2068
+			$template_args,
2069
+			true
2070
+		);
2071
+	}
2072 2072
 
2073 2073
 
2074
-    /**
2075
-     * @param array $all_datetimes
2076
-     * @param array $all_tickets
2077
-     * @return mixed
2078
-     * @throws ReflectionException
2079
-     * @throws InvalidArgumentException
2080
-     * @throws InvalidInterfaceException
2081
-     * @throws InvalidDataTypeException
2082
-     * @throws DomainException
2083
-     * @throws EE_Error
2084
-     */
2085
-    protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2086
-    {
2087
-        $template_args = array(
2088
-            'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2089
-                'DTTNUM',
2090
-                null,
2091
-                true,
2092
-                $all_datetimes
2093
-            ),
2094
-            'default_ticket_row'                       => $this->_get_ticket_row(
2095
-                'TICKETNUM',
2096
-                null,
2097
-                array(),
2098
-                array(),
2099
-                true
2100
-            ),
2101
-            'default_price_row'                        => $this->_get_ticket_price_row(
2102
-                'TICKETNUM',
2103
-                'PRICENUM',
2104
-                null,
2105
-                true,
2106
-                null
2107
-            ),
2108
-            'default_price_rows'                       => '',
2109
-            'default_base_price_amount'                => 0,
2110
-            'default_base_price_name'                  => '',
2111
-            'default_base_price_description'           => '',
2112
-            'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2113
-                'TICKETNUM',
2114
-                'PRICENUM',
2115
-                null,
2116
-                true
2117
-            ),
2118
-            'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2119
-                'DTTNUM',
2120
-                null,
2121
-                array(),
2122
-                array(),
2123
-                true
2124
-            ),
2125
-            'existing_available_datetime_tickets_list' => '',
2126
-            'existing_available_ticket_datetimes_list' => '',
2127
-            'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2128
-                'DTTNUM',
2129
-                'TICKETNUM',
2130
-                null,
2131
-                null,
2132
-                array(),
2133
-                true
2134
-            ),
2135
-            'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2136
-                'DTTNUM',
2137
-                'TICKETNUM',
2138
-                null,
2139
-                null,
2140
-                array(),
2141
-                true
2142
-            ),
2143
-        );
2144
-        $ticket_row = 1;
2145
-        foreach ($all_tickets as $ticket) {
2146
-            $template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2147
-                'DTTNUM',
2148
-                $ticket_row,
2149
-                null,
2150
-                $ticket,
2151
-                array(),
2152
-                true
2153
-            );
2154
-            $ticket_row++;
2155
-        }
2156
-        $datetime_row = 1;
2157
-        foreach ($all_datetimes as $datetime) {
2158
-            $template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2159
-                $datetime_row,
2160
-                'TICKETNUM',
2161
-                $datetime,
2162
-                null,
2163
-                array(),
2164
-                true
2165
-            );
2166
-            $datetime_row++;
2167
-        }
2168
-        /** @var EEM_Price $price_model */
2169
-        $price_model = EE_Registry::instance()->load_model('Price');
2170
-        $default_prices = $price_model->get_all_default_prices();
2171
-        $price_row = 1;
2172
-        foreach ($default_prices as $price) {
2173
-            if (! $price instanceof EE_Price) {
2174
-                continue;
2175
-            }
2176
-            if ($price->is_base_price()) {
2177
-                $template_args['default_base_price_amount'] = $price->get_pretty(
2178
-                    'PRC_amount',
2179
-                    'localized_float'
2180
-                );
2181
-                $template_args['default_base_price_name'] = $price->get('PRC_name');
2182
-                $template_args['default_base_price_description'] = $price->get('PRC_desc');
2183
-                $price_row++;
2184
-                continue;
2185
-            }
2186
-            $show_trash = ! ((count($default_prices) > 1 && $price_row === 1)
2187
-                             || count($default_prices) === 1);
2188
-            $show_create = ! (count($default_prices) > 1
2189
-                              && count($default_prices)
2190
-                                 !== $price_row);
2191
-            $template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2192
-                'TICKETNUM',
2193
-                $price_row,
2194
-                $price,
2195
-                true,
2196
-                null,
2197
-                $show_trash,
2198
-                $show_create
2199
-            );
2200
-            $price_row++;
2201
-        }
2202
-        $template_args = apply_filters(
2203
-            'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2204
-            $template_args,
2205
-            $all_datetimes,
2206
-            $all_tickets,
2207
-            $this->_is_creating_event
2208
-        );
2209
-        return EEH_Template::display_template(
2210
-            PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2211
-            $template_args,
2212
-            true
2213
-        );
2214
-    }
2074
+	/**
2075
+	 * @param array $all_datetimes
2076
+	 * @param array $all_tickets
2077
+	 * @return mixed
2078
+	 * @throws ReflectionException
2079
+	 * @throws InvalidArgumentException
2080
+	 * @throws InvalidInterfaceException
2081
+	 * @throws InvalidDataTypeException
2082
+	 * @throws DomainException
2083
+	 * @throws EE_Error
2084
+	 */
2085
+	protected function _get_ticket_js_structure($all_datetimes = array(), $all_tickets = array())
2086
+	{
2087
+		$template_args = array(
2088
+			'default_datetime_edit_row'                => $this->_get_dtt_edit_row(
2089
+				'DTTNUM',
2090
+				null,
2091
+				true,
2092
+				$all_datetimes
2093
+			),
2094
+			'default_ticket_row'                       => $this->_get_ticket_row(
2095
+				'TICKETNUM',
2096
+				null,
2097
+				array(),
2098
+				array(),
2099
+				true
2100
+			),
2101
+			'default_price_row'                        => $this->_get_ticket_price_row(
2102
+				'TICKETNUM',
2103
+				'PRICENUM',
2104
+				null,
2105
+				true,
2106
+				null
2107
+			),
2108
+			'default_price_rows'                       => '',
2109
+			'default_base_price_amount'                => 0,
2110
+			'default_base_price_name'                  => '',
2111
+			'default_base_price_description'           => '',
2112
+			'default_price_modifier_selector_row'      => $this->_get_price_modifier_template(
2113
+				'TICKETNUM',
2114
+				'PRICENUM',
2115
+				null,
2116
+				true
2117
+			),
2118
+			'default_available_tickets_for_datetime'   => $this->_get_dtt_attached_tickets_row(
2119
+				'DTTNUM',
2120
+				null,
2121
+				array(),
2122
+				array(),
2123
+				true
2124
+			),
2125
+			'existing_available_datetime_tickets_list' => '',
2126
+			'existing_available_ticket_datetimes_list' => '',
2127
+			'new_available_datetime_ticket_list_item'  => $this->_get_datetime_tickets_list_item(
2128
+				'DTTNUM',
2129
+				'TICKETNUM',
2130
+				null,
2131
+				null,
2132
+				array(),
2133
+				true
2134
+			),
2135
+			'new_available_ticket_datetime_list_item'  => $this->_get_ticket_datetime_list_item(
2136
+				'DTTNUM',
2137
+				'TICKETNUM',
2138
+				null,
2139
+				null,
2140
+				array(),
2141
+				true
2142
+			),
2143
+		);
2144
+		$ticket_row = 1;
2145
+		foreach ($all_tickets as $ticket) {
2146
+			$template_args['existing_available_datetime_tickets_list'] .= $this->_get_datetime_tickets_list_item(
2147
+				'DTTNUM',
2148
+				$ticket_row,
2149
+				null,
2150
+				$ticket,
2151
+				array(),
2152
+				true
2153
+			);
2154
+			$ticket_row++;
2155
+		}
2156
+		$datetime_row = 1;
2157
+		foreach ($all_datetimes as $datetime) {
2158
+			$template_args['existing_available_ticket_datetimes_list'] .= $this->_get_ticket_datetime_list_item(
2159
+				$datetime_row,
2160
+				'TICKETNUM',
2161
+				$datetime,
2162
+				null,
2163
+				array(),
2164
+				true
2165
+			);
2166
+			$datetime_row++;
2167
+		}
2168
+		/** @var EEM_Price $price_model */
2169
+		$price_model = EE_Registry::instance()->load_model('Price');
2170
+		$default_prices = $price_model->get_all_default_prices();
2171
+		$price_row = 1;
2172
+		foreach ($default_prices as $price) {
2173
+			if (! $price instanceof EE_Price) {
2174
+				continue;
2175
+			}
2176
+			if ($price->is_base_price()) {
2177
+				$template_args['default_base_price_amount'] = $price->get_pretty(
2178
+					'PRC_amount',
2179
+					'localized_float'
2180
+				);
2181
+				$template_args['default_base_price_name'] = $price->get('PRC_name');
2182
+				$template_args['default_base_price_description'] = $price->get('PRC_desc');
2183
+				$price_row++;
2184
+				continue;
2185
+			}
2186
+			$show_trash = ! ((count($default_prices) > 1 && $price_row === 1)
2187
+							 || count($default_prices) === 1);
2188
+			$show_create = ! (count($default_prices) > 1
2189
+							  && count($default_prices)
2190
+								 !== $price_row);
2191
+			$template_args['default_price_rows'] .= $this->_get_ticket_price_row(
2192
+				'TICKETNUM',
2193
+				$price_row,
2194
+				$price,
2195
+				true,
2196
+				null,
2197
+				$show_trash,
2198
+				$show_create
2199
+			);
2200
+			$price_row++;
2201
+		}
2202
+		$template_args = apply_filters(
2203
+			'FHEE__espresso_events_Pricing_Hooks___get_ticket_js_structure__template_args',
2204
+			$template_args,
2205
+			$all_datetimes,
2206
+			$all_tickets,
2207
+			$this->_is_creating_event
2208
+		);
2209
+		return EEH_Template::display_template(
2210
+			PRICING_TEMPLATE_PATH . 'event_tickets_datetime_ticket_js_structure.template.php',
2211
+			$template_args,
2212
+			true
2213
+		);
2214
+	}
2215 2215
 }
Please login to merge, or discard this patch.
admin_pages/payments/Payments_Admin_Page.core.php 2 patches
Indentation   +1149 added lines, -1149 removed lines patch added patch discarded remove patch
@@ -16,1153 +16,1153 @@
 block discarded – undo
16 16
 class Payments_Admin_Page extends EE_Admin_Page
17 17
 {
18 18
 
19
-    /**
20
-     * Variables used for when we're re-sorting the logs results, in case
21
-     * we needed to do two queries and we need to resort
22
-     *
23
-     * @var string
24
-     */
25
-    private $_sort_logs_again_direction;
26
-
27
-
28
-    /**
29
-     * @Constructor
30
-     * @access public
31
-     * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
32
-     * @throws EE_Error
33
-     * @throws InvalidArgumentException
34
-     * @throws InvalidDataTypeException
35
-     * @throws InvalidInterfaceException
36
-     * @throws ReflectionException
37
-     */
38
-    public function __construct($routing = true)
39
-    {
40
-        parent::__construct($routing);
41
-    }
42
-
43
-
44
-    protected function _init_page_props()
45
-    {
46
-        $this->page_slug = EE_PAYMENTS_PG_SLUG;
47
-        $this->page_label = __('Payment Methods', 'event_espresso');
48
-        $this->_admin_base_url = EE_PAYMENTS_ADMIN_URL;
49
-        $this->_admin_base_path = EE_PAYMENTS_ADMIN;
50
-    }
51
-
52
-
53
-    protected function _ajax_hooks()
54
-    {
55
-        // todo: all hooks for ajax goes here.
56
-    }
57
-
58
-
59
-    protected function _define_page_props()
60
-    {
61
-        $this->_admin_page_title = $this->page_label;
62
-        $this->_labels = array(
63
-            'publishbox' => __('Update Settings', 'event_espresso'),
64
-        );
65
-    }
66
-
67
-
68
-    protected function _set_page_routes()
69
-    {
70
-        /**
71
-         * note that with payment method capabilities, although we've implemented
72
-         * capability mapping which will be used for accessing payment methods owned by
73
-         * other users.  This is not fully implemented yet in the payment method ui.
74
-         * Currently only the "plural" caps are in active use.
75
-         * When cap mapping is implemented, some routes will need to use the singular form of
76
-         * capability method and also include the $id of the payment method for the route.
77
-         **/
78
-        $this->_page_routes = array(
79
-            'default'                   => array(
80
-                'func'       => '_payment_methods_list',
81
-                'capability' => 'ee_edit_payment_methods',
82
-            ),
83
-            'payment_settings'          => array(
84
-                'func'       => '_payment_settings',
85
-                'capability' => 'ee_manage_gateways',
86
-            ),
87
-            'activate_payment_method'   => array(
88
-                'func'       => '_activate_payment_method',
89
-                'noheader'   => true,
90
-                'capability' => 'ee_edit_payment_methods',
91
-            ),
92
-            'deactivate_payment_method' => array(
93
-                'func'       => '_deactivate_payment_method',
94
-                'noheader'   => true,
95
-                'capability' => 'ee_delete_payment_methods',
96
-            ),
97
-            'update_payment_method'     => array(
98
-                'func'               => '_update_payment_method',
99
-                'noheader'           => true,
100
-                'headers_sent_route' => 'default',
101
-                'capability'         => 'ee_edit_payment_methods',
102
-            ),
103
-            'update_payment_settings'   => array(
104
-                'func'       => '_update_payment_settings',
105
-                'noheader'   => true,
106
-                'capability' => 'ee_manage_gateways',
107
-            ),
108
-            'payment_log'               => array(
109
-                'func'       => '_payment_log_overview_list_table',
110
-                'capability' => 'ee_read_payment_methods',
111
-            ),
112
-            'payment_log_details'       => array(
113
-                'func'       => '_payment_log_details',
114
-                'capability' => 'ee_read_payment_methods',
115
-            ),
116
-        );
117
-    }
118
-
119
-
120
-    protected function _set_page_config()
121
-    {
122
-        $payment_method_list_config = array(
123
-            'nav'           => array(
124
-                'label' => __('Payment Methods', 'event_espresso'),
125
-                'order' => 10,
126
-            ),
127
-            'metaboxes'     => $this->_default_espresso_metaboxes,
128
-            'help_tabs'     => array_merge(
129
-                array(
130
-                    'payment_methods_overview_help_tab' => array(
131
-                        'title'    => __('Payment Methods Overview', 'event_espresso'),
132
-                        'filename' => 'payment_methods_overview',
133
-                    ),
134
-                ),
135
-                $this->_add_payment_method_help_tabs()
136
-            ),
137
-            'help_tour'     => array('Payment_Methods_Selection_Help_Tour'),
138
-            'require_nonce' => false,
139
-        );
140
-        $this->_page_config = array(
141
-            'default'          => $payment_method_list_config,
142
-            'payment_settings' => array(
143
-                'nav'           => array(
144
-                    'label' => __('Settings', 'event_espresso'),
145
-                    'order' => 20,
146
-                ),
147
-                'help_tabs'     => array(
148
-                    'payment_methods_settings_help_tab' => array(
149
-                        'title'    => __('Payment Method Settings', 'event_espresso'),
150
-                        'filename' => 'payment_methods_settings',
151
-                    ),
152
-                ),
153
-                // 'help_tour' => array( 'Payment_Methods_Settings_Help_Tour' ),
154
-                'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
155
-                'require_nonce' => false,
156
-            ),
157
-            'payment_log'      => array(
158
-                'nav'           => array(
159
-                    'label' => __("Logs", 'event_espresso'),
160
-                    'order' => 30,
161
-                ),
162
-                'list_table'    => 'Payment_Log_Admin_List_Table',
163
-                'metaboxes'     => $this->_default_espresso_metaboxes,
164
-                'require_nonce' => false,
165
-            ),
166
-        );
167
-    }
168
-
169
-
170
-    /**
171
-     * @return array
172
-     * @throws DomainException
173
-     * @throws EE_Error
174
-     * @throws InvalidArgumentException
175
-     * @throws InvalidDataTypeException
176
-     * @throws InvalidInterfaceException
177
-     * @throws ReflectionException
178
-     */
179
-    protected function _add_payment_method_help_tabs()
180
-    {
181
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
182
-        $payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
183
-        $all_pmt_help_tabs_config = array();
184
-        foreach ($payment_method_types as $payment_method_type) {
185
-            if (! EE_Registry::instance()->CAP->current_user_can(
186
-                $payment_method_type->cap_name(),
187
-                'specific_payment_method_type_access'
188
-            )
189
-            ) {
190
-                continue;
191
-            }
192
-            foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
193
-                $template_args = isset($config['template_args']) ? $config['template_args'] : array();
194
-                $template_args['admin_page_obj'] = $this;
195
-                $all_pmt_help_tabs_config[ $help_tab_name ] = array(
196
-                    'title'   => $config['title'],
197
-                    'content' => EEH_Template::display_template(
198
-                        $payment_method_type->file_folder() . 'help_tabs/' . $config['filename'] . '.help_tab.php',
199
-                        $template_args,
200
-                        true
201
-                    ),
202
-                );
203
-            }
204
-        }
205
-        return $all_pmt_help_tabs_config;
206
-    }
207
-
208
-
209
-    // none of the below group are currently used for Gateway Settings
210
-    protected function _add_screen_options()
211
-    {
212
-    }
213
-
214
-
215
-    protected function _add_feature_pointers()
216
-    {
217
-    }
218
-
219
-
220
-    public function admin_init()
221
-    {
222
-    }
223
-
224
-
225
-    public function admin_notices()
226
-    {
227
-    }
228
-
229
-
230
-    public function admin_footer_scripts()
231
-    {
232
-    }
233
-
234
-
235
-    public function load_scripts_styles()
236
-    {
237
-        // styles
238
-        wp_enqueue_style('espresso-ui-theme');
239
-        // scripts
240
-        wp_enqueue_script('ee_admin_js');
241
-        wp_enqueue_script('ee-text-links');
242
-        wp_enqueue_script(
243
-            'espresso_payments',
244
-            EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js',
245
-            array('ee-datepicker'),
246
-            EVENT_ESPRESSO_VERSION,
247
-            true
248
-        );
249
-    }
250
-
251
-
252
-    public function load_scripts_styles_default()
253
-    {
254
-        // styles
255
-        wp_register_style(
256
-            'espresso_payments',
257
-            EE_PAYMENTS_ASSETS_URL . 'ee-payments.css',
258
-            array(),
259
-            EVENT_ESPRESSO_VERSION
260
-        );
261
-        wp_enqueue_style('espresso_payments');
262
-        wp_enqueue_style('ee-text-links');
263
-        // scripts
264
-    }
265
-
266
-
267
-    protected function _payment_methods_list()
268
-    {
269
-        /**
270
-         * first let's ensure payment methods have been setup. We do this here because when people activate a
271
-         * payment method for the first time (as an addon), it may not setup its capabilities or get registered
272
-         * correctly due to the loading process.  However, people MUST setup the details for the payment method so its
273
-         * safe to do a recheck here.
274
-         */
275
-        EE_Registry::instance()->load_lib('Payment_Method_Manager');
276
-        EEM_Payment_Method::instance()->verify_button_urls();
277
-        // setup tabs, one for each payment method type
278
-        $tabs = array();
279
-        $payment_methods = array();
280
-        foreach (EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj) {
281
-            // we don't want to show admin-only PMTs for now
282
-            if ($pmt_obj instanceof EE_PMT_Admin_Only) {
283
-                continue;
284
-            }
285
-            // check access
286
-            if (! EE_Registry::instance()->CAP->current_user_can(
287
-                $pmt_obj->cap_name(),
288
-                'specific_payment_method_type_access'
289
-            )
290
-            ) {
291
-                continue;
292
-            }
293
-            // check for any active pms of that type
294
-            $payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
295
-            if (! $payment_method instanceof EE_Payment_Method) {
296
-                $payment_method = EE_Payment_Method::new_instance(
297
-                    array(
298
-                        'PMD_slug'       => sanitize_key($pmt_obj->system_name()),
299
-                        'PMD_type'       => $pmt_obj->system_name(),
300
-                        'PMD_name'       => $pmt_obj->pretty_name(),
301
-                        'PMD_admin_name' => $pmt_obj->pretty_name(),
302
-                    )
303
-                );
304
-            }
305
-            $payment_methods[ $payment_method->slug() ] = $payment_method;
306
-        }
307
-        $payment_methods = apply_filters(
308
-            'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods',
309
-            $payment_methods
310
-        );
311
-        foreach ($payment_methods as $payment_method) {
312
-            if ($payment_method instanceof EE_Payment_Method) {
313
-                add_meta_box(
314
-                    // html id
315
-                    'espresso_' . $payment_method->slug() . '_payment_settings',
316
-                    // title
317
-                    sprintf(__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
318
-                    // callback
319
-                    array($this, 'payment_method_settings_meta_box'),
320
-                    // post type
321
-                    null,
322
-                    // context
323
-                    'normal',
324
-                    // priority
325
-                    'default',
326
-                    // callback args
327
-                    array('payment_method' => $payment_method)
328
-                );
329
-                // setup for tabbed content
330
-                $tabs[ $payment_method->slug() ] = array(
331
-                    'label' => $payment_method->admin_name(),
332
-                    'class' => $payment_method->active() ? 'gateway-active' : '',
333
-                    'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
334
-                    'title' => __('Modify this Payment Method', 'event_espresso'),
335
-                    'slug'  => $payment_method->slug(),
336
-                );
337
-            }
338
-        }
339
-        $this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
340
-            $tabs,
341
-            'payment_method_links',
342
-            '|',
343
-            $this->_get_active_payment_method_slug()
344
-        );
345
-        $this->display_admin_page_with_sidebar();
346
-    }
347
-
348
-
349
-    /**
350
-     *   _get_active_payment_method_slug
351
-     *
352
-     * @return string
353
-     */
354
-    protected function _get_active_payment_method_slug()
355
-    {
356
-        $payment_method_slug = false;
357
-        // decide which payment method tab to open first, as dictated by the request's 'payment_method'
358
-        if (isset($this->_req_data['payment_method'])) {
359
-            // if they provided the current payment method, use it
360
-            $payment_method_slug = sanitize_key($this->_req_data['payment_method']);
361
-        }
362
-        $payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
363
-        // if that didn't work or wasn't provided, find another way to select the current pm
364
-        if (! $this->_verify_payment_method($payment_method)) {
365
-            // like, looking for an active one
366
-            $payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
367
-            // test that one as well
368
-            if ($this->_verify_payment_method($payment_method)) {
369
-                $payment_method_slug = $payment_method->slug();
370
-            } else {
371
-                $payment_method_slug = 'paypal_standard';
372
-            }
373
-        }
374
-        return $payment_method_slug;
375
-    }
376
-
377
-
378
-    /**
379
-     *    payment_method_settings_meta_box
380
-     *    returns TRUE if the passed payment method is properly constructed and the logged in user has the correct
381
-     *    capabilities to access it
382
-     *
383
-     * @param EE_Payment_Method $payment_method
384
-     * @return boolean
385
-     */
386
-    protected function _verify_payment_method($payment_method)
387
-    {
388
-        if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj() instanceof EE_PMT_Base
389
-            && EE_Registry::instance()->CAP->current_user_can(
390
-                $payment_method->type_obj()->cap_name(),
391
-                'specific_payment_method_type_access'
392
-            )
393
-        ) {
394
-            return true;
395
-        }
396
-        return false;
397
-    }
398
-
399
-
400
-    /**
401
-     *    payment_method_settings_meta_box
402
-     *
403
-     * @param NULL  $post_obj_which_is_null is an object containing the current post (as a $post object)
404
-     * @param array $metabox                is an array with metabox id, title, callback, and args elements. the value
405
-     *                                      at 'args' has key 'payment_method', as set within _payment_methods_list
406
-     * @return string
407
-     * @throws EE_Error
408
-     */
409
-    public function payment_method_settings_meta_box($post_obj_which_is_null, $metabox)
410
-    {
411
-        $payment_method = isset($metabox['args'], $metabox['args']['payment_method'])
412
-            ? $metabox['args']['payment_method'] : null;
413
-        if (! $payment_method instanceof EE_Payment_Method) {
414
-            throw new EE_Error(
415
-                sprintf(
416
-                    __(
417
-                        'Payment method metabox setup incorrectly. No Payment method object was supplied',
418
-                        'event_espresso'
419
-                    )
420
-                )
421
-            );
422
-        }
423
-        $payment_method_scopes = $payment_method->active();
424
-        // if the payment method really exists show its form, otherwise the activation template
425
-        if ($payment_method->ID() && ! empty($payment_method_scopes)) {
426
-            $form = $this->_generate_payment_method_settings_form($payment_method);
427
-            if ($form->form_data_present_in($this->_req_data)) {
428
-                $form->receive_form_submission($this->_req_data);
429
-            }
430
-            echo $form->form_open() . $form->get_html_and_js() . $form->form_close();
431
-        } else {
432
-            echo $this->_activate_payment_method_button($payment_method)->get_html_and_js();
433
-        }
434
-    }
435
-
436
-
437
-    /**
438
-     * Gets the form for all the settings related to this payment method type
439
-     *
440
-     * @access protected
441
-     * @param EE_Payment_Method $payment_method
442
-     * @return EE_Form_Section_Proper
443
-     */
444
-    protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method)
445
-    {
446
-        if (! $payment_method instanceof EE_Payment_Method) {
447
-            return new EE_Form_Section_Proper();
448
-        }
449
-        return new EE_Form_Section_Proper(
450
-            array(
451
-                'name'            => $payment_method->slug() . '_settings_form',
452
-                'html_id'         => $payment_method->slug() . '_settings_form',
453
-                'action'          => EE_Admin_Page::add_query_args_and_nonce(
454
-                    array(
455
-                        'action'         => 'update_payment_method',
456
-                        'payment_method' => $payment_method->slug(),
457
-                    ),
458
-                    EE_PAYMENTS_ADMIN_URL
459
-                ),
460
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
461
-                'subsections'     => apply_filters(
462
-                    'FHEE__Payments_Admin_Page___generate_payment_method_settings_form__form_subsections',
463
-                    array(
464
-                        'pci_dss_compliance'      => $this->_pci_dss_compliance($payment_method),
465
-                        'currency_support'        => $this->_currency_support($payment_method),
466
-                        'payment_method_settings' => $this->_payment_method_settings($payment_method),
467
-                        'update'                  => $this->_update_payment_method_button($payment_method),
468
-                        'deactivate'              => $this->_deactivate_payment_method_button($payment_method),
469
-                        'fine_print'              => $this->_fine_print(),
470
-                    ),
471
-                    $payment_method
472
-                ),
473
-            )
474
-        );
475
-    }
476
-
477
-
478
-    /**
479
-     * _pci_dss_compliance
480
-     *
481
-     * @access protected
482
-     * @param EE_Payment_Method $payment_method
483
-     * @return EE_Form_Section_Proper
484
-     */
485
-    protected function _pci_dss_compliance(EE_Payment_Method $payment_method)
486
-    {
487
-        if ($payment_method->type_obj()->requires_https()) {
488
-            return new EE_Form_Section_HTML(
489
-                EEH_HTML::table(
490
-                    EEH_HTML::tr(
491
-                        EEH_HTML::th(
492
-                            EEH_HTML::label(
493
-                                EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
494
-                            )
495
-                        ) .
496
-                        EEH_HTML::td(
497
-                            EEH_HTML::strong(
498
-                                __(
499
-                                    'You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.',
500
-                                    'event_espresso'
501
-                                )
502
-                            )
503
-                            .
504
-                            EEH_HTML::br()
505
-                            .
506
-                            __('Learn more about ', 'event_espresso')
507
-                            . EEH_HTML::link(
508
-                                'https://www.pcisecuritystandards.org/merchants/index.php',
509
-                                __('PCI DSS compliance', 'event_espresso')
510
-                            )
511
-                        )
512
-                    )
513
-                )
514
-            );
515
-        } else {
516
-            return new EE_Form_Section_HTML('');
517
-        }
518
-    }
519
-
520
-
521
-    /**
522
-     * _currency_support
523
-     *
524
-     * @access protected
525
-     * @param EE_Payment_Method $payment_method
526
-     * @return EE_Form_Section_Proper
527
-     */
528
-    protected function _currency_support(EE_Payment_Method $payment_method)
529
-    {
530
-        if (! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
531
-            return new EE_Form_Section_HTML(
532
-                EEH_HTML::table(
533
-                    EEH_HTML::tr(
534
-                        EEH_HTML::th(
535
-                            EEH_HTML::label(
536
-                                EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
537
-                            )
538
-                        ) .
539
-                        EEH_HTML::td(
540
-                            EEH_HTML::strong(
541
-                                sprintf(
542
-                                    __(
543
-                                        'This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.',
544
-                                        'event_espresso'
545
-                                    ),
546
-                                    EE_Config::instance()->currency->code
547
-                                )
548
-                            )
549
-                        )
550
-                    )
551
-                )
552
-            );
553
-        } else {
554
-            return new EE_Form_Section_HTML('');
555
-        }
556
-    }
557
-
558
-
559
-    /**
560
-     * _update_payment_method_button
561
-     *
562
-     * @access protected
563
-     * @param EE_Payment_Method $payment_method
564
-     * @return EE_Payment_Method_Form
565
-     */
566
-    protected function _payment_method_settings(EE_Payment_Method $payment_method)
567
-    {
568
-        // modify the form so we only have/show fields that will be implemented for this version
569
-        return $this->_simplify_form($payment_method->type_obj()->settings_form(), $payment_method->name());
570
-    }
571
-
572
-
573
-    /**
574
-     * Simplifies the form to merely reproduce 4.1's gateway settings functionality
575
-     *
576
-     * @param EE_Form_Section_Proper $form_section
577
-     * @param string                 $payment_method_name
578
-     * @return EE_Payment_Method_Form
579
-     * @throws EE_Error
580
-     */
581
-    protected function _simplify_form($form_section, $payment_method_name = '')
582
-    {
583
-        if ($form_section instanceof EE_Payment_Method_Form) {
584
-            $form_section->exclude(
585
-                array(
586
-                    'PMD_type', // dont want them changing the type
587
-                    'PMD_slug', // or the slug (probably never)
588
-                    'PMD_wp_user', // or the user's ID
589
-                    'Currency' // or the currency, until the rest of EE supports simultaneous currencies
590
-                )
591
-            );
592
-            return $form_section;
593
-        } else {
594
-            throw new EE_Error(
595
-                sprintf(
596
-                    __(
597
-                        'The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.',
598
-                        'event_espresso'
599
-                    ),
600
-                    $payment_method_name
601
-                )
602
-            );
603
-        }
604
-    }
605
-
606
-
607
-    /**
608
-     * _update_payment_method_button
609
-     *
610
-     * @access protected
611
-     * @param EE_Payment_Method $payment_method
612
-     * @return EE_Form_Section_HTML
613
-     */
614
-    protected function _update_payment_method_button(EE_Payment_Method $payment_method)
615
-    {
616
-        $update_button = new EE_Submit_Input(
617
-            array(
618
-                'name'       => 'submit',
619
-                'html_id'    => 'save_' . $payment_method->slug() . '_settings',
620
-                'default'    => sprintf(
621
-                    __('Update %s Payment Settings', 'event_espresso'),
622
-                    $payment_method->admin_name()
623
-                ),
624
-                'html_label' => EEH_HTML::nbsp(),
625
-            )
626
-        );
627
-        return new EE_Form_Section_HTML(
628
-            EEH_HTML::table(
629
-                EEH_HTML::no_row(EEH_HTML::br(2)) .
630
-                EEH_HTML::tr(
631
-                    EEH_HTML::th(__('Update Settings', 'event_espresso')) .
632
-                    EEH_HTML::td(
633
-                        $update_button->get_html_for_input()
634
-                    )
635
-                )
636
-            )
637
-        );
638
-    }
639
-
640
-
641
-    /**
642
-     * _deactivate_payment_method_button
643
-     *
644
-     * @access protected
645
-     * @param EE_Payment_Method $payment_method
646
-     * @return EE_Form_Section_Proper
647
-     */
648
-    protected function _deactivate_payment_method_button(EE_Payment_Method $payment_method)
649
-    {
650
-        $link_text_and_title = sprintf(
651
-            __('Deactivate %1$s Payments?', 'event_espresso'),
652
-            $payment_method->admin_name()
653
-        );
654
-        return new EE_Form_Section_HTML(
655
-            EEH_HTML::table(
656
-                EEH_HTML::tr(
657
-                    EEH_HTML::th(__('Deactivate Payment Method', 'event_espresso')) .
658
-                    EEH_HTML::td(
659
-                        EEH_HTML::link(
660
-                            EE_Admin_Page::add_query_args_and_nonce(
661
-                                array(
662
-                                    'action'         => 'deactivate_payment_method',
663
-                                    'payment_method' => $payment_method->slug(),
664
-                                ),
665
-                                EE_PAYMENTS_ADMIN_URL
666
-                            ),
667
-                            $link_text_and_title,
668
-                            $link_text_and_title,
669
-                            'deactivate_' . $payment_method->slug(),
670
-                            'espresso-button button-secondary'
671
-                        )
672
-                    )
673
-                )
674
-            )
675
-        );
676
-    }
677
-
678
-
679
-    /**
680
-     * _activate_payment_method_button
681
-     *
682
-     * @access protected
683
-     * @param EE_Payment_Method $payment_method
684
-     * @return EE_Form_Section_Proper
685
-     */
686
-    protected function _activate_payment_method_button(EE_Payment_Method $payment_method)
687
-    {
688
-        $link_text_and_title = sprintf(
689
-            __('Activate %1$s Payment Method?', 'event_espresso'),
690
-            $payment_method->admin_name()
691
-        );
692
-        return new EE_Form_Section_Proper(
693
-            array(
694
-                'name'            => 'activate_' . $payment_method->slug() . '_settings_form',
695
-                'html_id'         => 'activate_' . $payment_method->slug() . '_settings_form',
696
-                'action'          => '#',
697
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
698
-                'subsections'     => apply_filters(
699
-                    'FHEE__Payments_Admin_Page___activate_payment_method_button__form_subsections',
700
-                    array(
701
-                        new EE_Form_Section_HTML(
702
-                            EEH_HTML::table(
703
-                                EEH_HTML::tr(
704
-                                    EEH_HTML::td(
705
-                                        $payment_method->type_obj()->introductory_html(),
706
-                                        '',
707
-                                        '',
708
-                                        '',
709
-                                        'colspan="2"'
710
-                                    )
711
-                                ) .
712
-                                EEH_HTML::tr(
713
-                                    EEH_HTML::th(
714
-                                        EEH_HTML::label(__('Click to Activate ', 'event_espresso'))
715
-                                    ) .
716
-                                    EEH_HTML::td(
717
-                                        EEH_HTML::link(
718
-                                            EE_Admin_Page::add_query_args_and_nonce(
719
-                                                array(
720
-                                                    'action'              => 'activate_payment_method',
721
-                                                    'payment_method_type' => $payment_method->type(),
722
-                                                ),
723
-                                                EE_PAYMENTS_ADMIN_URL
724
-                                            ),
725
-                                            $link_text_and_title,
726
-                                            $link_text_and_title,
727
-                                            'activate_' . $payment_method->slug(),
728
-                                            'espresso-button-green button-primary'
729
-                                        )
730
-                                    )
731
-                                )
732
-                            )
733
-                        ),
734
-                    ),
735
-                    $payment_method
736
-                ),
737
-            )
738
-        );
739
-    }
740
-
741
-
742
-    /**
743
-     * _fine_print
744
-     *
745
-     * @access protected
746
-     * @return EE_Form_Section_HTML
747
-     */
748
-    protected function _fine_print()
749
-    {
750
-        return new EE_Form_Section_HTML(
751
-            EEH_HTML::table(
752
-                EEH_HTML::tr(
753
-                    EEH_HTML::th() .
754
-                    EEH_HTML::td(
755
-                        EEH_HTML::p(__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
756
-                    )
757
-                )
758
-            )
759
-        );
760
-    }
761
-
762
-
763
-    /**
764
-     * Activates a payment method of that type. Mostly assuming there is only 1 of that type (or none so far)
765
-     *
766
-     * @global WP_User $current_user
767
-     */
768
-    protected function _activate_payment_method()
769
-    {
770
-        if (isset($this->_req_data['payment_method_type'])) {
771
-            $payment_method_type = sanitize_text_field($this->_req_data['payment_method_type']);
772
-            // see if one exists
773
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
774
-            $payment_method = EE_Payment_Method_Manager::instance()
775
-                                                       ->activate_a_payment_method_of_type($payment_method_type);
776
-            $this->_redirect_after_action(
777
-                1,
778
-                'Payment Method',
779
-                'activated',
780
-                array('action' => 'default', 'payment_method' => $payment_method->slug())
781
-            );
782
-        } else {
783
-            $this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
784
-        }
785
-    }
786
-
787
-
788
-    /**
789
-     * Deactivates the payment method with the specified slug, and redirects.
790
-     */
791
-    protected function _deactivate_payment_method()
792
-    {
793
-        if (isset($this->_req_data['payment_method'])) {
794
-            $payment_method_slug = sanitize_key($this->_req_data['payment_method']);
795
-            // deactivate it
796
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
797
-            $count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method($payment_method_slug);
798
-            $this->_redirect_after_action(
799
-                $count_updated,
800
-                'Payment Method',
801
-                'deactivated',
802
-                array('action' => 'default', 'payment_method' => $payment_method_slug)
803
-            );
804
-        } else {
805
-            $this->_redirect_after_action(false, 'Payment Method', 'deactivated', array('action' => 'default'));
806
-        }
807
-    }
808
-
809
-
810
-    /**
811
-     * Processes the payment method form that was submitted. This is slightly trickier than usual form
812
-     * processing because we first need to identify WHICH form was processed and which payment method
813
-     * it corresponds to. Once we have done that, we see if the form is valid. If it is, the
814
-     * form's data is saved and we redirect to the default payment methods page, setting the updated payment method
815
-     * as the currently-selected one. If it DOESN'T validate, we render the page with the form's errors (in the
816
-     * subsequently called 'headers_sent_func' which is _payment_methods_list)
817
-     *
818
-     * @return void
819
-     */
820
-    protected function _update_payment_method()
821
-    {
822
-        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
823
-            // ok let's find which gateway form to use based on the form input
824
-            EE_Registry::instance()->load_lib('Payment_Method_Manager');
825
-            /** @var $correct_pmt_form_to_use EE_Payment_Method_Form */
826
-            $correct_pmt_form_to_use = null;
827
-            $payment_method = null;
828
-            foreach (EEM_Payment_Method::instance()->get_all() as $payment_method) {
829
-                // get the form and simplify it, like what we do when we display it
830
-                $pmt_form = $this->_generate_payment_method_settings_form($payment_method);
831
-                if ($pmt_form->form_data_present_in($this->_req_data)) {
832
-                    $correct_pmt_form_to_use = $pmt_form;
833
-                    break;
834
-                }
835
-            }
836
-            // if we couldn't find the correct payment method type...
837
-            if (! $correct_pmt_form_to_use) {
838
-                EE_Error::add_error(
839
-                    __(
840
-                        "We could not find which payment method type your form submission related to. Please contact support",
841
-                        'event_espresso'
842
-                    ),
843
-                    __FILE__,
844
-                    __FUNCTION__,
845
-                    __LINE__
846
-                );
847
-                $this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
848
-            }
849
-            $correct_pmt_form_to_use->receive_form_submission($this->_req_data);
850
-            if ($correct_pmt_form_to_use->is_valid()) {
851
-                $payment_settings_subform = $correct_pmt_form_to_use->get_subsection('payment_method_settings');
852
-                if (! $payment_settings_subform instanceof EE_Payment_Method_Form) {
853
-                    throw new EE_Error(
854
-                        sprintf(
855
-                            __(
856
-                                'The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.',
857
-                                'event_espresso'
858
-                            ),
859
-                            'payment_method_settings'
860
-                        )
861
-                    );
862
-                }
863
-                $payment_settings_subform->save();
864
-                /** @var $pm EE_Payment_Method */
865
-                $this->_redirect_after_action(
866
-                    true,
867
-                    'Payment Method',
868
-                    'updated',
869
-                    array('action' => 'default', 'payment_method' => $payment_method->slug())
870
-                );
871
-            } else {
872
-                EE_Error::add_error(
873
-                    sprintf(
874
-                        __(
875
-                            'Payment method of type %s was not saved because there were validation errors. They have been marked in the form',
876
-                            'event_espresso'
877
-                        ),
878
-                        $payment_method instanceof EE_Payment_Method ? $payment_method->type_obj()->pretty_name()
879
-                            : __('"(unknown)"', 'event_espresso')
880
-                    ),
881
-                    __FILE__,
882
-                    __FUNCTION__,
883
-                    __LINE__
884
-                );
885
-            }
886
-        }
887
-        return;
888
-    }
889
-
890
-
891
-    /**
892
-     * Displays payment settings (not payment METHOD settings, that's _payment_method_settings)
893
-     * @throws DomainException
894
-     * @throws EE_Error
895
-     * @throws InvalidArgumentException
896
-     * @throws InvalidDataTypeException
897
-     * @throws InvalidInterfaceException
898
-     */
899
-    protected function _payment_settings()
900
-    {
901
-        $form = $this->getPaymentSettingsForm();
902
-        $this->_set_add_edit_form_tags('update_payment_settings');
903
-        $this->_set_publish_post_box_vars(null, false, false, null, false);
904
-        $this->_template_args['admin_page_content'] =  $form->get_html_and_js();
905
-        $this->display_admin_page_with_sidebar();
906
-    }
907
-
908
-
909
-    /**
910
-     *        _update_payment_settings
911
-     *
912
-     * @access protected
913
-     * @return void
914
-     * @throws EE_Error
915
-     * @throws InvalidArgumentException
916
-     * @throws InvalidDataTypeException
917
-     * @throws InvalidInterfaceException
918
-     */
919
-    protected function _update_payment_settings()
920
-    {
921
-        $form = $this->getPaymentSettingsForm();
922
-        if ($form->was_submitted($this->_req_data)) {
923
-            $form->receive_form_submission($this->_req_data);
924
-            if ($form->is_valid()) {
925
-                /**
926
-                 * @var $reg_config EE_Registration_Config
927
-                 */
928
-                $loader = LoaderFactory::getLoader();
929
-                $reg_config = $loader->getShared('EE_Registration_Config');
930
-                $valid_data = $form->valid_data();
931
-                $reg_config->show_pending_payment_options = $valid_data['show_pending_payment_options'];
932
-                $reg_config->gateway_log_lifespan = $valid_data['gateway_log_lifespan'];
933
-            }
934
-        }
935
-        EE_Registry::instance()->CFG = apply_filters(
936
-            'FHEE__Payments_Admin_Page___update_payment_settings__CFG',
937
-            EE_Registry::instance()->CFG
938
-        );
939
-
940
-        $cfg =  EE_Registry::instance()->CFG ;
941
-
942
-        $what = __('Payment Settings', 'event_espresso');
943
-        $success = $this->_update_espresso_configuration(
944
-            $what,
945
-            EE_Registry::instance()->CFG,
946
-            __FILE__,
947
-            __FUNCTION__,
948
-            __LINE__
949
-        );
950
-        $this->_redirect_after_action(
951
-            $success,
952
-            $what,
953
-            __('updated', 'event_espresso'),
954
-            array('action' => 'payment_settings')
955
-        );
956
-    }
957
-
958
-
959
-    /**
960
-     * Gets the form used for updating payment settings
961
-     *
962
-     * @return EE_Form_Section_Proper
963
-     * @throws EE_Error
964
-     * @throws InvalidArgumentException
965
-     * @throws InvalidDataTypeException
966
-     * @throws InvalidInterfaceException
967
-     */
968
-    protected function getPaymentSettingsForm()
969
-    {
970
-        /**
971
-         * @var $reg_config EE_Registration_Config
972
-         */
973
-        $reg_config = LoaderFactory::getLoader()->getShared('EE_Registration_Config');
974
-        return new EE_Form_Section_Proper(
975
-            array(
976
-                'name' => 'payment-settings',
977
-                'layout_strategy' => new EE_Admin_Two_Column_Layout(),
978
-                'subsections' => array(
979
-                    'show_pending_payment_options' => new EE_Yes_No_Input(
980
-                        array(
981
-                            'html_name' => 'show_pending_payment_options',
982
-                            'default' => $reg_config->show_pending_payment_options,
983
-                            'html_help_text' => esc_html__(
984
-                                "If a payment is marked as 'Pending Payment', or if payment is deferred (ie, an offline gateway like Check, Bank, or Invoice is used), then give registrants the option to retry payment. ",
985
-                                'event_espresso'
986
-                            )
987
-                        )
988
-                    ),
989
-                    'gateway_log_lifespan' => new EE_Select_Input(
990
-                        $reg_config->gatewayLogLifespanOptions(),
991
-                        array(
992
-                            'html_label_text' => esc_html__('Gateway Logs Lifespan', 'event_espresso'),
993
-                            'html_help_text' => esc_html__('If issues arise with payments being made through a payment gateway, it\'s helpful to log non-sensitive communications with the payment gateway. But it\'s a security responsibility, so it\'s a good idea to not keep them for any longer than necessary.', 'event_espresso'),
994
-                            'default' => $reg_config->gateway_log_lifespan,
995
-                        )
996
-                    )
997
-                )
998
-            )
999
-        );
1000
-    }
1001
-
1002
-
1003
-    protected function _payment_log_overview_list_table()
1004
-    {
1005
-        $this->display_admin_list_table_page_with_sidebar();
1006
-    }
1007
-
1008
-
1009
-    protected function _set_list_table_views_payment_log()
1010
-    {
1011
-        $this->_views = array(
1012
-            'all' => array(
1013
-                'slug'  => 'all',
1014
-                'label' => __('View All Logs', 'event_espresso'),
1015
-                'count' => 0,
1016
-            ),
1017
-        );
1018
-    }
1019
-
1020
-
1021
-    /**
1022
-     * @param int  $per_page
1023
-     * @param int  $current_page
1024
-     * @param bool $count
1025
-     * @return array
1026
-     */
1027
-    public function get_payment_logs($per_page = 50, $current_page = 0, $count = false)
1028
-    {
1029
-        EE_Registry::instance()->load_model('Change_Log');
1030
-        // we may need to do multiple queries (joining differently), so we actually wan tan array of query params
1031
-        $query_params = array(array('LOG_type' => EEM_Change_Log::type_gateway));
1032
-        // check if they've selected a specific payment method
1033
-        if (isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all') {
1034
-            $query_params[0]['OR*pm_or_pay_pm'] = array(
1035
-                'Payment.Payment_Method.PMD_ID' => $this->_req_data['_payment_method'],
1036
-                'Payment_Method.PMD_ID'         => $this->_req_data['_payment_method'],
1037
-            );
1038
-        }
1039
-        // take into account search
1040
-        if (isset($this->_req_data['s']) && $this->_req_data['s']) {
1041
-            $similarity_string = array('LIKE', '%' . str_replace("", "%", $this->_req_data['s']) . '%');
1042
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
1043
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
1044
-            $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
1045
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_name'] = $similarity_string;
1046
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_admin_name'] = $similarity_string;
1047
-            $query_params[0]['OR*s']['Payment.Payment_Method.PMD_type'] = $similarity_string;
1048
-            $query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1049
-            $query_params[0]['OR*s']['Payment_Method.PMD_name'] = $similarity_string;
1050
-            $query_params[0]['OR*s']['Payment_Method.PMD_admin_name'] = $similarity_string;
1051
-            $query_params[0]['OR*s']['Payment_Method.PMD_type'] = $similarity_string;
1052
-            $query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1053
-        }
1054
-        if (isset($this->_req_data['payment-filter-start-date'])
1055
-            && isset($this->_req_data['payment-filter-end-date'])
1056
-        ) {
1057
-            // add date
1058
-            $start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
1059
-            $end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
1060
-            // make sure our timestamps start and end right at the boundaries for each day
1061
-            $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1062
-            $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1063
-            // convert to timestamps
1064
-            $start_date = strtotime($start_date);
1065
-            $end_date = strtotime($end_date);
1066
-            // makes sure start date is the lowest value and vice versa
1067
-            $start_date = min($start_date, $end_date);
1068
-            $end_date = max($start_date, $end_date);
1069
-            // convert for query
1070
-            $start_date = EEM_Change_Log::instance()
1071
-                                        ->convert_datetime_for_query(
1072
-                                            'LOG_time',
1073
-                                            date('Y-m-d H:i:s', $start_date),
1074
-                                            'Y-m-d H:i:s'
1075
-                                        );
1076
-            $end_date = EEM_Change_Log::instance()
1077
-                                      ->convert_datetime_for_query(
1078
-                                          'LOG_time',
1079
-                                          date('Y-m-d H:i:s', $end_date),
1080
-                                          'Y-m-d H:i:s'
1081
-                                      );
1082
-            $query_params[0]['LOG_time'] = array('BETWEEN', array($start_date, $end_date));
1083
-        }
1084
-        if ($count) {
1085
-            return EEM_Change_Log::instance()->count($query_params);
1086
-        }
1087
-        if (isset($this->_req_data['order'])) {
1088
-            $sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
1089
-                : 'DESC';
1090
-            $query_params['order_by'] = array('LOG_time' => $sort);
1091
-        } else {
1092
-            $query_params['order_by'] = array('LOG_time' => 'DESC');
1093
-        }
1094
-        $offset = ($current_page - 1) * $per_page;
1095
-        if (! isset($this->_req_data['download_results'])) {
1096
-            $query_params['limit'] = array($offset, $per_page);
1097
-        }
1098
-        // now they've requested to instead just download the file instead of viewing it.
1099
-        if (isset($this->_req_data['download_results'])) {
1100
-            $wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
1101
-            header('Content-Disposition: attachment');
1102
-            header("Content-Disposition: attachment; filename=ee_payment_logs_for_" . sanitize_key(site_url()));
1103
-            echo "<h1>Payment Logs for " . site_url() . "</h1>";
1104
-            echo "<h3>Query:</h3>";
1105
-            var_dump($query_params);
1106
-            echo "<h3>Results:</h3>";
1107
-            var_dump($wpdb_results);
1108
-            die;
1109
-        }
1110
-        $results = EEM_Change_Log::instance()->get_all($query_params);
1111
-        return $results;
1112
-    }
1113
-
1114
-
1115
-    /**
1116
-     * Used by usort to RE-sort log query results, because we lose the ordering
1117
-     * because we're possibly combining the results from two queries
1118
-     *
1119
-     * @param EE_Change_Log $logA
1120
-     * @param EE_Change_Log $logB
1121
-     * @return int
1122
-     */
1123
-    protected function _sort_logs_again($logA, $logB)
1124
-    {
1125
-        $timeA = $logA->get_raw('LOG_time');
1126
-        $timeB = $logB->get_raw('LOG_time');
1127
-        if ($timeA == $timeB) {
1128
-            return 0;
1129
-        }
1130
-        $comparison = $timeA < $timeB ? -1 : 1;
1131
-        if (strtoupper($this->_sort_logs_again_direction) == 'DESC') {
1132
-            return $comparison * -1;
1133
-        } else {
1134
-            return $comparison;
1135
-        }
1136
-    }
1137
-
1138
-
1139
-    protected function _payment_log_details()
1140
-    {
1141
-        EE_Registry::instance()->load_model('Change_Log');
1142
-        /** @var $payment_log EE_Change_Log */
1143
-        $payment_log = EEM_Change_Log::instance()->get_one_by_ID($this->_req_data['ID']);
1144
-        $payment_method = null;
1145
-        $transaction = null;
1146
-        if ($payment_log instanceof EE_Change_Log) {
1147
-            if ($payment_log->object() instanceof EE_Payment) {
1148
-                $payment_method = $payment_log->object()->payment_method();
1149
-                $transaction = $payment_log->object()->transaction();
1150
-            } elseif ($payment_log->object() instanceof EE_Payment_Method) {
1151
-                $payment_method = $payment_log->object();
1152
-            } elseif ($payment_log->object() instanceof EE_Transaction) {
1153
-                $transaction = $payment_log->object();
1154
-                $payment_method = $transaction->payment_method();
1155
-            }
1156
-        }
1157
-        $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1158
-            EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
1159
-            array(
1160
-                'payment_log'    => $payment_log,
1161
-                'payment_method' => $payment_method,
1162
-                'transaction'    => $transaction,
1163
-            ),
1164
-            true
1165
-        );
1166
-        $this->display_admin_page_with_sidebar();
1167
-    }
19
+	/**
20
+	 * Variables used for when we're re-sorting the logs results, in case
21
+	 * we needed to do two queries and we need to resort
22
+	 *
23
+	 * @var string
24
+	 */
25
+	private $_sort_logs_again_direction;
26
+
27
+
28
+	/**
29
+	 * @Constructor
30
+	 * @access public
31
+	 * @param bool $routing indicate whether we want to just load the object and handle routing or just load the object.
32
+	 * @throws EE_Error
33
+	 * @throws InvalidArgumentException
34
+	 * @throws InvalidDataTypeException
35
+	 * @throws InvalidInterfaceException
36
+	 * @throws ReflectionException
37
+	 */
38
+	public function __construct($routing = true)
39
+	{
40
+		parent::__construct($routing);
41
+	}
42
+
43
+
44
+	protected function _init_page_props()
45
+	{
46
+		$this->page_slug = EE_PAYMENTS_PG_SLUG;
47
+		$this->page_label = __('Payment Methods', 'event_espresso');
48
+		$this->_admin_base_url = EE_PAYMENTS_ADMIN_URL;
49
+		$this->_admin_base_path = EE_PAYMENTS_ADMIN;
50
+	}
51
+
52
+
53
+	protected function _ajax_hooks()
54
+	{
55
+		// todo: all hooks for ajax goes here.
56
+	}
57
+
58
+
59
+	protected function _define_page_props()
60
+	{
61
+		$this->_admin_page_title = $this->page_label;
62
+		$this->_labels = array(
63
+			'publishbox' => __('Update Settings', 'event_espresso'),
64
+		);
65
+	}
66
+
67
+
68
+	protected function _set_page_routes()
69
+	{
70
+		/**
71
+		 * note that with payment method capabilities, although we've implemented
72
+		 * capability mapping which will be used for accessing payment methods owned by
73
+		 * other users.  This is not fully implemented yet in the payment method ui.
74
+		 * Currently only the "plural" caps are in active use.
75
+		 * When cap mapping is implemented, some routes will need to use the singular form of
76
+		 * capability method and also include the $id of the payment method for the route.
77
+		 **/
78
+		$this->_page_routes = array(
79
+			'default'                   => array(
80
+				'func'       => '_payment_methods_list',
81
+				'capability' => 'ee_edit_payment_methods',
82
+			),
83
+			'payment_settings'          => array(
84
+				'func'       => '_payment_settings',
85
+				'capability' => 'ee_manage_gateways',
86
+			),
87
+			'activate_payment_method'   => array(
88
+				'func'       => '_activate_payment_method',
89
+				'noheader'   => true,
90
+				'capability' => 'ee_edit_payment_methods',
91
+			),
92
+			'deactivate_payment_method' => array(
93
+				'func'       => '_deactivate_payment_method',
94
+				'noheader'   => true,
95
+				'capability' => 'ee_delete_payment_methods',
96
+			),
97
+			'update_payment_method'     => array(
98
+				'func'               => '_update_payment_method',
99
+				'noheader'           => true,
100
+				'headers_sent_route' => 'default',
101
+				'capability'         => 'ee_edit_payment_methods',
102
+			),
103
+			'update_payment_settings'   => array(
104
+				'func'       => '_update_payment_settings',
105
+				'noheader'   => true,
106
+				'capability' => 'ee_manage_gateways',
107
+			),
108
+			'payment_log'               => array(
109
+				'func'       => '_payment_log_overview_list_table',
110
+				'capability' => 'ee_read_payment_methods',
111
+			),
112
+			'payment_log_details'       => array(
113
+				'func'       => '_payment_log_details',
114
+				'capability' => 'ee_read_payment_methods',
115
+			),
116
+		);
117
+	}
118
+
119
+
120
+	protected function _set_page_config()
121
+	{
122
+		$payment_method_list_config = array(
123
+			'nav'           => array(
124
+				'label' => __('Payment Methods', 'event_espresso'),
125
+				'order' => 10,
126
+			),
127
+			'metaboxes'     => $this->_default_espresso_metaboxes,
128
+			'help_tabs'     => array_merge(
129
+				array(
130
+					'payment_methods_overview_help_tab' => array(
131
+						'title'    => __('Payment Methods Overview', 'event_espresso'),
132
+						'filename' => 'payment_methods_overview',
133
+					),
134
+				),
135
+				$this->_add_payment_method_help_tabs()
136
+			),
137
+			'help_tour'     => array('Payment_Methods_Selection_Help_Tour'),
138
+			'require_nonce' => false,
139
+		);
140
+		$this->_page_config = array(
141
+			'default'          => $payment_method_list_config,
142
+			'payment_settings' => array(
143
+				'nav'           => array(
144
+					'label' => __('Settings', 'event_espresso'),
145
+					'order' => 20,
146
+				),
147
+				'help_tabs'     => array(
148
+					'payment_methods_settings_help_tab' => array(
149
+						'title'    => __('Payment Method Settings', 'event_espresso'),
150
+						'filename' => 'payment_methods_settings',
151
+					),
152
+				),
153
+				// 'help_tour' => array( 'Payment_Methods_Settings_Help_Tour' ),
154
+				'metaboxes'     => array_merge($this->_default_espresso_metaboxes, array('_publish_post_box')),
155
+				'require_nonce' => false,
156
+			),
157
+			'payment_log'      => array(
158
+				'nav'           => array(
159
+					'label' => __("Logs", 'event_espresso'),
160
+					'order' => 30,
161
+				),
162
+				'list_table'    => 'Payment_Log_Admin_List_Table',
163
+				'metaboxes'     => $this->_default_espresso_metaboxes,
164
+				'require_nonce' => false,
165
+			),
166
+		);
167
+	}
168
+
169
+
170
+	/**
171
+	 * @return array
172
+	 * @throws DomainException
173
+	 * @throws EE_Error
174
+	 * @throws InvalidArgumentException
175
+	 * @throws InvalidDataTypeException
176
+	 * @throws InvalidInterfaceException
177
+	 * @throws ReflectionException
178
+	 */
179
+	protected function _add_payment_method_help_tabs()
180
+	{
181
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
182
+		$payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
183
+		$all_pmt_help_tabs_config = array();
184
+		foreach ($payment_method_types as $payment_method_type) {
185
+			if (! EE_Registry::instance()->CAP->current_user_can(
186
+				$payment_method_type->cap_name(),
187
+				'specific_payment_method_type_access'
188
+			)
189
+			) {
190
+				continue;
191
+			}
192
+			foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
193
+				$template_args = isset($config['template_args']) ? $config['template_args'] : array();
194
+				$template_args['admin_page_obj'] = $this;
195
+				$all_pmt_help_tabs_config[ $help_tab_name ] = array(
196
+					'title'   => $config['title'],
197
+					'content' => EEH_Template::display_template(
198
+						$payment_method_type->file_folder() . 'help_tabs/' . $config['filename'] . '.help_tab.php',
199
+						$template_args,
200
+						true
201
+					),
202
+				);
203
+			}
204
+		}
205
+		return $all_pmt_help_tabs_config;
206
+	}
207
+
208
+
209
+	// none of the below group are currently used for Gateway Settings
210
+	protected function _add_screen_options()
211
+	{
212
+	}
213
+
214
+
215
+	protected function _add_feature_pointers()
216
+	{
217
+	}
218
+
219
+
220
+	public function admin_init()
221
+	{
222
+	}
223
+
224
+
225
+	public function admin_notices()
226
+	{
227
+	}
228
+
229
+
230
+	public function admin_footer_scripts()
231
+	{
232
+	}
233
+
234
+
235
+	public function load_scripts_styles()
236
+	{
237
+		// styles
238
+		wp_enqueue_style('espresso-ui-theme');
239
+		// scripts
240
+		wp_enqueue_script('ee_admin_js');
241
+		wp_enqueue_script('ee-text-links');
242
+		wp_enqueue_script(
243
+			'espresso_payments',
244
+			EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js',
245
+			array('ee-datepicker'),
246
+			EVENT_ESPRESSO_VERSION,
247
+			true
248
+		);
249
+	}
250
+
251
+
252
+	public function load_scripts_styles_default()
253
+	{
254
+		// styles
255
+		wp_register_style(
256
+			'espresso_payments',
257
+			EE_PAYMENTS_ASSETS_URL . 'ee-payments.css',
258
+			array(),
259
+			EVENT_ESPRESSO_VERSION
260
+		);
261
+		wp_enqueue_style('espresso_payments');
262
+		wp_enqueue_style('ee-text-links');
263
+		// scripts
264
+	}
265
+
266
+
267
+	protected function _payment_methods_list()
268
+	{
269
+		/**
270
+		 * first let's ensure payment methods have been setup. We do this here because when people activate a
271
+		 * payment method for the first time (as an addon), it may not setup its capabilities or get registered
272
+		 * correctly due to the loading process.  However, people MUST setup the details for the payment method so its
273
+		 * safe to do a recheck here.
274
+		 */
275
+		EE_Registry::instance()->load_lib('Payment_Method_Manager');
276
+		EEM_Payment_Method::instance()->verify_button_urls();
277
+		// setup tabs, one for each payment method type
278
+		$tabs = array();
279
+		$payment_methods = array();
280
+		foreach (EE_Payment_Method_Manager::instance()->payment_method_types() as $pmt_obj) {
281
+			// we don't want to show admin-only PMTs for now
282
+			if ($pmt_obj instanceof EE_PMT_Admin_Only) {
283
+				continue;
284
+			}
285
+			// check access
286
+			if (! EE_Registry::instance()->CAP->current_user_can(
287
+				$pmt_obj->cap_name(),
288
+				'specific_payment_method_type_access'
289
+			)
290
+			) {
291
+				continue;
292
+			}
293
+			// check for any active pms of that type
294
+			$payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
295
+			if (! $payment_method instanceof EE_Payment_Method) {
296
+				$payment_method = EE_Payment_Method::new_instance(
297
+					array(
298
+						'PMD_slug'       => sanitize_key($pmt_obj->system_name()),
299
+						'PMD_type'       => $pmt_obj->system_name(),
300
+						'PMD_name'       => $pmt_obj->pretty_name(),
301
+						'PMD_admin_name' => $pmt_obj->pretty_name(),
302
+					)
303
+				);
304
+			}
305
+			$payment_methods[ $payment_method->slug() ] = $payment_method;
306
+		}
307
+		$payment_methods = apply_filters(
308
+			'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods',
309
+			$payment_methods
310
+		);
311
+		foreach ($payment_methods as $payment_method) {
312
+			if ($payment_method instanceof EE_Payment_Method) {
313
+				add_meta_box(
314
+					// html id
315
+					'espresso_' . $payment_method->slug() . '_payment_settings',
316
+					// title
317
+					sprintf(__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
318
+					// callback
319
+					array($this, 'payment_method_settings_meta_box'),
320
+					// post type
321
+					null,
322
+					// context
323
+					'normal',
324
+					// priority
325
+					'default',
326
+					// callback args
327
+					array('payment_method' => $payment_method)
328
+				);
329
+				// setup for tabbed content
330
+				$tabs[ $payment_method->slug() ] = array(
331
+					'label' => $payment_method->admin_name(),
332
+					'class' => $payment_method->active() ? 'gateway-active' : '',
333
+					'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
334
+					'title' => __('Modify this Payment Method', 'event_espresso'),
335
+					'slug'  => $payment_method->slug(),
336
+				);
337
+			}
338
+		}
339
+		$this->_template_args['admin_page_header'] = EEH_Tabbed_Content::tab_text_links(
340
+			$tabs,
341
+			'payment_method_links',
342
+			'|',
343
+			$this->_get_active_payment_method_slug()
344
+		);
345
+		$this->display_admin_page_with_sidebar();
346
+	}
347
+
348
+
349
+	/**
350
+	 *   _get_active_payment_method_slug
351
+	 *
352
+	 * @return string
353
+	 */
354
+	protected function _get_active_payment_method_slug()
355
+	{
356
+		$payment_method_slug = false;
357
+		// decide which payment method tab to open first, as dictated by the request's 'payment_method'
358
+		if (isset($this->_req_data['payment_method'])) {
359
+			// if they provided the current payment method, use it
360
+			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
361
+		}
362
+		$payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
363
+		// if that didn't work or wasn't provided, find another way to select the current pm
364
+		if (! $this->_verify_payment_method($payment_method)) {
365
+			// like, looking for an active one
366
+			$payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
367
+			// test that one as well
368
+			if ($this->_verify_payment_method($payment_method)) {
369
+				$payment_method_slug = $payment_method->slug();
370
+			} else {
371
+				$payment_method_slug = 'paypal_standard';
372
+			}
373
+		}
374
+		return $payment_method_slug;
375
+	}
376
+
377
+
378
+	/**
379
+	 *    payment_method_settings_meta_box
380
+	 *    returns TRUE if the passed payment method is properly constructed and the logged in user has the correct
381
+	 *    capabilities to access it
382
+	 *
383
+	 * @param EE_Payment_Method $payment_method
384
+	 * @return boolean
385
+	 */
386
+	protected function _verify_payment_method($payment_method)
387
+	{
388
+		if ($payment_method instanceof EE_Payment_Method && $payment_method->type_obj() instanceof EE_PMT_Base
389
+			&& EE_Registry::instance()->CAP->current_user_can(
390
+				$payment_method->type_obj()->cap_name(),
391
+				'specific_payment_method_type_access'
392
+			)
393
+		) {
394
+			return true;
395
+		}
396
+		return false;
397
+	}
398
+
399
+
400
+	/**
401
+	 *    payment_method_settings_meta_box
402
+	 *
403
+	 * @param NULL  $post_obj_which_is_null is an object containing the current post (as a $post object)
404
+	 * @param array $metabox                is an array with metabox id, title, callback, and args elements. the value
405
+	 *                                      at 'args' has key 'payment_method', as set within _payment_methods_list
406
+	 * @return string
407
+	 * @throws EE_Error
408
+	 */
409
+	public function payment_method_settings_meta_box($post_obj_which_is_null, $metabox)
410
+	{
411
+		$payment_method = isset($metabox['args'], $metabox['args']['payment_method'])
412
+			? $metabox['args']['payment_method'] : null;
413
+		if (! $payment_method instanceof EE_Payment_Method) {
414
+			throw new EE_Error(
415
+				sprintf(
416
+					__(
417
+						'Payment method metabox setup incorrectly. No Payment method object was supplied',
418
+						'event_espresso'
419
+					)
420
+				)
421
+			);
422
+		}
423
+		$payment_method_scopes = $payment_method->active();
424
+		// if the payment method really exists show its form, otherwise the activation template
425
+		if ($payment_method->ID() && ! empty($payment_method_scopes)) {
426
+			$form = $this->_generate_payment_method_settings_form($payment_method);
427
+			if ($form->form_data_present_in($this->_req_data)) {
428
+				$form->receive_form_submission($this->_req_data);
429
+			}
430
+			echo $form->form_open() . $form->get_html_and_js() . $form->form_close();
431
+		} else {
432
+			echo $this->_activate_payment_method_button($payment_method)->get_html_and_js();
433
+		}
434
+	}
435
+
436
+
437
+	/**
438
+	 * Gets the form for all the settings related to this payment method type
439
+	 *
440
+	 * @access protected
441
+	 * @param EE_Payment_Method $payment_method
442
+	 * @return EE_Form_Section_Proper
443
+	 */
444
+	protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method)
445
+	{
446
+		if (! $payment_method instanceof EE_Payment_Method) {
447
+			return new EE_Form_Section_Proper();
448
+		}
449
+		return new EE_Form_Section_Proper(
450
+			array(
451
+				'name'            => $payment_method->slug() . '_settings_form',
452
+				'html_id'         => $payment_method->slug() . '_settings_form',
453
+				'action'          => EE_Admin_Page::add_query_args_and_nonce(
454
+					array(
455
+						'action'         => 'update_payment_method',
456
+						'payment_method' => $payment_method->slug(),
457
+					),
458
+					EE_PAYMENTS_ADMIN_URL
459
+				),
460
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
461
+				'subsections'     => apply_filters(
462
+					'FHEE__Payments_Admin_Page___generate_payment_method_settings_form__form_subsections',
463
+					array(
464
+						'pci_dss_compliance'      => $this->_pci_dss_compliance($payment_method),
465
+						'currency_support'        => $this->_currency_support($payment_method),
466
+						'payment_method_settings' => $this->_payment_method_settings($payment_method),
467
+						'update'                  => $this->_update_payment_method_button($payment_method),
468
+						'deactivate'              => $this->_deactivate_payment_method_button($payment_method),
469
+						'fine_print'              => $this->_fine_print(),
470
+					),
471
+					$payment_method
472
+				),
473
+			)
474
+		);
475
+	}
476
+
477
+
478
+	/**
479
+	 * _pci_dss_compliance
480
+	 *
481
+	 * @access protected
482
+	 * @param EE_Payment_Method $payment_method
483
+	 * @return EE_Form_Section_Proper
484
+	 */
485
+	protected function _pci_dss_compliance(EE_Payment_Method $payment_method)
486
+	{
487
+		if ($payment_method->type_obj()->requires_https()) {
488
+			return new EE_Form_Section_HTML(
489
+				EEH_HTML::table(
490
+					EEH_HTML::tr(
491
+						EEH_HTML::th(
492
+							EEH_HTML::label(
493
+								EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
494
+							)
495
+						) .
496
+						EEH_HTML::td(
497
+							EEH_HTML::strong(
498
+								__(
499
+									'You are responsible for your own website security and Payment Card Industry Data Security Standards (PCI DSS) compliance.',
500
+									'event_espresso'
501
+								)
502
+							)
503
+							.
504
+							EEH_HTML::br()
505
+							.
506
+							__('Learn more about ', 'event_espresso')
507
+							. EEH_HTML::link(
508
+								'https://www.pcisecuritystandards.org/merchants/index.php',
509
+								__('PCI DSS compliance', 'event_espresso')
510
+							)
511
+						)
512
+					)
513
+				)
514
+			);
515
+		} else {
516
+			return new EE_Form_Section_HTML('');
517
+		}
518
+	}
519
+
520
+
521
+	/**
522
+	 * _currency_support
523
+	 *
524
+	 * @access protected
525
+	 * @param EE_Payment_Method $payment_method
526
+	 * @return EE_Form_Section_Proper
527
+	 */
528
+	protected function _currency_support(EE_Payment_Method $payment_method)
529
+	{
530
+		if (! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
531
+			return new EE_Form_Section_HTML(
532
+				EEH_HTML::table(
533
+					EEH_HTML::tr(
534
+						EEH_HTML::th(
535
+							EEH_HTML::label(
536
+								EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
537
+							)
538
+						) .
539
+						EEH_HTML::td(
540
+							EEH_HTML::strong(
541
+								sprintf(
542
+									__(
543
+										'This payment method does not support the currency set on your site (%1$s). Please activate a different payment method or change your site\'s country and associated currency.',
544
+										'event_espresso'
545
+									),
546
+									EE_Config::instance()->currency->code
547
+								)
548
+							)
549
+						)
550
+					)
551
+				)
552
+			);
553
+		} else {
554
+			return new EE_Form_Section_HTML('');
555
+		}
556
+	}
557
+
558
+
559
+	/**
560
+	 * _update_payment_method_button
561
+	 *
562
+	 * @access protected
563
+	 * @param EE_Payment_Method $payment_method
564
+	 * @return EE_Payment_Method_Form
565
+	 */
566
+	protected function _payment_method_settings(EE_Payment_Method $payment_method)
567
+	{
568
+		// modify the form so we only have/show fields that will be implemented for this version
569
+		return $this->_simplify_form($payment_method->type_obj()->settings_form(), $payment_method->name());
570
+	}
571
+
572
+
573
+	/**
574
+	 * Simplifies the form to merely reproduce 4.1's gateway settings functionality
575
+	 *
576
+	 * @param EE_Form_Section_Proper $form_section
577
+	 * @param string                 $payment_method_name
578
+	 * @return EE_Payment_Method_Form
579
+	 * @throws EE_Error
580
+	 */
581
+	protected function _simplify_form($form_section, $payment_method_name = '')
582
+	{
583
+		if ($form_section instanceof EE_Payment_Method_Form) {
584
+			$form_section->exclude(
585
+				array(
586
+					'PMD_type', // dont want them changing the type
587
+					'PMD_slug', // or the slug (probably never)
588
+					'PMD_wp_user', // or the user's ID
589
+					'Currency' // or the currency, until the rest of EE supports simultaneous currencies
590
+				)
591
+			);
592
+			return $form_section;
593
+		} else {
594
+			throw new EE_Error(
595
+				sprintf(
596
+					__(
597
+						'The EE_Payment_Method_Form for the "%1$s" payment method is missing or invalid.',
598
+						'event_espresso'
599
+					),
600
+					$payment_method_name
601
+				)
602
+			);
603
+		}
604
+	}
605
+
606
+
607
+	/**
608
+	 * _update_payment_method_button
609
+	 *
610
+	 * @access protected
611
+	 * @param EE_Payment_Method $payment_method
612
+	 * @return EE_Form_Section_HTML
613
+	 */
614
+	protected function _update_payment_method_button(EE_Payment_Method $payment_method)
615
+	{
616
+		$update_button = new EE_Submit_Input(
617
+			array(
618
+				'name'       => 'submit',
619
+				'html_id'    => 'save_' . $payment_method->slug() . '_settings',
620
+				'default'    => sprintf(
621
+					__('Update %s Payment Settings', 'event_espresso'),
622
+					$payment_method->admin_name()
623
+				),
624
+				'html_label' => EEH_HTML::nbsp(),
625
+			)
626
+		);
627
+		return new EE_Form_Section_HTML(
628
+			EEH_HTML::table(
629
+				EEH_HTML::no_row(EEH_HTML::br(2)) .
630
+				EEH_HTML::tr(
631
+					EEH_HTML::th(__('Update Settings', 'event_espresso')) .
632
+					EEH_HTML::td(
633
+						$update_button->get_html_for_input()
634
+					)
635
+				)
636
+			)
637
+		);
638
+	}
639
+
640
+
641
+	/**
642
+	 * _deactivate_payment_method_button
643
+	 *
644
+	 * @access protected
645
+	 * @param EE_Payment_Method $payment_method
646
+	 * @return EE_Form_Section_Proper
647
+	 */
648
+	protected function _deactivate_payment_method_button(EE_Payment_Method $payment_method)
649
+	{
650
+		$link_text_and_title = sprintf(
651
+			__('Deactivate %1$s Payments?', 'event_espresso'),
652
+			$payment_method->admin_name()
653
+		);
654
+		return new EE_Form_Section_HTML(
655
+			EEH_HTML::table(
656
+				EEH_HTML::tr(
657
+					EEH_HTML::th(__('Deactivate Payment Method', 'event_espresso')) .
658
+					EEH_HTML::td(
659
+						EEH_HTML::link(
660
+							EE_Admin_Page::add_query_args_and_nonce(
661
+								array(
662
+									'action'         => 'deactivate_payment_method',
663
+									'payment_method' => $payment_method->slug(),
664
+								),
665
+								EE_PAYMENTS_ADMIN_URL
666
+							),
667
+							$link_text_and_title,
668
+							$link_text_and_title,
669
+							'deactivate_' . $payment_method->slug(),
670
+							'espresso-button button-secondary'
671
+						)
672
+					)
673
+				)
674
+			)
675
+		);
676
+	}
677
+
678
+
679
+	/**
680
+	 * _activate_payment_method_button
681
+	 *
682
+	 * @access protected
683
+	 * @param EE_Payment_Method $payment_method
684
+	 * @return EE_Form_Section_Proper
685
+	 */
686
+	protected function _activate_payment_method_button(EE_Payment_Method $payment_method)
687
+	{
688
+		$link_text_and_title = sprintf(
689
+			__('Activate %1$s Payment Method?', 'event_espresso'),
690
+			$payment_method->admin_name()
691
+		);
692
+		return new EE_Form_Section_Proper(
693
+			array(
694
+				'name'            => 'activate_' . $payment_method->slug() . '_settings_form',
695
+				'html_id'         => 'activate_' . $payment_method->slug() . '_settings_form',
696
+				'action'          => '#',
697
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
698
+				'subsections'     => apply_filters(
699
+					'FHEE__Payments_Admin_Page___activate_payment_method_button__form_subsections',
700
+					array(
701
+						new EE_Form_Section_HTML(
702
+							EEH_HTML::table(
703
+								EEH_HTML::tr(
704
+									EEH_HTML::td(
705
+										$payment_method->type_obj()->introductory_html(),
706
+										'',
707
+										'',
708
+										'',
709
+										'colspan="2"'
710
+									)
711
+								) .
712
+								EEH_HTML::tr(
713
+									EEH_HTML::th(
714
+										EEH_HTML::label(__('Click to Activate ', 'event_espresso'))
715
+									) .
716
+									EEH_HTML::td(
717
+										EEH_HTML::link(
718
+											EE_Admin_Page::add_query_args_and_nonce(
719
+												array(
720
+													'action'              => 'activate_payment_method',
721
+													'payment_method_type' => $payment_method->type(),
722
+												),
723
+												EE_PAYMENTS_ADMIN_URL
724
+											),
725
+											$link_text_and_title,
726
+											$link_text_and_title,
727
+											'activate_' . $payment_method->slug(),
728
+											'espresso-button-green button-primary'
729
+										)
730
+									)
731
+								)
732
+							)
733
+						),
734
+					),
735
+					$payment_method
736
+				),
737
+			)
738
+		);
739
+	}
740
+
741
+
742
+	/**
743
+	 * _fine_print
744
+	 *
745
+	 * @access protected
746
+	 * @return EE_Form_Section_HTML
747
+	 */
748
+	protected function _fine_print()
749
+	{
750
+		return new EE_Form_Section_HTML(
751
+			EEH_HTML::table(
752
+				EEH_HTML::tr(
753
+					EEH_HTML::th() .
754
+					EEH_HTML::td(
755
+						EEH_HTML::p(__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
756
+					)
757
+				)
758
+			)
759
+		);
760
+	}
761
+
762
+
763
+	/**
764
+	 * Activates a payment method of that type. Mostly assuming there is only 1 of that type (or none so far)
765
+	 *
766
+	 * @global WP_User $current_user
767
+	 */
768
+	protected function _activate_payment_method()
769
+	{
770
+		if (isset($this->_req_data['payment_method_type'])) {
771
+			$payment_method_type = sanitize_text_field($this->_req_data['payment_method_type']);
772
+			// see if one exists
773
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
774
+			$payment_method = EE_Payment_Method_Manager::instance()
775
+													   ->activate_a_payment_method_of_type($payment_method_type);
776
+			$this->_redirect_after_action(
777
+				1,
778
+				'Payment Method',
779
+				'activated',
780
+				array('action' => 'default', 'payment_method' => $payment_method->slug())
781
+			);
782
+		} else {
783
+			$this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
784
+		}
785
+	}
786
+
787
+
788
+	/**
789
+	 * Deactivates the payment method with the specified slug, and redirects.
790
+	 */
791
+	protected function _deactivate_payment_method()
792
+	{
793
+		if (isset($this->_req_data['payment_method'])) {
794
+			$payment_method_slug = sanitize_key($this->_req_data['payment_method']);
795
+			// deactivate it
796
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
797
+			$count_updated = EE_Payment_Method_Manager::instance()->deactivate_payment_method($payment_method_slug);
798
+			$this->_redirect_after_action(
799
+				$count_updated,
800
+				'Payment Method',
801
+				'deactivated',
802
+				array('action' => 'default', 'payment_method' => $payment_method_slug)
803
+			);
804
+		} else {
805
+			$this->_redirect_after_action(false, 'Payment Method', 'deactivated', array('action' => 'default'));
806
+		}
807
+	}
808
+
809
+
810
+	/**
811
+	 * Processes the payment method form that was submitted. This is slightly trickier than usual form
812
+	 * processing because we first need to identify WHICH form was processed and which payment method
813
+	 * it corresponds to. Once we have done that, we see if the form is valid. If it is, the
814
+	 * form's data is saved and we redirect to the default payment methods page, setting the updated payment method
815
+	 * as the currently-selected one. If it DOESN'T validate, we render the page with the form's errors (in the
816
+	 * subsequently called 'headers_sent_func' which is _payment_methods_list)
817
+	 *
818
+	 * @return void
819
+	 */
820
+	protected function _update_payment_method()
821
+	{
822
+		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
823
+			// ok let's find which gateway form to use based on the form input
824
+			EE_Registry::instance()->load_lib('Payment_Method_Manager');
825
+			/** @var $correct_pmt_form_to_use EE_Payment_Method_Form */
826
+			$correct_pmt_form_to_use = null;
827
+			$payment_method = null;
828
+			foreach (EEM_Payment_Method::instance()->get_all() as $payment_method) {
829
+				// get the form and simplify it, like what we do when we display it
830
+				$pmt_form = $this->_generate_payment_method_settings_form($payment_method);
831
+				if ($pmt_form->form_data_present_in($this->_req_data)) {
832
+					$correct_pmt_form_to_use = $pmt_form;
833
+					break;
834
+				}
835
+			}
836
+			// if we couldn't find the correct payment method type...
837
+			if (! $correct_pmt_form_to_use) {
838
+				EE_Error::add_error(
839
+					__(
840
+						"We could not find which payment method type your form submission related to. Please contact support",
841
+						'event_espresso'
842
+					),
843
+					__FILE__,
844
+					__FUNCTION__,
845
+					__LINE__
846
+				);
847
+				$this->_redirect_after_action(false, 'Payment Method', 'activated', array('action' => 'default'));
848
+			}
849
+			$correct_pmt_form_to_use->receive_form_submission($this->_req_data);
850
+			if ($correct_pmt_form_to_use->is_valid()) {
851
+				$payment_settings_subform = $correct_pmt_form_to_use->get_subsection('payment_method_settings');
852
+				if (! $payment_settings_subform instanceof EE_Payment_Method_Form) {
853
+					throw new EE_Error(
854
+						sprintf(
855
+							__(
856
+								'The payment method could not be saved because the form sections were misnamed. We expected to find %1$s, but did not.',
857
+								'event_espresso'
858
+							),
859
+							'payment_method_settings'
860
+						)
861
+					);
862
+				}
863
+				$payment_settings_subform->save();
864
+				/** @var $pm EE_Payment_Method */
865
+				$this->_redirect_after_action(
866
+					true,
867
+					'Payment Method',
868
+					'updated',
869
+					array('action' => 'default', 'payment_method' => $payment_method->slug())
870
+				);
871
+			} else {
872
+				EE_Error::add_error(
873
+					sprintf(
874
+						__(
875
+							'Payment method of type %s was not saved because there were validation errors. They have been marked in the form',
876
+							'event_espresso'
877
+						),
878
+						$payment_method instanceof EE_Payment_Method ? $payment_method->type_obj()->pretty_name()
879
+							: __('"(unknown)"', 'event_espresso')
880
+					),
881
+					__FILE__,
882
+					__FUNCTION__,
883
+					__LINE__
884
+				);
885
+			}
886
+		}
887
+		return;
888
+	}
889
+
890
+
891
+	/**
892
+	 * Displays payment settings (not payment METHOD settings, that's _payment_method_settings)
893
+	 * @throws DomainException
894
+	 * @throws EE_Error
895
+	 * @throws InvalidArgumentException
896
+	 * @throws InvalidDataTypeException
897
+	 * @throws InvalidInterfaceException
898
+	 */
899
+	protected function _payment_settings()
900
+	{
901
+		$form = $this->getPaymentSettingsForm();
902
+		$this->_set_add_edit_form_tags('update_payment_settings');
903
+		$this->_set_publish_post_box_vars(null, false, false, null, false);
904
+		$this->_template_args['admin_page_content'] =  $form->get_html_and_js();
905
+		$this->display_admin_page_with_sidebar();
906
+	}
907
+
908
+
909
+	/**
910
+	 *        _update_payment_settings
911
+	 *
912
+	 * @access protected
913
+	 * @return void
914
+	 * @throws EE_Error
915
+	 * @throws InvalidArgumentException
916
+	 * @throws InvalidDataTypeException
917
+	 * @throws InvalidInterfaceException
918
+	 */
919
+	protected function _update_payment_settings()
920
+	{
921
+		$form = $this->getPaymentSettingsForm();
922
+		if ($form->was_submitted($this->_req_data)) {
923
+			$form->receive_form_submission($this->_req_data);
924
+			if ($form->is_valid()) {
925
+				/**
926
+				 * @var $reg_config EE_Registration_Config
927
+				 */
928
+				$loader = LoaderFactory::getLoader();
929
+				$reg_config = $loader->getShared('EE_Registration_Config');
930
+				$valid_data = $form->valid_data();
931
+				$reg_config->show_pending_payment_options = $valid_data['show_pending_payment_options'];
932
+				$reg_config->gateway_log_lifespan = $valid_data['gateway_log_lifespan'];
933
+			}
934
+		}
935
+		EE_Registry::instance()->CFG = apply_filters(
936
+			'FHEE__Payments_Admin_Page___update_payment_settings__CFG',
937
+			EE_Registry::instance()->CFG
938
+		);
939
+
940
+		$cfg =  EE_Registry::instance()->CFG ;
941
+
942
+		$what = __('Payment Settings', 'event_espresso');
943
+		$success = $this->_update_espresso_configuration(
944
+			$what,
945
+			EE_Registry::instance()->CFG,
946
+			__FILE__,
947
+			__FUNCTION__,
948
+			__LINE__
949
+		);
950
+		$this->_redirect_after_action(
951
+			$success,
952
+			$what,
953
+			__('updated', 'event_espresso'),
954
+			array('action' => 'payment_settings')
955
+		);
956
+	}
957
+
958
+
959
+	/**
960
+	 * Gets the form used for updating payment settings
961
+	 *
962
+	 * @return EE_Form_Section_Proper
963
+	 * @throws EE_Error
964
+	 * @throws InvalidArgumentException
965
+	 * @throws InvalidDataTypeException
966
+	 * @throws InvalidInterfaceException
967
+	 */
968
+	protected function getPaymentSettingsForm()
969
+	{
970
+		/**
971
+		 * @var $reg_config EE_Registration_Config
972
+		 */
973
+		$reg_config = LoaderFactory::getLoader()->getShared('EE_Registration_Config');
974
+		return new EE_Form_Section_Proper(
975
+			array(
976
+				'name' => 'payment-settings',
977
+				'layout_strategy' => new EE_Admin_Two_Column_Layout(),
978
+				'subsections' => array(
979
+					'show_pending_payment_options' => new EE_Yes_No_Input(
980
+						array(
981
+							'html_name' => 'show_pending_payment_options',
982
+							'default' => $reg_config->show_pending_payment_options,
983
+							'html_help_text' => esc_html__(
984
+								"If a payment is marked as 'Pending Payment', or if payment is deferred (ie, an offline gateway like Check, Bank, or Invoice is used), then give registrants the option to retry payment. ",
985
+								'event_espresso'
986
+							)
987
+						)
988
+					),
989
+					'gateway_log_lifespan' => new EE_Select_Input(
990
+						$reg_config->gatewayLogLifespanOptions(),
991
+						array(
992
+							'html_label_text' => esc_html__('Gateway Logs Lifespan', 'event_espresso'),
993
+							'html_help_text' => esc_html__('If issues arise with payments being made through a payment gateway, it\'s helpful to log non-sensitive communications with the payment gateway. But it\'s a security responsibility, so it\'s a good idea to not keep them for any longer than necessary.', 'event_espresso'),
994
+							'default' => $reg_config->gateway_log_lifespan,
995
+						)
996
+					)
997
+				)
998
+			)
999
+		);
1000
+	}
1001
+
1002
+
1003
+	protected function _payment_log_overview_list_table()
1004
+	{
1005
+		$this->display_admin_list_table_page_with_sidebar();
1006
+	}
1007
+
1008
+
1009
+	protected function _set_list_table_views_payment_log()
1010
+	{
1011
+		$this->_views = array(
1012
+			'all' => array(
1013
+				'slug'  => 'all',
1014
+				'label' => __('View All Logs', 'event_espresso'),
1015
+				'count' => 0,
1016
+			),
1017
+		);
1018
+	}
1019
+
1020
+
1021
+	/**
1022
+	 * @param int  $per_page
1023
+	 * @param int  $current_page
1024
+	 * @param bool $count
1025
+	 * @return array
1026
+	 */
1027
+	public function get_payment_logs($per_page = 50, $current_page = 0, $count = false)
1028
+	{
1029
+		EE_Registry::instance()->load_model('Change_Log');
1030
+		// we may need to do multiple queries (joining differently), so we actually wan tan array of query params
1031
+		$query_params = array(array('LOG_type' => EEM_Change_Log::type_gateway));
1032
+		// check if they've selected a specific payment method
1033
+		if (isset($this->_req_data['_payment_method']) && $this->_req_data['_payment_method'] !== 'all') {
1034
+			$query_params[0]['OR*pm_or_pay_pm'] = array(
1035
+				'Payment.Payment_Method.PMD_ID' => $this->_req_data['_payment_method'],
1036
+				'Payment_Method.PMD_ID'         => $this->_req_data['_payment_method'],
1037
+			);
1038
+		}
1039
+		// take into account search
1040
+		if (isset($this->_req_data['s']) && $this->_req_data['s']) {
1041
+			$similarity_string = array('LIKE', '%' . str_replace("", "%", $this->_req_data['s']) . '%');
1042
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
1043
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
1044
+			$query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
1045
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_name'] = $similarity_string;
1046
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_admin_name'] = $similarity_string;
1047
+			$query_params[0]['OR*s']['Payment.Payment_Method.PMD_type'] = $similarity_string;
1048
+			$query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1049
+			$query_params[0]['OR*s']['Payment_Method.PMD_name'] = $similarity_string;
1050
+			$query_params[0]['OR*s']['Payment_Method.PMD_admin_name'] = $similarity_string;
1051
+			$query_params[0]['OR*s']['Payment_Method.PMD_type'] = $similarity_string;
1052
+			$query_params[0]['OR*s']['LOG_message'] = $similarity_string;
1053
+		}
1054
+		if (isset($this->_req_data['payment-filter-start-date'])
1055
+			&& isset($this->_req_data['payment-filter-end-date'])
1056
+		) {
1057
+			// add date
1058
+			$start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
1059
+			$end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
1060
+			// make sure our timestamps start and end right at the boundaries for each day
1061
+			$start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1062
+			$end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1063
+			// convert to timestamps
1064
+			$start_date = strtotime($start_date);
1065
+			$end_date = strtotime($end_date);
1066
+			// makes sure start date is the lowest value and vice versa
1067
+			$start_date = min($start_date, $end_date);
1068
+			$end_date = max($start_date, $end_date);
1069
+			// convert for query
1070
+			$start_date = EEM_Change_Log::instance()
1071
+										->convert_datetime_for_query(
1072
+											'LOG_time',
1073
+											date('Y-m-d H:i:s', $start_date),
1074
+											'Y-m-d H:i:s'
1075
+										);
1076
+			$end_date = EEM_Change_Log::instance()
1077
+									  ->convert_datetime_for_query(
1078
+										  'LOG_time',
1079
+										  date('Y-m-d H:i:s', $end_date),
1080
+										  'Y-m-d H:i:s'
1081
+									  );
1082
+			$query_params[0]['LOG_time'] = array('BETWEEN', array($start_date, $end_date));
1083
+		}
1084
+		if ($count) {
1085
+			return EEM_Change_Log::instance()->count($query_params);
1086
+		}
1087
+		if (isset($this->_req_data['order'])) {
1088
+			$sort = (isset($this->_req_data['order']) && ! empty($this->_req_data['order'])) ? $this->_req_data['order']
1089
+				: 'DESC';
1090
+			$query_params['order_by'] = array('LOG_time' => $sort);
1091
+		} else {
1092
+			$query_params['order_by'] = array('LOG_time' => 'DESC');
1093
+		}
1094
+		$offset = ($current_page - 1) * $per_page;
1095
+		if (! isset($this->_req_data['download_results'])) {
1096
+			$query_params['limit'] = array($offset, $per_page);
1097
+		}
1098
+		// now they've requested to instead just download the file instead of viewing it.
1099
+		if (isset($this->_req_data['download_results'])) {
1100
+			$wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
1101
+			header('Content-Disposition: attachment');
1102
+			header("Content-Disposition: attachment; filename=ee_payment_logs_for_" . sanitize_key(site_url()));
1103
+			echo "<h1>Payment Logs for " . site_url() . "</h1>";
1104
+			echo "<h3>Query:</h3>";
1105
+			var_dump($query_params);
1106
+			echo "<h3>Results:</h3>";
1107
+			var_dump($wpdb_results);
1108
+			die;
1109
+		}
1110
+		$results = EEM_Change_Log::instance()->get_all($query_params);
1111
+		return $results;
1112
+	}
1113
+
1114
+
1115
+	/**
1116
+	 * Used by usort to RE-sort log query results, because we lose the ordering
1117
+	 * because we're possibly combining the results from two queries
1118
+	 *
1119
+	 * @param EE_Change_Log $logA
1120
+	 * @param EE_Change_Log $logB
1121
+	 * @return int
1122
+	 */
1123
+	protected function _sort_logs_again($logA, $logB)
1124
+	{
1125
+		$timeA = $logA->get_raw('LOG_time');
1126
+		$timeB = $logB->get_raw('LOG_time');
1127
+		if ($timeA == $timeB) {
1128
+			return 0;
1129
+		}
1130
+		$comparison = $timeA < $timeB ? -1 : 1;
1131
+		if (strtoupper($this->_sort_logs_again_direction) == 'DESC') {
1132
+			return $comparison * -1;
1133
+		} else {
1134
+			return $comparison;
1135
+		}
1136
+	}
1137
+
1138
+
1139
+	protected function _payment_log_details()
1140
+	{
1141
+		EE_Registry::instance()->load_model('Change_Log');
1142
+		/** @var $payment_log EE_Change_Log */
1143
+		$payment_log = EEM_Change_Log::instance()->get_one_by_ID($this->_req_data['ID']);
1144
+		$payment_method = null;
1145
+		$transaction = null;
1146
+		if ($payment_log instanceof EE_Change_Log) {
1147
+			if ($payment_log->object() instanceof EE_Payment) {
1148
+				$payment_method = $payment_log->object()->payment_method();
1149
+				$transaction = $payment_log->object()->transaction();
1150
+			} elseif ($payment_log->object() instanceof EE_Payment_Method) {
1151
+				$payment_method = $payment_log->object();
1152
+			} elseif ($payment_log->object() instanceof EE_Transaction) {
1153
+				$transaction = $payment_log->object();
1154
+				$payment_method = $transaction->payment_method();
1155
+			}
1156
+		}
1157
+		$this->_template_args['admin_page_content'] = EEH_Template::display_template(
1158
+			EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
1159
+			array(
1160
+				'payment_log'    => $payment_log,
1161
+				'payment_method' => $payment_method,
1162
+				'transaction'    => $transaction,
1163
+			),
1164
+			true
1165
+		);
1166
+		$this->display_admin_page_with_sidebar();
1167
+	}
1168 1168
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
         $payment_method_types = EE_Payment_Method_Manager::instance()->payment_method_types();
183 183
         $all_pmt_help_tabs_config = array();
184 184
         foreach ($payment_method_types as $payment_method_type) {
185
-            if (! EE_Registry::instance()->CAP->current_user_can(
185
+            if ( ! EE_Registry::instance()->CAP->current_user_can(
186 186
                 $payment_method_type->cap_name(),
187 187
                 'specific_payment_method_type_access'
188 188
             )
@@ -192,10 +192,10 @@  discard block
 block discarded – undo
192 192
             foreach ($payment_method_type->help_tabs_config() as $help_tab_name => $config) {
193 193
                 $template_args = isset($config['template_args']) ? $config['template_args'] : array();
194 194
                 $template_args['admin_page_obj'] = $this;
195
-                $all_pmt_help_tabs_config[ $help_tab_name ] = array(
195
+                $all_pmt_help_tabs_config[$help_tab_name] = array(
196 196
                     'title'   => $config['title'],
197 197
                     'content' => EEH_Template::display_template(
198
-                        $payment_method_type->file_folder() . 'help_tabs/' . $config['filename'] . '.help_tab.php',
198
+                        $payment_method_type->file_folder().'help_tabs/'.$config['filename'].'.help_tab.php',
199 199
                         $template_args,
200 200
                         true
201 201
                     ),
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
         wp_enqueue_script('ee-text-links');
242 242
         wp_enqueue_script(
243 243
             'espresso_payments',
244
-            EE_PAYMENTS_ASSETS_URL . 'espresso_payments_admin.js',
244
+            EE_PAYMENTS_ASSETS_URL.'espresso_payments_admin.js',
245 245
             array('ee-datepicker'),
246 246
             EVENT_ESPRESSO_VERSION,
247 247
             true
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
         // styles
255 255
         wp_register_style(
256 256
             'espresso_payments',
257
-            EE_PAYMENTS_ASSETS_URL . 'ee-payments.css',
257
+            EE_PAYMENTS_ASSETS_URL.'ee-payments.css',
258 258
             array(),
259 259
             EVENT_ESPRESSO_VERSION
260 260
         );
@@ -283,7 +283,7 @@  discard block
 block discarded – undo
283 283
                 continue;
284 284
             }
285 285
             // check access
286
-            if (! EE_Registry::instance()->CAP->current_user_can(
286
+            if ( ! EE_Registry::instance()->CAP->current_user_can(
287 287
                 $pmt_obj->cap_name(),
288 288
                 'specific_payment_method_type_access'
289 289
             )
@@ -292,7 +292,7 @@  discard block
 block discarded – undo
292 292
             }
293 293
             // check for any active pms of that type
294 294
             $payment_method = EEM_Payment_Method::instance()->get_one_of_type($pmt_obj->system_name());
295
-            if (! $payment_method instanceof EE_Payment_Method) {
295
+            if ( ! $payment_method instanceof EE_Payment_Method) {
296 296
                 $payment_method = EE_Payment_Method::new_instance(
297 297
                     array(
298 298
                         'PMD_slug'       => sanitize_key($pmt_obj->system_name()),
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
                     )
303 303
                 );
304 304
             }
305
-            $payment_methods[ $payment_method->slug() ] = $payment_method;
305
+            $payment_methods[$payment_method->slug()] = $payment_method;
306 306
         }
307 307
         $payment_methods = apply_filters(
308 308
             'FHEE__Payments_Admin_Page___payment_methods_list__payment_methods',
@@ -312,7 +312,7 @@  discard block
 block discarded – undo
312 312
             if ($payment_method instanceof EE_Payment_Method) {
313 313
                 add_meta_box(
314 314
                     // html id
315
-                    'espresso_' . $payment_method->slug() . '_payment_settings',
315
+                    'espresso_'.$payment_method->slug().'_payment_settings',
316 316
                     // title
317 317
                     sprintf(__('%s Settings', 'event_espresso'), $payment_method->admin_name()),
318 318
                     // callback
@@ -327,10 +327,10 @@  discard block
 block discarded – undo
327 327
                     array('payment_method' => $payment_method)
328 328
                 );
329 329
                 // setup for tabbed content
330
-                $tabs[ $payment_method->slug() ] = array(
330
+                $tabs[$payment_method->slug()] = array(
331 331
                     'label' => $payment_method->admin_name(),
332 332
                     'class' => $payment_method->active() ? 'gateway-active' : '',
333
-                    'href'  => 'espresso_' . $payment_method->slug() . '_payment_settings',
333
+                    'href'  => 'espresso_'.$payment_method->slug().'_payment_settings',
334 334
                     'title' => __('Modify this Payment Method', 'event_espresso'),
335 335
                     'slug'  => $payment_method->slug(),
336 336
                 );
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
         }
362 362
         $payment_method = EEM_Payment_Method::instance()->get_one(array(array('PMD_slug' => $payment_method_slug)));
363 363
         // if that didn't work or wasn't provided, find another way to select the current pm
364
-        if (! $this->_verify_payment_method($payment_method)) {
364
+        if ( ! $this->_verify_payment_method($payment_method)) {
365 365
             // like, looking for an active one
366 366
             $payment_method = EEM_Payment_Method::instance()->get_one_active('CART');
367 367
             // test that one as well
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
     {
411 411
         $payment_method = isset($metabox['args'], $metabox['args']['payment_method'])
412 412
             ? $metabox['args']['payment_method'] : null;
413
-        if (! $payment_method instanceof EE_Payment_Method) {
413
+        if ( ! $payment_method instanceof EE_Payment_Method) {
414 414
             throw new EE_Error(
415 415
                 sprintf(
416 416
                     __(
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
             if ($form->form_data_present_in($this->_req_data)) {
428 428
                 $form->receive_form_submission($this->_req_data);
429 429
             }
430
-            echo $form->form_open() . $form->get_html_and_js() . $form->form_close();
430
+            echo $form->form_open().$form->get_html_and_js().$form->form_close();
431 431
         } else {
432 432
             echo $this->_activate_payment_method_button($payment_method)->get_html_and_js();
433 433
         }
@@ -443,13 +443,13 @@  discard block
 block discarded – undo
443 443
      */
444 444
     protected function _generate_payment_method_settings_form(EE_Payment_Method $payment_method)
445 445
     {
446
-        if (! $payment_method instanceof EE_Payment_Method) {
446
+        if ( ! $payment_method instanceof EE_Payment_Method) {
447 447
             return new EE_Form_Section_Proper();
448 448
         }
449 449
         return new EE_Form_Section_Proper(
450 450
             array(
451
-                'name'            => $payment_method->slug() . '_settings_form',
452
-                'html_id'         => $payment_method->slug() . '_settings_form',
451
+                'name'            => $payment_method->slug().'_settings_form',
452
+                'html_id'         => $payment_method->slug().'_settings_form',
453 453
                 'action'          => EE_Admin_Page::add_query_args_and_nonce(
454 454
                     array(
455 455
                         'action'         => 'update_payment_method',
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
                             EEH_HTML::label(
493 493
                                 EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
494 494
                             )
495
-                        ) .
495
+                        ).
496 496
                         EEH_HTML::td(
497 497
                             EEH_HTML::strong(
498 498
                                 __(
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
      */
528 528
     protected function _currency_support(EE_Payment_Method $payment_method)
529 529
     {
530
-        if (! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
530
+        if ( ! $payment_method->usable_for_currency(EE_Config::instance()->currency->code)) {
531 531
             return new EE_Form_Section_HTML(
532 532
                 EEH_HTML::table(
533 533
                     EEH_HTML::tr(
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
                             EEH_HTML::label(
536 536
                                 EEH_HTML::strong(__('IMPORTANT', 'event_espresso'), '', 'important-notice')
537 537
                             )
538
-                        ) .
538
+                        ).
539 539
                         EEH_HTML::td(
540 540
                             EEH_HTML::strong(
541 541
                                 sprintf(
@@ -616,7 +616,7 @@  discard block
 block discarded – undo
616 616
         $update_button = new EE_Submit_Input(
617 617
             array(
618 618
                 'name'       => 'submit',
619
-                'html_id'    => 'save_' . $payment_method->slug() . '_settings',
619
+                'html_id'    => 'save_'.$payment_method->slug().'_settings',
620 620
                 'default'    => sprintf(
621 621
                     __('Update %s Payment Settings', 'event_espresso'),
622 622
                     $payment_method->admin_name()
@@ -626,9 +626,9 @@  discard block
 block discarded – undo
626 626
         );
627 627
         return new EE_Form_Section_HTML(
628 628
             EEH_HTML::table(
629
-                EEH_HTML::no_row(EEH_HTML::br(2)) .
629
+                EEH_HTML::no_row(EEH_HTML::br(2)).
630 630
                 EEH_HTML::tr(
631
-                    EEH_HTML::th(__('Update Settings', 'event_espresso')) .
631
+                    EEH_HTML::th(__('Update Settings', 'event_espresso')).
632 632
                     EEH_HTML::td(
633 633
                         $update_button->get_html_for_input()
634 634
                     )
@@ -654,7 +654,7 @@  discard block
 block discarded – undo
654 654
         return new EE_Form_Section_HTML(
655 655
             EEH_HTML::table(
656 656
                 EEH_HTML::tr(
657
-                    EEH_HTML::th(__('Deactivate Payment Method', 'event_espresso')) .
657
+                    EEH_HTML::th(__('Deactivate Payment Method', 'event_espresso')).
658 658
                     EEH_HTML::td(
659 659
                         EEH_HTML::link(
660 660
                             EE_Admin_Page::add_query_args_and_nonce(
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
                             ),
667 667
                             $link_text_and_title,
668 668
                             $link_text_and_title,
669
-                            'deactivate_' . $payment_method->slug(),
669
+                            'deactivate_'.$payment_method->slug(),
670 670
                             'espresso-button button-secondary'
671 671
                         )
672 672
                     )
@@ -691,8 +691,8 @@  discard block
 block discarded – undo
691 691
         );
692 692
         return new EE_Form_Section_Proper(
693 693
             array(
694
-                'name'            => 'activate_' . $payment_method->slug() . '_settings_form',
695
-                'html_id'         => 'activate_' . $payment_method->slug() . '_settings_form',
694
+                'name'            => 'activate_'.$payment_method->slug().'_settings_form',
695
+                'html_id'         => 'activate_'.$payment_method->slug().'_settings_form',
696 696
                 'action'          => '#',
697 697
                 'layout_strategy' => new EE_Admin_Two_Column_Layout(),
698 698
                 'subsections'     => apply_filters(
@@ -708,11 +708,11 @@  discard block
 block discarded – undo
708 708
                                         '',
709 709
                                         'colspan="2"'
710 710
                                     )
711
-                                ) .
711
+                                ).
712 712
                                 EEH_HTML::tr(
713 713
                                     EEH_HTML::th(
714 714
                                         EEH_HTML::label(__('Click to Activate ', 'event_espresso'))
715
-                                    ) .
715
+                                    ).
716 716
                                     EEH_HTML::td(
717 717
                                         EEH_HTML::link(
718 718
                                             EE_Admin_Page::add_query_args_and_nonce(
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
                                             ),
725 725
                                             $link_text_and_title,
726 726
                                             $link_text_and_title,
727
-                                            'activate_' . $payment_method->slug(),
727
+                                            'activate_'.$payment_method->slug(),
728 728
                                             'espresso-button-green button-primary'
729 729
                                         )
730 730
                                     )
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
         return new EE_Form_Section_HTML(
751 751
             EEH_HTML::table(
752 752
                 EEH_HTML::tr(
753
-                    EEH_HTML::th() .
753
+                    EEH_HTML::th().
754 754
                     EEH_HTML::td(
755 755
                         EEH_HTML::p(__('All fields marked with a * are required fields', 'event_espresso'), '', 'grey-text')
756 756
                     )
@@ -834,7 +834,7 @@  discard block
 block discarded – undo
834 834
                 }
835 835
             }
836 836
             // if we couldn't find the correct payment method type...
837
-            if (! $correct_pmt_form_to_use) {
837
+            if ( ! $correct_pmt_form_to_use) {
838 838
                 EE_Error::add_error(
839 839
                     __(
840 840
                         "We could not find which payment method type your form submission related to. Please contact support",
@@ -849,7 +849,7 @@  discard block
 block discarded – undo
849 849
             $correct_pmt_form_to_use->receive_form_submission($this->_req_data);
850 850
             if ($correct_pmt_form_to_use->is_valid()) {
851 851
                 $payment_settings_subform = $correct_pmt_form_to_use->get_subsection('payment_method_settings');
852
-                if (! $payment_settings_subform instanceof EE_Payment_Method_Form) {
852
+                if ( ! $payment_settings_subform instanceof EE_Payment_Method_Form) {
853 853
                     throw new EE_Error(
854 854
                         sprintf(
855 855
                             __(
@@ -901,7 +901,7 @@  discard block
 block discarded – undo
901 901
         $form = $this->getPaymentSettingsForm();
902 902
         $this->_set_add_edit_form_tags('update_payment_settings');
903 903
         $this->_set_publish_post_box_vars(null, false, false, null, false);
904
-        $this->_template_args['admin_page_content'] =  $form->get_html_and_js();
904
+        $this->_template_args['admin_page_content'] = $form->get_html_and_js();
905 905
         $this->display_admin_page_with_sidebar();
906 906
     }
907 907
 
@@ -937,7 +937,7 @@  discard block
 block discarded – undo
937 937
             EE_Registry::instance()->CFG
938 938
         );
939 939
 
940
-        $cfg =  EE_Registry::instance()->CFG ;
940
+        $cfg = EE_Registry::instance()->CFG;
941 941
 
942 942
         $what = __('Payment Settings', 'event_espresso');
943 943
         $success = $this->_update_espresso_configuration(
@@ -1038,7 +1038,7 @@  discard block
 block discarded – undo
1038 1038
         }
1039 1039
         // take into account search
1040 1040
         if (isset($this->_req_data['s']) && $this->_req_data['s']) {
1041
-            $similarity_string = array('LIKE', '%' . str_replace("", "%", $this->_req_data['s']) . '%');
1041
+            $similarity_string = array('LIKE', '%'.str_replace("", "%", $this->_req_data['s']).'%');
1042 1042
             $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_fname'] = $similarity_string;
1043 1043
             $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_lname'] = $similarity_string;
1044 1044
             $query_params[0]['OR*s']['Payment.Transaction.Registration.Attendee.ATT_email'] = $similarity_string;
@@ -1058,8 +1058,8 @@  discard block
 block discarded – undo
1058 1058
             $start_date = wp_strip_all_tags($this->_req_data['payment-filter-start-date']);
1059 1059
             $end_date = wp_strip_all_tags($this->_req_data['payment-filter-end-date']);
1060 1060
             // make sure our timestamps start and end right at the boundaries for each day
1061
-            $start_date = date('Y-m-d', strtotime($start_date)) . ' 00:00:00';
1062
-            $end_date = date('Y-m-d', strtotime($end_date)) . ' 23:59:59';
1061
+            $start_date = date('Y-m-d', strtotime($start_date)).' 00:00:00';
1062
+            $end_date = date('Y-m-d', strtotime($end_date)).' 23:59:59';
1063 1063
             // convert to timestamps
1064 1064
             $start_date = strtotime($start_date);
1065 1065
             $end_date = strtotime($end_date);
@@ -1092,15 +1092,15 @@  discard block
 block discarded – undo
1092 1092
             $query_params['order_by'] = array('LOG_time' => 'DESC');
1093 1093
         }
1094 1094
         $offset = ($current_page - 1) * $per_page;
1095
-        if (! isset($this->_req_data['download_results'])) {
1095
+        if ( ! isset($this->_req_data['download_results'])) {
1096 1096
             $query_params['limit'] = array($offset, $per_page);
1097 1097
         }
1098 1098
         // now they've requested to instead just download the file instead of viewing it.
1099 1099
         if (isset($this->_req_data['download_results'])) {
1100 1100
             $wpdb_results = EEM_Change_Log::instance()->get_all_efficiently($query_params);
1101 1101
             header('Content-Disposition: attachment');
1102
-            header("Content-Disposition: attachment; filename=ee_payment_logs_for_" . sanitize_key(site_url()));
1103
-            echo "<h1>Payment Logs for " . site_url() . "</h1>";
1102
+            header("Content-Disposition: attachment; filename=ee_payment_logs_for_".sanitize_key(site_url()));
1103
+            echo "<h1>Payment Logs for ".site_url()."</h1>";
1104 1104
             echo "<h3>Query:</h3>";
1105 1105
             var_dump($query_params);
1106 1106
             echo "<h3>Results:</h3>";
@@ -1155,7 +1155,7 @@  discard block
 block discarded – undo
1155 1155
             }
1156 1156
         }
1157 1157
         $this->_template_args['admin_page_content'] = EEH_Template::display_template(
1158
-            EE_PAYMENTS_TEMPLATE_PATH . 'payment_log_details.template.php',
1158
+            EE_PAYMENTS_TEMPLATE_PATH.'payment_log_details.template.php',
1159 1159
             array(
1160 1160
                 'payment_log'    => $payment_log,
1161 1161
                 'payment_method' => $payment_method,
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -38,103 +38,103 @@
 block discarded – undo
38 38
  * @since           4.0
39 39
  */
40 40
 if (function_exists('espresso_version')) {
41
-    if (! function_exists('espresso_duplicate_plugin_error')) {
42
-        /**
43
-         *    espresso_duplicate_plugin_error
44
-         *    displays if more than one version of EE is activated at the same time
45
-         */
46
-        function espresso_duplicate_plugin_error()
47
-        {
48
-            ?>
41
+	if (! function_exists('espresso_duplicate_plugin_error')) {
42
+		/**
43
+		 *    espresso_duplicate_plugin_error
44
+		 *    displays if more than one version of EE is activated at the same time
45
+		 */
46
+		function espresso_duplicate_plugin_error()
47
+		{
48
+			?>
49 49
             <div class="error">
50 50
                 <p>
51 51
                     <?php
52
-                    echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                    ); ?>
52
+					echo esc_html__(
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+					); ?>
56 56
                 </p>
57 57
             </div>
58 58
             <?php
59
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-        }
61
-    }
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
59
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+		}
61
+	}
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
-    if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.6.2');
65
+	if (! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                        esc_html__(
79
-                            'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                            'event_espresso'
81
-                        ),
82
-                        EE_MIN_PHP_VER_REQUIRED,
83
-                        PHP_VERSION,
84
-                        '<br/>',
85
-                        '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+						esc_html__(
79
+							'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+							'event_espresso'
81
+						),
82
+						EE_MIN_PHP_VER_REQUIRED,
83
+						PHP_VERSION,
84
+						'<br/>',
85
+						'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
-        /**
98
-         * espresso_version
99
-         * Returns the plugin version
100
-         *
101
-         * @return string
102
-         */
103
-        function espresso_version()
104
-        {
105
-            return apply_filters('FHEE__espresso__espresso_version', '4.10.11.rc.021');
106
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
97
+		/**
98
+		 * espresso_version
99
+		 * Returns the plugin version
100
+		 *
101
+		 * @return string
102
+		 */
103
+		function espresso_version()
104
+		{
105
+			return apply_filters('FHEE__espresso__espresso_version', '4.10.11.rc.021');
106
+		}
107 107
 
108
-        /**
109
-         * espresso_plugin_activation
110
-         * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
-         */
112
-        function espresso_plugin_activation()
113
-        {
114
-            update_option('ee_espresso_activation', true);
115
-        }
108
+		/**
109
+		 * espresso_plugin_activation
110
+		 * adds a wp-option to indicate that EE has been activated via the WP admin plugins page
111
+		 */
112
+		function espresso_plugin_activation()
113
+		{
114
+			update_option('ee_espresso_activation', true);
115
+		}
116 116
 
117
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
117
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
118 118
 
119
-        require_once __DIR__ . '/core/bootstrap_espresso.php';
120
-        bootstrap_espresso();
121
-    }
119
+		require_once __DIR__ . '/core/bootstrap_espresso.php';
120
+		bootstrap_espresso();
121
+	}
122 122
 }
123 123
 if (! function_exists('espresso_deactivate_plugin')) {
124
-    /**
125
-     *    deactivate_plugin
126
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
-     *
128
-     * @access public
129
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
-     * @return    void
131
-     */
132
-    function espresso_deactivate_plugin($plugin_basename = '')
133
-    {
134
-        if (! function_exists('deactivate_plugins')) {
135
-            require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
-        }
137
-        unset($_GET['activate'], $_REQUEST['activate']);
138
-        deactivate_plugins($plugin_basename);
139
-    }
124
+	/**
125
+	 *    deactivate_plugin
126
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
127
+	 *
128
+	 * @access public
129
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
130
+	 * @return    void
131
+	 */
132
+	function espresso_deactivate_plugin($plugin_basename = '')
133
+	{
134
+		if (! function_exists('deactivate_plugins')) {
135
+			require_once ABSPATH . 'wp-admin/includes/plugin.php';
136
+		}
137
+		unset($_GET['activate'], $_REQUEST['activate']);
138
+		deactivate_plugins($plugin_basename);
139
+	}
140 140
 }
Please login to merge, or discard this patch.