Completed
Branch FET-Wait-List (17173f)
by
unknown
127:02 queued 116:59
created
core/db_models/EEM_Base.model.php 2 patches
Indentation   +6006 added lines, -6006 removed lines patch added patch discarded remove patch
@@ -32,6014 +32,6014 @@
 block discarded – undo
32 32
 abstract class EEM_Base extends EE_Base implements ResettableInterface
33 33
 {
34 34
 
35
-    /**
36
-     * Flag to indicate whether the values provided to EEM_Base have already been prepared
37
-     * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
38
-     * They almost always WILL NOT, but it's not necessarily a requirement.
39
-     * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
40
-     *
41
-     * @var boolean
42
-     */
43
-    private $_values_already_prepared_by_model_object = 0;
44
-
45
-    /**
46
-     * when $_values_already_prepared_by_model_object equals this, we assume
47
-     * the data is just like form input that needs to have the model fields'
48
-     * prepare_for_set and prepare_for_use_in_db called on it
49
-     */
50
-    const not_prepared_by_model_object = 0;
51
-
52
-    /**
53
-     * when $_values_already_prepared_by_model_object equals this, we
54
-     * assume this value is coming from a model object and doesn't need to have
55
-     * prepare_for_set called on it, just prepare_for_use_in_db is used
56
-     */
57
-    const prepared_by_model_object = 1;
58
-
59
-    /**
60
-     * when $_values_already_prepared_by_model_object equals this, we assume
61
-     * the values are already to be used in the database (ie no processing is done
62
-     * on them by the model's fields)
63
-     */
64
-    const prepared_for_use_in_db = 2;
65
-
66
-
67
-    protected $singular_item = 'Item';
68
-
69
-    protected $plural_item   = 'Items';
70
-
71
-    /**
72
-     * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
73
-     */
74
-    protected $_tables;
75
-
76
-    /**
77
-     * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
78
-     * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
79
-     * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
80
-     *
81
-     * @var \EE_Model_Field_Base[][] $_fields
82
-     */
83
-    protected $_fields;
84
-
85
-    /**
86
-     * array of different kinds of relations
87
-     *
88
-     * @var \EE_Model_Relation_Base[] $_model_relations
89
-     */
90
-    protected $_model_relations;
91
-
92
-    /**
93
-     * @var \EE_Index[] $_indexes
94
-     */
95
-    protected $_indexes = array();
96
-
97
-    /**
98
-     * Default strategy for getting where conditions on this model. This strategy is used to get default
99
-     * where conditions which are added to get_all, update, and delete queries. They can be overridden
100
-     * by setting the same columns as used in these queries in the query yourself.
101
-     *
102
-     * @var EE_Default_Where_Conditions
103
-     */
104
-    protected $_default_where_conditions_strategy;
105
-
106
-    /**
107
-     * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
108
-     * This is particularly useful when you want something between 'none' and 'default'
109
-     *
110
-     * @var EE_Default_Where_Conditions
111
-     */
112
-    protected $_minimum_where_conditions_strategy;
113
-
114
-    /**
115
-     * String describing how to find the "owner" of this model's objects.
116
-     * When there is a foreign key on this model to the wp_users table, this isn't needed.
117
-     * But when there isn't, this indicates which related model, or transiently-related model,
118
-     * has the foreign key to the wp_users table.
119
-     * Eg, for EEM_Registration this would be 'Event' because registrations are directly
120
-     * related to events, and events have a foreign key to wp_users.
121
-     * On EEM_Transaction, this would be 'Transaction.Event'
122
-     *
123
-     * @var string
124
-     */
125
-    protected $_model_chain_to_wp_user = '';
126
-
127
-    /**
128
-     * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
129
-     * don't need it (particularly CPT models)
130
-     *
131
-     * @var bool
132
-     */
133
-    protected $_ignore_where_strategy = false;
134
-
135
-    /**
136
-     * String used in caps relating to this model. Eg, if the caps relating to this
137
-     * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
138
-     *
139
-     * @var string. If null it hasn't been initialized yet. If false then we
140
-     * have indicated capabilities don't apply to this
141
-     */
142
-    protected $_caps_slug = null;
143
-
144
-    /**
145
-     * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
146
-     * and next-level keys are capability names, and each's value is a
147
-     * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
148
-     * they specify which context to use (ie, frontend, backend, edit or delete)
149
-     * and then each capability in the corresponding sub-array that they're missing
150
-     * adds the where conditions onto the query.
151
-     *
152
-     * @var array
153
-     */
154
-    protected $_cap_restrictions = array(
155
-        self::caps_read       => array(),
156
-        self::caps_read_admin => array(),
157
-        self::caps_edit       => array(),
158
-        self::caps_delete     => array(),
159
-    );
160
-
161
-    /**
162
-     * Array defining which cap restriction generators to use to create default
163
-     * cap restrictions to put in EEM_Base::_cap_restrictions.
164
-     * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
165
-     * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
166
-     * automatically set this to false (not just null).
167
-     *
168
-     * @var EE_Restriction_Generator_Base[]
169
-     */
170
-    protected $_cap_restriction_generators = array();
171
-
172
-    /**
173
-     * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
174
-     */
175
-    const caps_read       = 'read';
176
-
177
-    const caps_read_admin = 'read_admin';
178
-
179
-    const caps_edit       = 'edit';
180
-
181
-    const caps_delete     = 'delete';
182
-
183
-    /**
184
-     * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
185
-     * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
186
-     * maps to 'read' because when looking for relevant permissions we're going to use
187
-     * 'read' in teh capabilities names like 'ee_read_events' etc.
188
-     *
189
-     * @var array
190
-     */
191
-    protected $_cap_contexts_to_cap_action_map = array(
192
-        self::caps_read       => 'read',
193
-        self::caps_read_admin => 'read',
194
-        self::caps_edit       => 'edit',
195
-        self::caps_delete     => 'delete',
196
-    );
197
-
198
-    /**
199
-     * Timezone
200
-     * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
201
-     * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
202
-     * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
203
-     * EE_Datetime_Field data type will have access to it.
204
-     *
205
-     * @var string
206
-     */
207
-    protected $_timezone;
208
-
209
-
210
-    /**
211
-     * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
212
-     * multisite.
213
-     *
214
-     * @var int
215
-     */
216
-    protected static $_model_query_blog_id;
217
-
218
-    /**
219
-     * A copy of _fields, except the array keys are the model names pointed to by
220
-     * the field
221
-     *
222
-     * @var EE_Model_Field_Base[]
223
-     */
224
-    private $_cache_foreign_key_to_fields = array();
225
-
226
-    /**
227
-     * Cached list of all the fields on the model, indexed by their name
228
-     *
229
-     * @var EE_Model_Field_Base[]
230
-     */
231
-    private $_cached_fields = null;
232
-
233
-    /**
234
-     * Cached list of all the fields on the model, except those that are
235
-     * marked as only pertinent to the database
236
-     *
237
-     * @var EE_Model_Field_Base[]
238
-     */
239
-    private $_cached_fields_non_db_only = null;
240
-
241
-    /**
242
-     * A cached reference to the primary key for quick lookup
243
-     *
244
-     * @var EE_Model_Field_Base
245
-     */
246
-    private $_primary_key_field = null;
247
-
248
-    /**
249
-     * Flag indicating whether this model has a primary key or not
250
-     *
251
-     * @var boolean
252
-     */
253
-    protected $_has_primary_key_field = null;
254
-
255
-    /**
256
-     * Whether or not this model is based off a table in WP core only (CPTs should set
257
-     * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
258
-     * This should be true for models that deal with data that should exist independent of EE.
259
-     * For example, if the model can read and insert data that isn't used by EE, this should be true.
260
-     * It would be false, however, if you could guarantee the model would only interact with EE data,
261
-     * even if it uses a WP core table (eg event and venue models set this to false for that reason:
262
-     * they can only read and insert events and venues custom post types, not arbitrary post types)
263
-     * @var boolean
264
-     */
265
-    protected $_wp_core_model = false;
266
-
267
-    /**
268
-     *    List of valid operators that can be used for querying.
269
-     * The keys are all operators we'll accept, the values are the real SQL
270
-     * operators used
271
-     *
272
-     * @var array
273
-     */
274
-    protected $_valid_operators = array(
275
-        '='           => '=',
276
-        '<='          => '<=',
277
-        '<'           => '<',
278
-        '>='          => '>=',
279
-        '>'           => '>',
280
-        '!='          => '!=',
281
-        'LIKE'        => 'LIKE',
282
-        'like'        => 'LIKE',
283
-        'NOT_LIKE'    => 'NOT LIKE',
284
-        'not_like'    => 'NOT LIKE',
285
-        'NOT LIKE'    => 'NOT LIKE',
286
-        'not like'    => 'NOT LIKE',
287
-        'IN'          => 'IN',
288
-        'in'          => 'IN',
289
-        'NOT_IN'      => 'NOT IN',
290
-        'not_in'      => 'NOT IN',
291
-        'NOT IN'      => 'NOT IN',
292
-        'not in'      => 'NOT IN',
293
-        'between'     => 'BETWEEN',
294
-        'BETWEEN'     => 'BETWEEN',
295
-        'IS_NOT_NULL' => 'IS NOT NULL',
296
-        'is_not_null' => 'IS NOT NULL',
297
-        'IS NOT NULL' => 'IS NOT NULL',
298
-        'is not null' => 'IS NOT NULL',
299
-        'IS_NULL'     => 'IS NULL',
300
-        'is_null'     => 'IS NULL',
301
-        'IS NULL'     => 'IS NULL',
302
-        'is null'     => 'IS NULL',
303
-        'REGEXP'      => 'REGEXP',
304
-        'regexp'      => 'REGEXP',
305
-        'NOT_REGEXP'  => 'NOT REGEXP',
306
-        'not_regexp'  => 'NOT REGEXP',
307
-        'NOT REGEXP'  => 'NOT REGEXP',
308
-        'not regexp'  => 'NOT REGEXP',
309
-    );
310
-
311
-    /**
312
-     * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
313
-     *
314
-     * @var array
315
-     */
316
-    protected $_in_style_operators = array('IN', 'NOT IN');
317
-
318
-    /**
319
-     * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
320
-     * '12-31-2012'"
321
-     *
322
-     * @var array
323
-     */
324
-    protected $_between_style_operators = array('BETWEEN');
325
-
326
-    /**
327
-     * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
328
-     * @var array
329
-     */
330
-    protected $_like_style_operators = array('LIKE', 'NOT LIKE');
331
-    /**
332
-     * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
333
-     * on a join table.
334
-     *
335
-     * @var array
336
-     */
337
-    protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
338
-
339
-    /**
340
-     * Allowed values for $query_params['order'] for ordering in queries
341
-     *
342
-     * @var array
343
-     */
344
-    protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
345
-
346
-    /**
347
-     * When these are keys in a WHERE or HAVING clause, they are handled much differently
348
-     * than regular field names. It is assumed that their values are an array of WHERE conditions
349
-     *
350
-     * @var array
351
-     */
352
-    private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
353
-
354
-    /**
355
-     * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
356
-     * 'where', but 'where' clauses are so common that we thought we'd omit it
357
-     *
358
-     * @var array
359
-     */
360
-    private $_allowed_query_params = array(
361
-        0,
362
-        'limit',
363
-        'order_by',
364
-        'group_by',
365
-        'having',
366
-        'force_join',
367
-        'order',
368
-        'on_join_limit',
369
-        'default_where_conditions',
370
-        'caps',
371
-    );
372
-
373
-    /**
374
-     * All the data types that can be used in $wpdb->prepare statements.
375
-     *
376
-     * @var array
377
-     */
378
-    private $_valid_wpdb_data_types = array('%d', '%s', '%f');
379
-
380
-    /**
381
-     * @var EE_Registry $EE
382
-     */
383
-    protected $EE = null;
384
-
385
-
386
-    /**
387
-     * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
-     *
389
-     * @var int
390
-     */
391
-    protected $_show_next_x_db_queries = 0;
392
-
393
-    /**
394
-     * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
-     * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
-     *
397
-     * @var array
398
-     */
399
-    protected $_custom_selections = array();
400
-
401
-    /**
402
-     * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
-     * caches every model object we've fetched from the DB on this request
404
-     *
405
-     * @var array
406
-     */
407
-    protected $_entity_map;
408
-
409
-    /**
410
-     * @var LoaderInterface $loader
411
-     */
412
-    private static $loader;
413
-
414
-
415
-    /**
416
-     * constant used to show EEM_Base has not yet verified the db on this http request
417
-     */
418
-    const db_verified_none = 0;
419
-
420
-    /**
421
-     * constant used to show EEM_Base has verified the EE core db on this http request,
422
-     * but not the addons' dbs
423
-     */
424
-    const db_verified_core = 1;
425
-
426
-    /**
427
-     * constant used to show EEM_Base has verified the addons' dbs (and implicitly
428
-     * the EE core db too)
429
-     */
430
-    const db_verified_addons = 2;
431
-
432
-    /**
433
-     * indicates whether an EEM_Base child has already re-verified the DB
434
-     * is ok (we don't want to do it repetitively). Should be set to one the constants
435
-     * looking like EEM_Base::db_verified_*
436
-     *
437
-     * @var int - 0 = none, 1 = core, 2 = addons
438
-     */
439
-    protected static $_db_verification_level = EEM_Base::db_verified_none;
440
-
441
-    /**
442
-     * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
443
-     *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
444
-     *        registrations for non-trashed tickets for non-trashed datetimes)
445
-     */
446
-    const default_where_conditions_all = 'all';
447
-
448
-    /**
449
-     * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
450
-     *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
451
-     *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
452
-     *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
453
-     *        models which share tables with other models, this can return data for the wrong model.
454
-     */
455
-    const default_where_conditions_this_only = 'this_model_only';
456
-
457
-    /**
458
-     * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
459
-     *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
460
-     *        return all registrations related to non-trashed tickets and non-trashed datetimes)
461
-     */
462
-    const default_where_conditions_others_only = 'other_models_only';
463
-
464
-    /**
465
-     * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
466
-     *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
467
-     *        their table with other models, like the Event and Venue models. For example, when querying for events
468
-     *        ordered by their venues' name, this will be sure to only return real events with associated real venues
469
-     *        (regardless of whether those events and venues are trashed)
470
-     *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
471
-     *        events.
472
-     */
473
-    const default_where_conditions_minimum_all = 'minimum';
474
-
475
-    /**
476
-     * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
477
-     *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
478
-     *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
479
-     *        not)
480
-     */
481
-    const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
-
483
-    /**
484
-     * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
485
-     *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
486
-     *        it's possible it will return table entries for other models. You should use
487
-     *        EEM_Base::default_where_conditions_minimum_all instead.
488
-     */
489
-    const default_where_conditions_none = 'none';
490
-
491
-
492
-
493
-    /**
494
-     * About all child constructors:
495
-     * they should define the _tables, _fields and _model_relations arrays.
496
-     * Should ALWAYS be called after child constructor.
497
-     * In order to make the child constructors to be as simple as possible, this parent constructor
498
-     * finalizes constructing all the object's attributes.
499
-     * Generally, rather than requiring a child to code
500
-     * $this->_tables = array(
501
-     *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
502
-     *        ...);
503
-     *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
504
-     * each EE_Table has a function to set the table's alias after the constructor, using
505
-     * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
506
-     * do something similar.
507
-     *
508
-     * @param null $timezone
509
-     * @throws EE_Error
510
-     */
511
-    protected function __construct($timezone = null)
512
-    {
513
-        // check that the model has not been loaded too soon
514
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
-            throw new EE_Error (
516
-                sprintf(
517
-                    __('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.',
518
-                        'event_espresso'),
519
-                    get_class($this)
520
-                )
521
-            );
522
-        }
523
-        /**
524
-         * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
525
-         */
526
-        if (empty(EEM_Base::$_model_query_blog_id)) {
527
-            EEM_Base::set_model_query_blog_id();
528
-        }
529
-        /**
530
-         * Filters the list of tables on a model. It is best to NOT use this directly and instead
531
-         * just use EE_Register_Model_Extension
532
-         *
533
-         * @var EE_Table_Base[] $_tables
534
-         */
535
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
536
-        foreach ($this->_tables as $table_alias => $table_obj) {
537
-            /** @var $table_obj EE_Table_Base */
538
-            $table_obj->_construct_finalize_with_alias($table_alias);
539
-            if ($table_obj instanceof EE_Secondary_Table) {
540
-                /** @var $table_obj EE_Secondary_Table */
541
-                $table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
542
-            }
543
-        }
544
-        /**
545
-         * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
546
-         * EE_Register_Model_Extension
547
-         *
548
-         * @param EE_Model_Field_Base[] $_fields
549
-         */
550
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
551
-        $this->_invalidate_field_caches();
552
-        foreach ($this->_fields as $table_alias => $fields_for_table) {
553
-            if (! array_key_exists($table_alias, $this->_tables)) {
554
-                throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555
-                    'event_espresso'), $table_alias, implode(",", $this->_fields)));
556
-            }
557
-            foreach ($fields_for_table as $field_name => $field_obj) {
558
-                /** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
559
-                //primary key field base has a slightly different _construct_finalize
560
-                /** @var $field_obj EE_Model_Field_Base */
561
-                $field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
562
-            }
563
-        }
564
-        // everything is related to Extra_Meta
565
-        if (get_class($this) !== 'EEM_Extra_Meta') {
566
-            //make extra meta related to everything, but don't block deleting things just
567
-            //because they have related extra meta info. For now just orphan those extra meta
568
-            //in the future we should automatically delete them
569
-            $this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
570
-        }
571
-        //and change logs
572
-        if (get_class($this) !== 'EEM_Change_Log') {
573
-            $this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
574
-        }
575
-        /**
576
-         * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
577
-         * EE_Register_Model_Extension
578
-         *
579
-         * @param EE_Model_Relation_Base[] $_model_relations
580
-         */
581
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
582
-            $this->_model_relations);
583
-        foreach ($this->_model_relations as $model_name => $relation_obj) {
584
-            /** @var $relation_obj EE_Model_Relation_Base */
585
-            $relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
586
-        }
587
-        foreach ($this->_indexes as $index_name => $index_obj) {
588
-            /** @var $index_obj EE_Index */
589
-            $index_obj->_construct_finalize($index_name, $this->get_this_model_name());
590
-        }
591
-        $this->set_timezone($timezone);
592
-        //finalize default where condition strategy, or set default
593
-        if (! $this->_default_where_conditions_strategy) {
594
-            //nothing was set during child constructor, so set default
595
-            $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596
-        }
597
-        $this->_default_where_conditions_strategy->_finalize_construct($this);
598
-        if (! $this->_minimum_where_conditions_strategy) {
599
-            //nothing was set during child constructor, so set default
600
-            $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601
-        }
602
-        $this->_minimum_where_conditions_strategy->_finalize_construct($this);
603
-        //if the cap slug hasn't been set, and we haven't set it to false on purpose
604
-        //to indicate to NOT set it, set it to the logical default
605
-        if ($this->_caps_slug === null) {
606
-            $this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
607
-        }
608
-        //initialize the standard cap restriction generators if none were specified by the child constructor
609
-        if ($this->_cap_restriction_generators !== false) {
610
-            foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
612
-                    $this->_cap_restriction_generators[$cap_context] = apply_filters(
613
-                        'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614
-                        new EE_Restriction_Generator_Protected(),
615
-                        $cap_context,
616
-                        $this
617
-                    );
618
-                }
619
-            }
620
-        }
621
-        //if there are cap restriction generators, use them to make the default cap restrictions
622
-        if ($this->_cap_restriction_generators !== false) {
623
-            foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
-                if (! $generator_object) {
625
-                    continue;
626
-                }
627
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
628
-                    throw new EE_Error(
629
-                        sprintf(
630
-                            __('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.',
631
-                                'event_espresso'),
632
-                            $context,
633
-                            $this->get_this_model_name()
634
-                        )
635
-                    );
636
-                }
637
-                $action = $this->cap_action_for_context($context);
638
-                if (! $generator_object->construction_finalized()) {
639
-                    $generator_object->_construct_finalize($this, $action);
640
-                }
641
-            }
642
-        }
643
-        do_action('AHEE__' . get_class($this) . '__construct__end');
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * Used to set the $_model_query_blog_id static property.
650
-     *
651
-     * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
652
-     *                      value for get_current_blog_id() will be used.
653
-     */
654
-    public static function set_model_query_blog_id($blog_id = 0)
655
-    {
656
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
657
-    }
658
-
659
-
660
-
661
-    /**
662
-     * Returns whatever is set as the internal $model_query_blog_id.
663
-     *
664
-     * @return int
665
-     */
666
-    public static function get_model_query_blog_id()
667
-    {
668
-        return EEM_Base::$_model_query_blog_id;
669
-    }
670
-
671
-
672
-
673
-    /**
674
-     * This function is a singleton method used to instantiate the Espresso_model object
675
-     *
676
-     * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
677
-     *                                (and any incoming timezone data that gets saved).
678
-     *                                Note this just sends the timezone info to the date time model field objects.
679
-     *                                Default is NULL
680
-     *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
681
-     * @return static (as in the concrete child class)
682
-     * @throws EE_Error
683
-     * @throws InvalidArgumentException
684
-     * @throws InvalidDataTypeException
685
-     * @throws InvalidInterfaceException
686
-     */
687
-    public static function instance($timezone = null)
688
-    {
689
-        // check if instance of Espresso_model already exists
690
-        if (! static::$_instance instanceof static) {
691
-            // instantiate Espresso_model
692
-            static::$_instance = new static(
693
-                $timezone,
694
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
695
-            );
696
-        }
697
-        //we might have a timezone set, let set_timezone decide what to do with it
698
-        static::$_instance->set_timezone($timezone);
699
-        // Espresso_model object
700
-        return static::$_instance;
701
-    }
702
-
703
-
704
-
705
-    /**
706
-     * resets the model and returns it
707
-     *
708
-     * @param null | string $timezone
709
-     * @return EEM_Base|null (if the model was already instantiated, returns it, with
710
-     * all its properties reset; if it wasn't instantiated, returns null)
711
-     * @throws EE_Error
712
-     * @throws ReflectionException
713
-     * @throws InvalidArgumentException
714
-     * @throws InvalidDataTypeException
715
-     * @throws InvalidInterfaceException
716
-     */
717
-    public static function reset($timezone = null)
718
-    {
719
-        if (static::$_instance instanceof EEM_Base) {
720
-            //let's try to NOT swap out the current instance for a new one
721
-            //because if someone has a reference to it, we can't remove their reference
722
-            //so it's best to keep using the same reference, but change the original object
723
-            //reset all its properties to their original values as defined in the class
724
-            $r = new ReflectionClass(get_class(static::$_instance));
725
-            $static_properties = $r->getStaticProperties();
726
-            foreach ($r->getDefaultProperties() as $property => $value) {
727
-                //don't set instance to null like it was originally,
728
-                //but it's static anyways, and we're ignoring static properties (for now at least)
729
-                if (! isset($static_properties[$property])) {
730
-                    static::$_instance->{$property} = $value;
731
-                }
732
-            }
733
-            //and then directly call its constructor again, like we would if we were creating a new one
734
-            static::$_instance->__construct(
735
-                $timezone,
736
-                LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
737
-            );
738
-            return self::instance();
739
-        }
740
-        return null;
741
-    }
742
-
743
-
744
-
745
-    /**
746
-     * @return LoaderInterface
747
-     * @throws InvalidArgumentException
748
-     * @throws InvalidDataTypeException
749
-     * @throws InvalidInterfaceException
750
-     */
751
-    private static function getLoader()
752
-    {
753
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
754
-            EEM_Base::$loader = LoaderFactory::getLoader();
755
-        }
756
-        return EEM_Base::$loader;
757
-    }
758
-
759
-
760
-
761
-    /**
762
-     * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
763
-     *
764
-     * @param  boolean $translated return localized strings or JUST the array.
765
-     * @return array
766
-     * @throws EE_Error
767
-     * @throws InvalidArgumentException
768
-     * @throws InvalidDataTypeException
769
-     * @throws InvalidInterfaceException
770
-     */
771
-    public function status_array($translated = false)
772
-    {
773
-        if (! array_key_exists('Status', $this->_model_relations)) {
774
-            return array();
775
-        }
776
-        $model_name = $this->get_this_model_name();
777
-        $status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
778
-        $stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
779
-        $status_array = array();
780
-        foreach ($stati as $status) {
781
-            $status_array[$status->ID()] = $status->get('STS_code');
782
-        }
783
-        return $translated
784
-            ? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
785
-            : $status_array;
786
-    }
787
-
788
-
789
-
790
-    /**
791
-     * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
792
-     *
793
-     * @param array $query_params             {
794
-     * @var array $0 (where) array {
795
-     *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
796
-     *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
797
-     *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
798
-     *                                        conditions based on related models (and even
799
-     *                                        models-related-to-related-models) prepend the model's name onto the field
800
-     *                                        name. Eg,
801
-     *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
802
-     *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
803
-     *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
804
-     *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
805
-     *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
806
-     *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
807
-     *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
808
-     *                                        to Venues (even when each of those models actually consisted of two
809
-     *                                        tables). Also, you may chain the model relations together. Eg instead of
810
-     *                                        just having
811
-     *                                        "Venue.VNU_ID", you could have
812
-     *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
813
-     *                                        events are related to Registrations, which are related to Attendees). You
814
-     *                                        can take it even further with
815
-     *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
816
-     *                                        (from the default of '='), change the value to an numerically-indexed
817
-     *                                        array, where the first item in the list is the operator. eg: array(
818
-     *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
819
-     *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
820
-     *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
821
-     *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
822
-     *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
823
-     *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
824
-     *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
825
-     *                                        the operator is IN. Also, values can actually be field names. To indicate
826
-     *                                        the value is a field, simply provide a third array item (true) to the
827
-     *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
828
-     *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
829
-     *                                        Note: you can also use related model field names like you would any other
830
-     *                                        field name. eg:
831
-     *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
832
-     *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
833
-     *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
834
-     *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
835
-     *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
836
-     *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
837
-     *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
838
-     *                                        to be what you last specified. IE, "AND"s by default, but if you had
839
-     *                                        previously specified to use ORs to join, ORs will continue to be used.
840
-     *                                        So, if you specify to use an "OR" to join conditions, it will continue to
841
-     *                                        "stick" until you specify an AND. eg
842
-     *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
843
-     *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
844
-     *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
845
-     *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
846
-     *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
847
-     *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
848
-     *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
849
-     *                                        too, eg:
850
-     *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
851
-     * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
852
-     *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
853
-     *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
854
-     *                                        Remember when you provide two numbers for the limit, the 1st number is
855
-     *                                        the OFFSET, the 2nd is the LIMIT
856
-     * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
857
-     *                                        can do paging on one-to-many multi-table-joins. Send an array in the
858
-     *                                        following format array('on_join_limit'
859
-     *                                        => array( 'table_alias', array(1,2) ) ).
860
-     * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
861
-     *                                        values are either 'ASC' or 'DESC'.
862
-     *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
863
-     *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
864
-     *                                        DESC..." respectively. Like the
865
-     *                                        'where' conditions, these fields can be on related models. Eg
866
-     *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
867
-     *                                        perfectly valid from any model related to 'Registration' (like Event,
868
-     *                                        Attendee, Price, Datetime, etc.)
869
-     * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
870
-     *                                        'order' specifies whether to order the field specified in 'order_by' in
871
-     *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
872
-     *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
873
-     *                                        order by the primary key. Eg,
874
-     *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
875
-     *                                        //(will join with the Datetime model's table(s) and order by its field
876
-     *                                        DTT_EVT_start) or
877
-     *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
878
-     *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
879
-     * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
880
-     *                                        'group_by'=>'VNU_ID', or
881
-     *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
882
-     *                                        if no
883
-     *                                        $group_by is specified, and a limit is set, automatically groups by the
884
-     *                                        model's primary key (or combined primary keys). This avoids some
885
-     *                                        weirdness that results when using limits, tons of joins, and no group by,
886
-     *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
887
-     * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
888
-     *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
889
-     *                                        results)
890
-     * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
891
-     *                                        array where values are models to be joined in the query.Eg
892
-     *                                        array('Attendee','Payment','Datetime'). You may join with transient
893
-     *                                        models using period, eg "Registration.Transaction.Payment". You will
894
-     *                                        probably only want to do this in hopes of increasing efficiency, as
895
-     *                                        related models which belongs to the current model
896
-     *                                        (ie, the current model has a foreign key to them, like how Registration
897
-     *                                        belongs to Attendee) can be cached in order to avoid future queries
898
-     * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
899
-     *                                        set this to 'none' to disable all default where conditions. Eg, usually
900
-     *                                        soft-deleted objects are filtered-out if you want to include them, set
901
-     *                                        this query param to 'none'. If you want to ONLY disable THIS model's
902
-     *                                        default where conditions set it to 'other_models_only'. If you only want
903
-     *                                        this model's default where conditions added to the query, use
904
-     *                                        'this_model_only'. If you want to use all default where conditions
905
-     *                                        (default), set to 'all'.
906
-     * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
907
-     *                                        we just NOT apply any capabilities/permissions/restrictions and return
908
-     *                                        everything? Or should we only show the current user items they should be
909
-     *                                        able to view on the frontend, backend, edit, or delete? can be set to
910
-     *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
911
-     *                                        }
912
-     * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
913
-     *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
914
-     *                                        again. Array keys are object IDs (if there is a primary key on the model.
915
-     *                                        if not, numerically indexed) Some full examples: get 10 transactions
916
-     *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
917
-     *                                        array( array(
918
-     *                                        'OR'=>array(
919
-     *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
920
-     *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
921
-     *                                        )
922
-     *                                        ),
923
-     *                                        'limit'=>10,
924
-     *                                        'group_by'=>'TXN_ID'
925
-     *                                        ));
926
-     *                                        get all the answers to the question titled "shirt size" for event with id
927
-     *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
928
-     *                                        'Question.QST_display_text'=>'shirt size',
929
-     *                                        'Registration.Event.EVT_ID'=>12
930
-     *                                        ),
931
-     *                                        'order_by'=>array('ANS_value'=>'ASC')
932
-     *                                        ));
933
-     * @throws EE_Error
934
-     */
935
-    public function get_all($query_params = array())
936
-    {
937
-        if (isset($query_params['limit'])
938
-            && ! isset($query_params['group_by'])
939
-        ) {
940
-            $query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
941
-        }
942
-        return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
943
-    }
944
-
945
-
946
-
947
-    /**
948
-     * Modifies the query parameters so we only get back model objects
949
-     * that "belong" to the current user
950
-     *
951
-     * @param array $query_params @see EEM_Base::get_all()
952
-     * @return array like EEM_Base::get_all
953
-     */
954
-    public function alter_query_params_to_only_include_mine($query_params = array())
955
-    {
956
-        $wp_user_field_name = $this->wp_user_field_name();
957
-        if ($wp_user_field_name) {
958
-            $query_params[0][$wp_user_field_name] = get_current_user_id();
959
-        }
960
-        return $query_params;
961
-    }
962
-
963
-
964
-
965
-    /**
966
-     * Returns the name of the field's name that points to the WP_User table
967
-     *  on this model (or follows the _model_chain_to_wp_user and uses that model's
968
-     * foreign key to the WP_User table)
969
-     *
970
-     * @return string|boolean string on success, boolean false when there is no
971
-     * foreign key to the WP_User table
972
-     */
973
-    public function wp_user_field_name()
974
-    {
975
-        try {
976
-            if (! empty($this->_model_chain_to_wp_user)) {
977
-                $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
978
-                $last_model_name = end($models_to_follow_to_wp_users);
979
-                $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
980
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
981
-            } else {
982
-                $model_with_fk_to_wp_users = $this;
983
-                $model_chain_to_wp_user = '';
984
-            }
985
-            $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
986
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
987
-        } catch (EE_Error $e) {
988
-            return false;
989
-        }
990
-    }
991
-
992
-
993
-
994
-    /**
995
-     * Returns the _model_chain_to_wp_user string, which indicates which related model
996
-     * (or transiently-related model) has a foreign key to the wp_users table;
997
-     * useful for finding if model objects of this type are 'owned' by the current user.
998
-     * This is an empty string when the foreign key is on this model and when it isn't,
999
-     * but is only non-empty when this model's ownership is indicated by a RELATED model
1000
-     * (or transiently-related model)
1001
-     *
1002
-     * @return string
1003
-     */
1004
-    public function model_chain_to_wp_user()
1005
-    {
1006
-        return $this->_model_chain_to_wp_user;
1007
-    }
1008
-
1009
-
1010
-
1011
-    /**
1012
-     * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1013
-     * like how registrations don't have a foreign key to wp_users, but the
1014
-     * events they are for are), or is unrelated to wp users.
1015
-     * generally available
1016
-     *
1017
-     * @return boolean
1018
-     */
1019
-    public function is_owned()
1020
-    {
1021
-        if ($this->model_chain_to_wp_user()) {
1022
-            return true;
1023
-        }
1024
-        try {
1025
-            $this->get_foreign_key_to('WP_User');
1026
-            return true;
1027
-        } catch (EE_Error $e) {
1028
-            return false;
1029
-        }
1030
-    }
1031
-
1032
-
1033
-
1034
-    /**
1035
-     * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1036
-     * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1037
-     * the model)
1038
-     *
1039
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1040
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1041
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1042
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1043
-     *                                  override this and set the select to "*", or a specific column name, like
1044
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1045
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1046
-     *                                  the aliases used to refer to this selection, and values are to be
1047
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1048
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1049
-     * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1050
-     * @throws EE_Error
1051
-     */
1052
-    protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1053
-    {
1054
-        // remember the custom selections, if any, and type cast as array
1055
-        // (unless $columns_to_select is an object, then just set as an empty array)
1056
-        // Note: (array) 'some string' === array( 'some string' )
1057
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1058
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1059
-        $select_expressions = $columns_to_select !== null
1060
-            ? $this->_construct_select_from_input($columns_to_select)
1061
-            : $this->_construct_default_select_sql($model_query_info);
1062
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1063
-        return $this->_do_wpdb_query('get_results', array($SQL, $output));
1064
-    }
1065
-
1066
-
1067
-
1068
-    /**
1069
-     * Gets an array of rows from the database just like $wpdb->get_results would,
1070
-     * but you can use the $query_params like on EEM_Base::get_all() to more easily
1071
-     * take care of joins, field preparation etc.
1072
-     *
1073
-     * @param array  $query_params      like EEM_Base::get_all's $query_params
1074
-     * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1075
-     * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1076
-     *                                  fields on the model, and the models we joined to in the query. However, you can
1077
-     *                                  override this and set the select to "*", or a specific column name, like
1078
-     *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1079
-     *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1080
-     *                                  the aliases used to refer to this selection, and values are to be
1081
-     *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1082
-     *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1083
-     * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1084
-     * @throws EE_Error
1085
-     */
1086
-    public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1087
-    {
1088
-        return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1089
-    }
1090
-
1091
-
1092
-
1093
-    /**
1094
-     * For creating a custom select statement
1095
-     *
1096
-     * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1097
-     *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1098
-     *                                 SQL, and 1=>is the datatype
1099
-     * @throws EE_Error
1100
-     * @return string
1101
-     */
1102
-    private function _construct_select_from_input($columns_to_select)
1103
-    {
1104
-        if (is_array($columns_to_select)) {
1105
-            $select_sql_array = array();
1106
-            foreach ($columns_to_select as $alias => $selection_and_datatype) {
1107
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1108
-                    throw new EE_Error(
1109
-                        sprintf(
1110
-                            __(
1111
-                                "Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1112
-                                'event_espresso'
1113
-                            ),
1114
-                            $selection_and_datatype,
1115
-                            $alias
1116
-                        )
1117
-                    );
1118
-                }
1119
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1120
-                    throw new EE_Error(
1121
-                        sprintf(
1122
-                            esc_html__(
1123
-                                "Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1124
-                                'event_espresso'
1125
-                            ),
1126
-                            $selection_and_datatype[1],
1127
-                            $selection_and_datatype[0],
1128
-                            $alias,
1129
-                            implode(', ', $this->_valid_wpdb_data_types)
1130
-                        )
1131
-                    );
1132
-                }
1133
-                $select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1134
-            }
1135
-            $columns_to_select_string = implode(', ', $select_sql_array);
1136
-        } else {
1137
-            $columns_to_select_string = $columns_to_select;
1138
-        }
1139
-        return $columns_to_select_string;
1140
-    }
1141
-
1142
-
1143
-
1144
-    /**
1145
-     * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1146
-     *
1147
-     * @return string
1148
-     * @throws EE_Error
1149
-     */
1150
-    public function primary_key_name()
1151
-    {
1152
-        return $this->get_primary_key_field()->get_name();
1153
-    }
1154
-
1155
-
1156
-
1157
-    /**
1158
-     * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1159
-     * If there is no primary key on this model, $id is treated as primary key string
1160
-     *
1161
-     * @param mixed $id int or string, depending on the type of the model's primary key
1162
-     * @return EE_Base_Class
1163
-     */
1164
-    public function get_one_by_ID($id)
1165
-    {
1166
-        if ($this->get_from_entity_map($id)) {
1167
-            return $this->get_from_entity_map($id);
1168
-        }
1169
-        return $this->get_one(
1170
-            $this->alter_query_params_to_restrict_by_ID(
1171
-                $id,
1172
-                array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1173
-            )
1174
-        );
1175
-    }
1176
-
1177
-
1178
-
1179
-    /**
1180
-     * Alters query parameters to only get items with this ID are returned.
1181
-     * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1182
-     * or could just be a simple primary key ID
1183
-     *
1184
-     * @param int   $id
1185
-     * @param array $query_params
1186
-     * @return array of normal query params, @see EEM_Base::get_all
1187
-     * @throws EE_Error
1188
-     */
1189
-    public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1190
-    {
1191
-        if (! isset($query_params[0])) {
1192
-            $query_params[0] = array();
1193
-        }
1194
-        $conditions_from_id = $this->parse_index_primary_key_string($id);
1195
-        if ($conditions_from_id === null) {
1196
-            $query_params[0][$this->primary_key_name()] = $id;
1197
-        } else {
1198
-            //no primary key, so the $id must be from the get_index_primary_key_string()
1199
-            $query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1200
-        }
1201
-        return $query_params;
1202
-    }
1203
-
1204
-
1205
-
1206
-    /**
1207
-     * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1208
-     * array. If no item is found, null is returned.
1209
-     *
1210
-     * @param array $query_params like EEM_Base's $query_params variable.
1211
-     * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1212
-     * @throws EE_Error
1213
-     */
1214
-    public function get_one($query_params = array())
1215
-    {
1216
-        if (! is_array($query_params)) {
1217
-            EE_Error::doing_it_wrong('EEM_Base::get_one',
1218
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1219
-                    gettype($query_params)), '4.6.0');
1220
-            $query_params = array();
1221
-        }
1222
-        $query_params['limit'] = 1;
1223
-        $items = $this->get_all($query_params);
1224
-        if (empty($items)) {
1225
-            return null;
1226
-        }
1227
-        return array_shift($items);
1228
-    }
1229
-
1230
-
1231
-
1232
-    /**
1233
-     * Returns the next x number of items in sequence from the given value as
1234
-     * found in the database matching the given query conditions.
1235
-     *
1236
-     * @param mixed $current_field_value    Value used for the reference point.
1237
-     * @param null  $field_to_order_by      What field is used for the
1238
-     *                                      reference point.
1239
-     * @param int   $limit                  How many to return.
1240
-     * @param array $query_params           Extra conditions on the query.
1241
-     * @param null  $columns_to_select      If left null, then an array of
1242
-     *                                      EE_Base_Class objects is returned,
1243
-     *                                      otherwise you can indicate just the
1244
-     *                                      columns you want returned.
1245
-     * @return EE_Base_Class[]|array
1246
-     * @throws EE_Error
1247
-     */
1248
-    public function next_x(
1249
-        $current_field_value,
1250
-        $field_to_order_by = null,
1251
-        $limit = 1,
1252
-        $query_params = array(),
1253
-        $columns_to_select = null
1254
-    ) {
1255
-        return $this->_get_consecutive(
1256
-            $current_field_value,
1257
-            '>',
1258
-            $field_to_order_by,
1259
-            $limit,
1260
-            $query_params,
1261
-            $columns_to_select
1262
-        );
1263
-    }
1264
-
1265
-
1266
-
1267
-    /**
1268
-     * Returns the previous x number of items in sequence from the given value
1269
-     * as found in the database matching the given query conditions.
1270
-     *
1271
-     * @param mixed $current_field_value    Value used for the reference point.
1272
-     * @param null  $field_to_order_by      What field is used for the
1273
-     *                                      reference point.
1274
-     * @param int   $limit                  How many to return.
1275
-     * @param array $query_params           Extra conditions on the query.
1276
-     * @param null  $columns_to_select      If left null, then an array of
1277
-     *                                      EE_Base_Class objects is returned,
1278
-     *                                      otherwise you can indicate just the
1279
-     *                                      columns you want returned.
1280
-     * @return EE_Base_Class[]|array
1281
-     * @throws EE_Error
1282
-     */
1283
-    public function previous_x(
1284
-        $current_field_value,
1285
-        $field_to_order_by = null,
1286
-        $limit = 1,
1287
-        $query_params = array(),
1288
-        $columns_to_select = null
1289
-    ) {
1290
-        return $this->_get_consecutive(
1291
-            $current_field_value,
1292
-            '<',
1293
-            $field_to_order_by,
1294
-            $limit,
1295
-            $query_params,
1296
-            $columns_to_select
1297
-        );
1298
-    }
1299
-
1300
-
1301
-
1302
-    /**
1303
-     * Returns the next item in sequence from the given value as found in the
1304
-     * database matching the given query conditions.
1305
-     *
1306
-     * @param mixed $current_field_value    Value used for the reference point.
1307
-     * @param null  $field_to_order_by      What field is used for the
1308
-     *                                      reference point.
1309
-     * @param array $query_params           Extra conditions on the query.
1310
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1311
-     *                                      object is returned, otherwise you
1312
-     *                                      can indicate just the columns you
1313
-     *                                      want and a single array indexed by
1314
-     *                                      the columns will be returned.
1315
-     * @return EE_Base_Class|null|array()
1316
-     * @throws EE_Error
1317
-     */
1318
-    public function next(
1319
-        $current_field_value,
1320
-        $field_to_order_by = null,
1321
-        $query_params = array(),
1322
-        $columns_to_select = null
1323
-    ) {
1324
-        $results = $this->_get_consecutive(
1325
-            $current_field_value,
1326
-            '>',
1327
-            $field_to_order_by,
1328
-            1,
1329
-            $query_params,
1330
-            $columns_to_select
1331
-        );
1332
-        return empty($results) ? null : reset($results);
1333
-    }
1334
-
1335
-
1336
-
1337
-    /**
1338
-     * Returns the previous item in sequence from the given value as found in
1339
-     * the database matching the given query conditions.
1340
-     *
1341
-     * @param mixed $current_field_value    Value used for the reference point.
1342
-     * @param null  $field_to_order_by      What field is used for the
1343
-     *                                      reference point.
1344
-     * @param array $query_params           Extra conditions on the query.
1345
-     * @param null  $columns_to_select      If left null, then an EE_Base_Class
1346
-     *                                      object is returned, otherwise you
1347
-     *                                      can indicate just the columns you
1348
-     *                                      want and a single array indexed by
1349
-     *                                      the columns will be returned.
1350
-     * @return EE_Base_Class|null|array()
1351
-     * @throws EE_Error
1352
-     */
1353
-    public function previous(
1354
-        $current_field_value,
1355
-        $field_to_order_by = null,
1356
-        $query_params = array(),
1357
-        $columns_to_select = null
1358
-    ) {
1359
-        $results = $this->_get_consecutive(
1360
-            $current_field_value,
1361
-            '<',
1362
-            $field_to_order_by,
1363
-            1,
1364
-            $query_params,
1365
-            $columns_to_select
1366
-        );
1367
-        return empty($results) ? null : reset($results);
1368
-    }
1369
-
1370
-
1371
-
1372
-    /**
1373
-     * Returns the a consecutive number of items in sequence from the given
1374
-     * value as found in the database matching the given query conditions.
1375
-     *
1376
-     * @param mixed  $current_field_value   Value used for the reference point.
1377
-     * @param string $operand               What operand is used for the sequence.
1378
-     * @param string $field_to_order_by     What field is used for the reference point.
1379
-     * @param int    $limit                 How many to return.
1380
-     * @param array  $query_params          Extra conditions on the query.
1381
-     * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1382
-     *                                      otherwise you can indicate just the columns you want returned.
1383
-     * @return EE_Base_Class[]|array
1384
-     * @throws EE_Error
1385
-     */
1386
-    protected function _get_consecutive(
1387
-        $current_field_value,
1388
-        $operand = '>',
1389
-        $field_to_order_by = null,
1390
-        $limit = 1,
1391
-        $query_params = array(),
1392
-        $columns_to_select = null
1393
-    ) {
1394
-        //if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1395
-        if (empty($field_to_order_by)) {
1396
-            if ($this->has_primary_key_field()) {
1397
-                $field_to_order_by = $this->get_primary_key_field()->get_name();
1398
-            } else {
1399
-                if (WP_DEBUG) {
1400
-                    throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1401
-                        'event_espresso'));
1402
-                }
1403
-                EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1404
-                return array();
1405
-            }
1406
-        }
1407
-        if (! is_array($query_params)) {
1408
-            EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1409
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1410
-                    gettype($query_params)), '4.6.0');
1411
-            $query_params = array();
1412
-        }
1413
-        //let's add the where query param for consecutive look up.
1414
-        $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1415
-        $query_params['limit'] = $limit;
1416
-        //set direction
1417
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1418
-        $query_params['order_by'] = $operand === '>'
1419
-            ? array($field_to_order_by => 'ASC') + $incoming_orderby
1420
-            : array($field_to_order_by => 'DESC') + $incoming_orderby;
1421
-        //if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1422
-        if (empty($columns_to_select)) {
1423
-            return $this->get_all($query_params);
1424
-        }
1425
-        //getting just the fields
1426
-        return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1427
-    }
1428
-
1429
-
1430
-
1431
-    /**
1432
-     * This sets the _timezone property after model object has been instantiated.
1433
-     *
1434
-     * @param null | string $timezone valid PHP DateTimeZone timezone string
1435
-     */
1436
-    public function set_timezone($timezone)
1437
-    {
1438
-        if ($timezone !== null) {
1439
-            $this->_timezone = $timezone;
1440
-        }
1441
-        //note we need to loop through relations and set the timezone on those objects as well.
1442
-        foreach ($this->_model_relations as $relation) {
1443
-            $relation->set_timezone($timezone);
1444
-        }
1445
-        //and finally we do the same for any datetime fields
1446
-        foreach ($this->_fields as $field) {
1447
-            if ($field instanceof EE_Datetime_Field) {
1448
-                $field->set_timezone($timezone);
1449
-            }
1450
-        }
1451
-    }
1452
-
1453
-
1454
-
1455
-    /**
1456
-     * This just returns whatever is set for the current timezone.
1457
-     *
1458
-     * @access public
1459
-     * @return string
1460
-     */
1461
-    public function get_timezone()
1462
-    {
1463
-        //first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1464
-        if (empty($this->_timezone)) {
1465
-            foreach ($this->_fields as $field) {
1466
-                if ($field instanceof EE_Datetime_Field) {
1467
-                    $this->set_timezone($field->get_timezone());
1468
-                    break;
1469
-                }
1470
-            }
1471
-        }
1472
-        //if timezone STILL empty then return the default timezone for the site.
1473
-        if (empty($this->_timezone)) {
1474
-            $this->set_timezone(EEH_DTT_Helper::get_timezone());
1475
-        }
1476
-        return $this->_timezone;
1477
-    }
1478
-
1479
-
1480
-
1481
-    /**
1482
-     * This returns the date formats set for the given field name and also ensures that
1483
-     * $this->_timezone property is set correctly.
1484
-     *
1485
-     * @since 4.6.x
1486
-     * @param string $field_name The name of the field the formats are being retrieved for.
1487
-     * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
-     * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1489
-     * @return array formats in an array with the date format first, and the time format last.
1490
-     */
1491
-    public function get_formats_for($field_name, $pretty = false)
1492
-    {
1493
-        $field_settings = $this->field_settings_for($field_name);
1494
-        //if not a valid EE_Datetime_Field then throw error
1495
-        if (! $field_settings instanceof EE_Datetime_Field) {
1496
-            throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1497
-                'event_espresso'), $field_name));
1498
-        }
1499
-        //while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1500
-        //the field.
1501
-        $this->_timezone = $field_settings->get_timezone();
1502
-        return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1503
-    }
1504
-
1505
-
1506
-
1507
-    /**
1508
-     * This returns the current time in a format setup for a query on this model.
1509
-     * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1510
-     * it will return:
1511
-     *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1512
-     *  NOW
1513
-     *  - or a unix timestamp (equivalent to time())
1514
-     * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1515
-     * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1516
-     * the time returned to be the current time down to the exact second, set $timestamp to true.
1517
-     * @since 4.6.x
1518
-     * @param string $field_name       The field the current time is needed for.
1519
-     * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1520
-     *                                 formatted string matching the set format for the field in the set timezone will
1521
-     *                                 be returned.
1522
-     * @param string $what             Whether to return the string in just the time format, the date format, or both.
1523
-     * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1524
-     * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1525
-     *                                 exception is triggered.
1526
-     */
1527
-    public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1528
-    {
1529
-        $formats = $this->get_formats_for($field_name);
1530
-        $DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1531
-        if ($timestamp) {
1532
-            return $DateTime->format('U');
1533
-        }
1534
-        //not returning timestamp, so return formatted string in timezone.
1535
-        switch ($what) {
1536
-            case 'time' :
1537
-                return $DateTime->format($formats[1]);
1538
-                break;
1539
-            case 'date' :
1540
-                return $DateTime->format($formats[0]);
1541
-                break;
1542
-            default :
1543
-                return $DateTime->format(implode(' ', $formats));
1544
-                break;
1545
-        }
1546
-    }
1547
-
1548
-
1549
-
1550
-    /**
1551
-     * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1552
-     * for the model are.  Returns a DateTime object.
1553
-     * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1554
-     * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1555
-     * ignored.
1556
-     *
1557
-     * @param string $field_name      The field being setup.
1558
-     * @param string $timestring      The date time string being used.
1559
-     * @param string $incoming_format The format for the time string.
1560
-     * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1561
-     *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1562
-     *                                format is
1563
-     *                                'U', this is ignored.
1564
-     * @return DateTime
1565
-     * @throws EE_Error
1566
-     */
1567
-    public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1568
-    {
1569
-        //just using this to ensure the timezone is set correctly internally
1570
-        $this->get_formats_for($field_name);
1571
-        //load EEH_DTT_Helper
1572
-        $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1573
-        $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1574
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1575
-    }
1576
-
1577
-
1578
-
1579
-    /**
1580
-     * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1581
-     *
1582
-     * @return EE_Table_Base[]
1583
-     */
1584
-    public function get_tables()
1585
-    {
1586
-        return $this->_tables;
1587
-    }
1588
-
1589
-
1590
-
1591
-    /**
1592
-     * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1593
-     * also updates all the model objects, where the criteria expressed in $query_params are met..
1594
-     * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1595
-     * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1596
-     * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1597
-     * model object with EVT_ID = 1
1598
-     * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1599
-     * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1600
-     * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1601
-     * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1602
-     * are not specified)
1603
-     *
1604
-     * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1605
-     *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1606
-     *                                         are to be serialized. Basically, the values are what you'd expect to be
1607
-     *                                         values on the model, NOT necessarily what's in the DB. For example, if
1608
-     *                                         we wanted to update only the TXN_details on any Transactions where its
1609
-     *                                         ID=34, we'd use this method as follows:
1610
-     *                                         EEM_Transaction::instance()->update(
1611
-     *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1612
-     *                                         array(array('TXN_ID'=>34)));
1613
-     * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1614
-     *                                         in client code into what's expected to be stored on each field. Eg,
1615
-     *                                         consider updating Question's QST_admin_label field is of type
1616
-     *                                         Simple_HTML. If you use this function to update that field to $new_value
1617
-     *                                         = (note replace 8's with appropriate opening and closing tags in the
1618
-     *                                         following example)"8script8alert('I hack all');8/script88b8boom
1619
-     *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1620
-     *                                         TRUE, it is assumed that you've already called
1621
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1622
-     *                                         malicious javascript. However, if
1623
-     *                                         $values_already_prepared_by_model_object is left as FALSE, then
1624
-     *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1625
-     *                                         and every other field, before insertion. We provide this parameter
1626
-     *                                         because model objects perform their prepare_for_set function on all
1627
-     *                                         their values, and so don't need to be called again (and in many cases,
1628
-     *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1629
-     *                                         prepare_for_set method...)
1630
-     * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1631
-     *                                         in this model's entity map according to $fields_n_values that match
1632
-     *                                         $query_params. This obviously has some overhead, so you can disable it
1633
-     *                                         by setting this to FALSE, but be aware that model objects being used
1634
-     *                                         could get out-of-sync with the database
1635
-     * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1636
-     *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1637
-     *                                         bad)
1638
-     * @throws EE_Error
1639
-     */
1640
-    public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1641
-    {
1642
-        if (! is_array($query_params)) {
1643
-            EE_Error::doing_it_wrong('EEM_Base::update',
1644
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1645
-                    gettype($query_params)), '4.6.0');
1646
-            $query_params = array();
1647
-        }
1648
-        /**
1649
-         * Action called before a model update call has been made.
1650
-         *
1651
-         * @param EEM_Base $model
1652
-         * @param array    $fields_n_values the updated fields and their new values
1653
-         * @param array    $query_params    @see EEM_Base::get_all()
1654
-         */
1655
-        do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1656
-        /**
1657
-         * Filters the fields about to be updated given the query parameters. You can provide the
1658
-         * $query_params to $this->get_all() to find exactly which records will be updated
1659
-         *
1660
-         * @param array    $fields_n_values fields and their new values
1661
-         * @param EEM_Base $model           the model being queried
1662
-         * @param array    $query_params    see EEM_Base::get_all()
1663
-         */
1664
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1665
-            $query_params);
1666
-        //need to verify that, for any entry we want to update, there are entries in each secondary table.
1667
-        //to do that, for each table, verify that it's PK isn't null.
1668
-        $tables = $this->get_tables();
1669
-        //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
1670
-        //NOTE: we should make this code more efficient by NOT querying twice
1671
-        //before the real update, but that needs to first go through ALPHA testing
1672
-        //as it's dangerous. says Mike August 8 2014
1673
-        //we want to make sure the default_where strategy is ignored
1674
-        $this->_ignore_where_strategy = true;
1675
-        $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1676
-        foreach ($wpdb_select_results as $wpdb_result) {
1677
-            // type cast stdClass as array
1678
-            $wpdb_result = (array)$wpdb_result;
1679
-            //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1680
-            if ($this->has_primary_key_field()) {
1681
-                $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1682
-            } else {
1683
-                //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)
1684
-                $main_table_pk_value = null;
1685
-            }
1686
-            //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
1687
-            //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
1688
-            if (count($tables) > 1) {
1689
-                //foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1690
-                //in that table, and so we'll want to insert one
1691
-                foreach ($tables as $table_obj) {
1692
-                    $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1693
-                    //if there is no private key for this table on the results, it means there's no entry
1694
-                    //in this table, right? so insert a row in the current table, using any fields available
1695
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1696
-                           && $wpdb_result[$this_table_pk_column])
1697
-                    ) {
1698
-                        $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1699
-                            $main_table_pk_value);
1700
-                        //if we died here, report the error
1701
-                        if (! $success) {
1702
-                            return false;
1703
-                        }
1704
-                    }
1705
-                }
1706
-            }
1707
-            //				//and now check that if we have cached any models by that ID on the model, that
1708
-            //				//they also get updated properly
1709
-            //				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1710
-            //				if( $model_object ){
1711
-            //					foreach( $fields_n_values as $field => $value ){
1712
-            //						$model_object->set($field, $value);
1713
-            //let's make sure default_where strategy is followed now
1714
-            $this->_ignore_where_strategy = false;
1715
-        }
1716
-        //if we want to keep model objects in sync, AND
1717
-        //if this wasn't called from a model object (to update itself)
1718
-        //then we want to make sure we keep all the existing
1719
-        //model objects in sync with the db
1720
-        if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1721
-            if ($this->has_primary_key_field()) {
1722
-                $model_objs_affected_ids = $this->get_col($query_params);
1723
-            } else {
1724
-                //we need to select a bunch of columns and then combine them into the the "index primary key string"s
1725
-                $models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1726
-                $model_objs_affected_ids = array();
1727
-                foreach ($models_affected_key_columns as $row) {
1728
-                    $combined_index_key = $this->get_index_primary_key_string($row);
1729
-                    $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1730
-                }
1731
-            }
1732
-            if (! $model_objs_affected_ids) {
1733
-                //wait wait wait- if nothing was affected let's stop here
1734
-                return 0;
1735
-            }
1736
-            foreach ($model_objs_affected_ids as $id) {
1737
-                $model_obj_in_entity_map = $this->get_from_entity_map($id);
1738
-                if ($model_obj_in_entity_map) {
1739
-                    foreach ($fields_n_values as $field => $new_value) {
1740
-                        $model_obj_in_entity_map->set($field, $new_value);
1741
-                    }
1742
-                }
1743
-            }
1744
-            //if there is a primary key on this model, we can now do a slight optimization
1745
-            if ($this->has_primary_key_field()) {
1746
-                //we already know what we want to update. So let's make the query simpler so it's a little more efficient
1747
-                $query_params = array(
1748
-                    array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1749
-                    'limit'                    => count($model_objs_affected_ids),
1750
-                    'default_where_conditions' => EEM_Base::default_where_conditions_none,
1751
-                );
1752
-            }
1753
-        }
1754
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1755
-        $SQL = "UPDATE "
1756
-               . $model_query_info->get_full_join_sql()
1757
-               . " SET "
1758
-               . $this->_construct_update_sql($fields_n_values)
1759
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1760
-        $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1761
-        /**
1762
-         * Action called after a model update call has been made.
1763
-         *
1764
-         * @param EEM_Base $model
1765
-         * @param array    $fields_n_values the updated fields and their new values
1766
-         * @param array    $query_params    @see EEM_Base::get_all()
1767
-         * @param int      $rows_affected
1768
-         */
1769
-        do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1770
-        return $rows_affected;//how many supposedly got updated
1771
-    }
1772
-
1773
-
1774
-
1775
-    /**
1776
-     * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1777
-     * are teh values of the field specified (or by default the primary key field)
1778
-     * that matched the query params. Note that you should pass the name of the
1779
-     * model FIELD, not the database table's column name.
1780
-     *
1781
-     * @param array  $query_params @see EEM_Base::get_all()
1782
-     * @param string $field_to_select
1783
-     * @return array just like $wpdb->get_col()
1784
-     * @throws EE_Error
1785
-     */
1786
-    public function get_col($query_params = array(), $field_to_select = null)
1787
-    {
1788
-        if ($field_to_select) {
1789
-            $field = $this->field_settings_for($field_to_select);
1790
-        } elseif ($this->has_primary_key_field()) {
1791
-            $field = $this->get_primary_key_field();
1792
-        } else {
1793
-            //no primary key, just grab the first column
1794
-            $field = reset($this->field_settings());
1795
-        }
1796
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
1797
-        $select_expressions = $field->get_qualified_column();
1798
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1799
-        return $this->_do_wpdb_query('get_col', array($SQL));
1800
-    }
1801
-
1802
-
1803
-
1804
-    /**
1805
-     * Returns a single column value for a single row from the database
1806
-     *
1807
-     * @param array  $query_params    @see EEM_Base::get_all()
1808
-     * @param string $field_to_select @see EEM_Base::get_col()
1809
-     * @return string
1810
-     * @throws EE_Error
1811
-     */
1812
-    public function get_var($query_params = array(), $field_to_select = null)
1813
-    {
1814
-        $query_params['limit'] = 1;
1815
-        $col = $this->get_col($query_params, $field_to_select);
1816
-        if (! empty($col)) {
1817
-            return reset($col);
1818
-        }
1819
-        return null;
1820
-    }
1821
-
1822
-
1823
-
1824
-    /**
1825
-     * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1826
-     * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1827
-     * injection, but currently no further filtering is done
1828
-     *
1829
-     * @global      $wpdb
1830
-     * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1831
-     *                               be updated to in the DB
1832
-     * @return string of SQL
1833
-     * @throws EE_Error
1834
-     */
1835
-    public function _construct_update_sql($fields_n_values)
1836
-    {
1837
-        /** @type WPDB $wpdb */
1838
-        global $wpdb;
1839
-        $cols_n_values = array();
1840
-        foreach ($fields_n_values as $field_name => $value) {
1841
-            $field_obj = $this->field_settings_for($field_name);
1842
-            //if the value is NULL, we want to assign the value to that.
1843
-            //wpdb->prepare doesn't really handle that properly
1844
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1845
-            $value_sql = $prepared_value === null ? 'NULL'
1846
-                : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1847
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1848
-        }
1849
-        return implode(",", $cols_n_values);
1850
-    }
1851
-
1852
-
1853
-
1854
-    /**
1855
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1856
-     * Performs a HARD delete, meaning the database row should always be removed,
1857
-     * not just have a flag field on it switched
1858
-     * Wrapper for EEM_Base::delete_permanently()
1859
-     *
1860
-     * @param mixed $id
1861
-     * @param boolean $allow_blocking
1862
-     * @return int the number of rows deleted
1863
-     * @throws EE_Error
1864
-     */
1865
-    public function delete_permanently_by_ID($id, $allow_blocking = true)
1866
-    {
1867
-        return $this->delete_permanently(
1868
-            array(
1869
-                array($this->get_primary_key_field()->get_name() => $id),
1870
-                'limit' => 1,
1871
-            ),
1872
-            $allow_blocking
1873
-        );
1874
-    }
1875
-
1876
-
1877
-
1878
-    /**
1879
-     * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1880
-     * Wrapper for EEM_Base::delete()
1881
-     *
1882
-     * @param mixed $id
1883
-     * @param boolean $allow_blocking
1884
-     * @return int the number of rows deleted
1885
-     * @throws EE_Error
1886
-     */
1887
-    public function delete_by_ID($id, $allow_blocking = true)
1888
-    {
1889
-        return $this->delete(
1890
-            array(
1891
-                array($this->get_primary_key_field()->get_name() => $id),
1892
-                'limit' => 1,
1893
-            ),
1894
-            $allow_blocking
1895
-        );
1896
-    }
1897
-
1898
-
1899
-
1900
-    /**
1901
-     * Identical to delete_permanently, but does a "soft" delete if possible,
1902
-     * meaning if the model has a field that indicates its been "trashed" or
1903
-     * "soft deleted", we will just set that instead of actually deleting the rows.
1904
-     *
1905
-     * @see EEM_Base::delete_permanently
1906
-     * @param array   $query_params
1907
-     * @param boolean $allow_blocking
1908
-     * @return int how many rows got deleted
1909
-     * @throws EE_Error
1910
-     */
1911
-    public function delete($query_params, $allow_blocking = true)
1912
-    {
1913
-        return $this->delete_permanently($query_params, $allow_blocking);
1914
-    }
1915
-
1916
-
1917
-
1918
-    /**
1919
-     * Deletes the model objects that meet the query params. Note: this method is overridden
1920
-     * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1921
-     * as archived, not actually deleted
1922
-     *
1923
-     * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1924
-     * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1925
-     *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1926
-     *                                deletes regardless of other objects which may depend on it. Its generally
1927
-     *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1928
-     *                                DB
1929
-     * @return int how many rows got deleted
1930
-     * @throws EE_Error
1931
-     */
1932
-    public function delete_permanently($query_params, $allow_blocking = true)
1933
-    {
1934
-        /**
1935
-         * Action called just before performing a real deletion query. You can use the
1936
-         * model and its $query_params to find exactly which items will be deleted
1937
-         *
1938
-         * @param EEM_Base $model
1939
-         * @param array    $query_params   @see EEM_Base::get_all()
1940
-         * @param boolean  $allow_blocking whether or not to allow related model objects
1941
-         *                                 to block (prevent) this deletion
1942
-         */
1943
-        do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1944
-        //some MySQL databases may be running safe mode, which may restrict
1945
-        //deletion if there is no KEY column used in the WHERE statement of a deletion.
1946
-        //to get around this, we first do a SELECT, get all the IDs, and then run another query
1947
-        //to delete them
1948
-        $items_for_deletion = $this->_get_all_wpdb_results($query_params);
1949
-        $columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1950
-        $deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1951
-            $columns_and_ids_for_deleting
1952
-        );
1953
-        /**
1954
-         * Allows client code to act on the items being deleted before the query is actually executed.
1955
-         *
1956
-         * @param EEM_Base $this  The model instance being acted on.
1957
-         * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1958
-         * @param bool     $allow_blocking @see param description in method phpdoc block.
1959
-         * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1960
-         *                                                  derived from the incoming query parameters.
1961
-         *                                                  @see details on the structure of this array in the phpdocs
1962
-         *                                                  for the `_get_ids_for_delete_method`
1963
-         *
1964
-         */
1965
-        do_action('AHEE__EEM_Base__delete__before_query',
1966
-            $this,
1967
-            $query_params,
1968
-            $allow_blocking,
1969
-            $columns_and_ids_for_deleting
1970
-        );
1971
-        if ($deletion_where_query_part) {
1972
-            $model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
-            $table_aliases = array_keys($this->_tables);
1974
-            $SQL = "DELETE "
1975
-                   . implode(", ", $table_aliases)
1976
-                   . " FROM "
1977
-                   . $model_query_info->get_full_join_sql()
1978
-                   . " WHERE "
1979
-                   . $deletion_where_query_part;
1980
-            $rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
-        } else {
1982
-            $rows_deleted = 0;
1983
-        }
1984
-
1985
-        //Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
-        //there was no error with the delete query.
1987
-        if ($this->has_primary_key_field()
1988
-            && $rows_deleted !== false
1989
-            && isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1990
-        ) {
1991
-            $ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1992
-            foreach ($ids_for_removal as $id) {
1993
-                if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1994
-                    unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1995
-                }
1996
-            }
1997
-
1998
-            // delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1999
-            //`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2000
-            //unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2001
-            // (although it is possible).
2002
-            //Note this can be skipped by using the provided filter and returning false.
2003
-            if (apply_filters(
2004
-                'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2005
-                ! $this instanceof EEM_Extra_Meta,
2006
-                $this
2007
-            )) {
2008
-                EEM_Extra_Meta::instance()->delete_permanently(array(
2009
-                    0 => array(
2010
-                        'EXM_type' => $this->get_this_model_name(),
2011
-                        'OBJ_ID'   => array(
2012
-                            'IN',
2013
-                            $ids_for_removal
2014
-                        )
2015
-                    )
2016
-                ));
2017
-            }
2018
-        }
2019
-
2020
-        /**
2021
-         * Action called just after performing a real deletion query. Although at this point the
2022
-         * items should have been deleted
2023
-         *
2024
-         * @param EEM_Base $model
2025
-         * @param array    $query_params @see EEM_Base::get_all()
2026
-         * @param int      $rows_deleted
2027
-         */
2028
-        do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;//how many supposedly got deleted
2030
-    }
2031
-
2032
-
2033
-
2034
-    /**
2035
-     * Checks all the relations that throw error messages when there are blocking related objects
2036
-     * for related model objects. If there are any related model objects on those relations,
2037
-     * adds an EE_Error, and return true
2038
-     *
2039
-     * @param EE_Base_Class|int $this_model_obj_or_id
2040
-     * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
-     *                                                 should be ignored when determining whether there are related
2042
-     *                                                 model objects which block this model object's deletion. Useful
2043
-     *                                                 if you know A is related to B and are considering deleting A,
2044
-     *                                                 but want to see if A has any other objects blocking its deletion
2045
-     *                                                 before removing the relation between A and B
2046
-     * @return boolean
2047
-     * @throws EE_Error
2048
-     */
2049
-    public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
-    {
2051
-        //first, if $ignore_this_model_obj was supplied, get its model
2052
-        if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
-            $ignored_model = $ignore_this_model_obj->get_model();
2054
-        } else {
2055
-            $ignored_model = null;
2056
-        }
2057
-        //now check all the relations of $this_model_obj_or_id and see if there
2058
-        //are any related model objects blocking it?
2059
-        $is_blocked = false;
2060
-        foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
-            if ($relation_obj->block_delete_if_related_models_exist()) {
2062
-                //if $ignore_this_model_obj was supplied, then for the query
2063
-                //on that model needs to be told to ignore $ignore_this_model_obj
2064
-                if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
-                        array(
2067
-                            $ignored_model->get_primary_key_field()->get_name() => array(
2068
-                                '!=',
2069
-                                $ignore_this_model_obj->ID(),
2070
-                            ),
2071
-                        ),
2072
-                    ));
2073
-                } else {
2074
-                    $related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
-                }
2076
-                if ($related_model_objects) {
2077
-                    EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
-                    $is_blocked = true;
2079
-                }
2080
-            }
2081
-        }
2082
-        return $is_blocked;
2083
-    }
2084
-
2085
-
2086
-    /**
2087
-     * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
-     * @param array $row_results_for_deleting
2089
-     * @param bool  $allow_blocking
2090
-     * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
-     *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
-     *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
-     *                 deleted. Example:
2094
-     *                      array('Event.EVT_ID' => array( 1,2,3))
2095
-     *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
-     *                 where each element is a group of columns and values that get deleted. Example:
2097
-     *                      array(
2098
-     *                          0 => array(
2099
-     *                              'Term_Relationship.object_id' => 1
2100
-     *                              'Term_Relationship.term_taxonomy_id' => 5
2101
-     *                          ),
2102
-     *                          1 => array(
2103
-     *                              'Term_Relationship.object_id' => 1
2104
-     *                              'Term_Relationship.term_taxonomy_id' => 6
2105
-     *                          )
2106
-     *                      )
2107
-     * @throws EE_Error
2108
-     */
2109
-    protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
-    {
2111
-        $ids_to_delete_indexed_by_column = array();
2112
-        if ($this->has_primary_key_field()) {
2113
-            $primary_table = $this->_get_main_table();
2114
-            $primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
-            $other_tables = $this->_get_other_tables();
2116
-            $ids_to_delete_indexed_by_column = $query = array();
2117
-            foreach ($row_results_for_deleting as $item_to_delete) {
2118
-                //before we mark this item for deletion,
2119
-                //make sure there's no related entities blocking its deletion (if we're checking)
2120
-                if (
2121
-                    $allow_blocking
2122
-                    && $this->delete_is_blocked_by_related_models(
2123
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2124
-                    )
2125
-                ) {
2126
-                    continue;
2127
-                }
2128
-                //primary table deletes
2129
-                if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2130
-                    $ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2131
-                        $item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2132
-                }
2133
-            }
2134
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
-            $fields = $this->get_combined_primary_key_fields();
2136
-            foreach ($row_results_for_deleting as $item_to_delete) {
2137
-                $ids_to_delete_indexed_by_column_for_row = array();
2138
-                foreach ($fields as $cpk_field) {
2139
-                    if ($cpk_field instanceof EE_Model_Field_Base) {
2140
-                        $ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2141
-                            $item_to_delete[$cpk_field->get_qualified_column()];
2142
-                    }
2143
-                }
2144
-                $ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
-            }
2146
-        } else {
2147
-            //so there's no primary key and no combined key...
2148
-            //sorry, can't help you
2149
-            throw new EE_Error(
2150
-                sprintf(
2151
-                    __(
2152
-                        "Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
-                        "event_espresso"
2154
-                    ), get_class($this)
2155
-                )
2156
-            );
2157
-        }
2158
-        return $ids_to_delete_indexed_by_column;
2159
-    }
2160
-
2161
-
2162
-    /**
2163
-     * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
-     * the corresponding query_part for the query performing the delete.
2165
-     *
2166
-     * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
-     * @return string
2168
-     * @throws EE_Error
2169
-     */
2170
-    protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2171
-        $query_part = '';
2172
-        if (empty($ids_to_delete_indexed_by_column)) {
2173
-            return $query_part;
2174
-        } elseif ($this->has_primary_key_field()) {
2175
-            $query = array();
2176
-            foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2177
-                //make sure we have unique $ids
2178
-                $ids = array_unique($ids);
2179
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2180
-            }
2181
-            $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
-        } elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
-            $ways_to_identify_a_row = array();
2184
-            foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
-                $values_for_each_combined_primary_key_for_a_row = array();
2186
-                foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
-                }
2189
-                $ways_to_identify_a_row[] = '('
2190
-                                            . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
-                                            . ')';
2192
-            }
2193
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2194
-        }
2195
-        return $query_part;
2196
-    }
2197
-
2198
-
2199
-
2200
-    /**
2201
-     * Gets the model field by the fully qualified name
2202
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
-     * @return EE_Model_Field_Base
2204
-     */
2205
-    public function get_field_by_column($qualified_column_name)
2206
-    {
2207
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2208
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2209
-               return $field_obj;
2210
-           }
2211
-       }
2212
-        throw new EE_Error(
2213
-            sprintf(
2214
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
-                $this->get_this_model_name(),
2216
-                $qualified_column_name
2217
-            )
2218
-        );
2219
-    }
2220
-
2221
-
2222
-
2223
-    /**
2224
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2225
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
-     * column
2227
-     *
2228
-     * @param array  $query_params   like EEM_Base::get_all's
2229
-     * @param string $field_to_count field on model to count by (not column name)
2230
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
-     *                               that by the setting $distinct to TRUE;
2232
-     * @return int
2233
-     * @throws EE_Error
2234
-     */
2235
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
-    {
2237
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
-        if ($field_to_count) {
2239
-            $field_obj = $this->field_settings_for($field_to_count);
2240
-            $column_to_count = $field_obj->get_qualified_column();
2241
-        } elseif ($this->has_primary_key_field()) {
2242
-            $pk_field_obj = $this->get_primary_key_field();
2243
-            $column_to_count = $pk_field_obj->get_qualified_column();
2244
-        } else {
2245
-            //there's no primary key
2246
-            //if we're counting distinct items, and there's no primary key,
2247
-            //we need to list out the columns for distinction;
2248
-            //otherwise we can just use star
2249
-            if ($distinct) {
2250
-                $columns_to_use = array();
2251
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2253
-                }
2254
-                $column_to_count = implode(',', $columns_to_use);
2255
-            } else {
2256
-                $column_to_count = '*';
2257
-            }
2258
-        }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2262
-    }
2263
-
2264
-
2265
-
2266
-    /**
2267
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
-     *
2269
-     * @param array  $query_params like EEM_Base::get_all
2270
-     * @param string $field_to_sum name of field (array key in $_fields array)
2271
-     * @return float
2272
-     * @throws EE_Error
2273
-     */
2274
-    public function sum($query_params, $field_to_sum = null)
2275
-    {
2276
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
-        if ($field_to_sum) {
2278
-            $field_obj = $this->field_settings_for($field_to_sum);
2279
-        } else {
2280
-            $field_obj = $this->get_primary_key_field();
2281
-        }
2282
-        $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
-        $data_type = $field_obj->get_wpdb_data_type();
2286
-        if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float)$return_value;
2288
-        }
2289
-        //must be %f
2290
-        return (float)$return_value;
2291
-    }
2292
-
2293
-
2294
-
2295
-    /**
2296
-     * Just calls the specified method on $wpdb with the given arguments
2297
-     * Consolidates a little extra error handling code
2298
-     *
2299
-     * @param string $wpdb_method
2300
-     * @param array  $arguments_to_provide
2301
-     * @throws EE_Error
2302
-     * @global wpdb  $wpdb
2303
-     * @return mixed
2304
-     */
2305
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
-    {
2307
-        //if we're in maintenance mode level 2, DON'T run any queries
2308
-        //because level 2 indicates the database needs updating and
2309
-        //is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
-            throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2312
-                "event_espresso")));
2313
-        }
2314
-        /** @type WPDB $wpdb */
2315
-        global $wpdb;
2316
-        if (! method_exists($wpdb, $wpdb_method)) {
2317
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2318
-                'event_espresso'), $wpdb_method));
2319
-        }
2320
-        if (WP_DEBUG) {
2321
-            $old_show_errors_value = $wpdb->show_errors;
2322
-            $wpdb->show_errors(false);
2323
-        }
2324
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2325
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2326
-        if (WP_DEBUG) {
2327
-            $wpdb->show_errors($old_show_errors_value);
2328
-            if (! empty($wpdb->last_error)) {
2329
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2330
-            }
2331
-            if ($result === false) {
2332
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2334
-            }
2335
-        } elseif ($result === false) {
2336
-            EE_Error::add_error(
2337
-                sprintf(
2338
-                    __('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"',
2339
-                        'event_espresso'),
2340
-                    $wpdb_method,
2341
-                    var_export($arguments_to_provide, true),
2342
-                    $wpdb->last_error
2343
-                ),
2344
-                __FILE__,
2345
-                __FUNCTION__,
2346
-                __LINE__
2347
-            );
2348
-        }
2349
-        return $result;
2350
-    }
2351
-
2352
-
2353
-
2354
-    /**
2355
-     * Attempts to run the indicated WPDB method with the provided arguments,
2356
-     * and if there's an error tries to verify the DB is correct. Uses
2357
-     * the static property EEM_Base::$_db_verification_level to determine whether
2358
-     * we should try to fix the EE core db, the addons, or just give up
2359
-     *
2360
-     * @param string $wpdb_method
2361
-     * @param array  $arguments_to_provide
2362
-     * @return mixed
2363
-     */
2364
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2365
-    {
2366
-        /** @type WPDB $wpdb */
2367
-        global $wpdb;
2368
-        $wpdb->last_error = null;
2369
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2370
-        // was there an error running the query? but we don't care on new activations
2371
-        // (we're going to setup the DB anyway on new activations)
2372
-        if (($result === false || ! empty($wpdb->last_error))
2373
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2374
-        ) {
2375
-            switch (EEM_Base::$_db_verification_level) {
2376
-                case EEM_Base::db_verified_none :
2377
-                    // let's double-check core's DB
2378
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2379
-                    break;
2380
-                case EEM_Base::db_verified_core :
2381
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2382
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2383
-                    break;
2384
-                case EEM_Base::db_verified_addons :
2385
-                    // ummmm... you in trouble
2386
-                    return $result;
2387
-                    break;
2388
-            }
2389
-            if (! empty($error_message)) {
2390
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2391
-                trigger_error($error_message);
2392
-            }
2393
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2394
-        }
2395
-        return $result;
2396
-    }
2397
-
2398
-
2399
-
2400
-    /**
2401
-     * Verifies the EE core database is up-to-date and records that we've done it on
2402
-     * EEM_Base::$_db_verification_level
2403
-     *
2404
-     * @param string $wpdb_method
2405
-     * @param array  $arguments_to_provide
2406
-     * @return string
2407
-     */
2408
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2409
-    {
2410
-        /** @type WPDB $wpdb */
2411
-        global $wpdb;
2412
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2413
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2414
-        $error_message = sprintf(
2415
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2416
-                'event_espresso'),
2417
-            $wpdb->last_error,
2418
-            $wpdb_method,
2419
-            wp_json_encode($arguments_to_provide)
2420
-        );
2421
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2422
-        return $error_message;
2423
-    }
2424
-
2425
-
2426
-
2427
-    /**
2428
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2429
-     * EEM_Base::$_db_verification_level
2430
-     *
2431
-     * @param $wpdb_method
2432
-     * @param $arguments_to_provide
2433
-     * @return string
2434
-     */
2435
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2436
-    {
2437
-        /** @type WPDB $wpdb */
2438
-        global $wpdb;
2439
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2440
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2441
-        $error_message = sprintf(
2442
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2443
-                'event_espresso'),
2444
-            $wpdb->last_error,
2445
-            $wpdb_method,
2446
-            wp_json_encode($arguments_to_provide)
2447
-        );
2448
-        EE_System::instance()->initialize_addons();
2449
-        return $error_message;
2450
-    }
2451
-
2452
-
2453
-
2454
-    /**
2455
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2456
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2457
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2458
-     * ..."
2459
-     *
2460
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2461
-     * @return string
2462
-     */
2463
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464
-    {
2465
-        return " FROM " . $model_query_info->get_full_join_sql() .
2466
-               $model_query_info->get_where_sql() .
2467
-               $model_query_info->get_group_by_sql() .
2468
-               $model_query_info->get_having_sql() .
2469
-               $model_query_info->get_order_by_sql() .
2470
-               $model_query_info->get_limit_sql();
2471
-    }
2472
-
2473
-
2474
-
2475
-    /**
2476
-     * Set to easily debug the next X queries ran from this model.
2477
-     *
2478
-     * @param int $count
2479
-     */
2480
-    public function show_next_x_db_queries($count = 1)
2481
-    {
2482
-        $this->_show_next_x_db_queries = $count;
2483
-    }
2484
-
2485
-
2486
-
2487
-    /**
2488
-     * @param $sql_query
2489
-     */
2490
-    public function show_db_query_if_previously_requested($sql_query)
2491
-    {
2492
-        if ($this->_show_next_x_db_queries > 0) {
2493
-            echo $sql_query;
2494
-            $this->_show_next_x_db_queries--;
2495
-        }
2496
-    }
2497
-
2498
-
2499
-
2500
-    /**
2501
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2502
-     * There are the 3 cases:
2503
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2504
-     * $otherModelObject has no ID, it is first saved.
2505
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2506
-     * has no ID, it is first saved.
2507
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2508
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2509
-     * join table
2510
-     *
2511
-     * @param        EE_Base_Class                     /int $thisModelObject
2512
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2513
-     * @param string $relationName                     , key in EEM_Base::_relations
2514
-     *                                                 an attendee to a group, you also want to specify which role they
2515
-     *                                                 will have in that group. So you would use this parameter to
2516
-     *                                                 specify array('role-column-name'=>'role-id')
2517
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2518
-     *                                                 to for relation to methods that allow you to further specify
2519
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2520
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2521
-     *                                                 because these will be inserted in any new rows created as well.
2522
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2523
-     * @throws EE_Error
2524
-     */
2525
-    public function add_relationship_to(
2526
-        $id_or_obj,
2527
-        $other_model_id_or_obj,
2528
-        $relationName,
2529
-        $extra_join_model_fields_n_values = array()
2530
-    ) {
2531
-        $relation_obj = $this->related_settings_for($relationName);
2532
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2533
-    }
2534
-
2535
-
2536
-
2537
-    /**
2538
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2539
-     * There are the 3 cases:
2540
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2541
-     * error
2542
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2543
-     * an error
2544
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2545
-     *
2546
-     * @param        EE_Base_Class /int $id_or_obj
2547
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2548
-     * @param string $relationName key in EEM_Base::_relations
2549
-     * @return boolean of success
2550
-     * @throws EE_Error
2551
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2552
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2553
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2554
-     *                             because these will be inserted in any new rows created as well.
2555
-     */
2556
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2557
-    {
2558
-        $relation_obj = $this->related_settings_for($relationName);
2559
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2560
-    }
2561
-
2562
-
2563
-
2564
-    /**
2565
-     * @param mixed           $id_or_obj
2566
-     * @param string          $relationName
2567
-     * @param array           $where_query_params
2568
-     * @param EE_Base_Class[] objects to which relations were removed
2569
-     * @return \EE_Base_Class[]
2570
-     * @throws EE_Error
2571
-     */
2572
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2573
-    {
2574
-        $relation_obj = $this->related_settings_for($relationName);
2575
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2576
-    }
2577
-
2578
-
2579
-
2580
-    /**
2581
-     * Gets all the related items of the specified $model_name, using $query_params.
2582
-     * Note: by default, we remove the "default query params"
2583
-     * because we want to get even deleted items etc.
2584
-     *
2585
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2586
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2587
-     * @param array  $query_params like EEM_Base::get_all
2588
-     * @return EE_Base_Class[]
2589
-     * @throws EE_Error
2590
-     */
2591
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2592
-    {
2593
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2594
-        $relation_settings = $this->related_settings_for($model_name);
2595
-        return $relation_settings->get_all_related($model_obj, $query_params);
2596
-    }
2597
-
2598
-
2599
-
2600
-    /**
2601
-     * Deletes all the model objects across the relation indicated by $model_name
2602
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2603
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2604
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2605
-     *
2606
-     * @param EE_Base_Class|int|string $id_or_obj
2607
-     * @param string                   $model_name
2608
-     * @param array                    $query_params
2609
-     * @return int how many deleted
2610
-     * @throws EE_Error
2611
-     */
2612
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2613
-    {
2614
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2615
-        $relation_settings = $this->related_settings_for($model_name);
2616
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2617
-    }
2618
-
2619
-
2620
-
2621
-    /**
2622
-     * Hard deletes all the model objects across the relation indicated by $model_name
2623
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2624
-     * the model objects can't be hard deleted because of blocking related model objects,
2625
-     * just does a soft-delete on them instead.
2626
-     *
2627
-     * @param EE_Base_Class|int|string $id_or_obj
2628
-     * @param string                   $model_name
2629
-     * @param array                    $query_params
2630
-     * @return int how many deleted
2631
-     * @throws EE_Error
2632
-     */
2633
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2634
-    {
2635
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2636
-        $relation_settings = $this->related_settings_for($model_name);
2637
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2638
-    }
2639
-
2640
-
2641
-
2642
-    /**
2643
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2644
-     * unless otherwise specified in the $query_params
2645
-     *
2646
-     * @param        int             /EE_Base_Class $id_or_obj
2647
-     * @param string $model_name     like 'Event', or 'Registration'
2648
-     * @param array  $query_params   like EEM_Base::get_all's
2649
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2650
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2651
-     *                               that by the setting $distinct to TRUE;
2652
-     * @return int
2653
-     * @throws EE_Error
2654
-     */
2655
-    public function count_related(
2656
-        $id_or_obj,
2657
-        $model_name,
2658
-        $query_params = array(),
2659
-        $field_to_count = null,
2660
-        $distinct = false
2661
-    ) {
2662
-        $related_model = $this->get_related_model_obj($model_name);
2663
-        //we're just going to use the query params on the related model's normal get_all query,
2664
-        //except add a condition to say to match the current mod
2665
-        if (! isset($query_params['default_where_conditions'])) {
2666
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667
-        }
2668
-        $this_model_name = $this->get_this_model_name();
2669
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2671
-        return $related_model->count($query_params, $field_to_count, $distinct);
2672
-    }
2673
-
2674
-
2675
-
2676
-    /**
2677
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2678
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2679
-     *
2680
-     * @param        int           /EE_Base_Class $id_or_obj
2681
-     * @param string $model_name   like 'Event', or 'Registration'
2682
-     * @param array  $query_params like EEM_Base::get_all's
2683
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2684
-     * @return float
2685
-     * @throws EE_Error
2686
-     */
2687
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688
-    {
2689
-        $related_model = $this->get_related_model_obj($model_name);
2690
-        if (! is_array($query_params)) {
2691
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2692
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2693
-                    gettype($query_params)), '4.6.0');
2694
-            $query_params = array();
2695
-        }
2696
-        //we're just going to use the query params on the related model's normal get_all query,
2697
-        //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2699
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700
-        }
2701
-        $this_model_name = $this->get_this_model_name();
2702
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2704
-        return $related_model->sum($query_params, $field_to_sum);
2705
-    }
2706
-
2707
-
2708
-
2709
-    /**
2710
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2711
-     * $modelObject
2712
-     *
2713
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2714
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2715
-     * @param array               $query_params     like EEM_Base::get_all's
2716
-     * @return EE_Base_Class
2717
-     * @throws EE_Error
2718
-     */
2719
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2720
-    {
2721
-        $query_params['limit'] = 1;
2722
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2723
-        if ($results) {
2724
-            return array_shift($results);
2725
-        }
2726
-        return null;
2727
-    }
2728
-
2729
-
2730
-
2731
-    /**
2732
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2733
-     *
2734
-     * @return string
2735
-     */
2736
-    public function get_this_model_name()
2737
-    {
2738
-        return str_replace("EEM_", "", get_class($this));
2739
-    }
2740
-
2741
-
2742
-
2743
-    /**
2744
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2745
-     *
2746
-     * @return EE_Any_Foreign_Model_Name_Field
2747
-     * @throws EE_Error
2748
-     */
2749
-    public function get_field_containing_related_model_name()
2750
-    {
2751
-        foreach ($this->field_settings(true) as $field) {
2752
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2753
-                $field_with_model_name = $field;
2754
-            }
2755
-        }
2756
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2757
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2758
-                $this->get_this_model_name()));
2759
-        }
2760
-        return $field_with_model_name;
2761
-    }
2762
-
2763
-
2764
-
2765
-    /**
2766
-     * Inserts a new entry into the database, for each table.
2767
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2768
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2769
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2770
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2771
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2772
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2773
-     *
2774
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2775
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2776
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2777
-     *                              of EEM_Base)
2778
-     * @return int new primary key on main table that got inserted
2779
-     * @throws EE_Error
2780
-     */
2781
-    public function insert($field_n_values)
2782
-    {
2783
-        /**
2784
-         * Filters the fields and their values before inserting an item using the models
2785
-         *
2786
-         * @param array    $fields_n_values keys are the fields and values are their new values
2787
-         * @param EEM_Base $model           the model used
2788
-         */
2789
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2790
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2791
-            $main_table = $this->_get_main_table();
2792
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2793
-            if ($new_id !== false) {
2794
-                foreach ($this->_get_other_tables() as $other_table) {
2795
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2796
-                }
2797
-            }
2798
-            /**
2799
-             * Done just after attempting to insert a new model object
2800
-             *
2801
-             * @param EEM_Base   $model           used
2802
-             * @param array      $fields_n_values fields and their values
2803
-             * @param int|string the              ID of the newly-inserted model object
2804
-             */
2805
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2806
-            return $new_id;
2807
-        }
2808
-        return false;
2809
-    }
2810
-
2811
-
2812
-
2813
-    /**
2814
-     * Checks that the result would satisfy the unique indexes on this model
2815
-     *
2816
-     * @param array  $field_n_values
2817
-     * @param string $action
2818
-     * @return boolean
2819
-     * @throws EE_Error
2820
-     */
2821
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2822
-    {
2823
-        foreach ($this->unique_indexes() as $index_name => $index) {
2824
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2825
-            if ($this->exists(array($uniqueness_where_params))) {
2826
-                EE_Error::add_error(
2827
-                    sprintf(
2828
-                        __(
2829
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2830
-                            "event_espresso"
2831
-                        ),
2832
-                        $action,
2833
-                        $this->_get_class_name(),
2834
-                        $index_name,
2835
-                        implode(",", $index->field_names()),
2836
-                        http_build_query($uniqueness_where_params)
2837
-                    ),
2838
-                    __FILE__,
2839
-                    __FUNCTION__,
2840
-                    __LINE__
2841
-                );
2842
-                return false;
2843
-            }
2844
-        }
2845
-        return true;
2846
-    }
2847
-
2848
-
2849
-
2850
-    /**
2851
-     * Checks the database for an item that conflicts (ie, if this item were
2852
-     * saved to the DB would break some uniqueness requirement, like a primary key
2853
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2854
-     * can be either an EE_Base_Class or an array of fields n values
2855
-     *
2856
-     * @param EE_Base_Class|array $obj_or_fields_array
2857
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2858
-     *                                                 when looking for conflicts
2859
-     *                                                 (ie, if false, we ignore the model object's primary key
2860
-     *                                                 when finding "conflicts". If true, it's also considered).
2861
-     *                                                 Only works for INT primary key,
2862
-     *                                                 STRING primary keys cannot be ignored
2863
-     * @throws EE_Error
2864
-     * @return EE_Base_Class|array
2865
-     */
2866
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2867
-    {
2868
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2869
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2870
-        } elseif (is_array($obj_or_fields_array)) {
2871
-            $fields_n_values = $obj_or_fields_array;
2872
-        } else {
2873
-            throw new EE_Error(
2874
-                sprintf(
2875
-                    __(
2876
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2877
-                        "event_espresso"
2878
-                    ),
2879
-                    get_class($this),
2880
-                    $obj_or_fields_array
2881
-                )
2882
-            );
2883
-        }
2884
-        $query_params = array();
2885
-        if ($this->has_primary_key_field()
2886
-            && ($include_primary_key
2887
-                || $this->get_primary_key_field()
2888
-                   instanceof
2889
-                   EE_Primary_Key_String_Field)
2890
-            && isset($fields_n_values[$this->primary_key_name()])
2891
-        ) {
2892
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2893
-        }
2894
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2895
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2896
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2897
-        }
2898
-        //if there is nothing to base this search on, then we shouldn't find anything
2899
-        if (empty($query_params)) {
2900
-            return array();
2901
-        }
2902
-        return $this->get_one($query_params);
2903
-    }
2904
-
2905
-
2906
-
2907
-    /**
2908
-     * Like count, but is optimized and returns a boolean instead of an int
2909
-     *
2910
-     * @param array $query_params
2911
-     * @return boolean
2912
-     * @throws EE_Error
2913
-     */
2914
-    public function exists($query_params)
2915
-    {
2916
-        $query_params['limit'] = 1;
2917
-        return $this->count($query_params) > 0;
2918
-    }
2919
-
2920
-
2921
-
2922
-    /**
2923
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2924
-     *
2925
-     * @param int|string $id
2926
-     * @return boolean
2927
-     * @throws EE_Error
2928
-     */
2929
-    public function exists_by_ID($id)
2930
-    {
2931
-        return $this->exists(
2932
-            array(
2933
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2934
-                array(
2935
-                    $this->primary_key_name() => $id,
2936
-                ),
2937
-            )
2938
-        );
2939
-    }
2940
-
2941
-
2942
-
2943
-    /**
2944
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2945
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2946
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2947
-     * on the main table)
2948
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2949
-     * cases where we want to call it directly rather than via insert().
2950
-     *
2951
-     * @access   protected
2952
-     * @param EE_Table_Base $table
2953
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2954
-     *                                       float
2955
-     * @param int           $new_id          for now we assume only int keys
2956
-     * @throws EE_Error
2957
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2958
-     * @return int ID of new row inserted, or FALSE on failure
2959
-     */
2960
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2961
-    {
2962
-        global $wpdb;
2963
-        $insertion_col_n_values = array();
2964
-        $format_for_insertion = array();
2965
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2966
-        foreach ($fields_on_table as $field_name => $field_obj) {
2967
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2968
-            if ($field_obj->is_auto_increment()) {
2969
-                continue;
2970
-            }
2971
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2972
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2973
-            if ($prepared_value !== null) {
2974
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2975
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2976
-            }
2977
-        }
2978
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2979
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2980
-            //so add the fk to the main table as a column
2981
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2982
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2983
-        }
2984
-        //insert the new entry
2985
-        $result = $this->_do_wpdb_query('insert',
2986
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2987
-        if ($result === false) {
2988
-            return false;
2989
-        }
2990
-        //ok, now what do we return for the ID of the newly-inserted thing?
2991
-        if ($this->has_primary_key_field()) {
2992
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2993
-                return $wpdb->insert_id;
2994
-            }
2995
-            //it's not an auto-increment primary key, so
2996
-            //it must have been supplied
2997
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2998
-        }
2999
-        //we can't return a  primary key because there is none. instead return
3000
-        //a unique string indicating this model
3001
-        return $this->get_index_primary_key_string($fields_n_values);
3002
-    }
3003
-
3004
-
3005
-
3006
-    /**
3007
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3008
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3009
-     * and there is no default, we pass it along. WPDB will take care of it)
3010
-     *
3011
-     * @param EE_Model_Field_Base $field_obj
3012
-     * @param array               $fields_n_values
3013
-     * @return mixed string|int|float depending on what the table column will be expecting
3014
-     * @throws EE_Error
3015
-     */
3016
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3017
-    {
3018
-        //if this field doesn't allow nullable, don't allow it
3019
-        if (
3020
-            ! $field_obj->is_nullable()
3021
-            && (
3022
-                ! isset($fields_n_values[$field_obj->get_name()])
3023
-                || $fields_n_values[$field_obj->get_name()] === null
3024
-            )
3025
-        ) {
3026
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3027
-        }
3028
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3029
-            ? $fields_n_values[$field_obj->get_name()]
3030
-            : null;
3031
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3032
-    }
3033
-
3034
-
3035
-
3036
-    /**
3037
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3038
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3039
-     * the field's prepare_for_set() method.
3040
-     *
3041
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3042
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3043
-     *                                   top of file)
3044
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3045
-     *                                   $value is a custom selection
3046
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3047
-     */
3048
-    private function _prepare_value_for_use_in_db($value, $field)
3049
-    {
3050
-        if ($field && $field instanceof EE_Model_Field_Base) {
3051
-            switch ($this->_values_already_prepared_by_model_object) {
3052
-                /** @noinspection PhpMissingBreakStatementInspection */
3053
-                case self::not_prepared_by_model_object:
3054
-                    $value = $field->prepare_for_set($value);
3055
-                //purposefully left out "return"
3056
-                case self::prepared_by_model_object:
3057
-                    /** @noinspection SuspiciousAssignmentsInspection */
3058
-                    $value = $field->prepare_for_use_in_db($value);
3059
-                case self::prepared_for_use_in_db:
3060
-                    //leave the value alone
3061
-            }
3062
-            return $value;
3063
-        }
3064
-        return $value;
3065
-    }
3066
-
3067
-
3068
-
3069
-    /**
3070
-     * Returns the main table on this model
3071
-     *
3072
-     * @return EE_Primary_Table
3073
-     * @throws EE_Error
3074
-     */
3075
-    protected function _get_main_table()
3076
-    {
3077
-        foreach ($this->_tables as $table) {
3078
-            if ($table instanceof EE_Primary_Table) {
3079
-                return $table;
3080
-            }
3081
-        }
3082
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3083
-            'event_espresso'), get_class($this)));
3084
-    }
3085
-
3086
-
3087
-
3088
-    /**
3089
-     * table
3090
-     * returns EE_Primary_Table table name
3091
-     *
3092
-     * @return string
3093
-     * @throws EE_Error
3094
-     */
3095
-    public function table()
3096
-    {
3097
-        return $this->_get_main_table()->get_table_name();
3098
-    }
3099
-
3100
-
3101
-
3102
-    /**
3103
-     * table
3104
-     * returns first EE_Secondary_Table table name
3105
-     *
3106
-     * @return string
3107
-     */
3108
-    public function second_table()
3109
-    {
3110
-        // grab second table from tables array
3111
-        $second_table = end($this->_tables);
3112
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3113
-    }
3114
-
3115
-
3116
-
3117
-    /**
3118
-     * get_table_obj_by_alias
3119
-     * returns table name given it's alias
3120
-     *
3121
-     * @param string $table_alias
3122
-     * @return EE_Primary_Table | EE_Secondary_Table
3123
-     */
3124
-    public function get_table_obj_by_alias($table_alias = '')
3125
-    {
3126
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3127
-    }
3128
-
3129
-
3130
-
3131
-    /**
3132
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3133
-     *
3134
-     * @return EE_Secondary_Table[]
3135
-     */
3136
-    protected function _get_other_tables()
3137
-    {
3138
-        $other_tables = array();
3139
-        foreach ($this->_tables as $table_alias => $table) {
3140
-            if ($table instanceof EE_Secondary_Table) {
3141
-                $other_tables[$table_alias] = $table;
3142
-            }
3143
-        }
3144
-        return $other_tables;
3145
-    }
3146
-
3147
-
3148
-
3149
-    /**
3150
-     * Finds all the fields that correspond to the given table
3151
-     *
3152
-     * @param string $table_alias , array key in EEM_Base::_tables
3153
-     * @return EE_Model_Field_Base[]
3154
-     */
3155
-    public function _get_fields_for_table($table_alias)
3156
-    {
3157
-        return $this->_fields[$table_alias];
3158
-    }
3159
-
3160
-
3161
-
3162
-    /**
3163
-     * Recurses through all the where parameters, and finds all the related models we'll need
3164
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3165
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3166
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3167
-     * related Registration, Transaction, and Payment models.
3168
-     *
3169
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3170
-     * @return EE_Model_Query_Info_Carrier
3171
-     * @throws EE_Error
3172
-     */
3173
-    public function _extract_related_models_from_query($query_params)
3174
-    {
3175
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3176
-        if (array_key_exists(0, $query_params)) {
3177
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3178
-        }
3179
-        if (array_key_exists('group_by', $query_params)) {
3180
-            if (is_array($query_params['group_by'])) {
3181
-                $this->_extract_related_models_from_sub_params_array_values(
3182
-                    $query_params['group_by'],
3183
-                    $query_info_carrier,
3184
-                    'group_by'
3185
-                );
3186
-            } elseif (! empty ($query_params['group_by'])) {
3187
-                $this->_extract_related_model_info_from_query_param(
3188
-                    $query_params['group_by'],
3189
-                    $query_info_carrier,
3190
-                    'group_by'
3191
-                );
3192
-            }
3193
-        }
3194
-        if (array_key_exists('having', $query_params)) {
3195
-            $this->_extract_related_models_from_sub_params_array_keys(
3196
-                $query_params[0],
3197
-                $query_info_carrier,
3198
-                'having'
3199
-            );
3200
-        }
3201
-        if (array_key_exists('order_by', $query_params)) {
3202
-            if (is_array($query_params['order_by'])) {
3203
-                $this->_extract_related_models_from_sub_params_array_keys(
3204
-                    $query_params['order_by'],
3205
-                    $query_info_carrier,
3206
-                    'order_by'
3207
-                );
3208
-            } elseif (! empty($query_params['order_by'])) {
3209
-                $this->_extract_related_model_info_from_query_param(
3210
-                    $query_params['order_by'],
3211
-                    $query_info_carrier,
3212
-                    'order_by'
3213
-                );
3214
-            }
3215
-        }
3216
-        if (array_key_exists('force_join', $query_params)) {
3217
-            $this->_extract_related_models_from_sub_params_array_values(
3218
-                $query_params['force_join'],
3219
-                $query_info_carrier,
3220
-                'force_join'
3221
-            );
3222
-        }
3223
-        return $query_info_carrier;
3224
-    }
3225
-
3226
-
3227
-
3228
-    /**
3229
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3230
-     *
3231
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
-     *                                                      $query_params['having']
3233
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3235
-     * @throws EE_Error
3236
-     * @return \EE_Model_Query_Info_Carrier
3237
-     */
3238
-    private function _extract_related_models_from_sub_params_array_keys(
3239
-        $sub_query_params,
3240
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
-        $query_param_type
3242
-    ) {
3243
-        if (! empty($sub_query_params)) {
3244
-            $sub_query_params = (array)$sub_query_params;
3245
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3246
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3247
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3248
-                    $query_param_type);
3249
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3250
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3251
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3252
-                //of array('Registration.TXN_ID'=>23)
3253
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3254
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3255
-                    if (! is_array($possibly_array_of_params)) {
3256
-                        throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3257
-                            "event_espresso"),
3258
-                            $param, $possibly_array_of_params));
3259
-                    }
3260
-                    $this->_extract_related_models_from_sub_params_array_keys(
3261
-                        $possibly_array_of_params,
3262
-                        $model_query_info_carrier, $query_param_type
3263
-                    );
3264
-                } elseif ($query_param_type === 0 //ie WHERE
3265
-                          && is_array($possibly_array_of_params)
3266
-                          && isset($possibly_array_of_params[2])
3267
-                          && $possibly_array_of_params[2] == true
3268
-                ) {
3269
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3270
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3271
-                    //from which we should extract query parameters!
3272
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3273
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3274
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3275
-                    }
3276
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3277
-                        $model_query_info_carrier, $query_param_type);
3278
-                }
3279
-            }
3280
-        }
3281
-        return $model_query_info_carrier;
3282
-    }
3283
-
3284
-
3285
-
3286
-    /**
3287
-     * For extracting related models from forced_joins, where the array values contain the info about what
3288
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3289
-     *
3290
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3291
-     *                                                      $query_params['having']
3292
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3293
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3294
-     * @throws EE_Error
3295
-     * @return \EE_Model_Query_Info_Carrier
3296
-     */
3297
-    private function _extract_related_models_from_sub_params_array_values(
3298
-        $sub_query_params,
3299
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300
-        $query_param_type
3301
-    ) {
3302
-        if (! empty($sub_query_params)) {
3303
-            if (! is_array($sub_query_params)) {
3304
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3305
-                    $sub_query_params));
3306
-            }
3307
-            foreach ($sub_query_params as $param) {
3308
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3310
-                    $query_param_type);
3311
-            }
3312
-        }
3313
-        return $model_query_info_carrier;
3314
-    }
3315
-
3316
-
3317
-
3318
-    /**
3319
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3320
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3321
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3322
-     * but use them in a different order. Eg, we need to know what models we are querying
3323
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3324
-     * other models before we can finalize the where clause SQL.
3325
-     *
3326
-     * @param array $query_params
3327
-     * @throws EE_Error
3328
-     * @return EE_Model_Query_Info_Carrier
3329
-     */
3330
-    public function _create_model_query_info_carrier($query_params)
3331
-    {
3332
-        if (! is_array($query_params)) {
3333
-            EE_Error::doing_it_wrong(
3334
-                'EEM_Base::_create_model_query_info_carrier',
3335
-                sprintf(
3336
-                    __(
3337
-                        '$query_params should be an array, you passed a variable of type %s',
3338
-                        'event_espresso'
3339
-                    ),
3340
-                    gettype($query_params)
3341
-                ),
3342
-                '4.6.0'
3343
-            );
3344
-            $query_params = array();
3345
-        }
3346
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3347
-        //first check if we should alter the query to account for caps or not
3348
-        //because the caps might require us to do extra joins
3349
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3350
-            $query_params[0] = $where_query_params = array_replace_recursive(
3351
-                $where_query_params,
3352
-                $this->caps_where_conditions(
3353
-                    $query_params['caps']
3354
-                )
3355
-            );
3356
-        }
3357
-        $query_object = $this->_extract_related_models_from_query($query_params);
3358
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3359
-        foreach ($where_query_params as $key => $value) {
3360
-            if (is_int($key)) {
3361
-                throw new EE_Error(
3362
-                    sprintf(
3363
-                        __(
3364
-                            "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.",
3365
-                            "event_espresso"
3366
-                        ),
3367
-                        $key,
3368
-                        var_export($value, true),
3369
-                        var_export($query_params, true),
3370
-                        get_class($this)
3371
-                    )
3372
-                );
3373
-            }
3374
-        }
3375
-        if (
3376
-            array_key_exists('default_where_conditions', $query_params)
3377
-            && ! empty($query_params['default_where_conditions'])
3378
-        ) {
3379
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3380
-        } else {
3381
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3382
-        }
3383
-        $where_query_params = array_merge(
3384
-            $this->_get_default_where_conditions_for_models_in_query(
3385
-                $query_object,
3386
-                $use_default_where_conditions,
3387
-                $where_query_params
3388
-            ),
3389
-            $where_query_params
3390
-        );
3391
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3392
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3393
-        // So we need to setup a subquery and use that for the main join.
3394
-        // Note for now this only works on the primary table for the model.
3395
-        // So for instance, you could set the limit array like this:
3396
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3397
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3398
-            $query_object->set_main_model_join_sql(
3399
-                $this->_construct_limit_join_select(
3400
-                    $query_params['on_join_limit'][0],
3401
-                    $query_params['on_join_limit'][1]
3402
-                )
3403
-            );
3404
-        }
3405
-        //set limit
3406
-        if (array_key_exists('limit', $query_params)) {
3407
-            if (is_array($query_params['limit'])) {
3408
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3409
-                    $e = sprintf(
3410
-                        __(
3411
-                            "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)",
3412
-                            "event_espresso"
3413
-                        ),
3414
-                        http_build_query($query_params['limit'])
3415
-                    );
3416
-                    throw new EE_Error($e . "|" . $e);
3417
-                }
3418
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3419
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3420
-            } elseif (! empty ($query_params['limit'])) {
3421
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3422
-            }
3423
-        }
3424
-        //set order by
3425
-        if (array_key_exists('order_by', $query_params)) {
3426
-            if (is_array($query_params['order_by'])) {
3427
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3428
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3429
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3430
-                if (array_key_exists('order', $query_params)) {
3431
-                    throw new EE_Error(
3432
-                        sprintf(
3433
-                            __(
3434
-                                "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 ",
3435
-                                "event_espresso"
3436
-                            ),
3437
-                            get_class($this),
3438
-                            implode(", ", array_keys($query_params['order_by'])),
3439
-                            implode(", ", $query_params['order_by']),
3440
-                            $query_params['order']
3441
-                        )
3442
-                    );
3443
-                }
3444
-                $this->_extract_related_models_from_sub_params_array_keys(
3445
-                    $query_params['order_by'],
3446
-                    $query_object,
3447
-                    'order_by'
3448
-                );
3449
-                //assume it's an array of fields to order by
3450
-                $order_array = array();
3451
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3452
-                    $order = $this->_extract_order($order);
3453
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3454
-                }
3455
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3456
-            } elseif (! empty ($query_params['order_by'])) {
3457
-                $this->_extract_related_model_info_from_query_param(
3458
-                    $query_params['order_by'],
3459
-                    $query_object,
3460
-                    'order',
3461
-                    $query_params['order_by']
3462
-                );
3463
-                $order = isset($query_params['order'])
3464
-                    ? $this->_extract_order($query_params['order'])
3465
-                    : 'DESC';
3466
-                $query_object->set_order_by_sql(
3467
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3468
-                );
3469
-            }
3470
-        }
3471
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3472
-        if (! array_key_exists('order_by', $query_params)
3473
-            && array_key_exists('order', $query_params)
3474
-            && ! empty($query_params['order'])
3475
-        ) {
3476
-            $pk_field = $this->get_primary_key_field();
3477
-            $order = $this->_extract_order($query_params['order']);
3478
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3479
-        }
3480
-        //set group by
3481
-        if (array_key_exists('group_by', $query_params)) {
3482
-            if (is_array($query_params['group_by'])) {
3483
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3484
-                $group_by_array = array();
3485
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3486
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3487
-                }
3488
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3489
-            } elseif (! empty ($query_params['group_by'])) {
3490
-                $query_object->set_group_by_sql(
3491
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3492
-                );
3493
-            }
3494
-        }
3495
-        //set having
3496
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3497
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3498
-        }
3499
-        //now, just verify they didn't pass anything wack
3500
-        foreach ($query_params as $query_key => $query_value) {
3501
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3502
-                throw new EE_Error(
3503
-                    sprintf(
3504
-                        __(
3505
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3506
-                            'event_espresso'
3507
-                        ),
3508
-                        $query_key,
3509
-                        get_class($this),
3510
-                        //						print_r( $this->_allowed_query_params, TRUE )
3511
-                        implode(',', $this->_allowed_query_params)
3512
-                    )
3513
-                );
3514
-            }
3515
-        }
3516
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3517
-        if (empty($main_model_join_sql)) {
3518
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3519
-        }
3520
-        return $query_object;
3521
-    }
3522
-
3523
-
3524
-
3525
-    /**
3526
-     * Gets the where conditions that should be imposed on the query based on the
3527
-     * context (eg reading frontend, backend, edit or delete).
3528
-     *
3529
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3530
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3531
-     * @throws EE_Error
3532
-     */
3533
-    public function caps_where_conditions($context = self::caps_read)
3534
-    {
3535
-        EEM_Base::verify_is_valid_cap_context($context);
3536
-        $cap_where_conditions = array();
3537
-        $cap_restrictions = $this->caps_missing($context);
3538
-        /**
3539
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3540
-         */
3541
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3542
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3543
-                $restriction_if_no_cap->get_default_where_conditions());
3544
-        }
3545
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3546
-            $cap_restrictions);
3547
-    }
3548
-
3549
-
3550
-
3551
-    /**
3552
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3553
-     * otherwise throws an exception
3554
-     *
3555
-     * @param string $should_be_order_string
3556
-     * @return string either ASC, asc, DESC or desc
3557
-     * @throws EE_Error
3558
-     */
3559
-    private function _extract_order($should_be_order_string)
3560
-    {
3561
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3562
-            return $should_be_order_string;
3563
-        }
3564
-        throw new EE_Error(
3565
-            sprintf(
3566
-                __(
3567
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3568
-                    "event_espresso"
3569
-                ), get_class($this), $should_be_order_string
3570
-            )
3571
-        );
3572
-    }
3573
-
3574
-
3575
-
3576
-    /**
3577
-     * Looks at all the models which are included in this query, and asks each
3578
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3579
-     * so they can be merged
3580
-     *
3581
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3582
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3583
-     *                                                                  'none' means NO default where conditions will
3584
-     *                                                                  be used AT ALL during this query.
3585
-     *                                                                  'other_models_only' means default where
3586
-     *                                                                  conditions from other models will be used, but
3587
-     *                                                                  not for this primary model. 'all', the default,
3588
-     *                                                                  means default where conditions will apply as
3589
-     *                                                                  normal
3590
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3591
-     * @throws EE_Error
3592
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3593
-     */
3594
-    private function _get_default_where_conditions_for_models_in_query(
3595
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3596
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3597
-        $where_query_params = array()
3598
-    ) {
3599
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3600
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3601
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3602
-                "event_espresso"), $use_default_where_conditions,
3603
-                implode(", ", $allowed_used_default_where_conditions_values)));
3604
-        }
3605
-        $universal_query_params = array();
3606
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3607
-            $universal_query_params = $this->_get_default_where_conditions();
3608
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3609
-            $universal_query_params = $this->_get_minimum_where_conditions();
3610
-        }
3611
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3612
-            $related_model = $this->get_related_model_obj($model_name);
3613
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3614
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3615
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3616
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3617
-            } else {
3618
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3619
-                continue;
3620
-            }
3621
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3622
-                $related_model_universal_where_params,
3623
-                $where_query_params,
3624
-                $related_model,
3625
-                $model_relation_path
3626
-            );
3627
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3628
-                $universal_query_params,
3629
-                $overrides
3630
-            );
3631
-        }
3632
-        return $universal_query_params;
3633
-    }
3634
-
3635
-
3636
-
3637
-    /**
3638
-     * Determines whether or not we should use default where conditions for the model in question
3639
-     * (this model, or other related models).
3640
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3641
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3642
-     * We should use default where conditions on related models when they requested to use default where conditions
3643
-     * on all models, or specifically just on other related models
3644
-     * @param      $default_where_conditions_value
3645
-     * @param bool $for_this_model false means this is for OTHER related models
3646
-     * @return bool
3647
-     */
3648
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3649
-    {
3650
-        return (
3651
-                   $for_this_model
3652
-                   && in_array(
3653
-                       $default_where_conditions_value,
3654
-                       array(
3655
-                           EEM_Base::default_where_conditions_all,
3656
-                           EEM_Base::default_where_conditions_this_only,
3657
-                           EEM_Base::default_where_conditions_minimum_others,
3658
-                       ),
3659
-                       true
3660
-                   )
3661
-               )
3662
-               || (
3663
-                   ! $for_this_model
3664
-                   && in_array(
3665
-                       $default_where_conditions_value,
3666
-                       array(
3667
-                           EEM_Base::default_where_conditions_all,
3668
-                           EEM_Base::default_where_conditions_others_only,
3669
-                       ),
3670
-                       true
3671
-                   )
3672
-               );
3673
-    }
3674
-
3675
-    /**
3676
-     * Determines whether or not we should use default minimum conditions for the model in question
3677
-     * (this model, or other related models).
3678
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3679
-     * where conditions.
3680
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3681
-     * on this model or others
3682
-     * @param      $default_where_conditions_value
3683
-     * @param bool $for_this_model false means this is for OTHER related models
3684
-     * @return bool
3685
-     */
3686
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3687
-    {
3688
-        return (
3689
-                   $for_this_model
3690
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3691
-               )
3692
-               || (
3693
-                   ! $for_this_model
3694
-                   && in_array(
3695
-                       $default_where_conditions_value,
3696
-                       array(
3697
-                           EEM_Base::default_where_conditions_minimum_others,
3698
-                           EEM_Base::default_where_conditions_minimum_all,
3699
-                       ),
3700
-                       true
3701
-                   )
3702
-               );
3703
-    }
3704
-
3705
-
3706
-    /**
3707
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3708
-     * then we also add a special where condition which allows for that model's primary key
3709
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3710
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3711
-     *
3712
-     * @param array    $default_where_conditions
3713
-     * @param array    $provided_where_conditions
3714
-     * @param EEM_Base $model
3715
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3716
-     * @return array like EEM_Base::get_all's $query_params[0]
3717
-     * @throws EE_Error
3718
-     */
3719
-    private function _override_defaults_or_make_null_friendly(
3720
-        $default_where_conditions,
3721
-        $provided_where_conditions,
3722
-        $model,
3723
-        $model_relation_path
3724
-    ) {
3725
-        $null_friendly_where_conditions = array();
3726
-        $none_overridden = true;
3727
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3728
-        foreach ($default_where_conditions as $key => $val) {
3729
-            if (isset($provided_where_conditions[$key])) {
3730
-                $none_overridden = false;
3731
-            } else {
3732
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3733
-            }
3734
-        }
3735
-        if ($none_overridden && $default_where_conditions) {
3736
-            if ($model->has_primary_key_field()) {
3737
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3738
-                                                                                . "."
3739
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3740
-            }/*else{
35
+	/**
36
+	 * Flag to indicate whether the values provided to EEM_Base have already been prepared
37
+	 * by the model object or not (ie, the model object has used the field's _prepare_for_set function on the values).
38
+	 * They almost always WILL NOT, but it's not necessarily a requirement.
39
+	 * For example, if you want to run EEM_Event::instance()->get_all(array(array('EVT_ID'=>$_GET['event_id'])));
40
+	 *
41
+	 * @var boolean
42
+	 */
43
+	private $_values_already_prepared_by_model_object = 0;
44
+
45
+	/**
46
+	 * when $_values_already_prepared_by_model_object equals this, we assume
47
+	 * the data is just like form input that needs to have the model fields'
48
+	 * prepare_for_set and prepare_for_use_in_db called on it
49
+	 */
50
+	const not_prepared_by_model_object = 0;
51
+
52
+	/**
53
+	 * when $_values_already_prepared_by_model_object equals this, we
54
+	 * assume this value is coming from a model object and doesn't need to have
55
+	 * prepare_for_set called on it, just prepare_for_use_in_db is used
56
+	 */
57
+	const prepared_by_model_object = 1;
58
+
59
+	/**
60
+	 * when $_values_already_prepared_by_model_object equals this, we assume
61
+	 * the values are already to be used in the database (ie no processing is done
62
+	 * on them by the model's fields)
63
+	 */
64
+	const prepared_for_use_in_db = 2;
65
+
66
+
67
+	protected $singular_item = 'Item';
68
+
69
+	protected $plural_item   = 'Items';
70
+
71
+	/**
72
+	 * @type \EE_Table_Base[] $_tables array of EE_Table objects for defining which tables comprise this model.
73
+	 */
74
+	protected $_tables;
75
+
76
+	/**
77
+	 * with two levels: top-level has array keys which are database table aliases (ie, keys in _tables)
78
+	 * and the value is an array. Each of those sub-arrays have keys of field names (eg 'ATT_ID', which should also be
79
+	 * variable names on the model objects (eg, EE_Attendee), and the keys should be children of EE_Model_Field
80
+	 *
81
+	 * @var \EE_Model_Field_Base[][] $_fields
82
+	 */
83
+	protected $_fields;
84
+
85
+	/**
86
+	 * array of different kinds of relations
87
+	 *
88
+	 * @var \EE_Model_Relation_Base[] $_model_relations
89
+	 */
90
+	protected $_model_relations;
91
+
92
+	/**
93
+	 * @var \EE_Index[] $_indexes
94
+	 */
95
+	protected $_indexes = array();
96
+
97
+	/**
98
+	 * Default strategy for getting where conditions on this model. This strategy is used to get default
99
+	 * where conditions which are added to get_all, update, and delete queries. They can be overridden
100
+	 * by setting the same columns as used in these queries in the query yourself.
101
+	 *
102
+	 * @var EE_Default_Where_Conditions
103
+	 */
104
+	protected $_default_where_conditions_strategy;
105
+
106
+	/**
107
+	 * Strategy for getting conditions on this model when 'default_where_conditions' equals 'minimum'.
108
+	 * This is particularly useful when you want something between 'none' and 'default'
109
+	 *
110
+	 * @var EE_Default_Where_Conditions
111
+	 */
112
+	protected $_minimum_where_conditions_strategy;
113
+
114
+	/**
115
+	 * String describing how to find the "owner" of this model's objects.
116
+	 * When there is a foreign key on this model to the wp_users table, this isn't needed.
117
+	 * But when there isn't, this indicates which related model, or transiently-related model,
118
+	 * has the foreign key to the wp_users table.
119
+	 * Eg, for EEM_Registration this would be 'Event' because registrations are directly
120
+	 * related to events, and events have a foreign key to wp_users.
121
+	 * On EEM_Transaction, this would be 'Transaction.Event'
122
+	 *
123
+	 * @var string
124
+	 */
125
+	protected $_model_chain_to_wp_user = '';
126
+
127
+	/**
128
+	 * This is a flag typically set by updates so that we don't load the where strategy on updates because updates
129
+	 * don't need it (particularly CPT models)
130
+	 *
131
+	 * @var bool
132
+	 */
133
+	protected $_ignore_where_strategy = false;
134
+
135
+	/**
136
+	 * String used in caps relating to this model. Eg, if the caps relating to this
137
+	 * model are 'ee_edit_events', 'ee_read_events', etc, it would be 'events'.
138
+	 *
139
+	 * @var string. If null it hasn't been initialized yet. If false then we
140
+	 * have indicated capabilities don't apply to this
141
+	 */
142
+	protected $_caps_slug = null;
143
+
144
+	/**
145
+	 * 2d array where top-level keys are one of EEM_Base::valid_cap_contexts(),
146
+	 * and next-level keys are capability names, and each's value is a
147
+	 * EE_Default_Where_Condition. If the requester requests to apply caps to the query,
148
+	 * they specify which context to use (ie, frontend, backend, edit or delete)
149
+	 * and then each capability in the corresponding sub-array that they're missing
150
+	 * adds the where conditions onto the query.
151
+	 *
152
+	 * @var array
153
+	 */
154
+	protected $_cap_restrictions = array(
155
+		self::caps_read       => array(),
156
+		self::caps_read_admin => array(),
157
+		self::caps_edit       => array(),
158
+		self::caps_delete     => array(),
159
+	);
160
+
161
+	/**
162
+	 * Array defining which cap restriction generators to use to create default
163
+	 * cap restrictions to put in EEM_Base::_cap_restrictions.
164
+	 * Array-keys are one of EEM_Base::valid_cap_contexts(), and values are a child of
165
+	 * EE_Restriction_Generator_Base. If you don't want any cap restrictions generated
166
+	 * automatically set this to false (not just null).
167
+	 *
168
+	 * @var EE_Restriction_Generator_Base[]
169
+	 */
170
+	protected $_cap_restriction_generators = array();
171
+
172
+	/**
173
+	 * constants used to categorize capability restrictions on EEM_Base::_caps_restrictions
174
+	 */
175
+	const caps_read       = 'read';
176
+
177
+	const caps_read_admin = 'read_admin';
178
+
179
+	const caps_edit       = 'edit';
180
+
181
+	const caps_delete     = 'delete';
182
+
183
+	/**
184
+	 * Keys are all the cap contexts (ie constants EEM_Base::_caps_*) and values are their 'action'
185
+	 * as how they'd be used in capability names. Eg EEM_Base::caps_read ('read_frontend')
186
+	 * maps to 'read' because when looking for relevant permissions we're going to use
187
+	 * 'read' in teh capabilities names like 'ee_read_events' etc.
188
+	 *
189
+	 * @var array
190
+	 */
191
+	protected $_cap_contexts_to_cap_action_map = array(
192
+		self::caps_read       => 'read',
193
+		self::caps_read_admin => 'read',
194
+		self::caps_edit       => 'edit',
195
+		self::caps_delete     => 'delete',
196
+	);
197
+
198
+	/**
199
+	 * Timezone
200
+	 * This gets set via the constructor so that we know what timezone incoming strings|timestamps are in when there
201
+	 * are EE_Datetime_Fields in use.  This can also be used before a get to set what timezone you want strings coming
202
+	 * out of the created objects.  NOT all EEM_Base child classes use this property but any that use a
203
+	 * EE_Datetime_Field data type will have access to it.
204
+	 *
205
+	 * @var string
206
+	 */
207
+	protected $_timezone;
208
+
209
+
210
+	/**
211
+	 * This holds the id of the blog currently making the query.  Has no bearing on single site but is used for
212
+	 * multisite.
213
+	 *
214
+	 * @var int
215
+	 */
216
+	protected static $_model_query_blog_id;
217
+
218
+	/**
219
+	 * A copy of _fields, except the array keys are the model names pointed to by
220
+	 * the field
221
+	 *
222
+	 * @var EE_Model_Field_Base[]
223
+	 */
224
+	private $_cache_foreign_key_to_fields = array();
225
+
226
+	/**
227
+	 * Cached list of all the fields on the model, indexed by their name
228
+	 *
229
+	 * @var EE_Model_Field_Base[]
230
+	 */
231
+	private $_cached_fields = null;
232
+
233
+	/**
234
+	 * Cached list of all the fields on the model, except those that are
235
+	 * marked as only pertinent to the database
236
+	 *
237
+	 * @var EE_Model_Field_Base[]
238
+	 */
239
+	private $_cached_fields_non_db_only = null;
240
+
241
+	/**
242
+	 * A cached reference to the primary key for quick lookup
243
+	 *
244
+	 * @var EE_Model_Field_Base
245
+	 */
246
+	private $_primary_key_field = null;
247
+
248
+	/**
249
+	 * Flag indicating whether this model has a primary key or not
250
+	 *
251
+	 * @var boolean
252
+	 */
253
+	protected $_has_primary_key_field = null;
254
+
255
+	/**
256
+	 * Whether or not this model is based off a table in WP core only (CPTs should set
257
+	 * this to FALSE, but if we were to make an EE_WP_Post model, it should set this to true).
258
+	 * This should be true for models that deal with data that should exist independent of EE.
259
+	 * For example, if the model can read and insert data that isn't used by EE, this should be true.
260
+	 * It would be false, however, if you could guarantee the model would only interact with EE data,
261
+	 * even if it uses a WP core table (eg event and venue models set this to false for that reason:
262
+	 * they can only read and insert events and venues custom post types, not arbitrary post types)
263
+	 * @var boolean
264
+	 */
265
+	protected $_wp_core_model = false;
266
+
267
+	/**
268
+	 *    List of valid operators that can be used for querying.
269
+	 * The keys are all operators we'll accept, the values are the real SQL
270
+	 * operators used
271
+	 *
272
+	 * @var array
273
+	 */
274
+	protected $_valid_operators = array(
275
+		'='           => '=',
276
+		'<='          => '<=',
277
+		'<'           => '<',
278
+		'>='          => '>=',
279
+		'>'           => '>',
280
+		'!='          => '!=',
281
+		'LIKE'        => 'LIKE',
282
+		'like'        => 'LIKE',
283
+		'NOT_LIKE'    => 'NOT LIKE',
284
+		'not_like'    => 'NOT LIKE',
285
+		'NOT LIKE'    => 'NOT LIKE',
286
+		'not like'    => 'NOT LIKE',
287
+		'IN'          => 'IN',
288
+		'in'          => 'IN',
289
+		'NOT_IN'      => 'NOT IN',
290
+		'not_in'      => 'NOT IN',
291
+		'NOT IN'      => 'NOT IN',
292
+		'not in'      => 'NOT IN',
293
+		'between'     => 'BETWEEN',
294
+		'BETWEEN'     => 'BETWEEN',
295
+		'IS_NOT_NULL' => 'IS NOT NULL',
296
+		'is_not_null' => 'IS NOT NULL',
297
+		'IS NOT NULL' => 'IS NOT NULL',
298
+		'is not null' => 'IS NOT NULL',
299
+		'IS_NULL'     => 'IS NULL',
300
+		'is_null'     => 'IS NULL',
301
+		'IS NULL'     => 'IS NULL',
302
+		'is null'     => 'IS NULL',
303
+		'REGEXP'      => 'REGEXP',
304
+		'regexp'      => 'REGEXP',
305
+		'NOT_REGEXP'  => 'NOT REGEXP',
306
+		'not_regexp'  => 'NOT REGEXP',
307
+		'NOT REGEXP'  => 'NOT REGEXP',
308
+		'not regexp'  => 'NOT REGEXP',
309
+	);
310
+
311
+	/**
312
+	 * operators that work like 'IN', accepting a comma-separated list of values inside brackets. Eg '(1,2,3)'
313
+	 *
314
+	 * @var array
315
+	 */
316
+	protected $_in_style_operators = array('IN', 'NOT IN');
317
+
318
+	/**
319
+	 * operators that work like 'BETWEEN'.  Typically used for datetime calculations, i.e. "BETWEEN '12-1-2011' AND
320
+	 * '12-31-2012'"
321
+	 *
322
+	 * @var array
323
+	 */
324
+	protected $_between_style_operators = array('BETWEEN');
325
+
326
+	/**
327
+	 * Operators that work like SQL's like: input should be assumed to be a string, already prepared for a LIKE query.
328
+	 * @var array
329
+	 */
330
+	protected $_like_style_operators = array('LIKE', 'NOT LIKE');
331
+	/**
332
+	 * operators that are used for handling NUll and !NULL queries.  Typically used for when checking if a row exists
333
+	 * on a join table.
334
+	 *
335
+	 * @var array
336
+	 */
337
+	protected $_null_style_operators = array('IS NOT NULL', 'IS NULL');
338
+
339
+	/**
340
+	 * Allowed values for $query_params['order'] for ordering in queries
341
+	 *
342
+	 * @var array
343
+	 */
344
+	protected $_allowed_order_values = array('asc', 'desc', 'ASC', 'DESC');
345
+
346
+	/**
347
+	 * When these are keys in a WHERE or HAVING clause, they are handled much differently
348
+	 * than regular field names. It is assumed that their values are an array of WHERE conditions
349
+	 *
350
+	 * @var array
351
+	 */
352
+	private $_logic_query_param_keys = array('not', 'and', 'or', 'NOT', 'AND', 'OR');
353
+
354
+	/**
355
+	 * Allowed keys in $query_params arrays passed into queries. Note that 0 is meant to always be a
356
+	 * 'where', but 'where' clauses are so common that we thought we'd omit it
357
+	 *
358
+	 * @var array
359
+	 */
360
+	private $_allowed_query_params = array(
361
+		0,
362
+		'limit',
363
+		'order_by',
364
+		'group_by',
365
+		'having',
366
+		'force_join',
367
+		'order',
368
+		'on_join_limit',
369
+		'default_where_conditions',
370
+		'caps',
371
+	);
372
+
373
+	/**
374
+	 * All the data types that can be used in $wpdb->prepare statements.
375
+	 *
376
+	 * @var array
377
+	 */
378
+	private $_valid_wpdb_data_types = array('%d', '%s', '%f');
379
+
380
+	/**
381
+	 * @var EE_Registry $EE
382
+	 */
383
+	protected $EE = null;
384
+
385
+
386
+	/**
387
+	 * Property which, when set, will have this model echo out the next X queries to the page for debugging.
388
+	 *
389
+	 * @var int
390
+	 */
391
+	protected $_show_next_x_db_queries = 0;
392
+
393
+	/**
394
+	 * When using _get_all_wpdb_results, you can specify a custom selection. If you do so,
395
+	 * it gets saved on this property so those selections can be used in WHERE, GROUP_BY, etc.
396
+	 *
397
+	 * @var array
398
+	 */
399
+	protected $_custom_selections = array();
400
+
401
+	/**
402
+	 * key => value Entity Map using  array( EEM_Base::$_model_query_blog_id => array( ID => model object ) )
403
+	 * caches every model object we've fetched from the DB on this request
404
+	 *
405
+	 * @var array
406
+	 */
407
+	protected $_entity_map;
408
+
409
+	/**
410
+	 * @var LoaderInterface $loader
411
+	 */
412
+	private static $loader;
413
+
414
+
415
+	/**
416
+	 * constant used to show EEM_Base has not yet verified the db on this http request
417
+	 */
418
+	const db_verified_none = 0;
419
+
420
+	/**
421
+	 * constant used to show EEM_Base has verified the EE core db on this http request,
422
+	 * but not the addons' dbs
423
+	 */
424
+	const db_verified_core = 1;
425
+
426
+	/**
427
+	 * constant used to show EEM_Base has verified the addons' dbs (and implicitly
428
+	 * the EE core db too)
429
+	 */
430
+	const db_verified_addons = 2;
431
+
432
+	/**
433
+	 * indicates whether an EEM_Base child has already re-verified the DB
434
+	 * is ok (we don't want to do it repetitively). Should be set to one the constants
435
+	 * looking like EEM_Base::db_verified_*
436
+	 *
437
+	 * @var int - 0 = none, 1 = core, 2 = addons
438
+	 */
439
+	protected static $_db_verification_level = EEM_Base::db_verified_none;
440
+
441
+	/**
442
+	 * @const constant for 'default_where_conditions' to apply default where conditions to ALL queried models
443
+	 *        (eg, if retrieving registrations ordered by their datetimes, this will only return non-trashed
444
+	 *        registrations for non-trashed tickets for non-trashed datetimes)
445
+	 */
446
+	const default_where_conditions_all = 'all';
447
+
448
+	/**
449
+	 * @const constant for 'default_where_conditions' to apply default where conditions to THIS model only, but
450
+	 *        no other models which are joined to (eg, if retrieving registrations ordered by their datetimes, this will
451
+	 *        return non-trashed registrations, regardless of the related datetimes and tickets' statuses).
452
+	 *        It is preferred to use EEM_Base::default_where_conditions_minimum_others because, when joining to
453
+	 *        models which share tables with other models, this can return data for the wrong model.
454
+	 */
455
+	const default_where_conditions_this_only = 'this_model_only';
456
+
457
+	/**
458
+	 * @const constant for 'default_where_conditions' to apply default where conditions to other models queried,
459
+	 *        but not the current model (eg, if retrieving registrations ordered by their datetimes, this will
460
+	 *        return all registrations related to non-trashed tickets and non-trashed datetimes)
461
+	 */
462
+	const default_where_conditions_others_only = 'other_models_only';
463
+
464
+	/**
465
+	 * @const constant for 'default_where_conditions' to apply minimum where conditions to all models queried.
466
+	 *        For most models this the same as EEM_Base::default_where_conditions_none, except for models which share
467
+	 *        their table with other models, like the Event and Venue models. For example, when querying for events
468
+	 *        ordered by their venues' name, this will be sure to only return real events with associated real venues
469
+	 *        (regardless of whether those events and venues are trashed)
470
+	 *        In contrast, using EEM_Base::default_where_conditions_none would could return WP posts other than EE
471
+	 *        events.
472
+	 */
473
+	const default_where_conditions_minimum_all = 'minimum';
474
+
475
+	/**
476
+	 * @const constant for 'default_where_conditions' to apply apply where conditions to other models, and full default
477
+	 *        where conditions for the queried model (eg, when querying events ordered by venues' names, this will
478
+	 *        return non-trashed events for any venues, regardless of whether those associated venues are trashed or
479
+	 *        not)
480
+	 */
481
+	const default_where_conditions_minimum_others = 'full_this_minimum_others';
482
+
483
+	/**
484
+	 * @const constant for 'default_where_conditions' to NOT apply any where conditions. This should very rarely be
485
+	 *        used, because when querying from a model which shares its table with another model (eg Events and Venues)
486
+	 *        it's possible it will return table entries for other models. You should use
487
+	 *        EEM_Base::default_where_conditions_minimum_all instead.
488
+	 */
489
+	const default_where_conditions_none = 'none';
490
+
491
+
492
+
493
+	/**
494
+	 * About all child constructors:
495
+	 * they should define the _tables, _fields and _model_relations arrays.
496
+	 * Should ALWAYS be called after child constructor.
497
+	 * In order to make the child constructors to be as simple as possible, this parent constructor
498
+	 * finalizes constructing all the object's attributes.
499
+	 * Generally, rather than requiring a child to code
500
+	 * $this->_tables = array(
501
+	 *        'Event_Post_Table' => new EE_Table('Event_Post_Table','wp_posts')
502
+	 *        ...);
503
+	 *  (thus repeating itself in the array key and in the constructor of the new EE_Table,)
504
+	 * each EE_Table has a function to set the table's alias after the constructor, using
505
+	 * the array key ('Event_Post_Table'), instead of repeating it. The model fields and model relations
506
+	 * do something similar.
507
+	 *
508
+	 * @param null $timezone
509
+	 * @throws EE_Error
510
+	 */
511
+	protected function __construct($timezone = null)
512
+	{
513
+		// check that the model has not been loaded too soon
514
+		if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
+			throw new EE_Error (
516
+				sprintf(
517
+					__('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.',
518
+						'event_espresso'),
519
+					get_class($this)
520
+				)
521
+			);
522
+		}
523
+		/**
524
+		 * Set blogid for models to current blog. However we ONLY do this if $_model_query_blog_id is not already set.
525
+		 */
526
+		if (empty(EEM_Base::$_model_query_blog_id)) {
527
+			EEM_Base::set_model_query_blog_id();
528
+		}
529
+		/**
530
+		 * Filters the list of tables on a model. It is best to NOT use this directly and instead
531
+		 * just use EE_Register_Model_Extension
532
+		 *
533
+		 * @var EE_Table_Base[] $_tables
534
+		 */
535
+		$this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
536
+		foreach ($this->_tables as $table_alias => $table_obj) {
537
+			/** @var $table_obj EE_Table_Base */
538
+			$table_obj->_construct_finalize_with_alias($table_alias);
539
+			if ($table_obj instanceof EE_Secondary_Table) {
540
+				/** @var $table_obj EE_Secondary_Table */
541
+				$table_obj->_construct_finalize_set_table_to_join_with($this->_get_main_table());
542
+			}
543
+		}
544
+		/**
545
+		 * Filters the list of fields on a model. It is best to NOT use this directly and instead just use
546
+		 * EE_Register_Model_Extension
547
+		 *
548
+		 * @param EE_Model_Field_Base[] $_fields
549
+		 */
550
+		$this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
551
+		$this->_invalidate_field_caches();
552
+		foreach ($this->_fields as $table_alias => $fields_for_table) {
553
+			if (! array_key_exists($table_alias, $this->_tables)) {
554
+				throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555
+					'event_espresso'), $table_alias, implode(",", $this->_fields)));
556
+			}
557
+			foreach ($fields_for_table as $field_name => $field_obj) {
558
+				/** @var $field_obj EE_Model_Field_Base | EE_Primary_Key_Field_Base */
559
+				//primary key field base has a slightly different _construct_finalize
560
+				/** @var $field_obj EE_Model_Field_Base */
561
+				$field_obj->_construct_finalize($table_alias, $field_name, $this->get_this_model_name());
562
+			}
563
+		}
564
+		// everything is related to Extra_Meta
565
+		if (get_class($this) !== 'EEM_Extra_Meta') {
566
+			//make extra meta related to everything, but don't block deleting things just
567
+			//because they have related extra meta info. For now just orphan those extra meta
568
+			//in the future we should automatically delete them
569
+			$this->_model_relations['Extra_Meta'] = new EE_Has_Many_Any_Relation(false);
570
+		}
571
+		//and change logs
572
+		if (get_class($this) !== 'EEM_Change_Log') {
573
+			$this->_model_relations['Change_Log'] = new EE_Has_Many_Any_Relation(false);
574
+		}
575
+		/**
576
+		 * Filters the list of relations on a model. It is best to NOT use this directly and instead just use
577
+		 * EE_Register_Model_Extension
578
+		 *
579
+		 * @param EE_Model_Relation_Base[] $_model_relations
580
+		 */
581
+		$this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
582
+			$this->_model_relations);
583
+		foreach ($this->_model_relations as $model_name => $relation_obj) {
584
+			/** @var $relation_obj EE_Model_Relation_Base */
585
+			$relation_obj->_construct_finalize_set_models($this->get_this_model_name(), $model_name);
586
+		}
587
+		foreach ($this->_indexes as $index_name => $index_obj) {
588
+			/** @var $index_obj EE_Index */
589
+			$index_obj->_construct_finalize($index_name, $this->get_this_model_name());
590
+		}
591
+		$this->set_timezone($timezone);
592
+		//finalize default where condition strategy, or set default
593
+		if (! $this->_default_where_conditions_strategy) {
594
+			//nothing was set during child constructor, so set default
595
+			$this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596
+		}
597
+		$this->_default_where_conditions_strategy->_finalize_construct($this);
598
+		if (! $this->_minimum_where_conditions_strategy) {
599
+			//nothing was set during child constructor, so set default
600
+			$this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601
+		}
602
+		$this->_minimum_where_conditions_strategy->_finalize_construct($this);
603
+		//if the cap slug hasn't been set, and we haven't set it to false on purpose
604
+		//to indicate to NOT set it, set it to the logical default
605
+		if ($this->_caps_slug === null) {
606
+			$this->_caps_slug = EEH_Inflector::pluralize_and_lower($this->get_this_model_name());
607
+		}
608
+		//initialize the standard cap restriction generators if none were specified by the child constructor
609
+		if ($this->_cap_restriction_generators !== false) {
610
+			foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
+				if (! isset($this->_cap_restriction_generators[$cap_context])) {
612
+					$this->_cap_restriction_generators[$cap_context] = apply_filters(
613
+						'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614
+						new EE_Restriction_Generator_Protected(),
615
+						$cap_context,
616
+						$this
617
+					);
618
+				}
619
+			}
620
+		}
621
+		//if there are cap restriction generators, use them to make the default cap restrictions
622
+		if ($this->_cap_restriction_generators !== false) {
623
+			foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
+				if (! $generator_object) {
625
+					continue;
626
+				}
627
+				if (! $generator_object instanceof EE_Restriction_Generator_Base) {
628
+					throw new EE_Error(
629
+						sprintf(
630
+							__('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.',
631
+								'event_espresso'),
632
+							$context,
633
+							$this->get_this_model_name()
634
+						)
635
+					);
636
+				}
637
+				$action = $this->cap_action_for_context($context);
638
+				if (! $generator_object->construction_finalized()) {
639
+					$generator_object->_construct_finalize($this, $action);
640
+				}
641
+			}
642
+		}
643
+		do_action('AHEE__' . get_class($this) . '__construct__end');
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * Used to set the $_model_query_blog_id static property.
650
+	 *
651
+	 * @param int $blog_id  If provided then will set the blog_id for the models to this id.  If not provided then the
652
+	 *                      value for get_current_blog_id() will be used.
653
+	 */
654
+	public static function set_model_query_blog_id($blog_id = 0)
655
+	{
656
+		EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
657
+	}
658
+
659
+
660
+
661
+	/**
662
+	 * Returns whatever is set as the internal $model_query_blog_id.
663
+	 *
664
+	 * @return int
665
+	 */
666
+	public static function get_model_query_blog_id()
667
+	{
668
+		return EEM_Base::$_model_query_blog_id;
669
+	}
670
+
671
+
672
+
673
+	/**
674
+	 * This function is a singleton method used to instantiate the Espresso_model object
675
+	 *
676
+	 * @param string $timezone string representing the timezone we want to set for returned Date Time Strings
677
+	 *                                (and any incoming timezone data that gets saved).
678
+	 *                                Note this just sends the timezone info to the date time model field objects.
679
+	 *                                Default is NULL
680
+	 *                                (and will be assumed using the set timezone in the 'timezone_string' wp option)
681
+	 * @return static (as in the concrete child class)
682
+	 * @throws EE_Error
683
+	 * @throws InvalidArgumentException
684
+	 * @throws InvalidDataTypeException
685
+	 * @throws InvalidInterfaceException
686
+	 */
687
+	public static function instance($timezone = null)
688
+	{
689
+		// check if instance of Espresso_model already exists
690
+		if (! static::$_instance instanceof static) {
691
+			// instantiate Espresso_model
692
+			static::$_instance = new static(
693
+				$timezone,
694
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
695
+			);
696
+		}
697
+		//we might have a timezone set, let set_timezone decide what to do with it
698
+		static::$_instance->set_timezone($timezone);
699
+		// Espresso_model object
700
+		return static::$_instance;
701
+	}
702
+
703
+
704
+
705
+	/**
706
+	 * resets the model and returns it
707
+	 *
708
+	 * @param null | string $timezone
709
+	 * @return EEM_Base|null (if the model was already instantiated, returns it, with
710
+	 * all its properties reset; if it wasn't instantiated, returns null)
711
+	 * @throws EE_Error
712
+	 * @throws ReflectionException
713
+	 * @throws InvalidArgumentException
714
+	 * @throws InvalidDataTypeException
715
+	 * @throws InvalidInterfaceException
716
+	 */
717
+	public static function reset($timezone = null)
718
+	{
719
+		if (static::$_instance instanceof EEM_Base) {
720
+			//let's try to NOT swap out the current instance for a new one
721
+			//because if someone has a reference to it, we can't remove their reference
722
+			//so it's best to keep using the same reference, but change the original object
723
+			//reset all its properties to their original values as defined in the class
724
+			$r = new ReflectionClass(get_class(static::$_instance));
725
+			$static_properties = $r->getStaticProperties();
726
+			foreach ($r->getDefaultProperties() as $property => $value) {
727
+				//don't set instance to null like it was originally,
728
+				//but it's static anyways, and we're ignoring static properties (for now at least)
729
+				if (! isset($static_properties[$property])) {
730
+					static::$_instance->{$property} = $value;
731
+				}
732
+			}
733
+			//and then directly call its constructor again, like we would if we were creating a new one
734
+			static::$_instance->__construct(
735
+				$timezone,
736
+				LoaderFactory::getLoader()->load('EventEspresso\core\services\orm\ModelFieldFactory')
737
+			);
738
+			return self::instance();
739
+		}
740
+		return null;
741
+	}
742
+
743
+
744
+
745
+	/**
746
+	 * @return LoaderInterface
747
+	 * @throws InvalidArgumentException
748
+	 * @throws InvalidDataTypeException
749
+	 * @throws InvalidInterfaceException
750
+	 */
751
+	private static function getLoader()
752
+	{
753
+		if(! EEM_Base::$loader instanceof LoaderInterface) {
754
+			EEM_Base::$loader = LoaderFactory::getLoader();
755
+		}
756
+		return EEM_Base::$loader;
757
+	}
758
+
759
+
760
+
761
+	/**
762
+	 * retrieve the status details from esp_status table as an array IF this model has the status table as a relation.
763
+	 *
764
+	 * @param  boolean $translated return localized strings or JUST the array.
765
+	 * @return array
766
+	 * @throws EE_Error
767
+	 * @throws InvalidArgumentException
768
+	 * @throws InvalidDataTypeException
769
+	 * @throws InvalidInterfaceException
770
+	 */
771
+	public function status_array($translated = false)
772
+	{
773
+		if (! array_key_exists('Status', $this->_model_relations)) {
774
+			return array();
775
+		}
776
+		$model_name = $this->get_this_model_name();
777
+		$status_type = str_replace(' ', '_', strtolower(str_replace('_', ' ', $model_name)));
778
+		$stati = EEM_Status::instance()->get_all(array(array('STS_type' => $status_type)));
779
+		$status_array = array();
780
+		foreach ($stati as $status) {
781
+			$status_array[$status->ID()] = $status->get('STS_code');
782
+		}
783
+		return $translated
784
+			? EEM_Status::instance()->localized_status($status_array, false, 'sentence')
785
+			: $status_array;
786
+	}
787
+
788
+
789
+
790
+	/**
791
+	 * Gets all the EE_Base_Class objects which match the $query_params, by querying the DB.
792
+	 *
793
+	 * @param array $query_params             {
794
+	 * @var array $0 (where) array {
795
+	 *                                        eg: array('QST_display_text'=>'Are you bob?','QST_admin_text'=>'Determine
796
+	 *                                        if user is bob') becomes SQL >> "...WHERE QST_display_text = 'Are you
797
+	 *                                        bob?' AND QST_admin_text = 'Determine if user is bob'...") To add WHERE
798
+	 *                                        conditions based on related models (and even
799
+	 *                                        models-related-to-related-models) prepend the model's name onto the field
800
+	 *                                        name. Eg,
801
+	 *                                        EEM_Event::instance()->get_all(array(array('Venue.VNU_ID'=>12))); becomes
802
+	 *                                        SQL >> "SELECT * FROM wp_posts AS Event_CPT LEFT JOIN wp_esp_event_meta
803
+	 *                                        AS Event_Meta ON Event_CPT.ID = Event_Meta.EVT_ID LEFT JOIN
804
+	 *                                        wp_esp_event_venue AS Event_Venue ON Event_Venue.EVT_ID=Event_CPT.ID LEFT
805
+	 *                                        JOIN wp_posts AS Venue_CPT ON Venue_CPT.ID=Event_Venue.VNU_ID LEFT JOIN
806
+	 *                                        wp_esp_venue_meta AS Venue_Meta ON Venue_CPT.ID = Venue_Meta.VNU_ID WHERE
807
+	 *                                        Venue_CPT.ID = 12 Notice that automatically took care of joining Events
808
+	 *                                        to Venues (even when each of those models actually consisted of two
809
+	 *                                        tables). Also, you may chain the model relations together. Eg instead of
810
+	 *                                        just having
811
+	 *                                        "Venue.VNU_ID", you could have
812
+	 *                                        "Registration.Attendee.ATT_ID" as a field on a query for events (because
813
+	 *                                        events are related to Registrations, which are related to Attendees). You
814
+	 *                                        can take it even further with
815
+	 *                                        "Registration.Transaction.Payment.PAY_amount" etc. To change the operator
816
+	 *                                        (from the default of '='), change the value to an numerically-indexed
817
+	 *                                        array, where the first item in the list is the operator. eg: array(
818
+	 *                                        'QST_display_text' => array('LIKE','%bob%'), 'QST_ID' => array('<',34),
819
+	 *                                        'QST_wp_user' => array('in',array(1,2,7,23))) becomes SQL >> "...WHERE
820
+	 *                                        QST_display_text LIKE '%bob%' AND QST_ID < 34 AND QST_wp_user IN
821
+	 *                                        (1,2,7,23)...". Valid operators so far: =, !=, <, <=, >, >=, LIKE, NOT
822
+	 *                                        LIKE, IN (followed by numeric-indexed array), NOT IN (dido), BETWEEN
823
+	 *                                        (followed by an array with exactly 2 date strings), IS NULL, and IS NOT
824
+	 *                                        NULL Values can be a string, int, or float. They can also be arrays IFF
825
+	 *                                        the operator is IN. Also, values can actually be field names. To indicate
826
+	 *                                        the value is a field, simply provide a third array item (true) to the
827
+	 *                                        operator-value array like so: eg: array( 'DTT_reg_limit' => array('>',
828
+	 *                                        'DTT_sold', TRUE) ) becomes SQL >> "...WHERE DTT_reg_limit > DTT_sold"
829
+	 *                                        Note: you can also use related model field names like you would any other
830
+	 *                                        field name. eg:
831
+	 *                                        array('Datetime.DTT_reg_limit'=>array('=','Datetime.DTT_sold',TRUE) could
832
+	 *                                        be used if you were querying EEM_Tickets (because Datetime is directly related to tickets) Also, by default all the where conditions are AND'd together. To override this, add an array key 'OR' (or 'AND') and the array to be OR'd together eg: array('OR'=>array('TXN_ID' => 23 , 'TXN_timestamp__>' =>
833
+	 *                                        345678912)) becomes SQL >> "...WHERE TXN_ID = 23 OR TXN_timestamp =
834
+	 *                                        345678912...". Also, to negate an entire set of conditions, use 'NOT' as
835
+	 *                                        an array key. eg: array('NOT'=>array('TXN_total' =>
836
+	 *                                        50, 'TXN_paid'=>23) becomes SQL >> "...where ! (TXN_total =50 AND
837
+	 *                                        TXN_paid =23) Note: the 'glue' used to join each condition will continue
838
+	 *                                        to be what you last specified. IE, "AND"s by default, but if you had
839
+	 *                                        previously specified to use ORs to join, ORs will continue to be used.
840
+	 *                                        So, if you specify to use an "OR" to join conditions, it will continue to
841
+	 *                                        "stick" until you specify an AND. eg
842
+	 *                                        array('OR'=>array('NOT'=>array('TXN_total' => 50,
843
+	 *                                        'TXN_paid'=>23)),AND=>array('TXN_ID'=>1,'STS_ID'=>'TIN') becomes SQL >>
844
+	 *                                        "...where ! (TXN_total =50 OR TXN_paid =23) AND TXN_ID=1 AND
845
+	 *                                        STS_ID='TIN'" They can be nested indefinitely. eg:
846
+	 *                                        array('OR'=>array('TXN_total' => 23, 'NOT'=> array( 'TXN_timestamp'=> 345678912, 'AND'=>array('TXN_paid' => 53, 'STS_ID' => 'TIN')))) becomes SQL >> "...WHERE TXN_total = 23 OR ! (TXN_timestamp = 345678912 OR (TXN_paid = 53 AND STS_ID = 'TIN'))..." GOTCHA: because this is an array, array keys must be unique, making it impossible to place two or more where conditions applying to the same field. eg: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp'=>array('<',$end_date),'PAY_timestamp'=>array('!=',$special_date)), as PHP enforces that the array keys must be unique, thus removing the first two array entries with key 'PAY_timestamp'. becomes SQL >> "PAY_timestamp !=  4234232", ignoring the first two PAY_timestamp conditions). To overcome this, you can add a '*' character to the end of the field's name, followed by anything. These will be removed when generating the SQL string, but allow for the array keys to be unique. eg: you could rewrite the previous query as: array('PAY_timestamp'=>array('>',$start_date),'PAY_timestamp*1st'=>array('<',$end_date),'PAY_timestamp*2nd'=>array('!=',$special_date)) which correctly becomes SQL >>
847
+	 *                                        "PAY_timestamp > 123412341 AND PAY_timestamp < 2354235235234 AND
848
+	 *                                        PAY_timestamp != 1241234123" This can be applied to condition operators
849
+	 *                                        too, eg:
850
+	 *                                        array('OR'=>array('REG_ID'=>3,'Transaction.TXN_ID'=>23),'OR*whatever'=>array('Attendee.ATT_fname'=>'bob','Attendee.ATT_lname'=>'wilson')));
851
+	 * @var mixed   $limit                    int|array    adds a limit to the query just like the SQL limit clause, so
852
+	 *                                        limits of "23", "25,50", and array(23,42) are all valid would become SQL
853
+	 *                                        "...LIMIT 23", "...LIMIT 25,50", and "...LIMIT 23,42" respectively.
854
+	 *                                        Remember when you provide two numbers for the limit, the 1st number is
855
+	 *                                        the OFFSET, the 2nd is the LIMIT
856
+	 * @var array   $on_join_limit            allows the setting of a special select join with a internal limit so you
857
+	 *                                        can do paging on one-to-many multi-table-joins. Send an array in the
858
+	 *                                        following format array('on_join_limit'
859
+	 *                                        => array( 'table_alias', array(1,2) ) ).
860
+	 * @var mixed   $order_by                 name of a column to order by, or an array where keys are field names and
861
+	 *                                        values are either 'ASC' or 'DESC'.
862
+	 *                                        'limit'=>array('STS_ID'=>'ASC','REG_date'=>'DESC'), which would becomes
863
+	 *                                        SQL "...ORDER BY TXN_timestamp..." and "...ORDER BY STS_ID ASC, REG_date
864
+	 *                                        DESC..." respectively. Like the
865
+	 *                                        'where' conditions, these fields can be on related models. Eg
866
+	 *                                        'order_by'=>array('Registration.Transaction.TXN_amount'=>'ASC') is
867
+	 *                                        perfectly valid from any model related to 'Registration' (like Event,
868
+	 *                                        Attendee, Price, Datetime, etc.)
869
+	 * @var string  $order                    If 'order_by' is used and its value is a string (NOT an array), then
870
+	 *                                        'order' specifies whether to order the field specified in 'order_by' in
871
+	 *                                        ascending or descending order. Acceptable values are 'ASC' or 'DESC'. If,
872
+	 *                                        'order_by' isn't used, but 'order' is, then it is assumed you want to
873
+	 *                                        order by the primary key. Eg,
874
+	 *                                        EEM_Event::instance()->get_all(array('order_by'=>'Datetime.DTT_EVT_start','order'=>'ASC');
875
+	 *                                        //(will join with the Datetime model's table(s) and order by its field
876
+	 *                                        DTT_EVT_start) or
877
+	 *                                        EEM_Registration::instance()->get_all(array('order'=>'ASC'));//will make
878
+	 *                                        SQL "SELECT * FROM wp_esp_registration ORDER BY REG_ID ASC"
879
+	 * @var mixed   $group_by                 name of field to order by, or an array of fields. Eg either
880
+	 *                                        'group_by'=>'VNU_ID', or
881
+	 *                                        'group_by'=>array('EVT_name','Registration.Transaction.TXN_total') Note:
882
+	 *                                        if no
883
+	 *                                        $group_by is specified, and a limit is set, automatically groups by the
884
+	 *                                        model's primary key (or combined primary keys). This avoids some
885
+	 *                                        weirdness that results when using limits, tons of joins, and no group by,
886
+	 *                                        see https://events.codebasehq.com/projects/event-espresso/tickets/9389
887
+	 * @var array   $having                   exactly like WHERE parameters array, except these conditions apply to the
888
+	 *                                        grouped results (whereas WHERE conditions apply to the pre-grouped
889
+	 *                                        results)
890
+	 * @var array   $force_join               forces a join with the models named. Should be a numerically-indexed
891
+	 *                                        array where values are models to be joined in the query.Eg
892
+	 *                                        array('Attendee','Payment','Datetime'). You may join with transient
893
+	 *                                        models using period, eg "Registration.Transaction.Payment". You will
894
+	 *                                        probably only want to do this in hopes of increasing efficiency, as
895
+	 *                                        related models which belongs to the current model
896
+	 *                                        (ie, the current model has a foreign key to them, like how Registration
897
+	 *                                        belongs to Attendee) can be cached in order to avoid future queries
898
+	 * @var string  $default_where_conditions can be set to 'none', 'this_model_only', 'other_models_only', or 'all'.
899
+	 *                                        set this to 'none' to disable all default where conditions. Eg, usually
900
+	 *                                        soft-deleted objects are filtered-out if you want to include them, set
901
+	 *                                        this query param to 'none'. If you want to ONLY disable THIS model's
902
+	 *                                        default where conditions set it to 'other_models_only'. If you only want
903
+	 *                                        this model's default where conditions added to the query, use
904
+	 *                                        'this_model_only'. If you want to use all default where conditions
905
+	 *                                        (default), set to 'all'.
906
+	 * @var string  $caps                     controls what capability requirements to apply to the query; ie, should
907
+	 *                                        we just NOT apply any capabilities/permissions/restrictions and return
908
+	 *                                        everything? Or should we only show the current user items they should be
909
+	 *                                        able to view on the frontend, backend, edit, or delete? can be set to
910
+	 *                                        'none' (default), 'read_frontend', 'read_backend', 'edit' or 'delete'
911
+	 *                                        }
912
+	 * @return EE_Base_Class[]  *note that there is NO option to pass the output type. If you want results different
913
+	 *                                        from EE_Base_Class[], use _get_all_wpdb_results()and make it public
914
+	 *                                        again. Array keys are object IDs (if there is a primary key on the model.
915
+	 *                                        if not, numerically indexed) Some full examples: get 10 transactions
916
+	 *                                        which have Scottish attendees: EEM_Transaction::instance()->get_all(
917
+	 *                                        array( array(
918
+	 *                                        'OR'=>array(
919
+	 *                                        'Registration.Attendee.ATT_fname'=>array('like','Mc%'),
920
+	 *                                        'Registration.Attendee.ATT_fname*other'=>array('like','Mac%')
921
+	 *                                        )
922
+	 *                                        ),
923
+	 *                                        'limit'=>10,
924
+	 *                                        'group_by'=>'TXN_ID'
925
+	 *                                        ));
926
+	 *                                        get all the answers to the question titled "shirt size" for event with id
927
+	 *                                        12, ordered by their answer EEM_Answer::instance()->get_all(array( array(
928
+	 *                                        'Question.QST_display_text'=>'shirt size',
929
+	 *                                        'Registration.Event.EVT_ID'=>12
930
+	 *                                        ),
931
+	 *                                        'order_by'=>array('ANS_value'=>'ASC')
932
+	 *                                        ));
933
+	 * @throws EE_Error
934
+	 */
935
+	public function get_all($query_params = array())
936
+	{
937
+		if (isset($query_params['limit'])
938
+			&& ! isset($query_params['group_by'])
939
+		) {
940
+			$query_params['group_by'] = array_keys($this->get_combined_primary_key_fields());
941
+		}
942
+		return $this->_create_objects($this->_get_all_wpdb_results($query_params, ARRAY_A, null));
943
+	}
944
+
945
+
946
+
947
+	/**
948
+	 * Modifies the query parameters so we only get back model objects
949
+	 * that "belong" to the current user
950
+	 *
951
+	 * @param array $query_params @see EEM_Base::get_all()
952
+	 * @return array like EEM_Base::get_all
953
+	 */
954
+	public function alter_query_params_to_only_include_mine($query_params = array())
955
+	{
956
+		$wp_user_field_name = $this->wp_user_field_name();
957
+		if ($wp_user_field_name) {
958
+			$query_params[0][$wp_user_field_name] = get_current_user_id();
959
+		}
960
+		return $query_params;
961
+	}
962
+
963
+
964
+
965
+	/**
966
+	 * Returns the name of the field's name that points to the WP_User table
967
+	 *  on this model (or follows the _model_chain_to_wp_user and uses that model's
968
+	 * foreign key to the WP_User table)
969
+	 *
970
+	 * @return string|boolean string on success, boolean false when there is no
971
+	 * foreign key to the WP_User table
972
+	 */
973
+	public function wp_user_field_name()
974
+	{
975
+		try {
976
+			if (! empty($this->_model_chain_to_wp_user)) {
977
+				$models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
978
+				$last_model_name = end($models_to_follow_to_wp_users);
979
+				$model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
980
+				$model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
981
+			} else {
982
+				$model_with_fk_to_wp_users = $this;
983
+				$model_chain_to_wp_user = '';
984
+			}
985
+			$wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
986
+			return $model_chain_to_wp_user . $wp_user_field->get_name();
987
+		} catch (EE_Error $e) {
988
+			return false;
989
+		}
990
+	}
991
+
992
+
993
+
994
+	/**
995
+	 * Returns the _model_chain_to_wp_user string, which indicates which related model
996
+	 * (or transiently-related model) has a foreign key to the wp_users table;
997
+	 * useful for finding if model objects of this type are 'owned' by the current user.
998
+	 * This is an empty string when the foreign key is on this model and when it isn't,
999
+	 * but is only non-empty when this model's ownership is indicated by a RELATED model
1000
+	 * (or transiently-related model)
1001
+	 *
1002
+	 * @return string
1003
+	 */
1004
+	public function model_chain_to_wp_user()
1005
+	{
1006
+		return $this->_model_chain_to_wp_user;
1007
+	}
1008
+
1009
+
1010
+
1011
+	/**
1012
+	 * Whether this model is 'owned' by a specific wordpress user (even indirectly,
1013
+	 * like how registrations don't have a foreign key to wp_users, but the
1014
+	 * events they are for are), or is unrelated to wp users.
1015
+	 * generally available
1016
+	 *
1017
+	 * @return boolean
1018
+	 */
1019
+	public function is_owned()
1020
+	{
1021
+		if ($this->model_chain_to_wp_user()) {
1022
+			return true;
1023
+		}
1024
+		try {
1025
+			$this->get_foreign_key_to('WP_User');
1026
+			return true;
1027
+		} catch (EE_Error $e) {
1028
+			return false;
1029
+		}
1030
+	}
1031
+
1032
+
1033
+
1034
+	/**
1035
+	 * Used internally to get WPDB results, because other functions, besides get_all, may want to do some queries, but
1036
+	 * may want to preserve the WPDB results (eg, update, which first queries to make sure we have all the tables on
1037
+	 * the model)
1038
+	 *
1039
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1040
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1041
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1042
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1043
+	 *                                  override this and set the select to "*", or a specific column name, like
1044
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1045
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1046
+	 *                                  the aliases used to refer to this selection, and values are to be
1047
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1048
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1049
+	 * @return array | stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1050
+	 * @throws EE_Error
1051
+	 */
1052
+	protected function _get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1053
+	{
1054
+		// remember the custom selections, if any, and type cast as array
1055
+		// (unless $columns_to_select is an object, then just set as an empty array)
1056
+		// Note: (array) 'some string' === array( 'some string' )
1057
+		$this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1058
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1059
+		$select_expressions = $columns_to_select !== null
1060
+			? $this->_construct_select_from_input($columns_to_select)
1061
+			: $this->_construct_default_select_sql($model_query_info);
1062
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1063
+		return $this->_do_wpdb_query('get_results', array($SQL, $output));
1064
+	}
1065
+
1066
+
1067
+
1068
+	/**
1069
+	 * Gets an array of rows from the database just like $wpdb->get_results would,
1070
+	 * but you can use the $query_params like on EEM_Base::get_all() to more easily
1071
+	 * take care of joins, field preparation etc.
1072
+	 *
1073
+	 * @param array  $query_params      like EEM_Base::get_all's $query_params
1074
+	 * @param string $output            ARRAY_A, OBJECT_K, etc. Just like
1075
+	 * @param mixed  $columns_to_select , What columns to select. By default, we select all columns specified by the
1076
+	 *                                  fields on the model, and the models we joined to in the query. However, you can
1077
+	 *                                  override this and set the select to "*", or a specific column name, like
1078
+	 *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
1079
+	 *                                  GROUP_BY, or HAVING clauses, you must instead provide an array. Array keys are
1080
+	 *                                  the aliases used to refer to this selection, and values are to be
1081
+	 *                                  numerically-indexed arrays, where 0 is the selection and 1 is the data type.
1082
+	 *                                  Eg, array('count'=>array('COUNT(REG_ID)','%d'))
1083
+	 * @return array|stdClass[] like results of $wpdb->get_results($sql,OBJECT), (ie, output type is OBJECT)
1084
+	 * @throws EE_Error
1085
+	 */
1086
+	public function get_all_wpdb_results($query_params = array(), $output = ARRAY_A, $columns_to_select = null)
1087
+	{
1088
+		return $this->_get_all_wpdb_results($query_params, $output, $columns_to_select);
1089
+	}
1090
+
1091
+
1092
+
1093
+	/**
1094
+	 * For creating a custom select statement
1095
+	 *
1096
+	 * @param mixed $columns_to_select either a string to be inserted directly as the select statement,
1097
+	 *                                 or an array where keys are aliases, and values are arrays where 0=>the selection
1098
+	 *                                 SQL, and 1=>is the datatype
1099
+	 * @throws EE_Error
1100
+	 * @return string
1101
+	 */
1102
+	private function _construct_select_from_input($columns_to_select)
1103
+	{
1104
+		if (is_array($columns_to_select)) {
1105
+			$select_sql_array = array();
1106
+			foreach ($columns_to_select as $alias => $selection_and_datatype) {
1107
+				if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1108
+					throw new EE_Error(
1109
+						sprintf(
1110
+							__(
1111
+								"Custom selection %s (alias %s) needs to be an array like array('COUNT(REG_ID)','%%d')",
1112
+								'event_espresso'
1113
+							),
1114
+							$selection_and_datatype,
1115
+							$alias
1116
+						)
1117
+					);
1118
+				}
1119
+				if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1120
+					throw new EE_Error(
1121
+						sprintf(
1122
+							esc_html__(
1123
+								"Datatype %s (for selection '%s' and alias '%s') is not a valid wpdb datatype (eg %%s)",
1124
+								'event_espresso'
1125
+							),
1126
+							$selection_and_datatype[1],
1127
+							$selection_and_datatype[0],
1128
+							$alias,
1129
+							implode(', ', $this->_valid_wpdb_data_types)
1130
+						)
1131
+					);
1132
+				}
1133
+				$select_sql_array[] = "{$selection_and_datatype[0]} AS $alias";
1134
+			}
1135
+			$columns_to_select_string = implode(', ', $select_sql_array);
1136
+		} else {
1137
+			$columns_to_select_string = $columns_to_select;
1138
+		}
1139
+		return $columns_to_select_string;
1140
+	}
1141
+
1142
+
1143
+
1144
+	/**
1145
+	 * Convenient wrapper for getting the primary key field's name. Eg, on Registration, this would be 'REG_ID'
1146
+	 *
1147
+	 * @return string
1148
+	 * @throws EE_Error
1149
+	 */
1150
+	public function primary_key_name()
1151
+	{
1152
+		return $this->get_primary_key_field()->get_name();
1153
+	}
1154
+
1155
+
1156
+
1157
+	/**
1158
+	 * Gets a single item for this model from the DB, given only its ID (or null if none is found).
1159
+	 * If there is no primary key on this model, $id is treated as primary key string
1160
+	 *
1161
+	 * @param mixed $id int or string, depending on the type of the model's primary key
1162
+	 * @return EE_Base_Class
1163
+	 */
1164
+	public function get_one_by_ID($id)
1165
+	{
1166
+		if ($this->get_from_entity_map($id)) {
1167
+			return $this->get_from_entity_map($id);
1168
+		}
1169
+		return $this->get_one(
1170
+			$this->alter_query_params_to_restrict_by_ID(
1171
+				$id,
1172
+				array('default_where_conditions' => EEM_Base::default_where_conditions_minimum_all)
1173
+			)
1174
+		);
1175
+	}
1176
+
1177
+
1178
+
1179
+	/**
1180
+	 * Alters query parameters to only get items with this ID are returned.
1181
+	 * Takes into account that the ID might be a string produced by EEM_Base::get_index_primary_key_string(),
1182
+	 * or could just be a simple primary key ID
1183
+	 *
1184
+	 * @param int   $id
1185
+	 * @param array $query_params
1186
+	 * @return array of normal query params, @see EEM_Base::get_all
1187
+	 * @throws EE_Error
1188
+	 */
1189
+	public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1190
+	{
1191
+		if (! isset($query_params[0])) {
1192
+			$query_params[0] = array();
1193
+		}
1194
+		$conditions_from_id = $this->parse_index_primary_key_string($id);
1195
+		if ($conditions_from_id === null) {
1196
+			$query_params[0][$this->primary_key_name()] = $id;
1197
+		} else {
1198
+			//no primary key, so the $id must be from the get_index_primary_key_string()
1199
+			$query_params[0] = array_replace_recursive($query_params[0], $this->parse_index_primary_key_string($id));
1200
+		}
1201
+		return $query_params;
1202
+	}
1203
+
1204
+
1205
+
1206
+	/**
1207
+	 * Gets a single item for this model from the DB, given the $query_params. Only returns a single class, not an
1208
+	 * array. If no item is found, null is returned.
1209
+	 *
1210
+	 * @param array $query_params like EEM_Base's $query_params variable.
1211
+	 * @return EE_Base_Class|EE_Soft_Delete_Base_Class|NULL
1212
+	 * @throws EE_Error
1213
+	 */
1214
+	public function get_one($query_params = array())
1215
+	{
1216
+		if (! is_array($query_params)) {
1217
+			EE_Error::doing_it_wrong('EEM_Base::get_one',
1218
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1219
+					gettype($query_params)), '4.6.0');
1220
+			$query_params = array();
1221
+		}
1222
+		$query_params['limit'] = 1;
1223
+		$items = $this->get_all($query_params);
1224
+		if (empty($items)) {
1225
+			return null;
1226
+		}
1227
+		return array_shift($items);
1228
+	}
1229
+
1230
+
1231
+
1232
+	/**
1233
+	 * Returns the next x number of items in sequence from the given value as
1234
+	 * found in the database matching the given query conditions.
1235
+	 *
1236
+	 * @param mixed $current_field_value    Value used for the reference point.
1237
+	 * @param null  $field_to_order_by      What field is used for the
1238
+	 *                                      reference point.
1239
+	 * @param int   $limit                  How many to return.
1240
+	 * @param array $query_params           Extra conditions on the query.
1241
+	 * @param null  $columns_to_select      If left null, then an array of
1242
+	 *                                      EE_Base_Class objects is returned,
1243
+	 *                                      otherwise you can indicate just the
1244
+	 *                                      columns you want returned.
1245
+	 * @return EE_Base_Class[]|array
1246
+	 * @throws EE_Error
1247
+	 */
1248
+	public function next_x(
1249
+		$current_field_value,
1250
+		$field_to_order_by = null,
1251
+		$limit = 1,
1252
+		$query_params = array(),
1253
+		$columns_to_select = null
1254
+	) {
1255
+		return $this->_get_consecutive(
1256
+			$current_field_value,
1257
+			'>',
1258
+			$field_to_order_by,
1259
+			$limit,
1260
+			$query_params,
1261
+			$columns_to_select
1262
+		);
1263
+	}
1264
+
1265
+
1266
+
1267
+	/**
1268
+	 * Returns the previous x number of items in sequence from the given value
1269
+	 * as found in the database matching the given query conditions.
1270
+	 *
1271
+	 * @param mixed $current_field_value    Value used for the reference point.
1272
+	 * @param null  $field_to_order_by      What field is used for the
1273
+	 *                                      reference point.
1274
+	 * @param int   $limit                  How many to return.
1275
+	 * @param array $query_params           Extra conditions on the query.
1276
+	 * @param null  $columns_to_select      If left null, then an array of
1277
+	 *                                      EE_Base_Class objects is returned,
1278
+	 *                                      otherwise you can indicate just the
1279
+	 *                                      columns you want returned.
1280
+	 * @return EE_Base_Class[]|array
1281
+	 * @throws EE_Error
1282
+	 */
1283
+	public function previous_x(
1284
+		$current_field_value,
1285
+		$field_to_order_by = null,
1286
+		$limit = 1,
1287
+		$query_params = array(),
1288
+		$columns_to_select = null
1289
+	) {
1290
+		return $this->_get_consecutive(
1291
+			$current_field_value,
1292
+			'<',
1293
+			$field_to_order_by,
1294
+			$limit,
1295
+			$query_params,
1296
+			$columns_to_select
1297
+		);
1298
+	}
1299
+
1300
+
1301
+
1302
+	/**
1303
+	 * Returns the next item in sequence from the given value as found in the
1304
+	 * database matching the given query conditions.
1305
+	 *
1306
+	 * @param mixed $current_field_value    Value used for the reference point.
1307
+	 * @param null  $field_to_order_by      What field is used for the
1308
+	 *                                      reference point.
1309
+	 * @param array $query_params           Extra conditions on the query.
1310
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1311
+	 *                                      object is returned, otherwise you
1312
+	 *                                      can indicate just the columns you
1313
+	 *                                      want and a single array indexed by
1314
+	 *                                      the columns will be returned.
1315
+	 * @return EE_Base_Class|null|array()
1316
+	 * @throws EE_Error
1317
+	 */
1318
+	public function next(
1319
+		$current_field_value,
1320
+		$field_to_order_by = null,
1321
+		$query_params = array(),
1322
+		$columns_to_select = null
1323
+	) {
1324
+		$results = $this->_get_consecutive(
1325
+			$current_field_value,
1326
+			'>',
1327
+			$field_to_order_by,
1328
+			1,
1329
+			$query_params,
1330
+			$columns_to_select
1331
+		);
1332
+		return empty($results) ? null : reset($results);
1333
+	}
1334
+
1335
+
1336
+
1337
+	/**
1338
+	 * Returns the previous item in sequence from the given value as found in
1339
+	 * the database matching the given query conditions.
1340
+	 *
1341
+	 * @param mixed $current_field_value    Value used for the reference point.
1342
+	 * @param null  $field_to_order_by      What field is used for the
1343
+	 *                                      reference point.
1344
+	 * @param array $query_params           Extra conditions on the query.
1345
+	 * @param null  $columns_to_select      If left null, then an EE_Base_Class
1346
+	 *                                      object is returned, otherwise you
1347
+	 *                                      can indicate just the columns you
1348
+	 *                                      want and a single array indexed by
1349
+	 *                                      the columns will be returned.
1350
+	 * @return EE_Base_Class|null|array()
1351
+	 * @throws EE_Error
1352
+	 */
1353
+	public function previous(
1354
+		$current_field_value,
1355
+		$field_to_order_by = null,
1356
+		$query_params = array(),
1357
+		$columns_to_select = null
1358
+	) {
1359
+		$results = $this->_get_consecutive(
1360
+			$current_field_value,
1361
+			'<',
1362
+			$field_to_order_by,
1363
+			1,
1364
+			$query_params,
1365
+			$columns_to_select
1366
+		);
1367
+		return empty($results) ? null : reset($results);
1368
+	}
1369
+
1370
+
1371
+
1372
+	/**
1373
+	 * Returns the a consecutive number of items in sequence from the given
1374
+	 * value as found in the database matching the given query conditions.
1375
+	 *
1376
+	 * @param mixed  $current_field_value   Value used for the reference point.
1377
+	 * @param string $operand               What operand is used for the sequence.
1378
+	 * @param string $field_to_order_by     What field is used for the reference point.
1379
+	 * @param int    $limit                 How many to return.
1380
+	 * @param array  $query_params          Extra conditions on the query.
1381
+	 * @param null   $columns_to_select     If left null, then an array of EE_Base_Class objects is returned,
1382
+	 *                                      otherwise you can indicate just the columns you want returned.
1383
+	 * @return EE_Base_Class[]|array
1384
+	 * @throws EE_Error
1385
+	 */
1386
+	protected function _get_consecutive(
1387
+		$current_field_value,
1388
+		$operand = '>',
1389
+		$field_to_order_by = null,
1390
+		$limit = 1,
1391
+		$query_params = array(),
1392
+		$columns_to_select = null
1393
+	) {
1394
+		//if $field_to_order_by is empty then let's assume we're ordering by the primary key.
1395
+		if (empty($field_to_order_by)) {
1396
+			if ($this->has_primary_key_field()) {
1397
+				$field_to_order_by = $this->get_primary_key_field()->get_name();
1398
+			} else {
1399
+				if (WP_DEBUG) {
1400
+					throw new EE_Error(__('EEM_Base::_get_consecutive() has been called with no $field_to_order_by argument and there is no primary key on the field.  Please provide the field you would like to use as the base for retrieving the next item(s).',
1401
+						'event_espresso'));
1402
+				}
1403
+				EE_Error::add_error(__('There was an error with the query.', 'event_espresso'));
1404
+				return array();
1405
+			}
1406
+		}
1407
+		if (! is_array($query_params)) {
1408
+			EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1409
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1410
+					gettype($query_params)), '4.6.0');
1411
+			$query_params = array();
1412
+		}
1413
+		//let's add the where query param for consecutive look up.
1414
+		$query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1415
+		$query_params['limit'] = $limit;
1416
+		//set direction
1417
+		$incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1418
+		$query_params['order_by'] = $operand === '>'
1419
+			? array($field_to_order_by => 'ASC') + $incoming_orderby
1420
+			: array($field_to_order_by => 'DESC') + $incoming_orderby;
1421
+		//if $columns_to_select is empty then that means we're returning EE_Base_Class objects
1422
+		if (empty($columns_to_select)) {
1423
+			return $this->get_all($query_params);
1424
+		}
1425
+		//getting just the fields
1426
+		return $this->_get_all_wpdb_results($query_params, ARRAY_A, $columns_to_select);
1427
+	}
1428
+
1429
+
1430
+
1431
+	/**
1432
+	 * This sets the _timezone property after model object has been instantiated.
1433
+	 *
1434
+	 * @param null | string $timezone valid PHP DateTimeZone timezone string
1435
+	 */
1436
+	public function set_timezone($timezone)
1437
+	{
1438
+		if ($timezone !== null) {
1439
+			$this->_timezone = $timezone;
1440
+		}
1441
+		//note we need to loop through relations and set the timezone on those objects as well.
1442
+		foreach ($this->_model_relations as $relation) {
1443
+			$relation->set_timezone($timezone);
1444
+		}
1445
+		//and finally we do the same for any datetime fields
1446
+		foreach ($this->_fields as $field) {
1447
+			if ($field instanceof EE_Datetime_Field) {
1448
+				$field->set_timezone($timezone);
1449
+			}
1450
+		}
1451
+	}
1452
+
1453
+
1454
+
1455
+	/**
1456
+	 * This just returns whatever is set for the current timezone.
1457
+	 *
1458
+	 * @access public
1459
+	 * @return string
1460
+	 */
1461
+	public function get_timezone()
1462
+	{
1463
+		//first validate if timezone is set.  If not, then let's set it be whatever is set on the model fields.
1464
+		if (empty($this->_timezone)) {
1465
+			foreach ($this->_fields as $field) {
1466
+				if ($field instanceof EE_Datetime_Field) {
1467
+					$this->set_timezone($field->get_timezone());
1468
+					break;
1469
+				}
1470
+			}
1471
+		}
1472
+		//if timezone STILL empty then return the default timezone for the site.
1473
+		if (empty($this->_timezone)) {
1474
+			$this->set_timezone(EEH_DTT_Helper::get_timezone());
1475
+		}
1476
+		return $this->_timezone;
1477
+	}
1478
+
1479
+
1480
+
1481
+	/**
1482
+	 * This returns the date formats set for the given field name and also ensures that
1483
+	 * $this->_timezone property is set correctly.
1484
+	 *
1485
+	 * @since 4.6.x
1486
+	 * @param string $field_name The name of the field the formats are being retrieved for.
1487
+	 * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488
+	 * @throws EE_Error   If the given field_name is not of the EE_Datetime_Field type.
1489
+	 * @return array formats in an array with the date format first, and the time format last.
1490
+	 */
1491
+	public function get_formats_for($field_name, $pretty = false)
1492
+	{
1493
+		$field_settings = $this->field_settings_for($field_name);
1494
+		//if not a valid EE_Datetime_Field then throw error
1495
+		if (! $field_settings instanceof EE_Datetime_Field) {
1496
+			throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1497
+				'event_espresso'), $field_name));
1498
+		}
1499
+		//while we are here, let's make sure the timezone internally in EEM_Base matches what is stored on
1500
+		//the field.
1501
+		$this->_timezone = $field_settings->get_timezone();
1502
+		return array($field_settings->get_date_format($pretty), $field_settings->get_time_format($pretty));
1503
+	}
1504
+
1505
+
1506
+
1507
+	/**
1508
+	 * This returns the current time in a format setup for a query on this model.
1509
+	 * Usage of this method makes it easier to setup queries against EE_Datetime_Field columns because
1510
+	 * it will return:
1511
+	 *  - a formatted string in the timezone and format currently set on the EE_Datetime_Field for the given field for
1512
+	 *  NOW
1513
+	 *  - or a unix timestamp (equivalent to time())
1514
+	 * Note: When requesting a formatted string, if the date or time format doesn't include seconds, for example,
1515
+	 * the time returned, because it uses that format, will also NOT include seconds. For this reason, if you want
1516
+	 * the time returned to be the current time down to the exact second, set $timestamp to true.
1517
+	 * @since 4.6.x
1518
+	 * @param string $field_name       The field the current time is needed for.
1519
+	 * @param bool   $timestamp        True means to return a unix timestamp. Otherwise a
1520
+	 *                                 formatted string matching the set format for the field in the set timezone will
1521
+	 *                                 be returned.
1522
+	 * @param string $what             Whether to return the string in just the time format, the date format, or both.
1523
+	 * @throws EE_Error    If the given field_name is not of the EE_Datetime_Field type.
1524
+	 * @return int|string  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1525
+	 *                                 exception is triggered.
1526
+	 */
1527
+	public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
1528
+	{
1529
+		$formats = $this->get_formats_for($field_name);
1530
+		$DateTime = new DateTime("now", new DateTimeZone($this->_timezone));
1531
+		if ($timestamp) {
1532
+			return $DateTime->format('U');
1533
+		}
1534
+		//not returning timestamp, so return formatted string in timezone.
1535
+		switch ($what) {
1536
+			case 'time' :
1537
+				return $DateTime->format($formats[1]);
1538
+				break;
1539
+			case 'date' :
1540
+				return $DateTime->format($formats[0]);
1541
+				break;
1542
+			default :
1543
+				return $DateTime->format(implode(' ', $formats));
1544
+				break;
1545
+		}
1546
+	}
1547
+
1548
+
1549
+
1550
+	/**
1551
+	 * This receives a time string for a given field and ensures that it is setup to match what the internal settings
1552
+	 * for the model are.  Returns a DateTime object.
1553
+	 * Note: a gotcha for when you send in unix timestamp.  Remember a unix timestamp is already timezone agnostic,
1554
+	 * (functionally the equivalent of UTC+0).  So when you send it in, whatever timezone string you include is
1555
+	 * ignored.
1556
+	 *
1557
+	 * @param string $field_name      The field being setup.
1558
+	 * @param string $timestring      The date time string being used.
1559
+	 * @param string $incoming_format The format for the time string.
1560
+	 * @param string $timezone        By default, it is assumed the incoming time string is in timezone for
1561
+	 *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1562
+	 *                                format is
1563
+	 *                                'U', this is ignored.
1564
+	 * @return DateTime
1565
+	 * @throws EE_Error
1566
+	 */
1567
+	public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
1568
+	{
1569
+		//just using this to ensure the timezone is set correctly internally
1570
+		$this->get_formats_for($field_name);
1571
+		//load EEH_DTT_Helper
1572
+		$set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1573
+		$incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1574
+		return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1575
+	}
1576
+
1577
+
1578
+
1579
+	/**
1580
+	 * Gets all the tables comprising this model. Array keys are the table aliases, and values are EE_Table objects
1581
+	 *
1582
+	 * @return EE_Table_Base[]
1583
+	 */
1584
+	public function get_tables()
1585
+	{
1586
+		return $this->_tables;
1587
+	}
1588
+
1589
+
1590
+
1591
+	/**
1592
+	 * Updates all the database entries (in each table for this model) according to $fields_n_values and optionally
1593
+	 * also updates all the model objects, where the criteria expressed in $query_params are met..
1594
+	 * Also note: if this model has multiple tables, this update verifies all the secondary tables have an entry for
1595
+	 * each row (in the primary table) we're trying to update; if not, it inserts an entry in the secondary table. Eg:
1596
+	 * if our model has 2 tables: wp_posts (primary), and wp_esp_event (secondary). Let's say we are trying to update a
1597
+	 * model object with EVT_ID = 1
1598
+	 * (which means where wp_posts has ID = 1, because wp_posts.ID is the primary key's column), which exists, but
1599
+	 * there is no entry in wp_esp_event for this entry in wp_posts. So, this update script will insert a row into
1600
+	 * wp_esp_event, using any available parameters from $fields_n_values (eg, if "EVT_limit" => 40 is in
1601
+	 * $fields_n_values, the new entry in wp_esp_event will set EVT_limit = 40, and use default for other columns which
1602
+	 * are not specified)
1603
+	 *
1604
+	 * @param array   $fields_n_values         keys are model fields (exactly like keys in EEM_Base::_fields, NOT db
1605
+	 *                                         columns!), values are strings, ints, floats, and maybe arrays if they
1606
+	 *                                         are to be serialized. Basically, the values are what you'd expect to be
1607
+	 *                                         values on the model, NOT necessarily what's in the DB. For example, if
1608
+	 *                                         we wanted to update only the TXN_details on any Transactions where its
1609
+	 *                                         ID=34, we'd use this method as follows:
1610
+	 *                                         EEM_Transaction::instance()->update(
1611
+	 *                                         array('TXN_details'=>array('detail1'=>'monkey','detail2'=>'banana'),
1612
+	 *                                         array(array('TXN_ID'=>34)));
1613
+	 * @param array   $query_params            very much like EEM_Base::get_all's $query_params
1614
+	 *                                         in client code into what's expected to be stored on each field. Eg,
1615
+	 *                                         consider updating Question's QST_admin_label field is of type
1616
+	 *                                         Simple_HTML. If you use this function to update that field to $new_value
1617
+	 *                                         = (note replace 8's with appropriate opening and closing tags in the
1618
+	 *                                         following example)"8script8alert('I hack all');8/script88b8boom
1619
+	 *                                         baby8/b8", then if you set $values_already_prepared_by_model_object to
1620
+	 *                                         TRUE, it is assumed that you've already called
1621
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value), which removes the
1622
+	 *                                         malicious javascript. However, if
1623
+	 *                                         $values_already_prepared_by_model_object is left as FALSE, then
1624
+	 *                                         EE_Simple_HTML_Field->prepare_for_set($new_value) will be called on it,
1625
+	 *                                         and every other field, before insertion. We provide this parameter
1626
+	 *                                         because model objects perform their prepare_for_set function on all
1627
+	 *                                         their values, and so don't need to be called again (and in many cases,
1628
+	 *                                         shouldn't be called again. Eg: if we escape HTML characters in the
1629
+	 *                                         prepare_for_set method...)
1630
+	 * @param boolean $keep_model_objs_in_sync if TRUE, makes sure we ALSO update model objects
1631
+	 *                                         in this model's entity map according to $fields_n_values that match
1632
+	 *                                         $query_params. This obviously has some overhead, so you can disable it
1633
+	 *                                         by setting this to FALSE, but be aware that model objects being used
1634
+	 *                                         could get out-of-sync with the database
1635
+	 * @return int how many rows got updated or FALSE if something went wrong with the query (wp returns FALSE or num
1636
+	 *                                         rows affected which *could* include 0 which DOES NOT mean the query was
1637
+	 *                                         bad)
1638
+	 * @throws EE_Error
1639
+	 */
1640
+	public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1641
+	{
1642
+		if (! is_array($query_params)) {
1643
+			EE_Error::doing_it_wrong('EEM_Base::update',
1644
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1645
+					gettype($query_params)), '4.6.0');
1646
+			$query_params = array();
1647
+		}
1648
+		/**
1649
+		 * Action called before a model update call has been made.
1650
+		 *
1651
+		 * @param EEM_Base $model
1652
+		 * @param array    $fields_n_values the updated fields and their new values
1653
+		 * @param array    $query_params    @see EEM_Base::get_all()
1654
+		 */
1655
+		do_action('AHEE__EEM_Base__update__begin', $this, $fields_n_values, $query_params);
1656
+		/**
1657
+		 * Filters the fields about to be updated given the query parameters. You can provide the
1658
+		 * $query_params to $this->get_all() to find exactly which records will be updated
1659
+		 *
1660
+		 * @param array    $fields_n_values fields and their new values
1661
+		 * @param EEM_Base $model           the model being queried
1662
+		 * @param array    $query_params    see EEM_Base::get_all()
1663
+		 */
1664
+		$fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1665
+			$query_params);
1666
+		//need to verify that, for any entry we want to update, there are entries in each secondary table.
1667
+		//to do that, for each table, verify that it's PK isn't null.
1668
+		$tables = $this->get_tables();
1669
+		//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
1670
+		//NOTE: we should make this code more efficient by NOT querying twice
1671
+		//before the real update, but that needs to first go through ALPHA testing
1672
+		//as it's dangerous. says Mike August 8 2014
1673
+		//we want to make sure the default_where strategy is ignored
1674
+		$this->_ignore_where_strategy = true;
1675
+		$wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1676
+		foreach ($wpdb_select_results as $wpdb_result) {
1677
+			// type cast stdClass as array
1678
+			$wpdb_result = (array)$wpdb_result;
1679
+			//get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1680
+			if ($this->has_primary_key_field()) {
1681
+				$main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
1682
+			} else {
1683
+				//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)
1684
+				$main_table_pk_value = null;
1685
+			}
1686
+			//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
1687
+			//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
1688
+			if (count($tables) > 1) {
1689
+				//foreach matching row in the DB, ensure that each table's PK isn't null. If so, there must not be an entry
1690
+				//in that table, and so we'll want to insert one
1691
+				foreach ($tables as $table_obj) {
1692
+					$this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1693
+					//if there is no private key for this table on the results, it means there's no entry
1694
+					//in this table, right? so insert a row in the current table, using any fields available
1695
+					if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1696
+						   && $wpdb_result[$this_table_pk_column])
1697
+					) {
1698
+						$success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1699
+							$main_table_pk_value);
1700
+						//if we died here, report the error
1701
+						if (! $success) {
1702
+							return false;
1703
+						}
1704
+					}
1705
+				}
1706
+			}
1707
+			//				//and now check that if we have cached any models by that ID on the model, that
1708
+			//				//they also get updated properly
1709
+			//				$model_object = $this->get_from_entity_map( $main_table_pk_value );
1710
+			//				if( $model_object ){
1711
+			//					foreach( $fields_n_values as $field => $value ){
1712
+			//						$model_object->set($field, $value);
1713
+			//let's make sure default_where strategy is followed now
1714
+			$this->_ignore_where_strategy = false;
1715
+		}
1716
+		//if we want to keep model objects in sync, AND
1717
+		//if this wasn't called from a model object (to update itself)
1718
+		//then we want to make sure we keep all the existing
1719
+		//model objects in sync with the db
1720
+		if ($keep_model_objs_in_sync && ! $this->_values_already_prepared_by_model_object) {
1721
+			if ($this->has_primary_key_field()) {
1722
+				$model_objs_affected_ids = $this->get_col($query_params);
1723
+			} else {
1724
+				//we need to select a bunch of columns and then combine them into the the "index primary key string"s
1725
+				$models_affected_key_columns = $this->_get_all_wpdb_results($query_params, ARRAY_A);
1726
+				$model_objs_affected_ids = array();
1727
+				foreach ($models_affected_key_columns as $row) {
1728
+					$combined_index_key = $this->get_index_primary_key_string($row);
1729
+					$model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1730
+				}
1731
+			}
1732
+			if (! $model_objs_affected_ids) {
1733
+				//wait wait wait- if nothing was affected let's stop here
1734
+				return 0;
1735
+			}
1736
+			foreach ($model_objs_affected_ids as $id) {
1737
+				$model_obj_in_entity_map = $this->get_from_entity_map($id);
1738
+				if ($model_obj_in_entity_map) {
1739
+					foreach ($fields_n_values as $field => $new_value) {
1740
+						$model_obj_in_entity_map->set($field, $new_value);
1741
+					}
1742
+				}
1743
+			}
1744
+			//if there is a primary key on this model, we can now do a slight optimization
1745
+			if ($this->has_primary_key_field()) {
1746
+				//we already know what we want to update. So let's make the query simpler so it's a little more efficient
1747
+				$query_params = array(
1748
+					array($this->primary_key_name() => array('IN', $model_objs_affected_ids)),
1749
+					'limit'                    => count($model_objs_affected_ids),
1750
+					'default_where_conditions' => EEM_Base::default_where_conditions_none,
1751
+				);
1752
+			}
1753
+		}
1754
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1755
+		$SQL = "UPDATE "
1756
+			   . $model_query_info->get_full_join_sql()
1757
+			   . " SET "
1758
+			   . $this->_construct_update_sql($fields_n_values)
1759
+			   . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1760
+		$rows_affected = $this->_do_wpdb_query('query', array($SQL));
1761
+		/**
1762
+		 * Action called after a model update call has been made.
1763
+		 *
1764
+		 * @param EEM_Base $model
1765
+		 * @param array    $fields_n_values the updated fields and their new values
1766
+		 * @param array    $query_params    @see EEM_Base::get_all()
1767
+		 * @param int      $rows_affected
1768
+		 */
1769
+		do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1770
+		return $rows_affected;//how many supposedly got updated
1771
+	}
1772
+
1773
+
1774
+
1775
+	/**
1776
+	 * Analogous to $wpdb->get_col, returns a 1-dimensional array where teh values
1777
+	 * are teh values of the field specified (or by default the primary key field)
1778
+	 * that matched the query params. Note that you should pass the name of the
1779
+	 * model FIELD, not the database table's column name.
1780
+	 *
1781
+	 * @param array  $query_params @see EEM_Base::get_all()
1782
+	 * @param string $field_to_select
1783
+	 * @return array just like $wpdb->get_col()
1784
+	 * @throws EE_Error
1785
+	 */
1786
+	public function get_col($query_params = array(), $field_to_select = null)
1787
+	{
1788
+		if ($field_to_select) {
1789
+			$field = $this->field_settings_for($field_to_select);
1790
+		} elseif ($this->has_primary_key_field()) {
1791
+			$field = $this->get_primary_key_field();
1792
+		} else {
1793
+			//no primary key, just grab the first column
1794
+			$field = reset($this->field_settings());
1795
+		}
1796
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
1797
+		$select_expressions = $field->get_qualified_column();
1798
+		$SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1799
+		return $this->_do_wpdb_query('get_col', array($SQL));
1800
+	}
1801
+
1802
+
1803
+
1804
+	/**
1805
+	 * Returns a single column value for a single row from the database
1806
+	 *
1807
+	 * @param array  $query_params    @see EEM_Base::get_all()
1808
+	 * @param string $field_to_select @see EEM_Base::get_col()
1809
+	 * @return string
1810
+	 * @throws EE_Error
1811
+	 */
1812
+	public function get_var($query_params = array(), $field_to_select = null)
1813
+	{
1814
+		$query_params['limit'] = 1;
1815
+		$col = $this->get_col($query_params, $field_to_select);
1816
+		if (! empty($col)) {
1817
+			return reset($col);
1818
+		}
1819
+		return null;
1820
+	}
1821
+
1822
+
1823
+
1824
+	/**
1825
+	 * Makes the SQL for after "UPDATE table_X inner join table_Y..." and before "...WHERE". Eg "Question.name='party
1826
+	 * time?', Question.desc='what do you think?',..." Values are filtered through wpdb->prepare to avoid against SQL
1827
+	 * injection, but currently no further filtering is done
1828
+	 *
1829
+	 * @global      $wpdb
1830
+	 * @param array $fields_n_values array keys are field names on this model, and values are what those fields should
1831
+	 *                               be updated to in the DB
1832
+	 * @return string of SQL
1833
+	 * @throws EE_Error
1834
+	 */
1835
+	public function _construct_update_sql($fields_n_values)
1836
+	{
1837
+		/** @type WPDB $wpdb */
1838
+		global $wpdb;
1839
+		$cols_n_values = array();
1840
+		foreach ($fields_n_values as $field_name => $value) {
1841
+			$field_obj = $this->field_settings_for($field_name);
1842
+			//if the value is NULL, we want to assign the value to that.
1843
+			//wpdb->prepare doesn't really handle that properly
1844
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1845
+			$value_sql = $prepared_value === null ? 'NULL'
1846
+				: $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1847
+			$cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1848
+		}
1849
+		return implode(",", $cols_n_values);
1850
+	}
1851
+
1852
+
1853
+
1854
+	/**
1855
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1856
+	 * Performs a HARD delete, meaning the database row should always be removed,
1857
+	 * not just have a flag field on it switched
1858
+	 * Wrapper for EEM_Base::delete_permanently()
1859
+	 *
1860
+	 * @param mixed $id
1861
+	 * @param boolean $allow_blocking
1862
+	 * @return int the number of rows deleted
1863
+	 * @throws EE_Error
1864
+	 */
1865
+	public function delete_permanently_by_ID($id, $allow_blocking = true)
1866
+	{
1867
+		return $this->delete_permanently(
1868
+			array(
1869
+				array($this->get_primary_key_field()->get_name() => $id),
1870
+				'limit' => 1,
1871
+			),
1872
+			$allow_blocking
1873
+		);
1874
+	}
1875
+
1876
+
1877
+
1878
+	/**
1879
+	 * Deletes a single row from the DB given the model object's primary key value. (eg, EE_Attendee->ID()'s value).
1880
+	 * Wrapper for EEM_Base::delete()
1881
+	 *
1882
+	 * @param mixed $id
1883
+	 * @param boolean $allow_blocking
1884
+	 * @return int the number of rows deleted
1885
+	 * @throws EE_Error
1886
+	 */
1887
+	public function delete_by_ID($id, $allow_blocking = true)
1888
+	{
1889
+		return $this->delete(
1890
+			array(
1891
+				array($this->get_primary_key_field()->get_name() => $id),
1892
+				'limit' => 1,
1893
+			),
1894
+			$allow_blocking
1895
+		);
1896
+	}
1897
+
1898
+
1899
+
1900
+	/**
1901
+	 * Identical to delete_permanently, but does a "soft" delete if possible,
1902
+	 * meaning if the model has a field that indicates its been "trashed" or
1903
+	 * "soft deleted", we will just set that instead of actually deleting the rows.
1904
+	 *
1905
+	 * @see EEM_Base::delete_permanently
1906
+	 * @param array   $query_params
1907
+	 * @param boolean $allow_blocking
1908
+	 * @return int how many rows got deleted
1909
+	 * @throws EE_Error
1910
+	 */
1911
+	public function delete($query_params, $allow_blocking = true)
1912
+	{
1913
+		return $this->delete_permanently($query_params, $allow_blocking);
1914
+	}
1915
+
1916
+
1917
+
1918
+	/**
1919
+	 * Deletes the model objects that meet the query params. Note: this method is overridden
1920
+	 * in EEM_Soft_Delete_Base so that soft-deleted model objects are instead only flagged
1921
+	 * as archived, not actually deleted
1922
+	 *
1923
+	 * @param array   $query_params   very much like EEM_Base::get_all's $query_params
1924
+	 * @param boolean $allow_blocking if TRUE, matched objects will only be deleted if there is no related model info
1925
+	 *                                that blocks it (ie, there' sno other data that depends on this data); if false,
1926
+	 *                                deletes regardless of other objects which may depend on it. Its generally
1927
+	 *                                advisable to always leave this as TRUE, otherwise you could easily corrupt your
1928
+	 *                                DB
1929
+	 * @return int how many rows got deleted
1930
+	 * @throws EE_Error
1931
+	 */
1932
+	public function delete_permanently($query_params, $allow_blocking = true)
1933
+	{
1934
+		/**
1935
+		 * Action called just before performing a real deletion query. You can use the
1936
+		 * model and its $query_params to find exactly which items will be deleted
1937
+		 *
1938
+		 * @param EEM_Base $model
1939
+		 * @param array    $query_params   @see EEM_Base::get_all()
1940
+		 * @param boolean  $allow_blocking whether or not to allow related model objects
1941
+		 *                                 to block (prevent) this deletion
1942
+		 */
1943
+		do_action('AHEE__EEM_Base__delete__begin', $this, $query_params, $allow_blocking);
1944
+		//some MySQL databases may be running safe mode, which may restrict
1945
+		//deletion if there is no KEY column used in the WHERE statement of a deletion.
1946
+		//to get around this, we first do a SELECT, get all the IDs, and then run another query
1947
+		//to delete them
1948
+		$items_for_deletion = $this->_get_all_wpdb_results($query_params);
1949
+		$columns_and_ids_for_deleting = $this->_get_ids_for_delete($items_for_deletion, $allow_blocking);
1950
+		$deletion_where_query_part = $this->_build_query_part_for_deleting_from_columns_and_values(
1951
+			$columns_and_ids_for_deleting
1952
+		);
1953
+		/**
1954
+		 * Allows client code to act on the items being deleted before the query is actually executed.
1955
+		 *
1956
+		 * @param EEM_Base $this  The model instance being acted on.
1957
+		 * @param array    $query_params  The incoming array of query parameters influencing what gets deleted.
1958
+		 * @param bool     $allow_blocking @see param description in method phpdoc block.
1959
+		 * @param array $columns_and_ids_for_deleting       An array indicating what entities will get removed as
1960
+		 *                                                  derived from the incoming query parameters.
1961
+		 *                                                  @see details on the structure of this array in the phpdocs
1962
+		 *                                                  for the `_get_ids_for_delete_method`
1963
+		 *
1964
+		 */
1965
+		do_action('AHEE__EEM_Base__delete__before_query',
1966
+			$this,
1967
+			$query_params,
1968
+			$allow_blocking,
1969
+			$columns_and_ids_for_deleting
1970
+		);
1971
+		if ($deletion_where_query_part) {
1972
+			$model_query_info = $this->_create_model_query_info_carrier($query_params);
1973
+			$table_aliases = array_keys($this->_tables);
1974
+			$SQL = "DELETE "
1975
+				   . implode(", ", $table_aliases)
1976
+				   . " FROM "
1977
+				   . $model_query_info->get_full_join_sql()
1978
+				   . " WHERE "
1979
+				   . $deletion_where_query_part;
1980
+			$rows_deleted = $this->_do_wpdb_query('query', array($SQL));
1981
+		} else {
1982
+			$rows_deleted = 0;
1983
+		}
1984
+
1985
+		//Next, make sure those items are removed from the entity map; if they could be put into it at all; and if
1986
+		//there was no error with the delete query.
1987
+		if ($this->has_primary_key_field()
1988
+			&& $rows_deleted !== false
1989
+			&& isset($columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()])
1990
+		) {
1991
+			$ids_for_removal = $columns_and_ids_for_deleting[$this->get_primary_key_field()->get_qualified_column()];
1992
+			foreach ($ids_for_removal as $id) {
1993
+				if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
1994
+					unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
1995
+				}
1996
+			}
1997
+
1998
+			// delete any extra meta attached to the deleted entities but ONLY if this model is not an instance of
1999
+			//`EEM_Extra_Meta`.  In other words we want to prevent recursion on EEM_Extra_Meta::delete_permanently calls
2000
+			//unnecessarily.  It's very unlikely that users will have assigned Extra Meta to Extra Meta
2001
+			// (although it is possible).
2002
+			//Note this can be skipped by using the provided filter and returning false.
2003
+			if (apply_filters(
2004
+				'FHEE__EEM_Base__delete_permanently__dont_delete_extra_meta_for_extra_meta',
2005
+				! $this instanceof EEM_Extra_Meta,
2006
+				$this
2007
+			)) {
2008
+				EEM_Extra_Meta::instance()->delete_permanently(array(
2009
+					0 => array(
2010
+						'EXM_type' => $this->get_this_model_name(),
2011
+						'OBJ_ID'   => array(
2012
+							'IN',
2013
+							$ids_for_removal
2014
+						)
2015
+					)
2016
+				));
2017
+			}
2018
+		}
2019
+
2020
+		/**
2021
+		 * Action called just after performing a real deletion query. Although at this point the
2022
+		 * items should have been deleted
2023
+		 *
2024
+		 * @param EEM_Base $model
2025
+		 * @param array    $query_params @see EEM_Base::get_all()
2026
+		 * @param int      $rows_deleted
2027
+		 */
2028
+		do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
+		return $rows_deleted;//how many supposedly got deleted
2030
+	}
2031
+
2032
+
2033
+
2034
+	/**
2035
+	 * Checks all the relations that throw error messages when there are blocking related objects
2036
+	 * for related model objects. If there are any related model objects on those relations,
2037
+	 * adds an EE_Error, and return true
2038
+	 *
2039
+	 * @param EE_Base_Class|int $this_model_obj_or_id
2040
+	 * @param EE_Base_Class     $ignore_this_model_obj a model object like 'EE_Event', or 'EE_Term_Taxonomy', which
2041
+	 *                                                 should be ignored when determining whether there are related
2042
+	 *                                                 model objects which block this model object's deletion. Useful
2043
+	 *                                                 if you know A is related to B and are considering deleting A,
2044
+	 *                                                 but want to see if A has any other objects blocking its deletion
2045
+	 *                                                 before removing the relation between A and B
2046
+	 * @return boolean
2047
+	 * @throws EE_Error
2048
+	 */
2049
+	public function delete_is_blocked_by_related_models($this_model_obj_or_id, $ignore_this_model_obj = null)
2050
+	{
2051
+		//first, if $ignore_this_model_obj was supplied, get its model
2052
+		if ($ignore_this_model_obj && $ignore_this_model_obj instanceof EE_Base_Class) {
2053
+			$ignored_model = $ignore_this_model_obj->get_model();
2054
+		} else {
2055
+			$ignored_model = null;
2056
+		}
2057
+		//now check all the relations of $this_model_obj_or_id and see if there
2058
+		//are any related model objects blocking it?
2059
+		$is_blocked = false;
2060
+		foreach ($this->_model_relations as $relation_name => $relation_obj) {
2061
+			if ($relation_obj->block_delete_if_related_models_exist()) {
2062
+				//if $ignore_this_model_obj was supplied, then for the query
2063
+				//on that model needs to be told to ignore $ignore_this_model_obj
2064
+				if ($ignored_model && $relation_name === $ignored_model->get_this_model_name()) {
2065
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id, array(
2066
+						array(
2067
+							$ignored_model->get_primary_key_field()->get_name() => array(
2068
+								'!=',
2069
+								$ignore_this_model_obj->ID(),
2070
+							),
2071
+						),
2072
+					));
2073
+				} else {
2074
+					$related_model_objects = $relation_obj->get_all_related($this_model_obj_or_id);
2075
+				}
2076
+				if ($related_model_objects) {
2077
+					EE_Error::add_error($relation_obj->get_deletion_error_message(), __FILE__, __FUNCTION__, __LINE__);
2078
+					$is_blocked = true;
2079
+				}
2080
+			}
2081
+		}
2082
+		return $is_blocked;
2083
+	}
2084
+
2085
+
2086
+	/**
2087
+	 * Builds the columns and values for items to delete from the incoming $row_results_for_deleting array.
2088
+	 * @param array $row_results_for_deleting
2089
+	 * @param bool  $allow_blocking
2090
+	 * @return array   The shape of this array depends on whether the model `has_primary_key_field` or not.  If the
2091
+	 *                 model DOES have a primary_key_field, then the array will be a simple single dimension array where
2092
+	 *                 the key is the fully qualified primary key column and the value is an array of ids that will be
2093
+	 *                 deleted. Example:
2094
+	 *                      array('Event.EVT_ID' => array( 1,2,3))
2095
+	 *                 If the model DOES NOT have a primary_key_field, then the array will be a two dimensional array
2096
+	 *                 where each element is a group of columns and values that get deleted. Example:
2097
+	 *                      array(
2098
+	 *                          0 => array(
2099
+	 *                              'Term_Relationship.object_id' => 1
2100
+	 *                              'Term_Relationship.term_taxonomy_id' => 5
2101
+	 *                          ),
2102
+	 *                          1 => array(
2103
+	 *                              'Term_Relationship.object_id' => 1
2104
+	 *                              'Term_Relationship.term_taxonomy_id' => 6
2105
+	 *                          )
2106
+	 *                      )
2107
+	 * @throws EE_Error
2108
+	 */
2109
+	protected function _get_ids_for_delete(array $row_results_for_deleting, $allow_blocking = true)
2110
+	{
2111
+		$ids_to_delete_indexed_by_column = array();
2112
+		if ($this->has_primary_key_field()) {
2113
+			$primary_table = $this->_get_main_table();
2114
+			$primary_table_pk_field = $this->get_field_by_column($primary_table->get_fully_qualified_pk_column());
2115
+			$other_tables = $this->_get_other_tables();
2116
+			$ids_to_delete_indexed_by_column = $query = array();
2117
+			foreach ($row_results_for_deleting as $item_to_delete) {
2118
+				//before we mark this item for deletion,
2119
+				//make sure there's no related entities blocking its deletion (if we're checking)
2120
+				if (
2121
+					$allow_blocking
2122
+					&& $this->delete_is_blocked_by_related_models(
2123
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()]
2124
+					)
2125
+				) {
2126
+					continue;
2127
+				}
2128
+				//primary table deletes
2129
+				if (isset($item_to_delete[$primary_table->get_fully_qualified_pk_column()])) {
2130
+					$ids_to_delete_indexed_by_column[$primary_table->get_fully_qualified_pk_column()][] =
2131
+						$item_to_delete[$primary_table->get_fully_qualified_pk_column()];
2132
+				}
2133
+			}
2134
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2135
+			$fields = $this->get_combined_primary_key_fields();
2136
+			foreach ($row_results_for_deleting as $item_to_delete) {
2137
+				$ids_to_delete_indexed_by_column_for_row = array();
2138
+				foreach ($fields as $cpk_field) {
2139
+					if ($cpk_field instanceof EE_Model_Field_Base) {
2140
+						$ids_to_delete_indexed_by_column_for_row[$cpk_field->get_qualified_column()] =
2141
+							$item_to_delete[$cpk_field->get_qualified_column()];
2142
+					}
2143
+				}
2144
+				$ids_to_delete_indexed_by_column[] = $ids_to_delete_indexed_by_column_for_row;
2145
+			}
2146
+		} else {
2147
+			//so there's no primary key and no combined key...
2148
+			//sorry, can't help you
2149
+			throw new EE_Error(
2150
+				sprintf(
2151
+					__(
2152
+						"Cannot delete objects of type %s because there is no primary key NOR combined key",
2153
+						"event_espresso"
2154
+					), get_class($this)
2155
+				)
2156
+			);
2157
+		}
2158
+		return $ids_to_delete_indexed_by_column;
2159
+	}
2160
+
2161
+
2162
+	/**
2163
+	 * This receives an array of columns and values set to be deleted (as prepared by _get_ids_for_delete) and prepares
2164
+	 * the corresponding query_part for the query performing the delete.
2165
+	 *
2166
+	 * @param array $ids_to_delete_indexed_by_column @see _get_ids_for_delete for how this array might be shaped.
2167
+	 * @return string
2168
+	 * @throws EE_Error
2169
+	 */
2170
+	protected function _build_query_part_for_deleting_from_columns_and_values(array $ids_to_delete_indexed_by_column) {
2171
+		$query_part = '';
2172
+		if (empty($ids_to_delete_indexed_by_column)) {
2173
+			return $query_part;
2174
+		} elseif ($this->has_primary_key_field()) {
2175
+			$query = array();
2176
+			foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2177
+				//make sure we have unique $ids
2178
+				$ids = array_unique($ids);
2179
+				$query[] = $column . ' IN(' . implode(',', $ids) . ')';
2180
+			}
2181
+			$query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182
+		} elseif (count($this->get_combined_primary_key_fields()) > 1) {
2183
+			$ways_to_identify_a_row = array();
2184
+			foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185
+				$values_for_each_combined_primary_key_for_a_row = array();
2186
+				foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
+					$values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2188
+				}
2189
+				$ways_to_identify_a_row[] = '('
2190
+											. implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
2191
+											. ')';
2192
+			}
2193
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2194
+		}
2195
+		return $query_part;
2196
+	}
2197
+
2198
+
2199
+
2200
+	/**
2201
+	 * Gets the model field by the fully qualified name
2202
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2203
+	 * @return EE_Model_Field_Base
2204
+	 */
2205
+	public function get_field_by_column($qualified_column_name)
2206
+	{
2207
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2208
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2209
+			   return $field_obj;
2210
+		   }
2211
+	   }
2212
+		throw new EE_Error(
2213
+			sprintf(
2214
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2215
+				$this->get_this_model_name(),
2216
+				$qualified_column_name
2217
+			)
2218
+		);
2219
+	}
2220
+
2221
+
2222
+
2223
+	/**
2224
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2225
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2226
+	 * column
2227
+	 *
2228
+	 * @param array  $query_params   like EEM_Base::get_all's
2229
+	 * @param string $field_to_count field on model to count by (not column name)
2230
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2231
+	 *                               that by the setting $distinct to TRUE;
2232
+	 * @return int
2233
+	 * @throws EE_Error
2234
+	 */
2235
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2236
+	{
2237
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2238
+		if ($field_to_count) {
2239
+			$field_obj = $this->field_settings_for($field_to_count);
2240
+			$column_to_count = $field_obj->get_qualified_column();
2241
+		} elseif ($this->has_primary_key_field()) {
2242
+			$pk_field_obj = $this->get_primary_key_field();
2243
+			$column_to_count = $pk_field_obj->get_qualified_column();
2244
+		} else {
2245
+			//there's no primary key
2246
+			//if we're counting distinct items, and there's no primary key,
2247
+			//we need to list out the columns for distinction;
2248
+			//otherwise we can just use star
2249
+			if ($distinct) {
2250
+				$columns_to_use = array();
2251
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2252
+					$columns_to_use[] = $field_obj->get_qualified_column();
2253
+				}
2254
+				$column_to_count = implode(',', $columns_to_use);
2255
+			} else {
2256
+				$column_to_count = '*';
2257
+			}
2258
+		}
2259
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2262
+	}
2263
+
2264
+
2265
+
2266
+	/**
2267
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2268
+	 *
2269
+	 * @param array  $query_params like EEM_Base::get_all
2270
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2271
+	 * @return float
2272
+	 * @throws EE_Error
2273
+	 */
2274
+	public function sum($query_params, $field_to_sum = null)
2275
+	{
2276
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2277
+		if ($field_to_sum) {
2278
+			$field_obj = $this->field_settings_for($field_to_sum);
2279
+		} else {
2280
+			$field_obj = $this->get_primary_key_field();
2281
+		}
2282
+		$column_to_count = $field_obj->get_qualified_column();
2283
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2284
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285
+		$data_type = $field_obj->get_wpdb_data_type();
2286
+		if ($data_type === '%d' || $data_type === '%s') {
2287
+			return (float)$return_value;
2288
+		}
2289
+		//must be %f
2290
+		return (float)$return_value;
2291
+	}
2292
+
2293
+
2294
+
2295
+	/**
2296
+	 * Just calls the specified method on $wpdb with the given arguments
2297
+	 * Consolidates a little extra error handling code
2298
+	 *
2299
+	 * @param string $wpdb_method
2300
+	 * @param array  $arguments_to_provide
2301
+	 * @throws EE_Error
2302
+	 * @global wpdb  $wpdb
2303
+	 * @return mixed
2304
+	 */
2305
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2306
+	{
2307
+		//if we're in maintenance mode level 2, DON'T run any queries
2308
+		//because level 2 indicates the database needs updating and
2309
+		//is probably out of sync with the code
2310
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2311
+			throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2312
+				"event_espresso")));
2313
+		}
2314
+		/** @type WPDB $wpdb */
2315
+		global $wpdb;
2316
+		if (! method_exists($wpdb, $wpdb_method)) {
2317
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2318
+				'event_espresso'), $wpdb_method));
2319
+		}
2320
+		if (WP_DEBUG) {
2321
+			$old_show_errors_value = $wpdb->show_errors;
2322
+			$wpdb->show_errors(false);
2323
+		}
2324
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2325
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2326
+		if (WP_DEBUG) {
2327
+			$wpdb->show_errors($old_show_errors_value);
2328
+			if (! empty($wpdb->last_error)) {
2329
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2330
+			}
2331
+			if ($result === false) {
2332
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2333
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2334
+			}
2335
+		} elseif ($result === false) {
2336
+			EE_Error::add_error(
2337
+				sprintf(
2338
+					__('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"',
2339
+						'event_espresso'),
2340
+					$wpdb_method,
2341
+					var_export($arguments_to_provide, true),
2342
+					$wpdb->last_error
2343
+				),
2344
+				__FILE__,
2345
+				__FUNCTION__,
2346
+				__LINE__
2347
+			);
2348
+		}
2349
+		return $result;
2350
+	}
2351
+
2352
+
2353
+
2354
+	/**
2355
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2356
+	 * and if there's an error tries to verify the DB is correct. Uses
2357
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2358
+	 * we should try to fix the EE core db, the addons, or just give up
2359
+	 *
2360
+	 * @param string $wpdb_method
2361
+	 * @param array  $arguments_to_provide
2362
+	 * @return mixed
2363
+	 */
2364
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2365
+	{
2366
+		/** @type WPDB $wpdb */
2367
+		global $wpdb;
2368
+		$wpdb->last_error = null;
2369
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2370
+		// was there an error running the query? but we don't care on new activations
2371
+		// (we're going to setup the DB anyway on new activations)
2372
+		if (($result === false || ! empty($wpdb->last_error))
2373
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2374
+		) {
2375
+			switch (EEM_Base::$_db_verification_level) {
2376
+				case EEM_Base::db_verified_none :
2377
+					// let's double-check core's DB
2378
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2379
+					break;
2380
+				case EEM_Base::db_verified_core :
2381
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2382
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2383
+					break;
2384
+				case EEM_Base::db_verified_addons :
2385
+					// ummmm... you in trouble
2386
+					return $result;
2387
+					break;
2388
+			}
2389
+			if (! empty($error_message)) {
2390
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2391
+				trigger_error($error_message);
2392
+			}
2393
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2394
+		}
2395
+		return $result;
2396
+	}
2397
+
2398
+
2399
+
2400
+	/**
2401
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2402
+	 * EEM_Base::$_db_verification_level
2403
+	 *
2404
+	 * @param string $wpdb_method
2405
+	 * @param array  $arguments_to_provide
2406
+	 * @return string
2407
+	 */
2408
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2409
+	{
2410
+		/** @type WPDB $wpdb */
2411
+		global $wpdb;
2412
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2413
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2414
+		$error_message = sprintf(
2415
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2416
+				'event_espresso'),
2417
+			$wpdb->last_error,
2418
+			$wpdb_method,
2419
+			wp_json_encode($arguments_to_provide)
2420
+		);
2421
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2422
+		return $error_message;
2423
+	}
2424
+
2425
+
2426
+
2427
+	/**
2428
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2429
+	 * EEM_Base::$_db_verification_level
2430
+	 *
2431
+	 * @param $wpdb_method
2432
+	 * @param $arguments_to_provide
2433
+	 * @return string
2434
+	 */
2435
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2436
+	{
2437
+		/** @type WPDB $wpdb */
2438
+		global $wpdb;
2439
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2440
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2441
+		$error_message = sprintf(
2442
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2443
+				'event_espresso'),
2444
+			$wpdb->last_error,
2445
+			$wpdb_method,
2446
+			wp_json_encode($arguments_to_provide)
2447
+		);
2448
+		EE_System::instance()->initialize_addons();
2449
+		return $error_message;
2450
+	}
2451
+
2452
+
2453
+
2454
+	/**
2455
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2456
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2457
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2458
+	 * ..."
2459
+	 *
2460
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2461
+	 * @return string
2462
+	 */
2463
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464
+	{
2465
+		return " FROM " . $model_query_info->get_full_join_sql() .
2466
+			   $model_query_info->get_where_sql() .
2467
+			   $model_query_info->get_group_by_sql() .
2468
+			   $model_query_info->get_having_sql() .
2469
+			   $model_query_info->get_order_by_sql() .
2470
+			   $model_query_info->get_limit_sql();
2471
+	}
2472
+
2473
+
2474
+
2475
+	/**
2476
+	 * Set to easily debug the next X queries ran from this model.
2477
+	 *
2478
+	 * @param int $count
2479
+	 */
2480
+	public function show_next_x_db_queries($count = 1)
2481
+	{
2482
+		$this->_show_next_x_db_queries = $count;
2483
+	}
2484
+
2485
+
2486
+
2487
+	/**
2488
+	 * @param $sql_query
2489
+	 */
2490
+	public function show_db_query_if_previously_requested($sql_query)
2491
+	{
2492
+		if ($this->_show_next_x_db_queries > 0) {
2493
+			echo $sql_query;
2494
+			$this->_show_next_x_db_queries--;
2495
+		}
2496
+	}
2497
+
2498
+
2499
+
2500
+	/**
2501
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2502
+	 * There are the 3 cases:
2503
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2504
+	 * $otherModelObject has no ID, it is first saved.
2505
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2506
+	 * has no ID, it is first saved.
2507
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2508
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2509
+	 * join table
2510
+	 *
2511
+	 * @param        EE_Base_Class                     /int $thisModelObject
2512
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2513
+	 * @param string $relationName                     , key in EEM_Base::_relations
2514
+	 *                                                 an attendee to a group, you also want to specify which role they
2515
+	 *                                                 will have in that group. So you would use this parameter to
2516
+	 *                                                 specify array('role-column-name'=>'role-id')
2517
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2518
+	 *                                                 to for relation to methods that allow you to further specify
2519
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2520
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2521
+	 *                                                 because these will be inserted in any new rows created as well.
2522
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2523
+	 * @throws EE_Error
2524
+	 */
2525
+	public function add_relationship_to(
2526
+		$id_or_obj,
2527
+		$other_model_id_or_obj,
2528
+		$relationName,
2529
+		$extra_join_model_fields_n_values = array()
2530
+	) {
2531
+		$relation_obj = $this->related_settings_for($relationName);
2532
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2533
+	}
2534
+
2535
+
2536
+
2537
+	/**
2538
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2539
+	 * There are the 3 cases:
2540
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2541
+	 * error
2542
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2543
+	 * an error
2544
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2545
+	 *
2546
+	 * @param        EE_Base_Class /int $id_or_obj
2547
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2548
+	 * @param string $relationName key in EEM_Base::_relations
2549
+	 * @return boolean of success
2550
+	 * @throws EE_Error
2551
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2552
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2553
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2554
+	 *                             because these will be inserted in any new rows created as well.
2555
+	 */
2556
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2557
+	{
2558
+		$relation_obj = $this->related_settings_for($relationName);
2559
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2560
+	}
2561
+
2562
+
2563
+
2564
+	/**
2565
+	 * @param mixed           $id_or_obj
2566
+	 * @param string          $relationName
2567
+	 * @param array           $where_query_params
2568
+	 * @param EE_Base_Class[] objects to which relations were removed
2569
+	 * @return \EE_Base_Class[]
2570
+	 * @throws EE_Error
2571
+	 */
2572
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2573
+	{
2574
+		$relation_obj = $this->related_settings_for($relationName);
2575
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2576
+	}
2577
+
2578
+
2579
+
2580
+	/**
2581
+	 * Gets all the related items of the specified $model_name, using $query_params.
2582
+	 * Note: by default, we remove the "default query params"
2583
+	 * because we want to get even deleted items etc.
2584
+	 *
2585
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2586
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2587
+	 * @param array  $query_params like EEM_Base::get_all
2588
+	 * @return EE_Base_Class[]
2589
+	 * @throws EE_Error
2590
+	 */
2591
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2592
+	{
2593
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2594
+		$relation_settings = $this->related_settings_for($model_name);
2595
+		return $relation_settings->get_all_related($model_obj, $query_params);
2596
+	}
2597
+
2598
+
2599
+
2600
+	/**
2601
+	 * Deletes all the model objects across the relation indicated by $model_name
2602
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2603
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2604
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2605
+	 *
2606
+	 * @param EE_Base_Class|int|string $id_or_obj
2607
+	 * @param string                   $model_name
2608
+	 * @param array                    $query_params
2609
+	 * @return int how many deleted
2610
+	 * @throws EE_Error
2611
+	 */
2612
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2613
+	{
2614
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2615
+		$relation_settings = $this->related_settings_for($model_name);
2616
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2617
+	}
2618
+
2619
+
2620
+
2621
+	/**
2622
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2623
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2624
+	 * the model objects can't be hard deleted because of blocking related model objects,
2625
+	 * just does a soft-delete on them instead.
2626
+	 *
2627
+	 * @param EE_Base_Class|int|string $id_or_obj
2628
+	 * @param string                   $model_name
2629
+	 * @param array                    $query_params
2630
+	 * @return int how many deleted
2631
+	 * @throws EE_Error
2632
+	 */
2633
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2634
+	{
2635
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2636
+		$relation_settings = $this->related_settings_for($model_name);
2637
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2638
+	}
2639
+
2640
+
2641
+
2642
+	/**
2643
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2644
+	 * unless otherwise specified in the $query_params
2645
+	 *
2646
+	 * @param        int             /EE_Base_Class $id_or_obj
2647
+	 * @param string $model_name     like 'Event', or 'Registration'
2648
+	 * @param array  $query_params   like EEM_Base::get_all's
2649
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2650
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2651
+	 *                               that by the setting $distinct to TRUE;
2652
+	 * @return int
2653
+	 * @throws EE_Error
2654
+	 */
2655
+	public function count_related(
2656
+		$id_or_obj,
2657
+		$model_name,
2658
+		$query_params = array(),
2659
+		$field_to_count = null,
2660
+		$distinct = false
2661
+	) {
2662
+		$related_model = $this->get_related_model_obj($model_name);
2663
+		//we're just going to use the query params on the related model's normal get_all query,
2664
+		//except add a condition to say to match the current mod
2665
+		if (! isset($query_params['default_where_conditions'])) {
2666
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667
+		}
2668
+		$this_model_name = $this->get_this_model_name();
2669
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2671
+		return $related_model->count($query_params, $field_to_count, $distinct);
2672
+	}
2673
+
2674
+
2675
+
2676
+	/**
2677
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2678
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2679
+	 *
2680
+	 * @param        int           /EE_Base_Class $id_or_obj
2681
+	 * @param string $model_name   like 'Event', or 'Registration'
2682
+	 * @param array  $query_params like EEM_Base::get_all's
2683
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2684
+	 * @return float
2685
+	 * @throws EE_Error
2686
+	 */
2687
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688
+	{
2689
+		$related_model = $this->get_related_model_obj($model_name);
2690
+		if (! is_array($query_params)) {
2691
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2692
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2693
+					gettype($query_params)), '4.6.0');
2694
+			$query_params = array();
2695
+		}
2696
+		//we're just going to use the query params on the related model's normal get_all query,
2697
+		//except add a condition to say to match the current mod
2698
+		if (! isset($query_params['default_where_conditions'])) {
2699
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700
+		}
2701
+		$this_model_name = $this->get_this_model_name();
2702
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2704
+		return $related_model->sum($query_params, $field_to_sum);
2705
+	}
2706
+
2707
+
2708
+
2709
+	/**
2710
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2711
+	 * $modelObject
2712
+	 *
2713
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2714
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2715
+	 * @param array               $query_params     like EEM_Base::get_all's
2716
+	 * @return EE_Base_Class
2717
+	 * @throws EE_Error
2718
+	 */
2719
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2720
+	{
2721
+		$query_params['limit'] = 1;
2722
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2723
+		if ($results) {
2724
+			return array_shift($results);
2725
+		}
2726
+		return null;
2727
+	}
2728
+
2729
+
2730
+
2731
+	/**
2732
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2733
+	 *
2734
+	 * @return string
2735
+	 */
2736
+	public function get_this_model_name()
2737
+	{
2738
+		return str_replace("EEM_", "", get_class($this));
2739
+	}
2740
+
2741
+
2742
+
2743
+	/**
2744
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2745
+	 *
2746
+	 * @return EE_Any_Foreign_Model_Name_Field
2747
+	 * @throws EE_Error
2748
+	 */
2749
+	public function get_field_containing_related_model_name()
2750
+	{
2751
+		foreach ($this->field_settings(true) as $field) {
2752
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2753
+				$field_with_model_name = $field;
2754
+			}
2755
+		}
2756
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2757
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2758
+				$this->get_this_model_name()));
2759
+		}
2760
+		return $field_with_model_name;
2761
+	}
2762
+
2763
+
2764
+
2765
+	/**
2766
+	 * Inserts a new entry into the database, for each table.
2767
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2768
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2769
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2770
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2771
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2772
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2773
+	 *
2774
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2775
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2776
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2777
+	 *                              of EEM_Base)
2778
+	 * @return int new primary key on main table that got inserted
2779
+	 * @throws EE_Error
2780
+	 */
2781
+	public function insert($field_n_values)
2782
+	{
2783
+		/**
2784
+		 * Filters the fields and their values before inserting an item using the models
2785
+		 *
2786
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2787
+		 * @param EEM_Base $model           the model used
2788
+		 */
2789
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2790
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2791
+			$main_table = $this->_get_main_table();
2792
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2793
+			if ($new_id !== false) {
2794
+				foreach ($this->_get_other_tables() as $other_table) {
2795
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2796
+				}
2797
+			}
2798
+			/**
2799
+			 * Done just after attempting to insert a new model object
2800
+			 *
2801
+			 * @param EEM_Base   $model           used
2802
+			 * @param array      $fields_n_values fields and their values
2803
+			 * @param int|string the              ID of the newly-inserted model object
2804
+			 */
2805
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2806
+			return $new_id;
2807
+		}
2808
+		return false;
2809
+	}
2810
+
2811
+
2812
+
2813
+	/**
2814
+	 * Checks that the result would satisfy the unique indexes on this model
2815
+	 *
2816
+	 * @param array  $field_n_values
2817
+	 * @param string $action
2818
+	 * @return boolean
2819
+	 * @throws EE_Error
2820
+	 */
2821
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2822
+	{
2823
+		foreach ($this->unique_indexes() as $index_name => $index) {
2824
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2825
+			if ($this->exists(array($uniqueness_where_params))) {
2826
+				EE_Error::add_error(
2827
+					sprintf(
2828
+						__(
2829
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2830
+							"event_espresso"
2831
+						),
2832
+						$action,
2833
+						$this->_get_class_name(),
2834
+						$index_name,
2835
+						implode(",", $index->field_names()),
2836
+						http_build_query($uniqueness_where_params)
2837
+					),
2838
+					__FILE__,
2839
+					__FUNCTION__,
2840
+					__LINE__
2841
+				);
2842
+				return false;
2843
+			}
2844
+		}
2845
+		return true;
2846
+	}
2847
+
2848
+
2849
+
2850
+	/**
2851
+	 * Checks the database for an item that conflicts (ie, if this item were
2852
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2853
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2854
+	 * can be either an EE_Base_Class or an array of fields n values
2855
+	 *
2856
+	 * @param EE_Base_Class|array $obj_or_fields_array
2857
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2858
+	 *                                                 when looking for conflicts
2859
+	 *                                                 (ie, if false, we ignore the model object's primary key
2860
+	 *                                                 when finding "conflicts". If true, it's also considered).
2861
+	 *                                                 Only works for INT primary key,
2862
+	 *                                                 STRING primary keys cannot be ignored
2863
+	 * @throws EE_Error
2864
+	 * @return EE_Base_Class|array
2865
+	 */
2866
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2867
+	{
2868
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2869
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2870
+		} elseif (is_array($obj_or_fields_array)) {
2871
+			$fields_n_values = $obj_or_fields_array;
2872
+		} else {
2873
+			throw new EE_Error(
2874
+				sprintf(
2875
+					__(
2876
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2877
+						"event_espresso"
2878
+					),
2879
+					get_class($this),
2880
+					$obj_or_fields_array
2881
+				)
2882
+			);
2883
+		}
2884
+		$query_params = array();
2885
+		if ($this->has_primary_key_field()
2886
+			&& ($include_primary_key
2887
+				|| $this->get_primary_key_field()
2888
+				   instanceof
2889
+				   EE_Primary_Key_String_Field)
2890
+			&& isset($fields_n_values[$this->primary_key_name()])
2891
+		) {
2892
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2893
+		}
2894
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2895
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2896
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2897
+		}
2898
+		//if there is nothing to base this search on, then we shouldn't find anything
2899
+		if (empty($query_params)) {
2900
+			return array();
2901
+		}
2902
+		return $this->get_one($query_params);
2903
+	}
2904
+
2905
+
2906
+
2907
+	/**
2908
+	 * Like count, but is optimized and returns a boolean instead of an int
2909
+	 *
2910
+	 * @param array $query_params
2911
+	 * @return boolean
2912
+	 * @throws EE_Error
2913
+	 */
2914
+	public function exists($query_params)
2915
+	{
2916
+		$query_params['limit'] = 1;
2917
+		return $this->count($query_params) > 0;
2918
+	}
2919
+
2920
+
2921
+
2922
+	/**
2923
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2924
+	 *
2925
+	 * @param int|string $id
2926
+	 * @return boolean
2927
+	 * @throws EE_Error
2928
+	 */
2929
+	public function exists_by_ID($id)
2930
+	{
2931
+		return $this->exists(
2932
+			array(
2933
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2934
+				array(
2935
+					$this->primary_key_name() => $id,
2936
+				),
2937
+			)
2938
+		);
2939
+	}
2940
+
2941
+
2942
+
2943
+	/**
2944
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2945
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2946
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2947
+	 * on the main table)
2948
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2949
+	 * cases where we want to call it directly rather than via insert().
2950
+	 *
2951
+	 * @access   protected
2952
+	 * @param EE_Table_Base $table
2953
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2954
+	 *                                       float
2955
+	 * @param int           $new_id          for now we assume only int keys
2956
+	 * @throws EE_Error
2957
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2958
+	 * @return int ID of new row inserted, or FALSE on failure
2959
+	 */
2960
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2961
+	{
2962
+		global $wpdb;
2963
+		$insertion_col_n_values = array();
2964
+		$format_for_insertion = array();
2965
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2966
+		foreach ($fields_on_table as $field_name => $field_obj) {
2967
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2968
+			if ($field_obj->is_auto_increment()) {
2969
+				continue;
2970
+			}
2971
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2972
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2973
+			if ($prepared_value !== null) {
2974
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2975
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2976
+			}
2977
+		}
2978
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2979
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2980
+			//so add the fk to the main table as a column
2981
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2982
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2983
+		}
2984
+		//insert the new entry
2985
+		$result = $this->_do_wpdb_query('insert',
2986
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2987
+		if ($result === false) {
2988
+			return false;
2989
+		}
2990
+		//ok, now what do we return for the ID of the newly-inserted thing?
2991
+		if ($this->has_primary_key_field()) {
2992
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2993
+				return $wpdb->insert_id;
2994
+			}
2995
+			//it's not an auto-increment primary key, so
2996
+			//it must have been supplied
2997
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
2998
+		}
2999
+		//we can't return a  primary key because there is none. instead return
3000
+		//a unique string indicating this model
3001
+		return $this->get_index_primary_key_string($fields_n_values);
3002
+	}
3003
+
3004
+
3005
+
3006
+	/**
3007
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3008
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3009
+	 * and there is no default, we pass it along. WPDB will take care of it)
3010
+	 *
3011
+	 * @param EE_Model_Field_Base $field_obj
3012
+	 * @param array               $fields_n_values
3013
+	 * @return mixed string|int|float depending on what the table column will be expecting
3014
+	 * @throws EE_Error
3015
+	 */
3016
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3017
+	{
3018
+		//if this field doesn't allow nullable, don't allow it
3019
+		if (
3020
+			! $field_obj->is_nullable()
3021
+			&& (
3022
+				! isset($fields_n_values[$field_obj->get_name()])
3023
+				|| $fields_n_values[$field_obj->get_name()] === null
3024
+			)
3025
+		) {
3026
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3027
+		}
3028
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3029
+			? $fields_n_values[$field_obj->get_name()]
3030
+			: null;
3031
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3032
+	}
3033
+
3034
+
3035
+
3036
+	/**
3037
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3038
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3039
+	 * the field's prepare_for_set() method.
3040
+	 *
3041
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3042
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3043
+	 *                                   top of file)
3044
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3045
+	 *                                   $value is a custom selection
3046
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3047
+	 */
3048
+	private function _prepare_value_for_use_in_db($value, $field)
3049
+	{
3050
+		if ($field && $field instanceof EE_Model_Field_Base) {
3051
+			switch ($this->_values_already_prepared_by_model_object) {
3052
+				/** @noinspection PhpMissingBreakStatementInspection */
3053
+				case self::not_prepared_by_model_object:
3054
+					$value = $field->prepare_for_set($value);
3055
+				//purposefully left out "return"
3056
+				case self::prepared_by_model_object:
3057
+					/** @noinspection SuspiciousAssignmentsInspection */
3058
+					$value = $field->prepare_for_use_in_db($value);
3059
+				case self::prepared_for_use_in_db:
3060
+					//leave the value alone
3061
+			}
3062
+			return $value;
3063
+		}
3064
+		return $value;
3065
+	}
3066
+
3067
+
3068
+
3069
+	/**
3070
+	 * Returns the main table on this model
3071
+	 *
3072
+	 * @return EE_Primary_Table
3073
+	 * @throws EE_Error
3074
+	 */
3075
+	protected function _get_main_table()
3076
+	{
3077
+		foreach ($this->_tables as $table) {
3078
+			if ($table instanceof EE_Primary_Table) {
3079
+				return $table;
3080
+			}
3081
+		}
3082
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3083
+			'event_espresso'), get_class($this)));
3084
+	}
3085
+
3086
+
3087
+
3088
+	/**
3089
+	 * table
3090
+	 * returns EE_Primary_Table table name
3091
+	 *
3092
+	 * @return string
3093
+	 * @throws EE_Error
3094
+	 */
3095
+	public function table()
3096
+	{
3097
+		return $this->_get_main_table()->get_table_name();
3098
+	}
3099
+
3100
+
3101
+
3102
+	/**
3103
+	 * table
3104
+	 * returns first EE_Secondary_Table table name
3105
+	 *
3106
+	 * @return string
3107
+	 */
3108
+	public function second_table()
3109
+	{
3110
+		// grab second table from tables array
3111
+		$second_table = end($this->_tables);
3112
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3113
+	}
3114
+
3115
+
3116
+
3117
+	/**
3118
+	 * get_table_obj_by_alias
3119
+	 * returns table name given it's alias
3120
+	 *
3121
+	 * @param string $table_alias
3122
+	 * @return EE_Primary_Table | EE_Secondary_Table
3123
+	 */
3124
+	public function get_table_obj_by_alias($table_alias = '')
3125
+	{
3126
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3127
+	}
3128
+
3129
+
3130
+
3131
+	/**
3132
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3133
+	 *
3134
+	 * @return EE_Secondary_Table[]
3135
+	 */
3136
+	protected function _get_other_tables()
3137
+	{
3138
+		$other_tables = array();
3139
+		foreach ($this->_tables as $table_alias => $table) {
3140
+			if ($table instanceof EE_Secondary_Table) {
3141
+				$other_tables[$table_alias] = $table;
3142
+			}
3143
+		}
3144
+		return $other_tables;
3145
+	}
3146
+
3147
+
3148
+
3149
+	/**
3150
+	 * Finds all the fields that correspond to the given table
3151
+	 *
3152
+	 * @param string $table_alias , array key in EEM_Base::_tables
3153
+	 * @return EE_Model_Field_Base[]
3154
+	 */
3155
+	public function _get_fields_for_table($table_alias)
3156
+	{
3157
+		return $this->_fields[$table_alias];
3158
+	}
3159
+
3160
+
3161
+
3162
+	/**
3163
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3164
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3165
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3166
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3167
+	 * related Registration, Transaction, and Payment models.
3168
+	 *
3169
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3170
+	 * @return EE_Model_Query_Info_Carrier
3171
+	 * @throws EE_Error
3172
+	 */
3173
+	public function _extract_related_models_from_query($query_params)
3174
+	{
3175
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3176
+		if (array_key_exists(0, $query_params)) {
3177
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3178
+		}
3179
+		if (array_key_exists('group_by', $query_params)) {
3180
+			if (is_array($query_params['group_by'])) {
3181
+				$this->_extract_related_models_from_sub_params_array_values(
3182
+					$query_params['group_by'],
3183
+					$query_info_carrier,
3184
+					'group_by'
3185
+				);
3186
+			} elseif (! empty ($query_params['group_by'])) {
3187
+				$this->_extract_related_model_info_from_query_param(
3188
+					$query_params['group_by'],
3189
+					$query_info_carrier,
3190
+					'group_by'
3191
+				);
3192
+			}
3193
+		}
3194
+		if (array_key_exists('having', $query_params)) {
3195
+			$this->_extract_related_models_from_sub_params_array_keys(
3196
+				$query_params[0],
3197
+				$query_info_carrier,
3198
+				'having'
3199
+			);
3200
+		}
3201
+		if (array_key_exists('order_by', $query_params)) {
3202
+			if (is_array($query_params['order_by'])) {
3203
+				$this->_extract_related_models_from_sub_params_array_keys(
3204
+					$query_params['order_by'],
3205
+					$query_info_carrier,
3206
+					'order_by'
3207
+				);
3208
+			} elseif (! empty($query_params['order_by'])) {
3209
+				$this->_extract_related_model_info_from_query_param(
3210
+					$query_params['order_by'],
3211
+					$query_info_carrier,
3212
+					'order_by'
3213
+				);
3214
+			}
3215
+		}
3216
+		if (array_key_exists('force_join', $query_params)) {
3217
+			$this->_extract_related_models_from_sub_params_array_values(
3218
+				$query_params['force_join'],
3219
+				$query_info_carrier,
3220
+				'force_join'
3221
+			);
3222
+		}
3223
+		return $query_info_carrier;
3224
+	}
3225
+
3226
+
3227
+
3228
+	/**
3229
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3230
+	 *
3231
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3232
+	 *                                                      $query_params['having']
3233
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3234
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3235
+	 * @throws EE_Error
3236
+	 * @return \EE_Model_Query_Info_Carrier
3237
+	 */
3238
+	private function _extract_related_models_from_sub_params_array_keys(
3239
+		$sub_query_params,
3240
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241
+		$query_param_type
3242
+	) {
3243
+		if (! empty($sub_query_params)) {
3244
+			$sub_query_params = (array)$sub_query_params;
3245
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3246
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3247
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3248
+					$query_param_type);
3249
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3250
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3251
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3252
+				//of array('Registration.TXN_ID'=>23)
3253
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3254
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3255
+					if (! is_array($possibly_array_of_params)) {
3256
+						throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3257
+							"event_espresso"),
3258
+							$param, $possibly_array_of_params));
3259
+					}
3260
+					$this->_extract_related_models_from_sub_params_array_keys(
3261
+						$possibly_array_of_params,
3262
+						$model_query_info_carrier, $query_param_type
3263
+					);
3264
+				} elseif ($query_param_type === 0 //ie WHERE
3265
+						  && is_array($possibly_array_of_params)
3266
+						  && isset($possibly_array_of_params[2])
3267
+						  && $possibly_array_of_params[2] == true
3268
+				) {
3269
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3270
+					//indicating that $possible_array_of_params[1] is actually a field name,
3271
+					//from which we should extract query parameters!
3272
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3273
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3274
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3275
+					}
3276
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3277
+						$model_query_info_carrier, $query_param_type);
3278
+				}
3279
+			}
3280
+		}
3281
+		return $model_query_info_carrier;
3282
+	}
3283
+
3284
+
3285
+
3286
+	/**
3287
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3288
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3289
+	 *
3290
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3291
+	 *                                                      $query_params['having']
3292
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3293
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3294
+	 * @throws EE_Error
3295
+	 * @return \EE_Model_Query_Info_Carrier
3296
+	 */
3297
+	private function _extract_related_models_from_sub_params_array_values(
3298
+		$sub_query_params,
3299
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300
+		$query_param_type
3301
+	) {
3302
+		if (! empty($sub_query_params)) {
3303
+			if (! is_array($sub_query_params)) {
3304
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3305
+					$sub_query_params));
3306
+			}
3307
+			foreach ($sub_query_params as $param) {
3308
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3309
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3310
+					$query_param_type);
3311
+			}
3312
+		}
3313
+		return $model_query_info_carrier;
3314
+	}
3315
+
3316
+
3317
+
3318
+	/**
3319
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3320
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3321
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3322
+	 * but use them in a different order. Eg, we need to know what models we are querying
3323
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3324
+	 * other models before we can finalize the where clause SQL.
3325
+	 *
3326
+	 * @param array $query_params
3327
+	 * @throws EE_Error
3328
+	 * @return EE_Model_Query_Info_Carrier
3329
+	 */
3330
+	public function _create_model_query_info_carrier($query_params)
3331
+	{
3332
+		if (! is_array($query_params)) {
3333
+			EE_Error::doing_it_wrong(
3334
+				'EEM_Base::_create_model_query_info_carrier',
3335
+				sprintf(
3336
+					__(
3337
+						'$query_params should be an array, you passed a variable of type %s',
3338
+						'event_espresso'
3339
+					),
3340
+					gettype($query_params)
3341
+				),
3342
+				'4.6.0'
3343
+			);
3344
+			$query_params = array();
3345
+		}
3346
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3347
+		//first check if we should alter the query to account for caps or not
3348
+		//because the caps might require us to do extra joins
3349
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3350
+			$query_params[0] = $where_query_params = array_replace_recursive(
3351
+				$where_query_params,
3352
+				$this->caps_where_conditions(
3353
+					$query_params['caps']
3354
+				)
3355
+			);
3356
+		}
3357
+		$query_object = $this->_extract_related_models_from_query($query_params);
3358
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3359
+		foreach ($where_query_params as $key => $value) {
3360
+			if (is_int($key)) {
3361
+				throw new EE_Error(
3362
+					sprintf(
3363
+						__(
3364
+							"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.",
3365
+							"event_espresso"
3366
+						),
3367
+						$key,
3368
+						var_export($value, true),
3369
+						var_export($query_params, true),
3370
+						get_class($this)
3371
+					)
3372
+				);
3373
+			}
3374
+		}
3375
+		if (
3376
+			array_key_exists('default_where_conditions', $query_params)
3377
+			&& ! empty($query_params['default_where_conditions'])
3378
+		) {
3379
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3380
+		} else {
3381
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3382
+		}
3383
+		$where_query_params = array_merge(
3384
+			$this->_get_default_where_conditions_for_models_in_query(
3385
+				$query_object,
3386
+				$use_default_where_conditions,
3387
+				$where_query_params
3388
+			),
3389
+			$where_query_params
3390
+		);
3391
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3392
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3393
+		// So we need to setup a subquery and use that for the main join.
3394
+		// Note for now this only works on the primary table for the model.
3395
+		// So for instance, you could set the limit array like this:
3396
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3397
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3398
+			$query_object->set_main_model_join_sql(
3399
+				$this->_construct_limit_join_select(
3400
+					$query_params['on_join_limit'][0],
3401
+					$query_params['on_join_limit'][1]
3402
+				)
3403
+			);
3404
+		}
3405
+		//set limit
3406
+		if (array_key_exists('limit', $query_params)) {
3407
+			if (is_array($query_params['limit'])) {
3408
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3409
+					$e = sprintf(
3410
+						__(
3411
+							"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)",
3412
+							"event_espresso"
3413
+						),
3414
+						http_build_query($query_params['limit'])
3415
+					);
3416
+					throw new EE_Error($e . "|" . $e);
3417
+				}
3418
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3419
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3420
+			} elseif (! empty ($query_params['limit'])) {
3421
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3422
+			}
3423
+		}
3424
+		//set order by
3425
+		if (array_key_exists('order_by', $query_params)) {
3426
+			if (is_array($query_params['order_by'])) {
3427
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3428
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3429
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3430
+				if (array_key_exists('order', $query_params)) {
3431
+					throw new EE_Error(
3432
+						sprintf(
3433
+							__(
3434
+								"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 ",
3435
+								"event_espresso"
3436
+							),
3437
+							get_class($this),
3438
+							implode(", ", array_keys($query_params['order_by'])),
3439
+							implode(", ", $query_params['order_by']),
3440
+							$query_params['order']
3441
+						)
3442
+					);
3443
+				}
3444
+				$this->_extract_related_models_from_sub_params_array_keys(
3445
+					$query_params['order_by'],
3446
+					$query_object,
3447
+					'order_by'
3448
+				);
3449
+				//assume it's an array of fields to order by
3450
+				$order_array = array();
3451
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3452
+					$order = $this->_extract_order($order);
3453
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3454
+				}
3455
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3456
+			} elseif (! empty ($query_params['order_by'])) {
3457
+				$this->_extract_related_model_info_from_query_param(
3458
+					$query_params['order_by'],
3459
+					$query_object,
3460
+					'order',
3461
+					$query_params['order_by']
3462
+				);
3463
+				$order = isset($query_params['order'])
3464
+					? $this->_extract_order($query_params['order'])
3465
+					: 'DESC';
3466
+				$query_object->set_order_by_sql(
3467
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3468
+				);
3469
+			}
3470
+		}
3471
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3472
+		if (! array_key_exists('order_by', $query_params)
3473
+			&& array_key_exists('order', $query_params)
3474
+			&& ! empty($query_params['order'])
3475
+		) {
3476
+			$pk_field = $this->get_primary_key_field();
3477
+			$order = $this->_extract_order($query_params['order']);
3478
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3479
+		}
3480
+		//set group by
3481
+		if (array_key_exists('group_by', $query_params)) {
3482
+			if (is_array($query_params['group_by'])) {
3483
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3484
+				$group_by_array = array();
3485
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3486
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3487
+				}
3488
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3489
+			} elseif (! empty ($query_params['group_by'])) {
3490
+				$query_object->set_group_by_sql(
3491
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3492
+				);
3493
+			}
3494
+		}
3495
+		//set having
3496
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3497
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3498
+		}
3499
+		//now, just verify they didn't pass anything wack
3500
+		foreach ($query_params as $query_key => $query_value) {
3501
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3502
+				throw new EE_Error(
3503
+					sprintf(
3504
+						__(
3505
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3506
+							'event_espresso'
3507
+						),
3508
+						$query_key,
3509
+						get_class($this),
3510
+						//						print_r( $this->_allowed_query_params, TRUE )
3511
+						implode(',', $this->_allowed_query_params)
3512
+					)
3513
+				);
3514
+			}
3515
+		}
3516
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3517
+		if (empty($main_model_join_sql)) {
3518
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3519
+		}
3520
+		return $query_object;
3521
+	}
3522
+
3523
+
3524
+
3525
+	/**
3526
+	 * Gets the where conditions that should be imposed on the query based on the
3527
+	 * context (eg reading frontend, backend, edit or delete).
3528
+	 *
3529
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3530
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3531
+	 * @throws EE_Error
3532
+	 */
3533
+	public function caps_where_conditions($context = self::caps_read)
3534
+	{
3535
+		EEM_Base::verify_is_valid_cap_context($context);
3536
+		$cap_where_conditions = array();
3537
+		$cap_restrictions = $this->caps_missing($context);
3538
+		/**
3539
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3540
+		 */
3541
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3542
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3543
+				$restriction_if_no_cap->get_default_where_conditions());
3544
+		}
3545
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3546
+			$cap_restrictions);
3547
+	}
3548
+
3549
+
3550
+
3551
+	/**
3552
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3553
+	 * otherwise throws an exception
3554
+	 *
3555
+	 * @param string $should_be_order_string
3556
+	 * @return string either ASC, asc, DESC or desc
3557
+	 * @throws EE_Error
3558
+	 */
3559
+	private function _extract_order($should_be_order_string)
3560
+	{
3561
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3562
+			return $should_be_order_string;
3563
+		}
3564
+		throw new EE_Error(
3565
+			sprintf(
3566
+				__(
3567
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3568
+					"event_espresso"
3569
+				), get_class($this), $should_be_order_string
3570
+			)
3571
+		);
3572
+	}
3573
+
3574
+
3575
+
3576
+	/**
3577
+	 * Looks at all the models which are included in this query, and asks each
3578
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3579
+	 * so they can be merged
3580
+	 *
3581
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3582
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3583
+	 *                                                                  'none' means NO default where conditions will
3584
+	 *                                                                  be used AT ALL during this query.
3585
+	 *                                                                  'other_models_only' means default where
3586
+	 *                                                                  conditions from other models will be used, but
3587
+	 *                                                                  not for this primary model. 'all', the default,
3588
+	 *                                                                  means default where conditions will apply as
3589
+	 *                                                                  normal
3590
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3591
+	 * @throws EE_Error
3592
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3593
+	 */
3594
+	private function _get_default_where_conditions_for_models_in_query(
3595
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3596
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3597
+		$where_query_params = array()
3598
+	) {
3599
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3600
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3601
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3602
+				"event_espresso"), $use_default_where_conditions,
3603
+				implode(", ", $allowed_used_default_where_conditions_values)));
3604
+		}
3605
+		$universal_query_params = array();
3606
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3607
+			$universal_query_params = $this->_get_default_where_conditions();
3608
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3609
+			$universal_query_params = $this->_get_minimum_where_conditions();
3610
+		}
3611
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3612
+			$related_model = $this->get_related_model_obj($model_name);
3613
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3614
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3615
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3616
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3617
+			} else {
3618
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3619
+				continue;
3620
+			}
3621
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3622
+				$related_model_universal_where_params,
3623
+				$where_query_params,
3624
+				$related_model,
3625
+				$model_relation_path
3626
+			);
3627
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3628
+				$universal_query_params,
3629
+				$overrides
3630
+			);
3631
+		}
3632
+		return $universal_query_params;
3633
+	}
3634
+
3635
+
3636
+
3637
+	/**
3638
+	 * Determines whether or not we should use default where conditions for the model in question
3639
+	 * (this model, or other related models).
3640
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3641
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3642
+	 * We should use default where conditions on related models when they requested to use default where conditions
3643
+	 * on all models, or specifically just on other related models
3644
+	 * @param      $default_where_conditions_value
3645
+	 * @param bool $for_this_model false means this is for OTHER related models
3646
+	 * @return bool
3647
+	 */
3648
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3649
+	{
3650
+		return (
3651
+				   $for_this_model
3652
+				   && in_array(
3653
+					   $default_where_conditions_value,
3654
+					   array(
3655
+						   EEM_Base::default_where_conditions_all,
3656
+						   EEM_Base::default_where_conditions_this_only,
3657
+						   EEM_Base::default_where_conditions_minimum_others,
3658
+					   ),
3659
+					   true
3660
+				   )
3661
+			   )
3662
+			   || (
3663
+				   ! $for_this_model
3664
+				   && in_array(
3665
+					   $default_where_conditions_value,
3666
+					   array(
3667
+						   EEM_Base::default_where_conditions_all,
3668
+						   EEM_Base::default_where_conditions_others_only,
3669
+					   ),
3670
+					   true
3671
+				   )
3672
+			   );
3673
+	}
3674
+
3675
+	/**
3676
+	 * Determines whether or not we should use default minimum conditions for the model in question
3677
+	 * (this model, or other related models).
3678
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3679
+	 * where conditions.
3680
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3681
+	 * on this model or others
3682
+	 * @param      $default_where_conditions_value
3683
+	 * @param bool $for_this_model false means this is for OTHER related models
3684
+	 * @return bool
3685
+	 */
3686
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3687
+	{
3688
+		return (
3689
+				   $for_this_model
3690
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3691
+			   )
3692
+			   || (
3693
+				   ! $for_this_model
3694
+				   && in_array(
3695
+					   $default_where_conditions_value,
3696
+					   array(
3697
+						   EEM_Base::default_where_conditions_minimum_others,
3698
+						   EEM_Base::default_where_conditions_minimum_all,
3699
+					   ),
3700
+					   true
3701
+				   )
3702
+			   );
3703
+	}
3704
+
3705
+
3706
+	/**
3707
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3708
+	 * then we also add a special where condition which allows for that model's primary key
3709
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3710
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3711
+	 *
3712
+	 * @param array    $default_where_conditions
3713
+	 * @param array    $provided_where_conditions
3714
+	 * @param EEM_Base $model
3715
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3716
+	 * @return array like EEM_Base::get_all's $query_params[0]
3717
+	 * @throws EE_Error
3718
+	 */
3719
+	private function _override_defaults_or_make_null_friendly(
3720
+		$default_where_conditions,
3721
+		$provided_where_conditions,
3722
+		$model,
3723
+		$model_relation_path
3724
+	) {
3725
+		$null_friendly_where_conditions = array();
3726
+		$none_overridden = true;
3727
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3728
+		foreach ($default_where_conditions as $key => $val) {
3729
+			if (isset($provided_where_conditions[$key])) {
3730
+				$none_overridden = false;
3731
+			} else {
3732
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3733
+			}
3734
+		}
3735
+		if ($none_overridden && $default_where_conditions) {
3736
+			if ($model->has_primary_key_field()) {
3737
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3738
+																				. "."
3739
+																				. $model->primary_key_name()] = array('IS NULL');
3740
+			}/*else{
3741 3741
 				//@todo NO PK, use other defaults
3742 3742
 			}*/
3743
-        }
3744
-        return $null_friendly_where_conditions;
3745
-    }
3746
-
3747
-
3748
-
3749
-    /**
3750
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3751
-     * default where conditions on all get_all, update, and delete queries done by this model.
3752
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3753
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3754
-     *
3755
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3756
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3757
-     */
3758
-    private function _get_default_where_conditions($model_relation_path = null)
3759
-    {
3760
-        if ($this->_ignore_where_strategy) {
3761
-            return array();
3762
-        }
3763
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3764
-    }
3765
-
3766
-
3767
-
3768
-    /**
3769
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3770
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3771
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3772
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3773
-     * Similar to _get_default_where_conditions
3774
-     *
3775
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3776
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3777
-     */
3778
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3779
-    {
3780
-        if ($this->_ignore_where_strategy) {
3781
-            return array();
3782
-        }
3783
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3784
-    }
3785
-
3786
-
3787
-
3788
-    /**
3789
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3790
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3791
-     *
3792
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3793
-     * @return string
3794
-     * @throws EE_Error
3795
-     */
3796
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3797
-    {
3798
-        $selects = $this->_get_columns_to_select_for_this_model();
3799
-        foreach (
3800
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3801
-            $name_of_other_model_included
3802
-        ) {
3803
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3804
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3805
-            foreach ($other_model_selects as $key => $value) {
3806
-                $selects[] = $value;
3807
-            }
3808
-        }
3809
-        return implode(", ", $selects);
3810
-    }
3811
-
3812
-
3813
-
3814
-    /**
3815
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3816
-     * So that's going to be the columns for all the fields on the model
3817
-     *
3818
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3819
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3820
-     */
3821
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3822
-    {
3823
-        $fields = $this->field_settings();
3824
-        $selects = array();
3825
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3826
-            $this->get_this_model_name());
3827
-        foreach ($fields as $field_obj) {
3828
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3829
-                         . $field_obj->get_table_alias()
3830
-                         . "."
3831
-                         . $field_obj->get_table_column()
3832
-                         . " AS '"
3833
-                         . $table_alias_with_model_relation_chain_prefix
3834
-                         . $field_obj->get_table_alias()
3835
-                         . "."
3836
-                         . $field_obj->get_table_column()
3837
-                         . "'";
3838
-        }
3839
-        //make sure we are also getting the PKs of each table
3840
-        $tables = $this->get_tables();
3841
-        if (count($tables) > 1) {
3842
-            foreach ($tables as $table_obj) {
3843
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3844
-                                       . $table_obj->get_fully_qualified_pk_column();
3845
-                if (! in_array($qualified_pk_column, $selects)) {
3846
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3847
-                }
3848
-            }
3849
-        }
3850
-        return $selects;
3851
-    }
3852
-
3853
-
3854
-
3855
-    /**
3856
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3857
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3858
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3859
-     * SQL for joining, and the data types
3860
-     *
3861
-     * @param null|string                 $original_query_param
3862
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3863
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3864
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3865
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3866
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3867
-     *                                                          or 'Registration's
3868
-     * @param string                      $original_query_param what it originally was (eg
3869
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3870
-     *                                                          matches $query_param
3871
-     * @throws EE_Error
3872
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3873
-     */
3874
-    private function _extract_related_model_info_from_query_param(
3875
-        $query_param,
3876
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3877
-        $query_param_type,
3878
-        $original_query_param = null
3879
-    ) {
3880
-        if ($original_query_param === null) {
3881
-            $original_query_param = $query_param;
3882
-        }
3883
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3884
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3885
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3886
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3887
-        //check to see if we have a field on this model
3888
-        $this_model_fields = $this->field_settings(true);
3889
-        if (array_key_exists($query_param, $this_model_fields)) {
3890
-            if ($allow_fields) {
3891
-                return;
3892
-            }
3893
-            throw new EE_Error(
3894
-                sprintf(
3895
-                    __(
3896
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3897
-                        "event_espresso"
3898
-                    ),
3899
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3900
-                )
3901
-            );
3902
-        }
3903
-        //check if this is a special logic query param
3904
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3905
-            if ($allow_logic_query_params) {
3906
-                return;
3907
-            }
3908
-            throw new EE_Error(
3909
-                sprintf(
3910
-                    __(
3911
-                        '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',
3912
-                        'event_espresso'
3913
-                    ),
3914
-                    implode('", "', $this->_logic_query_param_keys),
3915
-                    $query_param,
3916
-                    get_class($this),
3917
-                    '<br />',
3918
-                    "\t"
3919
-                    . ' $passed_in_query_info = <pre>'
3920
-                    . print_r($passed_in_query_info, true)
3921
-                    . '</pre>'
3922
-                    . "\n\t"
3923
-                    . ' $query_param_type = '
3924
-                    . $query_param_type
3925
-                    . "\n\t"
3926
-                    . ' $original_query_param = '
3927
-                    . $original_query_param
3928
-                )
3929
-            );
3930
-        }
3931
-        //check if it's a custom selection
3932
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3933
-            return;
3934
-        }
3935
-        //check if has a model name at the beginning
3936
-        //and
3937
-        //check if it's a field on a related model
3938
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3939
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3940
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3941
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3942
-                if ($query_param === '') {
3943
-                    //nothing left to $query_param
3944
-                    //we should actually end in a field name, not a model like this!
3945
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3946
-                        "event_espresso"),
3947
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3948
-                }
3949
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3950
-                $related_model_obj->_extract_related_model_info_from_query_param(
3951
-                    $query_param,
3952
-                    $passed_in_query_info, $query_param_type, $original_query_param
3953
-                );
3954
-                return;
3955
-            }
3956
-            if ($query_param === $valid_related_model_name) {
3957
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3958
-                return;
3959
-            }
3960
-        }
3961
-        //ok so $query_param didn't start with a model name
3962
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3963
-        //it's wack, that's what it is
3964
-        throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3965
-            "event_espresso"),
3966
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3967
-    }
3968
-
3969
-
3970
-
3971
-    /**
3972
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3973
-     * and store it on $passed_in_query_info
3974
-     *
3975
-     * @param string                      $model_name
3976
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3977
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3978
-     *                                                          model and $model_name. Eg, if we are querying Event,
3979
-     *                                                          and are adding a join to 'Payment' with the original
3980
-     *                                                          query param key
3981
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3982
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3983
-     *                                                          Payment wants to add default query params so that it
3984
-     *                                                          will know what models to prepend onto its default query
3985
-     *                                                          params or in case it wants to rename tables (in case
3986
-     *                                                          there are multiple joins to the same table)
3987
-     * @return void
3988
-     * @throws EE_Error
3989
-     */
3990
-    private function _add_join_to_model(
3991
-        $model_name,
3992
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3993
-        $original_query_param
3994
-    ) {
3995
-        $relation_obj = $this->related_settings_for($model_name);
3996
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3997
-        //check if the relation is HABTM, because then we're essentially doing two joins
3998
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3999
-        if ($relation_obj instanceof EE_HABTM_Relation) {
4000
-            $join_model_obj = $relation_obj->get_join_model();
4001
-            //replace the model specified with the join model for this relation chain, whi
4002
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4003
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4004
-            $passed_in_query_info->merge(
4005
-                new EE_Model_Query_Info_Carrier(
4006
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4007
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4008
-                )
4009
-            );
4010
-        }
4011
-        //now just join to the other table pointed to by the relation object, and add its data types
4012
-        $passed_in_query_info->merge(
4013
-            new EE_Model_Query_Info_Carrier(
4014
-                array($model_relation_chain => $model_name),
4015
-                $relation_obj->get_join_statement($model_relation_chain)
4016
-            )
4017
-        );
4018
-    }
4019
-
4020
-
4021
-
4022
-    /**
4023
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4024
-     *
4025
-     * @param array $where_params like EEM_Base::get_all
4026
-     * @return string of SQL
4027
-     * @throws EE_Error
4028
-     */
4029
-    private function _construct_where_clause($where_params)
4030
-    {
4031
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4032
-        if ($SQL) {
4033
-            return " WHERE " . $SQL;
4034
-        }
4035
-        return '';
4036
-    }
4037
-
4038
-
4039
-
4040
-    /**
4041
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4042
-     * and should be passed HAVING parameters, not WHERE parameters
4043
-     *
4044
-     * @param array $having_params
4045
-     * @return string
4046
-     * @throws EE_Error
4047
-     */
4048
-    private function _construct_having_clause($having_params)
4049
-    {
4050
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4051
-        if ($SQL) {
4052
-            return " HAVING " . $SQL;
4053
-        }
4054
-        return '';
4055
-    }
4056
-
4057
-
4058
-    /**
4059
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4060
-     * Event_Meta.meta_value = 'foo'))"
4061
-     *
4062
-     * @param array  $where_params see EEM_Base::get_all for documentation
4063
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4064
-     * @throws EE_Error
4065
-     * @return string of SQL
4066
-     */
4067
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4068
-    {
4069
-        $where_clauses = array();
4070
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4071
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4072
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4073
-                switch ($query_param) {
4074
-                    case 'not':
4075
-                    case 'NOT':
4076
-                        $where_clauses[] = "! ("
4077
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4078
-                                $glue)
4079
-                                           . ")";
4080
-                        break;
4081
-                    case 'and':
4082
-                    case 'AND':
4083
-                        $where_clauses[] = " ("
4084
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4085
-                                ' AND ')
4086
-                                           . ")";
4087
-                        break;
4088
-                    case 'or':
4089
-                    case 'OR':
4090
-                        $where_clauses[] = " ("
4091
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4092
-                                ' OR ')
4093
-                                           . ")";
4094
-                        break;
4095
-                }
4096
-            } else {
4097
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4098
-                //if it's not a normal field, maybe it's a custom selection?
4099
-                if (! $field_obj) {
4100
-                    if (isset($this->_custom_selections[$query_param][1])) {
4101
-                        $field_obj = $this->_custom_selections[$query_param][1];
4102
-                    } else {
4103
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4104
-                            "event_espresso"), $query_param));
4105
-                    }
4106
-                }
4107
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4108
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4109
-            }
4110
-        }
4111
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4112
-    }
4113
-
4114
-
4115
-
4116
-    /**
4117
-     * Takes the input parameter and extract the table name (alias) and column name
4118
-     *
4119
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4120
-     * @throws EE_Error
4121
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4122
-     */
4123
-    private function _deduce_column_name_from_query_param($query_param)
4124
-    {
4125
-        $field = $this->_deduce_field_from_query_param($query_param);
4126
-        if ($field) {
4127
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4128
-                $query_param);
4129
-            return $table_alias_prefix . $field->get_qualified_column();
4130
-        }
4131
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4132
-            //maybe it's custom selection item?
4133
-            //if so, just use it as the "column name"
4134
-            return $query_param;
4135
-        }
4136
-        throw new EE_Error(
4137
-            sprintf(
4138
-                __(
4139
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4140
-                    "event_espresso"
4141
-                ), $query_param, implode(",", $this->_custom_selections)
4142
-            )
4143
-        );
4144
-    }
4145
-
4146
-
4147
-
4148
-    /**
4149
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4150
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4151
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4152
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4153
-     *
4154
-     * @param string $condition_query_param_key
4155
-     * @return string
4156
-     */
4157
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4158
-    {
4159
-        $pos_of_star = strpos($condition_query_param_key, '*');
4160
-        if ($pos_of_star === false) {
4161
-            return $condition_query_param_key;
4162
-        }
4163
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4164
-        return $condition_query_param_sans_star;
4165
-    }
4166
-
4167
-
4168
-
4169
-    /**
4170
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4171
-     *
4172
-     * @param                            mixed      array | string    $op_and_value
4173
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4174
-     * @throws EE_Error
4175
-     * @return string
4176
-     */
4177
-    private function _construct_op_and_value($op_and_value, $field_obj)
4178
-    {
4179
-        if (is_array($op_and_value)) {
4180
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4181
-            if (! $operator) {
4182
-                $php_array_like_string = array();
4183
-                foreach ($op_and_value as $key => $value) {
4184
-                    $php_array_like_string[] = "$key=>$value";
4185
-                }
4186
-                throw new EE_Error(
4187
-                    sprintf(
4188
-                        __(
4189
-                            "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))",
4190
-                            "event_espresso"
4191
-                        ),
4192
-                        implode(",", $php_array_like_string)
4193
-                    )
4194
-                );
4195
-            }
4196
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4197
-        } else {
4198
-            $operator = '=';
4199
-            $value = $op_and_value;
4200
-        }
4201
-        //check to see if the value is actually another field
4202
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4203
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4204
-        }
4205
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4206
-            //in this case, the value should be an array, or at least a comma-separated list
4207
-            //it will need to handle a little differently
4208
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4209
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4210
-            return $operator . SP . $cleaned_value;
4211
-        }
4212
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4213
-            //the value should be an array with count of two.
4214
-            if (count($value) !== 2) {
4215
-                throw new EE_Error(
4216
-                    sprintf(
4217
-                        __(
4218
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4219
-                            'event_espresso'
4220
-                        ),
4221
-                        "BETWEEN"
4222
-                    )
4223
-                );
4224
-            }
4225
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4226
-            return $operator . SP . $cleaned_value;
4227
-        }
4228
-        if (in_array($operator, $this->valid_null_style_operators())) {
4229
-            if ($value !== null) {
4230
-                throw new EE_Error(
4231
-                    sprintf(
4232
-                        __(
4233
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4234
-                            "event_espresso"
4235
-                        ),
4236
-                        $value,
4237
-                        $operator
4238
-                    )
4239
-                );
4240
-            }
4241
-            return $operator;
4242
-        }
4243
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4244
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4245
-            //remove other junk. So just treat it as a string.
4246
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4247
-        }
4248
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4249
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4250
-        }
4251
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4252
-            throw new EE_Error(
4253
-                sprintf(
4254
-                    __(
4255
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4256
-                        'event_espresso'
4257
-                    ),
4258
-                    $operator,
4259
-                    $operator
4260
-                )
4261
-            );
4262
-        }
4263
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4264
-            throw new EE_Error(
4265
-                sprintf(
4266
-                    __(
4267
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4268
-                        'event_espresso'
4269
-                    ),
4270
-                    $operator,
4271
-                    $operator
4272
-                )
4273
-            );
4274
-        }
4275
-        throw new EE_Error(
4276
-            sprintf(
4277
-                __(
4278
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4279
-                    "event_espresso"
4280
-                ),
4281
-                http_build_query($op_and_value)
4282
-            )
4283
-        );
4284
-    }
4285
-
4286
-
4287
-
4288
-    /**
4289
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4290
-     *
4291
-     * @param array                      $values
4292
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4293
-     *                                              '%s'
4294
-     * @return string
4295
-     * @throws EE_Error
4296
-     */
4297
-    public function _construct_between_value($values, $field_obj)
4298
-    {
4299
-        $cleaned_values = array();
4300
-        foreach ($values as $value) {
4301
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4302
-        }
4303
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4304
-    }
4305
-
4306
-
4307
-
4308
-    /**
4309
-     * Takes an array or a comma-separated list of $values and cleans them
4310
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4311
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4312
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4313
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4314
-     *
4315
-     * @param mixed                      $values    array or comma-separated string
4316
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4317
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4318
-     * @throws EE_Error
4319
-     */
4320
-    public function _construct_in_value($values, $field_obj)
4321
-    {
4322
-        //check if the value is a CSV list
4323
-        if (is_string($values)) {
4324
-            //in which case, turn it into an array
4325
-            $values = explode(",", $values);
4326
-        }
4327
-        $cleaned_values = array();
4328
-        foreach ($values as $value) {
4329
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4330
-        }
4331
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4332
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4333
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4334
-        if (empty($cleaned_values)) {
4335
-            $all_fields = $this->field_settings();
4336
-            $a_field = array_shift($all_fields);
4337
-            $main_table = $this->_get_main_table();
4338
-            $cleaned_values[] = "SELECT "
4339
-                                . $a_field->get_table_column()
4340
-                                . " FROM "
4341
-                                . $main_table->get_table_name()
4342
-                                . " WHERE FALSE";
4343
-        }
4344
-        return "(" . implode(",", $cleaned_values) . ")";
4345
-    }
4346
-
4347
-
4348
-
4349
-    /**
4350
-     * @param mixed                      $value
4351
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4352
-     * @throws EE_Error
4353
-     * @return false|null|string
4354
-     */
4355
-    private function _wpdb_prepare_using_field($value, $field_obj)
4356
-    {
4357
-        /** @type WPDB $wpdb */
4358
-        global $wpdb;
4359
-        if ($field_obj instanceof EE_Model_Field_Base) {
4360
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4361
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4362
-        } //$field_obj should really just be a data type
4363
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4364
-            throw new EE_Error(
4365
-                sprintf(
4366
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4367
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4368
-                )
4369
-            );
4370
-        }
4371
-        return $wpdb->prepare($field_obj, $value);
4372
-    }
4373
-
4374
-
4375
-
4376
-    /**
4377
-     * Takes the input parameter and finds the model field that it indicates.
4378
-     *
4379
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4380
-     * @throws EE_Error
4381
-     * @return EE_Model_Field_Base
4382
-     */
4383
-    protected function _deduce_field_from_query_param($query_param_name)
4384
-    {
4385
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4386
-        //which will help us find the database table and column
4387
-        $query_param_parts = explode(".", $query_param_name);
4388
-        if (empty($query_param_parts)) {
4389
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4390
-                'event_espresso'), $query_param_name));
4391
-        }
4392
-        $number_of_parts = count($query_param_parts);
4393
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4394
-        if ($number_of_parts === 1) {
4395
-            $field_name = $last_query_param_part;
4396
-            $model_obj = $this;
4397
-        } else {// $number_of_parts >= 2
4398
-            //the last part is the column name, and there are only 2parts. therefore...
4399
-            $field_name = $last_query_param_part;
4400
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4401
-        }
4402
-        try {
4403
-            return $model_obj->field_settings_for($field_name);
4404
-        } catch (EE_Error $e) {
4405
-            return null;
4406
-        }
4407
-    }
4408
-
4409
-
4410
-
4411
-    /**
4412
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4413
-     * alias and column which corresponds to it
4414
-     *
4415
-     * @param string $field_name
4416
-     * @throws EE_Error
4417
-     * @return string
4418
-     */
4419
-    public function _get_qualified_column_for_field($field_name)
4420
-    {
4421
-        $all_fields = $this->field_settings();
4422
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4423
-        if ($field) {
4424
-            return $field->get_qualified_column();
4425
-        }
4426
-        throw new EE_Error(
4427
-            sprintf(
4428
-                __(
4429
-                    "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.",
4430
-                    'event_espresso'
4431
-                ), $field_name, get_class($this)
4432
-            )
4433
-        );
4434
-    }
4435
-
4436
-
4437
-
4438
-    /**
4439
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4440
-     * Example usage:
4441
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4442
-     *      array(),
4443
-     *      ARRAY_A,
4444
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4445
-     *  );
4446
-     * is equivalent to
4447
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4448
-     * and
4449
-     *  EEM_Event::instance()->get_all_wpdb_results(
4450
-     *      array(
4451
-     *          array(
4452
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4453
-     *          ),
4454
-     *          ARRAY_A,
4455
-     *          implode(
4456
-     *              ', ',
4457
-     *              array_merge(
4458
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4459
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4460
-     *              )
4461
-     *          )
4462
-     *      )
4463
-     *  );
4464
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4465
-     *
4466
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4467
-     *                                            and the one whose fields you are selecting for example: when querying
4468
-     *                                            tickets model and selecting fields from the tickets model you would
4469
-     *                                            leave this parameter empty, because no models are needed to join
4470
-     *                                            between the queried model and the selected one. Likewise when
4471
-     *                                            querying the datetime model and selecting fields from the tickets
4472
-     *                                            model, it would also be left empty, because there is a direct
4473
-     *                                            relation from datetimes to tickets, so no model is needed to join
4474
-     *                                            them together. However, when querying from the event model and
4475
-     *                                            selecting fields from the ticket model, you should provide the string
4476
-     *                                            'Datetime', indicating that the event model must first join to the
4477
-     *                                            datetime model in order to find its relation to ticket model.
4478
-     *                                            Also, when querying from the venue model and selecting fields from
4479
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4480
-     *                                            indicating you need to join the venue model to the event model,
4481
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4482
-     *                                            This string is used to deduce the prefix that gets added onto the
4483
-     *                                            models' tables qualified columns
4484
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4485
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4486
-     *                                            qualified column names
4487
-     * @return array|string
4488
-     */
4489
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4490
-    {
4491
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4492
-        $qualified_columns = array();
4493
-        foreach ($this->field_settings() as $field_name => $field) {
4494
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4495
-        }
4496
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4497
-    }
4498
-
4499
-
4500
-
4501
-    /**
4502
-     * constructs the select use on special limit joins
4503
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4504
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4505
-     * (as that is typically where the limits would be set).
4506
-     *
4507
-     * @param  string       $table_alias The table the select is being built for
4508
-     * @param  mixed|string $limit       The limit for this select
4509
-     * @return string                The final select join element for the query.
4510
-     */
4511
-    public function _construct_limit_join_select($table_alias, $limit)
4512
-    {
4513
-        $SQL = '';
4514
-        foreach ($this->_tables as $table_obj) {
4515
-            if ($table_obj instanceof EE_Primary_Table) {
4516
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4517
-                    ? $table_obj->get_select_join_limit($limit)
4518
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4519
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4520
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4521
-                    ? $table_obj->get_select_join_limit_join($limit)
4522
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4523
-            }
4524
-        }
4525
-        return $SQL;
4526
-    }
4527
-
4528
-
4529
-
4530
-    /**
4531
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4532
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4533
-     *
4534
-     * @return string SQL
4535
-     * @throws EE_Error
4536
-     */
4537
-    public function _construct_internal_join()
4538
-    {
4539
-        $SQL = $this->_get_main_table()->get_table_sql();
4540
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4541
-        return $SQL;
4542
-    }
4543
-
4544
-
4545
-
4546
-    /**
4547
-     * Constructs the SQL for joining all the tables on this model.
4548
-     * Normally $alias should be the primary table's alias, but in cases where
4549
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4550
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4551
-     * alias, this will construct SQL like:
4552
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4553
-     * With $alias being a secondary table's alias, this will construct SQL like:
4554
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4555
-     *
4556
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4557
-     * @return string
4558
-     */
4559
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4560
-    {
4561
-        $SQL = '';
4562
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4563
-        foreach ($this->_tables as $table_obj) {
4564
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4565
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4566
-                    //so we're joining to this table, meaning the table is already in
4567
-                    //the FROM statement, BUT the primary table isn't. So we want
4568
-                    //to add the inverse join sql
4569
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4570
-                } else {
4571
-                    //just add a regular JOIN to this table from the primary table
4572
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4573
-                }
4574
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4575
-        }
4576
-        return $SQL;
4577
-    }
4578
-
4579
-
4580
-
4581
-    /**
4582
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4583
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4584
-     * their data type (eg, '%s', '%d', etc)
4585
-     *
4586
-     * @return array
4587
-     */
4588
-    public function _get_data_types()
4589
-    {
4590
-        $data_types = array();
4591
-        foreach ($this->field_settings() as $field_obj) {
4592
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4593
-            /** @var $field_obj EE_Model_Field_Base */
4594
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4595
-        }
4596
-        return $data_types;
4597
-    }
4598
-
4599
-
4600
-
4601
-    /**
4602
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4603
-     *
4604
-     * @param string $model_name
4605
-     * @throws EE_Error
4606
-     * @return EEM_Base
4607
-     */
4608
-    public function get_related_model_obj($model_name)
4609
-    {
4610
-        $model_classname = "EEM_" . $model_name;
4611
-        if (! class_exists($model_classname)) {
4612
-            throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4613
-                'event_espresso'), $model_name, $model_classname));
4614
-        }
4615
-        return call_user_func($model_classname . "::instance");
4616
-    }
4617
-
4618
-
4619
-
4620
-    /**
4621
-     * Returns the array of EE_ModelRelations for this model.
4622
-     *
4623
-     * @return EE_Model_Relation_Base[]
4624
-     */
4625
-    public function relation_settings()
4626
-    {
4627
-        return $this->_model_relations;
4628
-    }
4629
-
4630
-
4631
-
4632
-    /**
4633
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4634
-     * because without THOSE models, this model probably doesn't have much purpose.
4635
-     * (Eg, without an event, datetimes have little purpose.)
4636
-     *
4637
-     * @return EE_Belongs_To_Relation[]
4638
-     */
4639
-    public function belongs_to_relations()
4640
-    {
4641
-        $belongs_to_relations = array();
4642
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4643
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4644
-                $belongs_to_relations[$model_name] = $relation_obj;
4645
-            }
4646
-        }
4647
-        return $belongs_to_relations;
4648
-    }
4649
-
4650
-
4651
-
4652
-    /**
4653
-     * Returns the specified EE_Model_Relation, or throws an exception
4654
-     *
4655
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4656
-     * @throws EE_Error
4657
-     * @return EE_Model_Relation_Base
4658
-     */
4659
-    public function related_settings_for($relation_name)
4660
-    {
4661
-        $relatedModels = $this->relation_settings();
4662
-        if (! array_key_exists($relation_name, $relatedModels)) {
4663
-            throw new EE_Error(
4664
-                sprintf(
4665
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4666
-                        'event_espresso'),
4667
-                    $relation_name,
4668
-                    $this->_get_class_name(),
4669
-                    implode(', ', array_keys($relatedModels))
4670
-                )
4671
-            );
4672
-        }
4673
-        return $relatedModels[$relation_name];
4674
-    }
4675
-
4676
-
4677
-
4678
-    /**
4679
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4680
-     * fields
4681
-     *
4682
-     * @param string $fieldName
4683
-     * @param boolean $include_db_only_fields
4684
-     * @throws EE_Error
4685
-     * @return EE_Model_Field_Base
4686
-     */
4687
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4688
-    {
4689
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4690
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4691
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4692
-                get_class($this)));
4693
-        }
4694
-        return $fieldSettings[$fieldName];
4695
-    }
4696
-
4697
-
4698
-
4699
-    /**
4700
-     * Checks if this field exists on this model
4701
-     *
4702
-     * @param string $fieldName a key in the model's _field_settings array
4703
-     * @return boolean
4704
-     */
4705
-    public function has_field($fieldName)
4706
-    {
4707
-        $fieldSettings = $this->field_settings(true);
4708
-        if (isset($fieldSettings[$fieldName])) {
4709
-            return true;
4710
-        }
4711
-        return false;
4712
-    }
4713
-
4714
-
4715
-
4716
-    /**
4717
-     * Returns whether or not this model has a relation to the specified model
4718
-     *
4719
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4720
-     * @return boolean
4721
-     */
4722
-    public function has_relation($relation_name)
4723
-    {
4724
-        $relations = $this->relation_settings();
4725
-        if (isset($relations[$relation_name])) {
4726
-            return true;
4727
-        }
4728
-        return false;
4729
-    }
4730
-
4731
-
4732
-
4733
-    /**
4734
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4735
-     * Eg, on EE_Answer that would be ANS_ID field object
4736
-     *
4737
-     * @param $field_obj
4738
-     * @return boolean
4739
-     */
4740
-    public function is_primary_key_field($field_obj)
4741
-    {
4742
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4743
-    }
4744
-
4745
-
4746
-
4747
-    /**
4748
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4749
-     * Eg, on EE_Answer that would be ANS_ID field object
4750
-     *
4751
-     * @return EE_Model_Field_Base
4752
-     * @throws EE_Error
4753
-     */
4754
-    public function get_primary_key_field()
4755
-    {
4756
-        if ($this->_primary_key_field === null) {
4757
-            foreach ($this->field_settings(true) as $field_obj) {
4758
-                if ($this->is_primary_key_field($field_obj)) {
4759
-                    $this->_primary_key_field = $field_obj;
4760
-                    break;
4761
-                }
4762
-            }
4763
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4764
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4765
-                    get_class($this)));
4766
-            }
4767
-        }
4768
-        return $this->_primary_key_field;
4769
-    }
4770
-
4771
-
4772
-
4773
-    /**
4774
-     * Returns whether or not not there is a primary key on this model.
4775
-     * Internally does some caching.
4776
-     *
4777
-     * @return boolean
4778
-     */
4779
-    public function has_primary_key_field()
4780
-    {
4781
-        if ($this->_has_primary_key_field === null) {
4782
-            try {
4783
-                $this->get_primary_key_field();
4784
-                $this->_has_primary_key_field = true;
4785
-            } catch (EE_Error $e) {
4786
-                $this->_has_primary_key_field = false;
4787
-            }
4788
-        }
4789
-        return $this->_has_primary_key_field;
4790
-    }
4791
-
4792
-
4793
-
4794
-    /**
4795
-     * Finds the first field of type $field_class_name.
4796
-     *
4797
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4798
-     *                                 EE_Foreign_Key_Field, etc
4799
-     * @return EE_Model_Field_Base or null if none is found
4800
-     */
4801
-    public function get_a_field_of_type($field_class_name)
4802
-    {
4803
-        foreach ($this->field_settings() as $field) {
4804
-            if ($field instanceof $field_class_name) {
4805
-                return $field;
4806
-            }
4807
-        }
4808
-        return null;
4809
-    }
4810
-
4811
-
4812
-
4813
-    /**
4814
-     * Gets a foreign key field pointing to model.
4815
-     *
4816
-     * @param string $model_name eg Event, Registration, not EEM_Event
4817
-     * @return EE_Foreign_Key_Field_Base
4818
-     * @throws EE_Error
4819
-     */
4820
-    public function get_foreign_key_to($model_name)
4821
-    {
4822
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4823
-            foreach ($this->field_settings() as $field) {
4824
-                if (
4825
-                    $field instanceof EE_Foreign_Key_Field_Base
4826
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4827
-                ) {
4828
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4829
-                    break;
4830
-                }
4831
-            }
4832
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4834
-                    'event_espresso'), $model_name, get_class($this)));
4835
-            }
4836
-        }
4837
-        return $this->_cache_foreign_key_to_fields[$model_name];
4838
-    }
4839
-
4840
-
4841
-
4842
-    /**
4843
-     * Gets the table name (including $wpdb->prefix) for the table alias
4844
-     *
4845
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4846
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4847
-     *                            Either one works
4848
-     * @return string
4849
-     */
4850
-    public function get_table_for_alias($table_alias)
4851
-    {
4852
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4853
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4854
-    }
4855
-
4856
-
4857
-
4858
-    /**
4859
-     * Returns a flat array of all field son this model, instead of organizing them
4860
-     * by table_alias as they are in the constructor.
4861
-     *
4862
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4863
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4864
-     */
4865
-    public function field_settings($include_db_only_fields = false)
4866
-    {
4867
-        if ($include_db_only_fields) {
4868
-            if ($this->_cached_fields === null) {
4869
-                $this->_cached_fields = array();
4870
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4871
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4872
-                        $this->_cached_fields[$field_name] = $field_obj;
4873
-                    }
4874
-                }
4875
-            }
4876
-            return $this->_cached_fields;
4877
-        }
4878
-        if ($this->_cached_fields_non_db_only === null) {
4879
-            $this->_cached_fields_non_db_only = array();
4880
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4881
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882
-                    /** @var $field_obj EE_Model_Field_Base */
4883
-                    if (! $field_obj->is_db_only_field()) {
4884
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4885
-                    }
4886
-                }
4887
-            }
4888
-        }
4889
-        return $this->_cached_fields_non_db_only;
4890
-    }
4891
-
4892
-
4893
-
4894
-    /**
4895
-     *        cycle though array of attendees and create objects out of each item
4896
-     *
4897
-     * @access        private
4898
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4899
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4900
-     *                           numerically indexed)
4901
-     * @throws EE_Error
4902
-     */
4903
-    protected function _create_objects($rows = array())
4904
-    {
4905
-        $array_of_objects = array();
4906
-        if (empty($rows)) {
4907
-            return array();
4908
-        }
4909
-        $count_if_model_has_no_primary_key = 0;
4910
-        $has_primary_key = $this->has_primary_key_field();
4911
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4912
-        foreach ((array)$rows as $row) {
4913
-            if (empty($row)) {
4914
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4915
-                return array();
4916
-            }
4917
-            //check if we've already set this object in the results array,
4918
-            //in which case there's no need to process it further (again)
4919
-            if ($has_primary_key) {
4920
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4921
-                    $row,
4922
-                    $primary_key_field->get_qualified_column(),
4923
-                    $primary_key_field->get_table_column()
4924
-                );
4925
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4926
-                    continue;
4927
-                }
4928
-            }
4929
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4930
-            if (! $classInstance) {
4931
-                throw new EE_Error(
4932
-                    sprintf(
4933
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4934
-                        $this->get_this_model_name(),
4935
-                        http_build_query($row)
4936
-                    )
4937
-                );
4938
-            }
4939
-            //set the timezone on the instantiated objects
4940
-            $classInstance->set_timezone($this->_timezone);
4941
-            //make sure if there is any timezone setting present that we set the timezone for the object
4942
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4943
-            $array_of_objects[$key] = $classInstance;
4944
-            //also, for all the relations of type BelongsTo, see if we can cache
4945
-            //those related models
4946
-            //(we could do this for other relations too, but if there are conditions
4947
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4948
-            //so it requires a little more thought than just caching them immediately...)
4949
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4950
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4951
-                    //check if this model's INFO is present. If so, cache it on the model
4952
-                    $other_model = $relation_obj->get_other_model();
4953
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4954
-                    //if we managed to make a model object from the results, cache it on the main model object
4955
-                    if ($other_model_obj_maybe) {
4956
-                        //set timezone on these other model objects if they are present
4957
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4958
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4959
-                    }
4960
-                }
4961
-            }
4962
-        }
4963
-        return $array_of_objects;
4964
-    }
4965
-
4966
-
4967
-
4968
-    /**
4969
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4970
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4971
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4972
-     * object (as set in the model_field!).
4973
-     *
4974
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4975
-     */
4976
-    public function create_default_object()
4977
-    {
4978
-        $this_model_fields_and_values = array();
4979
-        //setup the row using default values;
4980
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4981
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4982
-        }
4983
-        $className = $this->_get_class_name();
4984
-        $classInstance = EE_Registry::instance()
4985
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4986
-        return $classInstance;
4987
-    }
4988
-
4989
-
4990
-
4991
-    /**
4992
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4993
-     *                             or an stdClass where each property is the name of a column,
4994
-     * @return EE_Base_Class
4995
-     * @throws EE_Error
4996
-     */
4997
-    public function instantiate_class_from_array_or_object($cols_n_values)
4998
-    {
4999
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5000
-            $cols_n_values = get_object_vars($cols_n_values);
5001
-        }
5002
-        $primary_key = null;
5003
-        //make sure the array only has keys that are fields/columns on this model
5004
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5005
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5006
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5007
-        }
5008
-        $className = $this->_get_class_name();
5009
-        //check we actually found results that we can use to build our model object
5010
-        //if not, return null
5011
-        if ($this->has_primary_key_field()) {
5012
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5013
-                return null;
5014
-            }
5015
-        } else if ($this->unique_indexes()) {
5016
-            $first_column = reset($this_model_fields_n_values);
5017
-            if (empty($first_column)) {
5018
-                return null;
5019
-            }
5020
-        }
5021
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5022
-        if ($primary_key) {
5023
-            $classInstance = $this->get_from_entity_map($primary_key);
5024
-            if (! $classInstance) {
5025
-                $classInstance = EE_Registry::instance()
5026
-                                            ->load_class($className,
5027
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5028
-                // add this new object to the entity map
5029
-                $classInstance = $this->add_to_entity_map($classInstance);
5030
-            }
5031
-        } else {
5032
-            $classInstance = EE_Registry::instance()
5033
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5034
-                                            true, false);
5035
-        }
5036
-        return $classInstance;
5037
-    }
5038
-
5039
-
5040
-
5041
-    /**
5042
-     * Gets the model object from the  entity map if it exists
5043
-     *
5044
-     * @param int|string $id the ID of the model object
5045
-     * @return EE_Base_Class
5046
-     */
5047
-    public function get_from_entity_map($id)
5048
-    {
5049
-        return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5050
-            ? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5051
-    }
5052
-
5053
-
5054
-
5055
-    /**
5056
-     * add_to_entity_map
5057
-     * Adds the object to the model's entity mappings
5058
-     *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5059
-     *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5060
-     *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5061
-     *        If the database gets updated directly and you want the entity mapper to reflect that change,
5062
-     *        then this method should be called immediately after the update query
5063
-     * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5064
-     * so on multisite, the entity map is specific to the query being done for a specific site.
5065
-     *
5066
-     * @param    EE_Base_Class $object
5067
-     * @throws EE_Error
5068
-     * @return \EE_Base_Class
5069
-     */
5070
-    public function add_to_entity_map(EE_Base_Class $object)
5071
-    {
5072
-        $className = $this->_get_class_name();
5073
-        if (! $object instanceof $className) {
5074
-            throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5075
-                is_object($object) ? get_class($object) : $object, $className));
5076
-        }
5077
-        /** @var $object EE_Base_Class */
5078
-        if (! $object->ID()) {
5079
-            throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5080
-                "event_espresso"), get_class($this)));
5081
-        }
5082
-        // double check it's not already there
5083
-        $classInstance = $this->get_from_entity_map($object->ID());
5084
-        if ($classInstance) {
5085
-            return $classInstance;
5086
-        }
5087
-        $this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5088
-        return $object;
5089
-    }
5090
-
5091
-
5092
-
5093
-    /**
5094
-     * if a valid identifier is provided, then that entity is unset from the entity map,
5095
-     * if no identifier is provided, then the entire entity map is emptied
5096
-     *
5097
-     * @param int|string $id the ID of the model object
5098
-     * @return boolean
5099
-     */
5100
-    public function clear_entity_map($id = null)
5101
-    {
5102
-        if (empty($id)) {
5103
-            $this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5104
-            return true;
5105
-        }
5106
-        if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5107
-            unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5108
-            return true;
5109
-        }
5110
-        return false;
5111
-    }
5112
-
5113
-
5114
-
5115
-    /**
5116
-     * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5117
-     * Given an array where keys are column (or column alias) names and values,
5118
-     * returns an array of their corresponding field names and database values
5119
-     *
5120
-     * @param array $cols_n_values
5121
-     * @return array
5122
-     */
5123
-    public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5124
-    {
5125
-        return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5126
-    }
5127
-
5128
-
5129
-
5130
-    /**
5131
-     * _deduce_fields_n_values_from_cols_n_values
5132
-     * Given an array where keys are column (or column alias) names and values,
5133
-     * returns an array of their corresponding field names and database values
5134
-     *
5135
-     * @param string $cols_n_values
5136
-     * @return array
5137
-     */
5138
-    protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5139
-    {
5140
-        $this_model_fields_n_values = array();
5141
-        foreach ($this->get_tables() as $table_alias => $table_obj) {
5142
-            $table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5143
-                $table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5144
-            //there is a primary key on this table and its not set. Use defaults for all its columns
5145
-            if ($table_pk_value === null && $table_obj->get_pk_column()) {
5146
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5147
-                    if (! $field_obj->is_db_only_field()) {
5148
-                        //prepare field as if its coming from db
5149
-                        $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5150
-                        $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5151
-                    }
5152
-                }
5153
-            } else {
5154
-                //the table's rows existed. Use their values
5155
-                foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5156
-                    if (! $field_obj->is_db_only_field()) {
5157
-                        $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5158
-                            $cols_n_values, $field_obj->get_qualified_column(),
5159
-                            $field_obj->get_table_column()
5160
-                        );
5161
-                    }
5162
-                }
5163
-            }
5164
-        }
5165
-        return $this_model_fields_n_values;
5166
-    }
5167
-
5168
-
5169
-
5170
-    /**
5171
-     * @param $cols_n_values
5172
-     * @param $qualified_column
5173
-     * @param $regular_column
5174
-     * @return null
5175
-     */
5176
-    protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5177
-    {
5178
-        $value = null;
5179
-        //ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5180
-        //does the field on the model relate to this column retrieved from the db?
5181
-        //or is it a db-only field? (not relating to the model)
5182
-        if (isset($cols_n_values[$qualified_column])) {
5183
-            $value = $cols_n_values[$qualified_column];
5184
-        } elseif (isset($cols_n_values[$regular_column])) {
5185
-            $value = $cols_n_values[$regular_column];
5186
-        }
5187
-        return $value;
5188
-    }
5189
-
5190
-
5191
-
5192
-    /**
5193
-     * refresh_entity_map_from_db
5194
-     * Makes sure the model object in the entity map at $id assumes the values
5195
-     * of the database (opposite of EE_base_Class::save())
5196
-     *
5197
-     * @param int|string $id
5198
-     * @return EE_Base_Class
5199
-     * @throws EE_Error
5200
-     */
5201
-    public function refresh_entity_map_from_db($id)
5202
-    {
5203
-        $obj_in_map = $this->get_from_entity_map($id);
5204
-        if ($obj_in_map) {
5205
-            $wpdb_results = $this->_get_all_wpdb_results(
5206
-                array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5207
-            );
5208
-            if ($wpdb_results && is_array($wpdb_results)) {
5209
-                $one_row = reset($wpdb_results);
5210
-                foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5211
-                    $obj_in_map->set_from_db($field_name, $db_value);
5212
-                }
5213
-                //clear the cache of related model objects
5214
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5215
-                    $obj_in_map->clear_cache($relation_name, null, true);
5216
-                }
5217
-            }
5218
-            $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5219
-            return $obj_in_map;
5220
-        }
5221
-        return $this->get_one_by_ID($id);
5222
-    }
5223
-
5224
-
5225
-
5226
-    /**
5227
-     * refresh_entity_map_with
5228
-     * Leaves the entry in the entity map alone, but updates it to match the provided
5229
-     * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5230
-     * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5231
-     * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5232
-     *
5233
-     * @param int|string    $id
5234
-     * @param EE_Base_Class $replacing_model_obj
5235
-     * @return \EE_Base_Class
5236
-     * @throws EE_Error
5237
-     */
5238
-    public function refresh_entity_map_with($id, $replacing_model_obj)
5239
-    {
5240
-        $obj_in_map = $this->get_from_entity_map($id);
5241
-        if ($obj_in_map) {
5242
-            if ($replacing_model_obj instanceof EE_Base_Class) {
5243
-                foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5244
-                    $obj_in_map->set($field_name, $value);
5245
-                }
5246
-                //make the model object in the entity map's cache match the $replacing_model_obj
5247
-                foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5248
-                    $obj_in_map->clear_cache($relation_name, null, true);
5249
-                    foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5250
-                        $obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5251
-                    }
5252
-                }
5253
-            }
5254
-            return $obj_in_map;
5255
-        }
5256
-        $this->add_to_entity_map($replacing_model_obj);
5257
-        return $replacing_model_obj;
5258
-    }
5259
-
5260
-
5261
-
5262
-    /**
5263
-     * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5264
-     * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5265
-     * require_once($this->_getClassName().".class.php");
5266
-     *
5267
-     * @return string
5268
-     */
5269
-    private function _get_class_name()
5270
-    {
5271
-        return "EE_" . $this->get_this_model_name();
5272
-    }
5273
-
5274
-
5275
-
5276
-    /**
5277
-     * Get the name of the items this model represents, for the quantity specified. Eg,
5278
-     * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5279
-     * it would be 'Events'.
5280
-     *
5281
-     * @param int $quantity
5282
-     * @return string
5283
-     */
5284
-    public function item_name($quantity = 1)
5285
-    {
5286
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5287
-    }
5288
-
5289
-
5290
-
5291
-    /**
5292
-     * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5293
-     * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5294
-     * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5295
-     * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5296
-     * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5297
-     * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5298
-     * was called, and an array of the original arguments passed to the function. Whatever their callback function
5299
-     * returns will be returned by this function. Example: in functions.php (or in a plugin):
5300
-     * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5301
-     * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5302
-     * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5303
-     *        return $previousReturnValue.$returnString;
5304
-     * }
5305
-     * require('EEM_Answer.model.php');
5306
-     * $answer=EEM_Answer::instance();
5307
-     * echo $answer->my_callback('monkeys',100);
5308
-     * //will output "you called my_callback! and passed args:monkeys,100"
5309
-     *
5310
-     * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5311
-     * @param array  $args       array of original arguments passed to the function
5312
-     * @throws EE_Error
5313
-     * @return mixed whatever the plugin which calls add_filter decides
5314
-     */
5315
-    public function __call($methodName, $args)
5316
-    {
5317
-        $className = get_class($this);
5318
-        $tagName = "FHEE__{$className}__{$methodName}";
5319
-        if (! has_filter($tagName)) {
5320
-            throw new EE_Error(
5321
-                sprintf(
5322
-                    __('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 );',
5323
-                        'event_espresso'),
5324
-                    $methodName,
5325
-                    $className,
5326
-                    $tagName,
5327
-                    '<br />'
5328
-                )
5329
-            );
5330
-        }
5331
-        return apply_filters($tagName, null, $this, $args);
5332
-    }
5333
-
5334
-
5335
-
5336
-    /**
5337
-     * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5338
-     * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5339
-     *
5340
-     * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5341
-     *                                                       the EE_Base_Class object that corresponds to this Model,
5342
-     *                                                       the object's class name
5343
-     *                                                       or object's ID
5344
-     * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5345
-     *                                                       exists in the database. If it does not, we add it
5346
-     * @throws EE_Error
5347
-     * @return EE_Base_Class
5348
-     */
5349
-    public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5350
-    {
5351
-        $className = $this->_get_class_name();
5352
-        if ($base_class_obj_or_id instanceof $className) {
5353
-            $model_object = $base_class_obj_or_id;
5354
-        } else {
5355
-            $primary_key_field = $this->get_primary_key_field();
5356
-            if (
5357
-                $primary_key_field instanceof EE_Primary_Key_Int_Field
5358
-                && (
5359
-                    is_int($base_class_obj_or_id)
5360
-                    || is_string($base_class_obj_or_id)
5361
-                )
5362
-            ) {
5363
-                // assume it's an ID.
5364
-                // either a proper integer or a string representing an integer (eg "101" instead of 101)
5365
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5366
-            } else if (
5367
-                $primary_key_field instanceof EE_Primary_Key_String_Field
5368
-                && is_string($base_class_obj_or_id)
5369
-            ) {
5370
-                // assume its a string representation of the object
5371
-                $model_object = $this->get_one_by_ID($base_class_obj_or_id);
5372
-            } else {
5373
-                throw new EE_Error(
5374
-                    sprintf(
5375
-                        __(
5376
-                            "'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5377
-                            'event_espresso'
5378
-                        ),
5379
-                        $base_class_obj_or_id,
5380
-                        $this->_get_class_name(),
5381
-                        print_r($base_class_obj_or_id, true)
5382
-                    )
5383
-                );
5384
-            }
5385
-        }
5386
-        if ($ensure_is_in_db && $model_object->ID() !== null) {
5387
-            $model_object->save();
5388
-        }
5389
-        return $model_object;
5390
-    }
5391
-
5392
-
5393
-
5394
-    /**
5395
-     * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5396
-     * is a value of the this model's primary key. If it's an EE_Base_Class child,
5397
-     * returns it ID.
5398
-     *
5399
-     * @param EE_Base_Class|int|string $base_class_obj_or_id
5400
-     * @return int|string depending on the type of this model object's ID
5401
-     * @throws EE_Error
5402
-     */
5403
-    public function ensure_is_ID($base_class_obj_or_id)
5404
-    {
5405
-        $className = $this->_get_class_name();
5406
-        if ($base_class_obj_or_id instanceof $className) {
5407
-            /** @var $base_class_obj_or_id EE_Base_Class */
5408
-            $id = $base_class_obj_or_id->ID();
5409
-        } elseif (is_int($base_class_obj_or_id)) {
5410
-            //assume it's an ID
5411
-            $id = $base_class_obj_or_id;
5412
-        } elseif (is_string($base_class_obj_or_id)) {
5413
-            //assume its a string representation of the object
5414
-            $id = $base_class_obj_or_id;
5415
-        } else {
5416
-            throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5417
-                'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5418
-                print_r($base_class_obj_or_id, true)));
5419
-        }
5420
-        return $id;
5421
-    }
5422
-
5423
-
5424
-
5425
-    /**
5426
-     * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5427
-     * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5428
-     * been sanitized and converted into the appropriate domain.
5429
-     * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5430
-     * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5431
-     * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5432
-     * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5433
-     * $EVT = EEM_Event::instance(); $old_setting =
5434
-     * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5435
-     * $EVT->assume_values_already_prepared_by_model_object(true);
5436
-     * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5437
-     * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5438
-     *
5439
-     * @param int $values_already_prepared like one of the constants on EEM_Base
5440
-     * @return void
5441
-     */
5442
-    public function assume_values_already_prepared_by_model_object(
5443
-        $values_already_prepared = self::not_prepared_by_model_object
5444
-    ) {
5445
-        $this->_values_already_prepared_by_model_object = $values_already_prepared;
5446
-    }
5447
-
5448
-
5449
-
5450
-    /**
5451
-     * Read comments for assume_values_already_prepared_by_model_object()
5452
-     *
5453
-     * @return int
5454
-     */
5455
-    public function get_assumption_concerning_values_already_prepared_by_model_object()
5456
-    {
5457
-        return $this->_values_already_prepared_by_model_object;
5458
-    }
5459
-
5460
-
5461
-
5462
-    /**
5463
-     * Gets all the indexes on this model
5464
-     *
5465
-     * @return EE_Index[]
5466
-     */
5467
-    public function indexes()
5468
-    {
5469
-        return $this->_indexes;
5470
-    }
5471
-
5472
-
5473
-
5474
-    /**
5475
-     * Gets all the Unique Indexes on this model
5476
-     *
5477
-     * @return EE_Unique_Index[]
5478
-     */
5479
-    public function unique_indexes()
5480
-    {
5481
-        $unique_indexes = array();
5482
-        foreach ($this->_indexes as $name => $index) {
5483
-            if ($index instanceof EE_Unique_Index) {
5484
-                $unique_indexes [$name] = $index;
5485
-            }
5486
-        }
5487
-        return $unique_indexes;
5488
-    }
5489
-
5490
-
5491
-
5492
-    /**
5493
-     * Gets all the fields which, when combined, make the primary key.
5494
-     * This is usually just an array with 1 element (the primary key), but in cases
5495
-     * where there is no primary key, it's a combination of fields as defined
5496
-     * on a primary index
5497
-     *
5498
-     * @return EE_Model_Field_Base[] indexed by the field's name
5499
-     * @throws EE_Error
5500
-     */
5501
-    public function get_combined_primary_key_fields()
5502
-    {
5503
-        foreach ($this->indexes() as $index) {
5504
-            if ($index instanceof EE_Primary_Key_Index) {
5505
-                return $index->fields();
5506
-            }
5507
-        }
5508
-        return array($this->primary_key_name() => $this->get_primary_key_field());
5509
-    }
5510
-
5511
-
5512
-
5513
-    /**
5514
-     * Used to build a primary key string (when the model has no primary key),
5515
-     * which can be used a unique string to identify this model object.
5516
-     *
5517
-     * @param array $cols_n_values keys are field names, values are their values
5518
-     * @return string
5519
-     * @throws EE_Error
5520
-     */
5521
-    public function get_index_primary_key_string($cols_n_values)
5522
-    {
5523
-        $cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5524
-            $this->get_combined_primary_key_fields());
5525
-        return http_build_query($cols_n_values_for_primary_key_index);
5526
-    }
5527
-
5528
-
5529
-
5530
-    /**
5531
-     * Gets the field values from the primary key string
5532
-     *
5533
-     * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5534
-     * @param string $index_primary_key_string
5535
-     * @return null|array
5536
-     * @throws EE_Error
5537
-     */
5538
-    public function parse_index_primary_key_string($index_primary_key_string)
5539
-    {
5540
-        $key_fields = $this->get_combined_primary_key_fields();
5541
-        //check all of them are in the $id
5542
-        $key_vals_in_combined_pk = array();
5543
-        parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5544
-        foreach ($key_fields as $key_field_name => $field_obj) {
5545
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5546
-                return null;
5547
-            }
5548
-        }
5549
-        return $key_vals_in_combined_pk;
5550
-    }
5551
-
5552
-
5553
-
5554
-    /**
5555
-     * verifies that an array of key-value pairs for model fields has a key
5556
-     * for each field comprising the primary key index
5557
-     *
5558
-     * @param array $key_vals
5559
-     * @return boolean
5560
-     * @throws EE_Error
5561
-     */
5562
-    public function has_all_combined_primary_key_fields($key_vals)
5563
-    {
5564
-        $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5565
-        foreach ($keys_it_should_have as $key) {
5566
-            if (! isset($key_vals[$key])) {
5567
-                return false;
5568
-            }
5569
-        }
5570
-        return true;
5571
-    }
5572
-
5573
-
5574
-
5575
-    /**
5576
-     * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5577
-     * We consider something to be a copy if all the attributes match (except the ID, of course).
5578
-     *
5579
-     * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5580
-     * @param array               $query_params                     like EEM_Base::get_all's query_params.
5581
-     * @throws EE_Error
5582
-     * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5583
-     *                                                              indexed)
5584
-     */
5585
-    public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5586
-    {
5587
-        if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5588
-            $attributes_array = $model_object_or_attributes_array->model_field_array();
5589
-        } elseif (is_array($model_object_or_attributes_array)) {
5590
-            $attributes_array = $model_object_or_attributes_array;
5591
-        } else {
5592
-            throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5593
-                "event_espresso"), $model_object_or_attributes_array));
5594
-        }
5595
-        //even copies obviously won't have the same ID, so remove the primary key
5596
-        //from the WHERE conditions for finding copies (if there is a primary key, of course)
5597
-        if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5598
-            unset($attributes_array[$this->primary_key_name()]);
5599
-        }
5600
-        if (isset($query_params[0])) {
5601
-            $query_params[0] = array_merge($attributes_array, $query_params);
5602
-        } else {
5603
-            $query_params[0] = $attributes_array;
5604
-        }
5605
-        return $this->get_all($query_params);
5606
-    }
5607
-
5608
-
5609
-
5610
-    /**
5611
-     * Gets the first copy we find. See get_all_copies for more details
5612
-     *
5613
-     * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5614
-     * @param array $query_params
5615
-     * @return EE_Base_Class
5616
-     * @throws EE_Error
5617
-     */
5618
-    public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5619
-    {
5620
-        if (! is_array($query_params)) {
5621
-            EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5622
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5623
-                    gettype($query_params)), '4.6.0');
5624
-            $query_params = array();
5625
-        }
5626
-        $query_params['limit'] = 1;
5627
-        $copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5628
-        if (is_array($copies)) {
5629
-            return array_shift($copies);
5630
-        }
5631
-        return null;
5632
-    }
5633
-
5634
-
5635
-
5636
-    /**
5637
-     * Updates the item with the specified id. Ignores default query parameters because
5638
-     * we have specified the ID, and its assumed we KNOW what we're doing
5639
-     *
5640
-     * @param array      $fields_n_values keys are field names, values are their new values
5641
-     * @param int|string $id              the value of the primary key to update
5642
-     * @return int number of rows updated
5643
-     * @throws EE_Error
5644
-     */
5645
-    public function update_by_ID($fields_n_values, $id)
5646
-    {
5647
-        $query_params = array(
5648
-            0                          => array($this->get_primary_key_field()->get_name() => $id),
5649
-            'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5650
-        );
5651
-        return $this->update($fields_n_values, $query_params);
5652
-    }
5653
-
5654
-
5655
-
5656
-    /**
5657
-     * Changes an operator which was supplied to the models into one usable in SQL
5658
-     *
5659
-     * @param string $operator_supplied
5660
-     * @return string an operator which can be used in SQL
5661
-     * @throws EE_Error
5662
-     */
5663
-    private function _prepare_operator_for_sql($operator_supplied)
5664
-    {
5665
-        $sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5666
-            : null;
5667
-        if ($sql_operator) {
5668
-            return $sql_operator;
5669
-        }
5670
-        throw new EE_Error(
5671
-            sprintf(
5672
-                __(
5673
-                    "The operator '%s' is not in the list of valid operators: %s",
5674
-                    "event_espresso"
5675
-                ), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5676
-            )
5677
-        );
5678
-    }
5679
-
5680
-
5681
-
5682
-    /**
5683
-     * Gets the valid operators
5684
-     * @return array keys are accepted strings, values are the SQL they are converted to
5685
-     */
5686
-    public function valid_operators(){
5687
-        return $this->_valid_operators;
5688
-    }
5689
-
5690
-
5691
-
5692
-    /**
5693
-     * Gets the between-style operators (take 2 arguments).
5694
-     * @return array keys are accepted strings, values are the SQL they are converted to
5695
-     */
5696
-    public function valid_between_style_operators()
5697
-    {
5698
-        return array_intersect(
5699
-            $this->valid_operators(),
5700
-            $this->_between_style_operators
5701
-        );
5702
-    }
5703
-
5704
-    /**
5705
-     * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5706
-     * @return array keys are accepted strings, values are the SQL they are converted to
5707
-     */
5708
-    public function valid_like_style_operators()
5709
-    {
5710
-        return array_intersect(
5711
-            $this->valid_operators(),
5712
-            $this->_like_style_operators
5713
-        );
5714
-    }
5715
-
5716
-    /**
5717
-     * Gets the "in"-style operators
5718
-     * @return array keys are accepted strings, values are the SQL they are converted to
5719
-     */
5720
-    public function valid_in_style_operators()
5721
-    {
5722
-        return array_intersect(
5723
-            $this->valid_operators(),
5724
-            $this->_in_style_operators
5725
-        );
5726
-    }
5727
-
5728
-    /**
5729
-     * Gets the "null"-style operators (accept no arguments)
5730
-     * @return array keys are accepted strings, values are the SQL they are converted to
5731
-     */
5732
-    public function valid_null_style_operators()
5733
-    {
5734
-        return array_intersect(
5735
-            $this->valid_operators(),
5736
-            $this->_null_style_operators
5737
-        );
5738
-    }
5739
-
5740
-    /**
5741
-     * Gets an array where keys are the primary keys and values are their 'names'
5742
-     * (as determined by the model object's name() function, which is often overridden)
5743
-     *
5744
-     * @param array $query_params like get_all's
5745
-     * @return string[]
5746
-     * @throws EE_Error
5747
-     */
5748
-    public function get_all_names($query_params = array())
5749
-    {
5750
-        $objs = $this->get_all($query_params);
5751
-        $names = array();
5752
-        foreach ($objs as $obj) {
5753
-            $names[$obj->ID()] = $obj->name();
5754
-        }
5755
-        return $names;
5756
-    }
5757
-
5758
-
5759
-
5760
-    /**
5761
-     * Gets an array of primary keys from the model objects. If you acquired the model objects
5762
-     * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5763
-     * this is duplicated effort and reduces efficiency) you would be better to use
5764
-     * array_keys() on $model_objects.
5765
-     *
5766
-     * @param \EE_Base_Class[] $model_objects
5767
-     * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5768
-     *                                               in the returned array
5769
-     * @return array
5770
-     * @throws EE_Error
5771
-     */
5772
-    public function get_IDs($model_objects, $filter_out_empty_ids = false)
5773
-    {
5774
-        if (! $this->has_primary_key_field()) {
5775
-            if (WP_DEBUG) {
5776
-                EE_Error::add_error(
5777
-                    __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5778
-                    __FILE__,
5779
-                    __FUNCTION__,
5780
-                    __LINE__
5781
-                );
5782
-            }
5783
-        }
5784
-        $IDs = array();
5785
-        foreach ($model_objects as $model_object) {
5786
-            $id = $model_object->ID();
5787
-            if (! $id) {
5788
-                if ($filter_out_empty_ids) {
5789
-                    continue;
5790
-                }
5791
-                if (WP_DEBUG) {
5792
-                    EE_Error::add_error(
5793
-                        __(
5794
-                            'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5795
-                            'event_espresso'
5796
-                        ),
5797
-                        __FILE__,
5798
-                        __FUNCTION__,
5799
-                        __LINE__
5800
-                    );
5801
-                }
5802
-            }
5803
-            $IDs[] = $id;
5804
-        }
5805
-        return $IDs;
5806
-    }
5807
-
5808
-
5809
-
5810
-    /**
5811
-     * Returns the string used in capabilities relating to this model. If there
5812
-     * are no capabilities that relate to this model returns false
5813
-     *
5814
-     * @return string|false
5815
-     */
5816
-    public function cap_slug()
5817
-    {
5818
-        return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5819
-    }
5820
-
5821
-
5822
-
5823
-    /**
5824
-     * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5825
-     * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5826
-     * only returns the cap restrictions array in that context (ie, the array
5827
-     * at that key)
5828
-     *
5829
-     * @param string $context
5830
-     * @return EE_Default_Where_Conditions[] indexed by associated capability
5831
-     * @throws EE_Error
5832
-     */
5833
-    public function cap_restrictions($context = EEM_Base::caps_read)
5834
-    {
5835
-        EEM_Base::verify_is_valid_cap_context($context);
5836
-        //check if we ought to run the restriction generator first
5837
-        if (
5838
-            isset($this->_cap_restriction_generators[$context])
5839
-            && $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5840
-            && ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5841
-        ) {
5842
-            $this->_cap_restrictions[$context] = array_merge(
5843
-                $this->_cap_restrictions[$context],
5844
-                $this->_cap_restriction_generators[$context]->generate_restrictions()
5845
-            );
5846
-        }
5847
-        //and make sure we've finalized the construction of each restriction
5848
-        foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5849
-            if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5850
-                $where_conditions_obj->_finalize_construct($this);
5851
-            }
5852
-        }
5853
-        return $this->_cap_restrictions[$context];
5854
-    }
5855
-
5856
-
5857
-
5858
-    /**
5859
-     * Indicating whether or not this model thinks its a wp core model
5860
-     *
5861
-     * @return boolean
5862
-     */
5863
-    public function is_wp_core_model()
5864
-    {
5865
-        return $this->_wp_core_model;
5866
-    }
5867
-
5868
-
5869
-
5870
-    /**
5871
-     * Gets all the caps that are missing which impose a restriction on
5872
-     * queries made in this context
5873
-     *
5874
-     * @param string $context one of EEM_Base::caps_ constants
5875
-     * @return EE_Default_Where_Conditions[] indexed by capability name
5876
-     * @throws EE_Error
5877
-     */
5878
-    public function caps_missing($context = EEM_Base::caps_read)
5879
-    {
5880
-        $missing_caps = array();
5881
-        $cap_restrictions = $this->cap_restrictions($context);
5882
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5883
-            if (! EE_Capabilities::instance()
5884
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5885
-            ) {
5886
-                $missing_caps[$cap] = $restriction_if_no_cap;
5887
-            }
5888
-        }
5889
-        return $missing_caps;
5890
-    }
5891
-
5892
-
5893
-
5894
-    /**
5895
-     * Gets the mapping from capability contexts to action strings used in capability names
5896
-     *
5897
-     * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5898
-     * one of 'read', 'edit', or 'delete'
5899
-     */
5900
-    public function cap_contexts_to_cap_action_map()
5901
-    {
5902
-        return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5903
-            $this);
5904
-    }
5905
-
5906
-
5907
-
5908
-    /**
5909
-     * Gets the action string for the specified capability context
5910
-     *
5911
-     * @param string $context
5912
-     * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5913
-     * @throws EE_Error
5914
-     */
5915
-    public function cap_action_for_context($context)
5916
-    {
5917
-        $mapping = $this->cap_contexts_to_cap_action_map();
5918
-        if (isset($mapping[$context])) {
5919
-            return $mapping[$context];
5920
-        }
5921
-        if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5922
-            return $action;
5923
-        }
5924
-        throw new EE_Error(
5925
-            sprintf(
5926
-                __('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5927
-                $context,
5928
-                implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5929
-            )
5930
-        );
5931
-    }
5932
-
5933
-
5934
-
5935
-    /**
5936
-     * Returns all the capability contexts which are valid when querying models
5937
-     *
5938
-     * @return array
5939
-     */
5940
-    public static function valid_cap_contexts()
5941
-    {
5942
-        return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5943
-            self::caps_read,
5944
-            self::caps_read_admin,
5945
-            self::caps_edit,
5946
-            self::caps_delete,
5947
-        ));
5948
-    }
5949
-
5950
-
5951
-
5952
-    /**
5953
-     * Returns all valid options for 'default_where_conditions'
5954
-     *
5955
-     * @return array
5956
-     */
5957
-    public static function valid_default_where_conditions()
5958
-    {
5959
-        return array(
5960
-            EEM_Base::default_where_conditions_all,
5961
-            EEM_Base::default_where_conditions_this_only,
5962
-            EEM_Base::default_where_conditions_others_only,
5963
-            EEM_Base::default_where_conditions_minimum_all,
5964
-            EEM_Base::default_where_conditions_minimum_others,
5965
-            EEM_Base::default_where_conditions_none
5966
-        );
5967
-    }
5968
-
5969
-    // public static function default_where_conditions_full
5970
-    /**
5971
-     * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5972
-     *
5973
-     * @param string $context
5974
-     * @return bool
5975
-     * @throws EE_Error
5976
-     */
5977
-    static public function verify_is_valid_cap_context($context)
5978
-    {
5979
-        $valid_cap_contexts = EEM_Base::valid_cap_contexts();
5980
-        if (in_array($context, $valid_cap_contexts)) {
5981
-            return true;
5982
-        }
5983
-        throw new EE_Error(
5984
-            sprintf(
5985
-                __(
5986
-                    'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5987
-                    'event_espresso'
5988
-                ),
5989
-                $context,
5990
-                'EEM_Base',
5991
-                implode(',', $valid_cap_contexts)
5992
-            )
5993
-        );
5994
-    }
5995
-
5996
-
5997
-
5998
-    /**
5999
-     * Clears all the models field caches. This is only useful when a sub-class
6000
-     * might have added a field or something and these caches might be invalidated
6001
-     */
6002
-    protected function _invalidate_field_caches()
6003
-    {
6004
-        $this->_cache_foreign_key_to_fields = array();
6005
-        $this->_cached_fields = null;
6006
-        $this->_cached_fields_non_db_only = null;
6007
-    }
6008
-
6009
-
6010
-
6011
-    /**
6012
-     * Gets the list of all the where query param keys that relate to logic instead of field names
6013
-     * (eg "and", "or", "not").
6014
-     *
6015
-     * @return array
6016
-     */
6017
-    public function logic_query_param_keys()
6018
-    {
6019
-        return $this->_logic_query_param_keys;
6020
-    }
6021
-
6022
-
6023
-
6024
-    /**
6025
-     * Determines whether or not the where query param array key is for a logic query param.
6026
-     * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6027
-     * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6028
-     *
6029
-     * @param $query_param_key
6030
-     * @return bool
6031
-     */
6032
-    public function is_logic_query_param_key($query_param_key)
6033
-    {
6034
-        foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6035
-            if ($query_param_key === $logic_query_param_key
6036
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6037
-            ) {
6038
-                return true;
6039
-            }
6040
-        }
6041
-        return false;
6042
-    }
3743
+		}
3744
+		return $null_friendly_where_conditions;
3745
+	}
3746
+
3747
+
3748
+
3749
+	/**
3750
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3751
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3752
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3753
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3754
+	 *
3755
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3756
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3757
+	 */
3758
+	private function _get_default_where_conditions($model_relation_path = null)
3759
+	{
3760
+		if ($this->_ignore_where_strategy) {
3761
+			return array();
3762
+		}
3763
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3764
+	}
3765
+
3766
+
3767
+
3768
+	/**
3769
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3770
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3771
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3772
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3773
+	 * Similar to _get_default_where_conditions
3774
+	 *
3775
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3776
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3777
+	 */
3778
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3779
+	{
3780
+		if ($this->_ignore_where_strategy) {
3781
+			return array();
3782
+		}
3783
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3784
+	}
3785
+
3786
+
3787
+
3788
+	/**
3789
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3790
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3791
+	 *
3792
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3793
+	 * @return string
3794
+	 * @throws EE_Error
3795
+	 */
3796
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3797
+	{
3798
+		$selects = $this->_get_columns_to_select_for_this_model();
3799
+		foreach (
3800
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3801
+			$name_of_other_model_included
3802
+		) {
3803
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3804
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3805
+			foreach ($other_model_selects as $key => $value) {
3806
+				$selects[] = $value;
3807
+			}
3808
+		}
3809
+		return implode(", ", $selects);
3810
+	}
3811
+
3812
+
3813
+
3814
+	/**
3815
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3816
+	 * So that's going to be the columns for all the fields on the model
3817
+	 *
3818
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3819
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3820
+	 */
3821
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3822
+	{
3823
+		$fields = $this->field_settings();
3824
+		$selects = array();
3825
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3826
+			$this->get_this_model_name());
3827
+		foreach ($fields as $field_obj) {
3828
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3829
+						 . $field_obj->get_table_alias()
3830
+						 . "."
3831
+						 . $field_obj->get_table_column()
3832
+						 . " AS '"
3833
+						 . $table_alias_with_model_relation_chain_prefix
3834
+						 . $field_obj->get_table_alias()
3835
+						 . "."
3836
+						 . $field_obj->get_table_column()
3837
+						 . "'";
3838
+		}
3839
+		//make sure we are also getting the PKs of each table
3840
+		$tables = $this->get_tables();
3841
+		if (count($tables) > 1) {
3842
+			foreach ($tables as $table_obj) {
3843
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3844
+									   . $table_obj->get_fully_qualified_pk_column();
3845
+				if (! in_array($qualified_pk_column, $selects)) {
3846
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3847
+				}
3848
+			}
3849
+		}
3850
+		return $selects;
3851
+	}
3852
+
3853
+
3854
+
3855
+	/**
3856
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3857
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3858
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3859
+	 * SQL for joining, and the data types
3860
+	 *
3861
+	 * @param null|string                 $original_query_param
3862
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3863
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3864
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3865
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3866
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3867
+	 *                                                          or 'Registration's
3868
+	 * @param string                      $original_query_param what it originally was (eg
3869
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3870
+	 *                                                          matches $query_param
3871
+	 * @throws EE_Error
3872
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3873
+	 */
3874
+	private function _extract_related_model_info_from_query_param(
3875
+		$query_param,
3876
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3877
+		$query_param_type,
3878
+		$original_query_param = null
3879
+	) {
3880
+		if ($original_query_param === null) {
3881
+			$original_query_param = $query_param;
3882
+		}
3883
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3884
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3885
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3886
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3887
+		//check to see if we have a field on this model
3888
+		$this_model_fields = $this->field_settings(true);
3889
+		if (array_key_exists($query_param, $this_model_fields)) {
3890
+			if ($allow_fields) {
3891
+				return;
3892
+			}
3893
+			throw new EE_Error(
3894
+				sprintf(
3895
+					__(
3896
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3897
+						"event_espresso"
3898
+					),
3899
+					$query_param, get_class($this), $query_param_type, $original_query_param
3900
+				)
3901
+			);
3902
+		}
3903
+		//check if this is a special logic query param
3904
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3905
+			if ($allow_logic_query_params) {
3906
+				return;
3907
+			}
3908
+			throw new EE_Error(
3909
+				sprintf(
3910
+					__(
3911
+						'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',
3912
+						'event_espresso'
3913
+					),
3914
+					implode('", "', $this->_logic_query_param_keys),
3915
+					$query_param,
3916
+					get_class($this),
3917
+					'<br />',
3918
+					"\t"
3919
+					. ' $passed_in_query_info = <pre>'
3920
+					. print_r($passed_in_query_info, true)
3921
+					. '</pre>'
3922
+					. "\n\t"
3923
+					. ' $query_param_type = '
3924
+					. $query_param_type
3925
+					. "\n\t"
3926
+					. ' $original_query_param = '
3927
+					. $original_query_param
3928
+				)
3929
+			);
3930
+		}
3931
+		//check if it's a custom selection
3932
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3933
+			return;
3934
+		}
3935
+		//check if has a model name at the beginning
3936
+		//and
3937
+		//check if it's a field on a related model
3938
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3939
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3940
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3941
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3942
+				if ($query_param === '') {
3943
+					//nothing left to $query_param
3944
+					//we should actually end in a field name, not a model like this!
3945
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3946
+						"event_espresso"),
3947
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3948
+				}
3949
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3950
+				$related_model_obj->_extract_related_model_info_from_query_param(
3951
+					$query_param,
3952
+					$passed_in_query_info, $query_param_type, $original_query_param
3953
+				);
3954
+				return;
3955
+			}
3956
+			if ($query_param === $valid_related_model_name) {
3957
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3958
+				return;
3959
+			}
3960
+		}
3961
+		//ok so $query_param didn't start with a model name
3962
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3963
+		//it's wack, that's what it is
3964
+		throw new EE_Error(sprintf(__("There is no model named '%s' related to %s. Query param type is %s and original query param is %s",
3965
+			"event_espresso"),
3966
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3967
+	}
3968
+
3969
+
3970
+
3971
+	/**
3972
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3973
+	 * and store it on $passed_in_query_info
3974
+	 *
3975
+	 * @param string                      $model_name
3976
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3977
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3978
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3979
+	 *                                                          and are adding a join to 'Payment' with the original
3980
+	 *                                                          query param key
3981
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3982
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3983
+	 *                                                          Payment wants to add default query params so that it
3984
+	 *                                                          will know what models to prepend onto its default query
3985
+	 *                                                          params or in case it wants to rename tables (in case
3986
+	 *                                                          there are multiple joins to the same table)
3987
+	 * @return void
3988
+	 * @throws EE_Error
3989
+	 */
3990
+	private function _add_join_to_model(
3991
+		$model_name,
3992
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3993
+		$original_query_param
3994
+	) {
3995
+		$relation_obj = $this->related_settings_for($model_name);
3996
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3997
+		//check if the relation is HABTM, because then we're essentially doing two joins
3998
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3999
+		if ($relation_obj instanceof EE_HABTM_Relation) {
4000
+			$join_model_obj = $relation_obj->get_join_model();
4001
+			//replace the model specified with the join model for this relation chain, whi
4002
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4003
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4004
+			$passed_in_query_info->merge(
4005
+				new EE_Model_Query_Info_Carrier(
4006
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4007
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4008
+				)
4009
+			);
4010
+		}
4011
+		//now just join to the other table pointed to by the relation object, and add its data types
4012
+		$passed_in_query_info->merge(
4013
+			new EE_Model_Query_Info_Carrier(
4014
+				array($model_relation_chain => $model_name),
4015
+				$relation_obj->get_join_statement($model_relation_chain)
4016
+			)
4017
+		);
4018
+	}
4019
+
4020
+
4021
+
4022
+	/**
4023
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4024
+	 *
4025
+	 * @param array $where_params like EEM_Base::get_all
4026
+	 * @return string of SQL
4027
+	 * @throws EE_Error
4028
+	 */
4029
+	private function _construct_where_clause($where_params)
4030
+	{
4031
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4032
+		if ($SQL) {
4033
+			return " WHERE " . $SQL;
4034
+		}
4035
+		return '';
4036
+	}
4037
+
4038
+
4039
+
4040
+	/**
4041
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4042
+	 * and should be passed HAVING parameters, not WHERE parameters
4043
+	 *
4044
+	 * @param array $having_params
4045
+	 * @return string
4046
+	 * @throws EE_Error
4047
+	 */
4048
+	private function _construct_having_clause($having_params)
4049
+	{
4050
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4051
+		if ($SQL) {
4052
+			return " HAVING " . $SQL;
4053
+		}
4054
+		return '';
4055
+	}
4056
+
4057
+
4058
+	/**
4059
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4060
+	 * Event_Meta.meta_value = 'foo'))"
4061
+	 *
4062
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4063
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4064
+	 * @throws EE_Error
4065
+	 * @return string of SQL
4066
+	 */
4067
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4068
+	{
4069
+		$where_clauses = array();
4070
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4071
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4072
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4073
+				switch ($query_param) {
4074
+					case 'not':
4075
+					case 'NOT':
4076
+						$where_clauses[] = "! ("
4077
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4078
+								$glue)
4079
+										   . ")";
4080
+						break;
4081
+					case 'and':
4082
+					case 'AND':
4083
+						$where_clauses[] = " ("
4084
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4085
+								' AND ')
4086
+										   . ")";
4087
+						break;
4088
+					case 'or':
4089
+					case 'OR':
4090
+						$where_clauses[] = " ("
4091
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4092
+								' OR ')
4093
+										   . ")";
4094
+						break;
4095
+				}
4096
+			} else {
4097
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4098
+				//if it's not a normal field, maybe it's a custom selection?
4099
+				if (! $field_obj) {
4100
+					if (isset($this->_custom_selections[$query_param][1])) {
4101
+						$field_obj = $this->_custom_selections[$query_param][1];
4102
+					} else {
4103
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4104
+							"event_espresso"), $query_param));
4105
+					}
4106
+				}
4107
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4108
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4109
+			}
4110
+		}
4111
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4112
+	}
4113
+
4114
+
4115
+
4116
+	/**
4117
+	 * Takes the input parameter and extract the table name (alias) and column name
4118
+	 *
4119
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4120
+	 * @throws EE_Error
4121
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4122
+	 */
4123
+	private function _deduce_column_name_from_query_param($query_param)
4124
+	{
4125
+		$field = $this->_deduce_field_from_query_param($query_param);
4126
+		if ($field) {
4127
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4128
+				$query_param);
4129
+			return $table_alias_prefix . $field->get_qualified_column();
4130
+		}
4131
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4132
+			//maybe it's custom selection item?
4133
+			//if so, just use it as the "column name"
4134
+			return $query_param;
4135
+		}
4136
+		throw new EE_Error(
4137
+			sprintf(
4138
+				__(
4139
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4140
+					"event_espresso"
4141
+				), $query_param, implode(",", $this->_custom_selections)
4142
+			)
4143
+		);
4144
+	}
4145
+
4146
+
4147
+
4148
+	/**
4149
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4150
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4151
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4152
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4153
+	 *
4154
+	 * @param string $condition_query_param_key
4155
+	 * @return string
4156
+	 */
4157
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4158
+	{
4159
+		$pos_of_star = strpos($condition_query_param_key, '*');
4160
+		if ($pos_of_star === false) {
4161
+			return $condition_query_param_key;
4162
+		}
4163
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4164
+		return $condition_query_param_sans_star;
4165
+	}
4166
+
4167
+
4168
+
4169
+	/**
4170
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4171
+	 *
4172
+	 * @param                            mixed      array | string    $op_and_value
4173
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4174
+	 * @throws EE_Error
4175
+	 * @return string
4176
+	 */
4177
+	private function _construct_op_and_value($op_and_value, $field_obj)
4178
+	{
4179
+		if (is_array($op_and_value)) {
4180
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4181
+			if (! $operator) {
4182
+				$php_array_like_string = array();
4183
+				foreach ($op_and_value as $key => $value) {
4184
+					$php_array_like_string[] = "$key=>$value";
4185
+				}
4186
+				throw new EE_Error(
4187
+					sprintf(
4188
+						__(
4189
+							"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))",
4190
+							"event_espresso"
4191
+						),
4192
+						implode(",", $php_array_like_string)
4193
+					)
4194
+				);
4195
+			}
4196
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4197
+		} else {
4198
+			$operator = '=';
4199
+			$value = $op_and_value;
4200
+		}
4201
+		//check to see if the value is actually another field
4202
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4203
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4204
+		}
4205
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4206
+			//in this case, the value should be an array, or at least a comma-separated list
4207
+			//it will need to handle a little differently
4208
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4209
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4210
+			return $operator . SP . $cleaned_value;
4211
+		}
4212
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4213
+			//the value should be an array with count of two.
4214
+			if (count($value) !== 2) {
4215
+				throw new EE_Error(
4216
+					sprintf(
4217
+						__(
4218
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4219
+							'event_espresso'
4220
+						),
4221
+						"BETWEEN"
4222
+					)
4223
+				);
4224
+			}
4225
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4226
+			return $operator . SP . $cleaned_value;
4227
+		}
4228
+		if (in_array($operator, $this->valid_null_style_operators())) {
4229
+			if ($value !== null) {
4230
+				throw new EE_Error(
4231
+					sprintf(
4232
+						__(
4233
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4234
+							"event_espresso"
4235
+						),
4236
+						$value,
4237
+						$operator
4238
+					)
4239
+				);
4240
+			}
4241
+			return $operator;
4242
+		}
4243
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4244
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4245
+			//remove other junk. So just treat it as a string.
4246
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4247
+		}
4248
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4249
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4250
+		}
4251
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4252
+			throw new EE_Error(
4253
+				sprintf(
4254
+					__(
4255
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4256
+						'event_espresso'
4257
+					),
4258
+					$operator,
4259
+					$operator
4260
+				)
4261
+			);
4262
+		}
4263
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4264
+			throw new EE_Error(
4265
+				sprintf(
4266
+					__(
4267
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4268
+						'event_espresso'
4269
+					),
4270
+					$operator,
4271
+					$operator
4272
+				)
4273
+			);
4274
+		}
4275
+		throw new EE_Error(
4276
+			sprintf(
4277
+				__(
4278
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4279
+					"event_espresso"
4280
+				),
4281
+				http_build_query($op_and_value)
4282
+			)
4283
+		);
4284
+	}
4285
+
4286
+
4287
+
4288
+	/**
4289
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4290
+	 *
4291
+	 * @param array                      $values
4292
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4293
+	 *                                              '%s'
4294
+	 * @return string
4295
+	 * @throws EE_Error
4296
+	 */
4297
+	public function _construct_between_value($values, $field_obj)
4298
+	{
4299
+		$cleaned_values = array();
4300
+		foreach ($values as $value) {
4301
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4302
+		}
4303
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4304
+	}
4305
+
4306
+
4307
+
4308
+	/**
4309
+	 * Takes an array or a comma-separated list of $values and cleans them
4310
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4311
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4312
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4313
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4314
+	 *
4315
+	 * @param mixed                      $values    array or comma-separated string
4316
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4317
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4318
+	 * @throws EE_Error
4319
+	 */
4320
+	public function _construct_in_value($values, $field_obj)
4321
+	{
4322
+		//check if the value is a CSV list
4323
+		if (is_string($values)) {
4324
+			//in which case, turn it into an array
4325
+			$values = explode(",", $values);
4326
+		}
4327
+		$cleaned_values = array();
4328
+		foreach ($values as $value) {
4329
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4330
+		}
4331
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4332
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4333
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4334
+		if (empty($cleaned_values)) {
4335
+			$all_fields = $this->field_settings();
4336
+			$a_field = array_shift($all_fields);
4337
+			$main_table = $this->_get_main_table();
4338
+			$cleaned_values[] = "SELECT "
4339
+								. $a_field->get_table_column()
4340
+								. " FROM "
4341
+								. $main_table->get_table_name()
4342
+								. " WHERE FALSE";
4343
+		}
4344
+		return "(" . implode(",", $cleaned_values) . ")";
4345
+	}
4346
+
4347
+
4348
+
4349
+	/**
4350
+	 * @param mixed                      $value
4351
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4352
+	 * @throws EE_Error
4353
+	 * @return false|null|string
4354
+	 */
4355
+	private function _wpdb_prepare_using_field($value, $field_obj)
4356
+	{
4357
+		/** @type WPDB $wpdb */
4358
+		global $wpdb;
4359
+		if ($field_obj instanceof EE_Model_Field_Base) {
4360
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4361
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4362
+		} //$field_obj should really just be a data type
4363
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4364
+			throw new EE_Error(
4365
+				sprintf(
4366
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4367
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4368
+				)
4369
+			);
4370
+		}
4371
+		return $wpdb->prepare($field_obj, $value);
4372
+	}
4373
+
4374
+
4375
+
4376
+	/**
4377
+	 * Takes the input parameter and finds the model field that it indicates.
4378
+	 *
4379
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4380
+	 * @throws EE_Error
4381
+	 * @return EE_Model_Field_Base
4382
+	 */
4383
+	protected function _deduce_field_from_query_param($query_param_name)
4384
+	{
4385
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4386
+		//which will help us find the database table and column
4387
+		$query_param_parts = explode(".", $query_param_name);
4388
+		if (empty($query_param_parts)) {
4389
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4390
+				'event_espresso'), $query_param_name));
4391
+		}
4392
+		$number_of_parts = count($query_param_parts);
4393
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4394
+		if ($number_of_parts === 1) {
4395
+			$field_name = $last_query_param_part;
4396
+			$model_obj = $this;
4397
+		} else {// $number_of_parts >= 2
4398
+			//the last part is the column name, and there are only 2parts. therefore...
4399
+			$field_name = $last_query_param_part;
4400
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4401
+		}
4402
+		try {
4403
+			return $model_obj->field_settings_for($field_name);
4404
+		} catch (EE_Error $e) {
4405
+			return null;
4406
+		}
4407
+	}
4408
+
4409
+
4410
+
4411
+	/**
4412
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4413
+	 * alias and column which corresponds to it
4414
+	 *
4415
+	 * @param string $field_name
4416
+	 * @throws EE_Error
4417
+	 * @return string
4418
+	 */
4419
+	public function _get_qualified_column_for_field($field_name)
4420
+	{
4421
+		$all_fields = $this->field_settings();
4422
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4423
+		if ($field) {
4424
+			return $field->get_qualified_column();
4425
+		}
4426
+		throw new EE_Error(
4427
+			sprintf(
4428
+				__(
4429
+					"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.",
4430
+					'event_espresso'
4431
+				), $field_name, get_class($this)
4432
+			)
4433
+		);
4434
+	}
4435
+
4436
+
4437
+
4438
+	/**
4439
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4440
+	 * Example usage:
4441
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4442
+	 *      array(),
4443
+	 *      ARRAY_A,
4444
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4445
+	 *  );
4446
+	 * is equivalent to
4447
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4448
+	 * and
4449
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4450
+	 *      array(
4451
+	 *          array(
4452
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4453
+	 *          ),
4454
+	 *          ARRAY_A,
4455
+	 *          implode(
4456
+	 *              ', ',
4457
+	 *              array_merge(
4458
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4459
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4460
+	 *              )
4461
+	 *          )
4462
+	 *      )
4463
+	 *  );
4464
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4465
+	 *
4466
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4467
+	 *                                            and the one whose fields you are selecting for example: when querying
4468
+	 *                                            tickets model and selecting fields from the tickets model you would
4469
+	 *                                            leave this parameter empty, because no models are needed to join
4470
+	 *                                            between the queried model and the selected one. Likewise when
4471
+	 *                                            querying the datetime model and selecting fields from the tickets
4472
+	 *                                            model, it would also be left empty, because there is a direct
4473
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4474
+	 *                                            them together. However, when querying from the event model and
4475
+	 *                                            selecting fields from the ticket model, you should provide the string
4476
+	 *                                            'Datetime', indicating that the event model must first join to the
4477
+	 *                                            datetime model in order to find its relation to ticket model.
4478
+	 *                                            Also, when querying from the venue model and selecting fields from
4479
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4480
+	 *                                            indicating you need to join the venue model to the event model,
4481
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4482
+	 *                                            This string is used to deduce the prefix that gets added onto the
4483
+	 *                                            models' tables qualified columns
4484
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4485
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4486
+	 *                                            qualified column names
4487
+	 * @return array|string
4488
+	 */
4489
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4490
+	{
4491
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4492
+		$qualified_columns = array();
4493
+		foreach ($this->field_settings() as $field_name => $field) {
4494
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4495
+		}
4496
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4497
+	}
4498
+
4499
+
4500
+
4501
+	/**
4502
+	 * constructs the select use on special limit joins
4503
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4504
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4505
+	 * (as that is typically where the limits would be set).
4506
+	 *
4507
+	 * @param  string       $table_alias The table the select is being built for
4508
+	 * @param  mixed|string $limit       The limit for this select
4509
+	 * @return string                The final select join element for the query.
4510
+	 */
4511
+	public function _construct_limit_join_select($table_alias, $limit)
4512
+	{
4513
+		$SQL = '';
4514
+		foreach ($this->_tables as $table_obj) {
4515
+			if ($table_obj instanceof EE_Primary_Table) {
4516
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4517
+					? $table_obj->get_select_join_limit($limit)
4518
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4519
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4520
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4521
+					? $table_obj->get_select_join_limit_join($limit)
4522
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4523
+			}
4524
+		}
4525
+		return $SQL;
4526
+	}
4527
+
4528
+
4529
+
4530
+	/**
4531
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4532
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4533
+	 *
4534
+	 * @return string SQL
4535
+	 * @throws EE_Error
4536
+	 */
4537
+	public function _construct_internal_join()
4538
+	{
4539
+		$SQL = $this->_get_main_table()->get_table_sql();
4540
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4541
+		return $SQL;
4542
+	}
4543
+
4544
+
4545
+
4546
+	/**
4547
+	 * Constructs the SQL for joining all the tables on this model.
4548
+	 * Normally $alias should be the primary table's alias, but in cases where
4549
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4550
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4551
+	 * alias, this will construct SQL like:
4552
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4553
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4554
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4555
+	 *
4556
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4557
+	 * @return string
4558
+	 */
4559
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4560
+	{
4561
+		$SQL = '';
4562
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4563
+		foreach ($this->_tables as $table_obj) {
4564
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4565
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4566
+					//so we're joining to this table, meaning the table is already in
4567
+					//the FROM statement, BUT the primary table isn't. So we want
4568
+					//to add the inverse join sql
4569
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4570
+				} else {
4571
+					//just add a regular JOIN to this table from the primary table
4572
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4573
+				}
4574
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4575
+		}
4576
+		return $SQL;
4577
+	}
4578
+
4579
+
4580
+
4581
+	/**
4582
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4583
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4584
+	 * their data type (eg, '%s', '%d', etc)
4585
+	 *
4586
+	 * @return array
4587
+	 */
4588
+	public function _get_data_types()
4589
+	{
4590
+		$data_types = array();
4591
+		foreach ($this->field_settings() as $field_obj) {
4592
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4593
+			/** @var $field_obj EE_Model_Field_Base */
4594
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4595
+		}
4596
+		return $data_types;
4597
+	}
4598
+
4599
+
4600
+
4601
+	/**
4602
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4603
+	 *
4604
+	 * @param string $model_name
4605
+	 * @throws EE_Error
4606
+	 * @return EEM_Base
4607
+	 */
4608
+	public function get_related_model_obj($model_name)
4609
+	{
4610
+		$model_classname = "EEM_" . $model_name;
4611
+		if (! class_exists($model_classname)) {
4612
+			throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4613
+				'event_espresso'), $model_name, $model_classname));
4614
+		}
4615
+		return call_user_func($model_classname . "::instance");
4616
+	}
4617
+
4618
+
4619
+
4620
+	/**
4621
+	 * Returns the array of EE_ModelRelations for this model.
4622
+	 *
4623
+	 * @return EE_Model_Relation_Base[]
4624
+	 */
4625
+	public function relation_settings()
4626
+	{
4627
+		return $this->_model_relations;
4628
+	}
4629
+
4630
+
4631
+
4632
+	/**
4633
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4634
+	 * because without THOSE models, this model probably doesn't have much purpose.
4635
+	 * (Eg, without an event, datetimes have little purpose.)
4636
+	 *
4637
+	 * @return EE_Belongs_To_Relation[]
4638
+	 */
4639
+	public function belongs_to_relations()
4640
+	{
4641
+		$belongs_to_relations = array();
4642
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4643
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4644
+				$belongs_to_relations[$model_name] = $relation_obj;
4645
+			}
4646
+		}
4647
+		return $belongs_to_relations;
4648
+	}
4649
+
4650
+
4651
+
4652
+	/**
4653
+	 * Returns the specified EE_Model_Relation, or throws an exception
4654
+	 *
4655
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4656
+	 * @throws EE_Error
4657
+	 * @return EE_Model_Relation_Base
4658
+	 */
4659
+	public function related_settings_for($relation_name)
4660
+	{
4661
+		$relatedModels = $this->relation_settings();
4662
+		if (! array_key_exists($relation_name, $relatedModels)) {
4663
+			throw new EE_Error(
4664
+				sprintf(
4665
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4666
+						'event_espresso'),
4667
+					$relation_name,
4668
+					$this->_get_class_name(),
4669
+					implode(', ', array_keys($relatedModels))
4670
+				)
4671
+			);
4672
+		}
4673
+		return $relatedModels[$relation_name];
4674
+	}
4675
+
4676
+
4677
+
4678
+	/**
4679
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4680
+	 * fields
4681
+	 *
4682
+	 * @param string $fieldName
4683
+	 * @param boolean $include_db_only_fields
4684
+	 * @throws EE_Error
4685
+	 * @return EE_Model_Field_Base
4686
+	 */
4687
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4688
+	{
4689
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4690
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4691
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4692
+				get_class($this)));
4693
+		}
4694
+		return $fieldSettings[$fieldName];
4695
+	}
4696
+
4697
+
4698
+
4699
+	/**
4700
+	 * Checks if this field exists on this model
4701
+	 *
4702
+	 * @param string $fieldName a key in the model's _field_settings array
4703
+	 * @return boolean
4704
+	 */
4705
+	public function has_field($fieldName)
4706
+	{
4707
+		$fieldSettings = $this->field_settings(true);
4708
+		if (isset($fieldSettings[$fieldName])) {
4709
+			return true;
4710
+		}
4711
+		return false;
4712
+	}
4713
+
4714
+
4715
+
4716
+	/**
4717
+	 * Returns whether or not this model has a relation to the specified model
4718
+	 *
4719
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4720
+	 * @return boolean
4721
+	 */
4722
+	public function has_relation($relation_name)
4723
+	{
4724
+		$relations = $this->relation_settings();
4725
+		if (isset($relations[$relation_name])) {
4726
+			return true;
4727
+		}
4728
+		return false;
4729
+	}
4730
+
4731
+
4732
+
4733
+	/**
4734
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4735
+	 * Eg, on EE_Answer that would be ANS_ID field object
4736
+	 *
4737
+	 * @param $field_obj
4738
+	 * @return boolean
4739
+	 */
4740
+	public function is_primary_key_field($field_obj)
4741
+	{
4742
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4743
+	}
4744
+
4745
+
4746
+
4747
+	/**
4748
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4749
+	 * Eg, on EE_Answer that would be ANS_ID field object
4750
+	 *
4751
+	 * @return EE_Model_Field_Base
4752
+	 * @throws EE_Error
4753
+	 */
4754
+	public function get_primary_key_field()
4755
+	{
4756
+		if ($this->_primary_key_field === null) {
4757
+			foreach ($this->field_settings(true) as $field_obj) {
4758
+				if ($this->is_primary_key_field($field_obj)) {
4759
+					$this->_primary_key_field = $field_obj;
4760
+					break;
4761
+				}
4762
+			}
4763
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4764
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4765
+					get_class($this)));
4766
+			}
4767
+		}
4768
+		return $this->_primary_key_field;
4769
+	}
4770
+
4771
+
4772
+
4773
+	/**
4774
+	 * Returns whether or not not there is a primary key on this model.
4775
+	 * Internally does some caching.
4776
+	 *
4777
+	 * @return boolean
4778
+	 */
4779
+	public function has_primary_key_field()
4780
+	{
4781
+		if ($this->_has_primary_key_field === null) {
4782
+			try {
4783
+				$this->get_primary_key_field();
4784
+				$this->_has_primary_key_field = true;
4785
+			} catch (EE_Error $e) {
4786
+				$this->_has_primary_key_field = false;
4787
+			}
4788
+		}
4789
+		return $this->_has_primary_key_field;
4790
+	}
4791
+
4792
+
4793
+
4794
+	/**
4795
+	 * Finds the first field of type $field_class_name.
4796
+	 *
4797
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4798
+	 *                                 EE_Foreign_Key_Field, etc
4799
+	 * @return EE_Model_Field_Base or null if none is found
4800
+	 */
4801
+	public function get_a_field_of_type($field_class_name)
4802
+	{
4803
+		foreach ($this->field_settings() as $field) {
4804
+			if ($field instanceof $field_class_name) {
4805
+				return $field;
4806
+			}
4807
+		}
4808
+		return null;
4809
+	}
4810
+
4811
+
4812
+
4813
+	/**
4814
+	 * Gets a foreign key field pointing to model.
4815
+	 *
4816
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4817
+	 * @return EE_Foreign_Key_Field_Base
4818
+	 * @throws EE_Error
4819
+	 */
4820
+	public function get_foreign_key_to($model_name)
4821
+	{
4822
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4823
+			foreach ($this->field_settings() as $field) {
4824
+				if (
4825
+					$field instanceof EE_Foreign_Key_Field_Base
4826
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4827
+				) {
4828
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4829
+					break;
4830
+				}
4831
+			}
4832
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4834
+					'event_espresso'), $model_name, get_class($this)));
4835
+			}
4836
+		}
4837
+		return $this->_cache_foreign_key_to_fields[$model_name];
4838
+	}
4839
+
4840
+
4841
+
4842
+	/**
4843
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4844
+	 *
4845
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4846
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4847
+	 *                            Either one works
4848
+	 * @return string
4849
+	 */
4850
+	public function get_table_for_alias($table_alias)
4851
+	{
4852
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4853
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4854
+	}
4855
+
4856
+
4857
+
4858
+	/**
4859
+	 * Returns a flat array of all field son this model, instead of organizing them
4860
+	 * by table_alias as they are in the constructor.
4861
+	 *
4862
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4863
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4864
+	 */
4865
+	public function field_settings($include_db_only_fields = false)
4866
+	{
4867
+		if ($include_db_only_fields) {
4868
+			if ($this->_cached_fields === null) {
4869
+				$this->_cached_fields = array();
4870
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4871
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4872
+						$this->_cached_fields[$field_name] = $field_obj;
4873
+					}
4874
+				}
4875
+			}
4876
+			return $this->_cached_fields;
4877
+		}
4878
+		if ($this->_cached_fields_non_db_only === null) {
4879
+			$this->_cached_fields_non_db_only = array();
4880
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4881
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882
+					/** @var $field_obj EE_Model_Field_Base */
4883
+					if (! $field_obj->is_db_only_field()) {
4884
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4885
+					}
4886
+				}
4887
+			}
4888
+		}
4889
+		return $this->_cached_fields_non_db_only;
4890
+	}
4891
+
4892
+
4893
+
4894
+	/**
4895
+	 *        cycle though array of attendees and create objects out of each item
4896
+	 *
4897
+	 * @access        private
4898
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4899
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4900
+	 *                           numerically indexed)
4901
+	 * @throws EE_Error
4902
+	 */
4903
+	protected function _create_objects($rows = array())
4904
+	{
4905
+		$array_of_objects = array();
4906
+		if (empty($rows)) {
4907
+			return array();
4908
+		}
4909
+		$count_if_model_has_no_primary_key = 0;
4910
+		$has_primary_key = $this->has_primary_key_field();
4911
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4912
+		foreach ((array)$rows as $row) {
4913
+			if (empty($row)) {
4914
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4915
+				return array();
4916
+			}
4917
+			//check if we've already set this object in the results array,
4918
+			//in which case there's no need to process it further (again)
4919
+			if ($has_primary_key) {
4920
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4921
+					$row,
4922
+					$primary_key_field->get_qualified_column(),
4923
+					$primary_key_field->get_table_column()
4924
+				);
4925
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4926
+					continue;
4927
+				}
4928
+			}
4929
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4930
+			if (! $classInstance) {
4931
+				throw new EE_Error(
4932
+					sprintf(
4933
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4934
+						$this->get_this_model_name(),
4935
+						http_build_query($row)
4936
+					)
4937
+				);
4938
+			}
4939
+			//set the timezone on the instantiated objects
4940
+			$classInstance->set_timezone($this->_timezone);
4941
+			//make sure if there is any timezone setting present that we set the timezone for the object
4942
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4943
+			$array_of_objects[$key] = $classInstance;
4944
+			//also, for all the relations of type BelongsTo, see if we can cache
4945
+			//those related models
4946
+			//(we could do this for other relations too, but if there are conditions
4947
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4948
+			//so it requires a little more thought than just caching them immediately...)
4949
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4950
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4951
+					//check if this model's INFO is present. If so, cache it on the model
4952
+					$other_model = $relation_obj->get_other_model();
4953
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4954
+					//if we managed to make a model object from the results, cache it on the main model object
4955
+					if ($other_model_obj_maybe) {
4956
+						//set timezone on these other model objects if they are present
4957
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4958
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4959
+					}
4960
+				}
4961
+			}
4962
+		}
4963
+		return $array_of_objects;
4964
+	}
4965
+
4966
+
4967
+
4968
+	/**
4969
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4970
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4971
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4972
+	 * object (as set in the model_field!).
4973
+	 *
4974
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4975
+	 */
4976
+	public function create_default_object()
4977
+	{
4978
+		$this_model_fields_and_values = array();
4979
+		//setup the row using default values;
4980
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4981
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4982
+		}
4983
+		$className = $this->_get_class_name();
4984
+		$classInstance = EE_Registry::instance()
4985
+									->load_class($className, array($this_model_fields_and_values), false, false);
4986
+		return $classInstance;
4987
+	}
4988
+
4989
+
4990
+
4991
+	/**
4992
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4993
+	 *                             or an stdClass where each property is the name of a column,
4994
+	 * @return EE_Base_Class
4995
+	 * @throws EE_Error
4996
+	 */
4997
+	public function instantiate_class_from_array_or_object($cols_n_values)
4998
+	{
4999
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
5000
+			$cols_n_values = get_object_vars($cols_n_values);
5001
+		}
5002
+		$primary_key = null;
5003
+		//make sure the array only has keys that are fields/columns on this model
5004
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5005
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5006
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5007
+		}
5008
+		$className = $this->_get_class_name();
5009
+		//check we actually found results that we can use to build our model object
5010
+		//if not, return null
5011
+		if ($this->has_primary_key_field()) {
5012
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5013
+				return null;
5014
+			}
5015
+		} else if ($this->unique_indexes()) {
5016
+			$first_column = reset($this_model_fields_n_values);
5017
+			if (empty($first_column)) {
5018
+				return null;
5019
+			}
5020
+		}
5021
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5022
+		if ($primary_key) {
5023
+			$classInstance = $this->get_from_entity_map($primary_key);
5024
+			if (! $classInstance) {
5025
+				$classInstance = EE_Registry::instance()
5026
+											->load_class($className,
5027
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5028
+				// add this new object to the entity map
5029
+				$classInstance = $this->add_to_entity_map($classInstance);
5030
+			}
5031
+		} else {
5032
+			$classInstance = EE_Registry::instance()
5033
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5034
+											true, false);
5035
+		}
5036
+		return $classInstance;
5037
+	}
5038
+
5039
+
5040
+
5041
+	/**
5042
+	 * Gets the model object from the  entity map if it exists
5043
+	 *
5044
+	 * @param int|string $id the ID of the model object
5045
+	 * @return EE_Base_Class
5046
+	 */
5047
+	public function get_from_entity_map($id)
5048
+	{
5049
+		return isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])
5050
+			? $this->_entity_map[EEM_Base::$_model_query_blog_id][$id] : null;
5051
+	}
5052
+
5053
+
5054
+
5055
+	/**
5056
+	 * add_to_entity_map
5057
+	 * Adds the object to the model's entity mappings
5058
+	 *        Effectively tells the models "Hey, this model object is the most up-to-date representation of the data,
5059
+	 *        and for the remainder of the request, it's even more up-to-date than what's in the database.
5060
+	 *        So, if the database doesn't agree with what's in the entity mapper, ignore the database"
5061
+	 *        If the database gets updated directly and you want the entity mapper to reflect that change,
5062
+	 *        then this method should be called immediately after the update query
5063
+	 * Note: The map is indexed by whatever the current blog id is set (via EEM_Base::$_model_query_blog_id).  This is
5064
+	 * so on multisite, the entity map is specific to the query being done for a specific site.
5065
+	 *
5066
+	 * @param    EE_Base_Class $object
5067
+	 * @throws EE_Error
5068
+	 * @return \EE_Base_Class
5069
+	 */
5070
+	public function add_to_entity_map(EE_Base_Class $object)
5071
+	{
5072
+		$className = $this->_get_class_name();
5073
+		if (! $object instanceof $className) {
5074
+			throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5075
+				is_object($object) ? get_class($object) : $object, $className));
5076
+		}
5077
+		/** @var $object EE_Base_Class */
5078
+		if (! $object->ID()) {
5079
+			throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5080
+				"event_espresso"), get_class($this)));
5081
+		}
5082
+		// double check it's not already there
5083
+		$classInstance = $this->get_from_entity_map($object->ID());
5084
+		if ($classInstance) {
5085
+			return $classInstance;
5086
+		}
5087
+		$this->_entity_map[EEM_Base::$_model_query_blog_id][$object->ID()] = $object;
5088
+		return $object;
5089
+	}
5090
+
5091
+
5092
+
5093
+	/**
5094
+	 * if a valid identifier is provided, then that entity is unset from the entity map,
5095
+	 * if no identifier is provided, then the entire entity map is emptied
5096
+	 *
5097
+	 * @param int|string $id the ID of the model object
5098
+	 * @return boolean
5099
+	 */
5100
+	public function clear_entity_map($id = null)
5101
+	{
5102
+		if (empty($id)) {
5103
+			$this->_entity_map[EEM_Base::$_model_query_blog_id] = array();
5104
+			return true;
5105
+		}
5106
+		if (isset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id])) {
5107
+			unset($this->_entity_map[EEM_Base::$_model_query_blog_id][$id]);
5108
+			return true;
5109
+		}
5110
+		return false;
5111
+	}
5112
+
5113
+
5114
+
5115
+	/**
5116
+	 * Public wrapper for _deduce_fields_n_values_from_cols_n_values.
5117
+	 * Given an array where keys are column (or column alias) names and values,
5118
+	 * returns an array of their corresponding field names and database values
5119
+	 *
5120
+	 * @param array $cols_n_values
5121
+	 * @return array
5122
+	 */
5123
+	public function deduce_fields_n_values_from_cols_n_values($cols_n_values)
5124
+	{
5125
+		return $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5126
+	}
5127
+
5128
+
5129
+
5130
+	/**
5131
+	 * _deduce_fields_n_values_from_cols_n_values
5132
+	 * Given an array where keys are column (or column alias) names and values,
5133
+	 * returns an array of their corresponding field names and database values
5134
+	 *
5135
+	 * @param string $cols_n_values
5136
+	 * @return array
5137
+	 */
5138
+	protected function _deduce_fields_n_values_from_cols_n_values($cols_n_values)
5139
+	{
5140
+		$this_model_fields_n_values = array();
5141
+		foreach ($this->get_tables() as $table_alias => $table_obj) {
5142
+			$table_pk_value = $this->_get_column_value_with_table_alias_or_not($cols_n_values,
5143
+				$table_obj->get_fully_qualified_pk_column(), $table_obj->get_pk_column());
5144
+			//there is a primary key on this table and its not set. Use defaults for all its columns
5145
+			if ($table_pk_value === null && $table_obj->get_pk_column()) {
5146
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5147
+					if (! $field_obj->is_db_only_field()) {
5148
+						//prepare field as if its coming from db
5149
+						$prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5150
+						$this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
5151
+					}
5152
+				}
5153
+			} else {
5154
+				//the table's rows existed. Use their values
5155
+				foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5156
+					if (! $field_obj->is_db_only_field()) {
5157
+						$this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5158
+							$cols_n_values, $field_obj->get_qualified_column(),
5159
+							$field_obj->get_table_column()
5160
+						);
5161
+					}
5162
+				}
5163
+			}
5164
+		}
5165
+		return $this_model_fields_n_values;
5166
+	}
5167
+
5168
+
5169
+
5170
+	/**
5171
+	 * @param $cols_n_values
5172
+	 * @param $qualified_column
5173
+	 * @param $regular_column
5174
+	 * @return null
5175
+	 */
5176
+	protected function _get_column_value_with_table_alias_or_not($cols_n_values, $qualified_column, $regular_column)
5177
+	{
5178
+		$value = null;
5179
+		//ask the field what it think it's table_name.column_name should be, and call it the "qualified column"
5180
+		//does the field on the model relate to this column retrieved from the db?
5181
+		//or is it a db-only field? (not relating to the model)
5182
+		if (isset($cols_n_values[$qualified_column])) {
5183
+			$value = $cols_n_values[$qualified_column];
5184
+		} elseif (isset($cols_n_values[$regular_column])) {
5185
+			$value = $cols_n_values[$regular_column];
5186
+		}
5187
+		return $value;
5188
+	}
5189
+
5190
+
5191
+
5192
+	/**
5193
+	 * refresh_entity_map_from_db
5194
+	 * Makes sure the model object in the entity map at $id assumes the values
5195
+	 * of the database (opposite of EE_base_Class::save())
5196
+	 *
5197
+	 * @param int|string $id
5198
+	 * @return EE_Base_Class
5199
+	 * @throws EE_Error
5200
+	 */
5201
+	public function refresh_entity_map_from_db($id)
5202
+	{
5203
+		$obj_in_map = $this->get_from_entity_map($id);
5204
+		if ($obj_in_map) {
5205
+			$wpdb_results = $this->_get_all_wpdb_results(
5206
+				array(array($this->get_primary_key_field()->get_name() => $id), 'limit' => 1)
5207
+			);
5208
+			if ($wpdb_results && is_array($wpdb_results)) {
5209
+				$one_row = reset($wpdb_results);
5210
+				foreach ($this->_deduce_fields_n_values_from_cols_n_values($one_row) as $field_name => $db_value) {
5211
+					$obj_in_map->set_from_db($field_name, $db_value);
5212
+				}
5213
+				//clear the cache of related model objects
5214
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5215
+					$obj_in_map->clear_cache($relation_name, null, true);
5216
+				}
5217
+			}
5218
+			$this->_entity_map[EEM_Base::$_model_query_blog_id][$id] = $obj_in_map;
5219
+			return $obj_in_map;
5220
+		}
5221
+		return $this->get_one_by_ID($id);
5222
+	}
5223
+
5224
+
5225
+
5226
+	/**
5227
+	 * refresh_entity_map_with
5228
+	 * Leaves the entry in the entity map alone, but updates it to match the provided
5229
+	 * $replacing_model_obj (which we assume to be its equivalent but somehow NOT in the entity map).
5230
+	 * This is useful if you have a model object you want to make authoritative over what's in the entity map currently.
5231
+	 * Note: The old $replacing_model_obj should now be destroyed as it's now un-authoritative
5232
+	 *
5233
+	 * @param int|string    $id
5234
+	 * @param EE_Base_Class $replacing_model_obj
5235
+	 * @return \EE_Base_Class
5236
+	 * @throws EE_Error
5237
+	 */
5238
+	public function refresh_entity_map_with($id, $replacing_model_obj)
5239
+	{
5240
+		$obj_in_map = $this->get_from_entity_map($id);
5241
+		if ($obj_in_map) {
5242
+			if ($replacing_model_obj instanceof EE_Base_Class) {
5243
+				foreach ($replacing_model_obj->model_field_array() as $field_name => $value) {
5244
+					$obj_in_map->set($field_name, $value);
5245
+				}
5246
+				//make the model object in the entity map's cache match the $replacing_model_obj
5247
+				foreach ($this->relation_settings() as $relation_name => $relation_obj) {
5248
+					$obj_in_map->clear_cache($relation_name, null, true);
5249
+					foreach ($replacing_model_obj->get_all_from_cache($relation_name) as $cache_id => $cached_obj) {
5250
+						$obj_in_map->cache($relation_name, $cached_obj, $cache_id);
5251
+					}
5252
+				}
5253
+			}
5254
+			return $obj_in_map;
5255
+		}
5256
+		$this->add_to_entity_map($replacing_model_obj);
5257
+		return $replacing_model_obj;
5258
+	}
5259
+
5260
+
5261
+
5262
+	/**
5263
+	 * Gets the EE class that corresponds to this model. Eg, for EEM_Answer that
5264
+	 * would be EE_Answer.To import that class, you'd just add ".class.php" to the name, like so
5265
+	 * require_once($this->_getClassName().".class.php");
5266
+	 *
5267
+	 * @return string
5268
+	 */
5269
+	private function _get_class_name()
5270
+	{
5271
+		return "EE_" . $this->get_this_model_name();
5272
+	}
5273
+
5274
+
5275
+
5276
+	/**
5277
+	 * Get the name of the items this model represents, for the quantity specified. Eg,
5278
+	 * if $quantity==1, on EEM_Event, it would 'Event' (internationalized), otherwise
5279
+	 * it would be 'Events'.
5280
+	 *
5281
+	 * @param int $quantity
5282
+	 * @return string
5283
+	 */
5284
+	public function item_name($quantity = 1)
5285
+	{
5286
+		return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5287
+	}
5288
+
5289
+
5290
+
5291
+	/**
5292
+	 * Very handy general function to allow for plugins to extend any child of EE_TempBase.
5293
+	 * If a method is called on a child of EE_TempBase that doesn't exist, this function is called
5294
+	 * (http://www.garfieldtech.com/blog/php-magic-call) and passed the method's name and arguments. Instead of
5295
+	 * requiring a plugin to extend the EE_TempBase (which works fine is there's only 1 plugin, but when will that
5296
+	 * happen?) they can add a hook onto 'filters_hook_espresso__{className}__{methodName}' (eg,
5297
+	 * filters_hook_espresso__EE_Answer__my_great_function) and accepts 2 arguments: the object on which the function
5298
+	 * was called, and an array of the original arguments passed to the function. Whatever their callback function
5299
+	 * returns will be returned by this function. Example: in functions.php (or in a plugin):
5300
+	 * add_filter('FHEE__EE_Answer__my_callback','my_callback',10,3); function
5301
+	 * my_callback($previousReturnValue,EE_TempBase $object,$argsArray){
5302
+	 * $returnString= "you called my_callback! and passed args:".implode(",",$argsArray);
5303
+	 *        return $previousReturnValue.$returnString;
5304
+	 * }
5305
+	 * require('EEM_Answer.model.php');
5306
+	 * $answer=EEM_Answer::instance();
5307
+	 * echo $answer->my_callback('monkeys',100);
5308
+	 * //will output "you called my_callback! and passed args:monkeys,100"
5309
+	 *
5310
+	 * @param string $methodName name of method which was called on a child of EE_TempBase, but which
5311
+	 * @param array  $args       array of original arguments passed to the function
5312
+	 * @throws EE_Error
5313
+	 * @return mixed whatever the plugin which calls add_filter decides
5314
+	 */
5315
+	public function __call($methodName, $args)
5316
+	{
5317
+		$className = get_class($this);
5318
+		$tagName = "FHEE__{$className}__{$methodName}";
5319
+		if (! has_filter($tagName)) {
5320
+			throw new EE_Error(
5321
+				sprintf(
5322
+					__('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 );',
5323
+						'event_espresso'),
5324
+					$methodName,
5325
+					$className,
5326
+					$tagName,
5327
+					'<br />'
5328
+				)
5329
+			);
5330
+		}
5331
+		return apply_filters($tagName, null, $this, $args);
5332
+	}
5333
+
5334
+
5335
+
5336
+	/**
5337
+	 * Ensures $base_class_obj_or_id is of the EE_Base_Class child that corresponds ot this model.
5338
+	 * If not, assumes its an ID, and uses $this->get_one_by_ID() to get the EE_Base_Class.
5339
+	 *
5340
+	 * @param EE_Base_Class|string|int $base_class_obj_or_id either:
5341
+	 *                                                       the EE_Base_Class object that corresponds to this Model,
5342
+	 *                                                       the object's class name
5343
+	 *                                                       or object's ID
5344
+	 * @param boolean                  $ensure_is_in_db      if set, we will also verify this model object
5345
+	 *                                                       exists in the database. If it does not, we add it
5346
+	 * @throws EE_Error
5347
+	 * @return EE_Base_Class
5348
+	 */
5349
+	public function ensure_is_obj($base_class_obj_or_id, $ensure_is_in_db = false)
5350
+	{
5351
+		$className = $this->_get_class_name();
5352
+		if ($base_class_obj_or_id instanceof $className) {
5353
+			$model_object = $base_class_obj_or_id;
5354
+		} else {
5355
+			$primary_key_field = $this->get_primary_key_field();
5356
+			if (
5357
+				$primary_key_field instanceof EE_Primary_Key_Int_Field
5358
+				&& (
5359
+					is_int($base_class_obj_or_id)
5360
+					|| is_string($base_class_obj_or_id)
5361
+				)
5362
+			) {
5363
+				// assume it's an ID.
5364
+				// either a proper integer or a string representing an integer (eg "101" instead of 101)
5365
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5366
+			} else if (
5367
+				$primary_key_field instanceof EE_Primary_Key_String_Field
5368
+				&& is_string($base_class_obj_or_id)
5369
+			) {
5370
+				// assume its a string representation of the object
5371
+				$model_object = $this->get_one_by_ID($base_class_obj_or_id);
5372
+			} else {
5373
+				throw new EE_Error(
5374
+					sprintf(
5375
+						__(
5376
+							"'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5377
+							'event_espresso'
5378
+						),
5379
+						$base_class_obj_or_id,
5380
+						$this->_get_class_name(),
5381
+						print_r($base_class_obj_or_id, true)
5382
+					)
5383
+				);
5384
+			}
5385
+		}
5386
+		if ($ensure_is_in_db && $model_object->ID() !== null) {
5387
+			$model_object->save();
5388
+		}
5389
+		return $model_object;
5390
+	}
5391
+
5392
+
5393
+
5394
+	/**
5395
+	 * Similar to ensure_is_obj(), this method makes sure $base_class_obj_or_id
5396
+	 * is a value of the this model's primary key. If it's an EE_Base_Class child,
5397
+	 * returns it ID.
5398
+	 *
5399
+	 * @param EE_Base_Class|int|string $base_class_obj_or_id
5400
+	 * @return int|string depending on the type of this model object's ID
5401
+	 * @throws EE_Error
5402
+	 */
5403
+	public function ensure_is_ID($base_class_obj_or_id)
5404
+	{
5405
+		$className = $this->_get_class_name();
5406
+		if ($base_class_obj_or_id instanceof $className) {
5407
+			/** @var $base_class_obj_or_id EE_Base_Class */
5408
+			$id = $base_class_obj_or_id->ID();
5409
+		} elseif (is_int($base_class_obj_or_id)) {
5410
+			//assume it's an ID
5411
+			$id = $base_class_obj_or_id;
5412
+		} elseif (is_string($base_class_obj_or_id)) {
5413
+			//assume its a string representation of the object
5414
+			$id = $base_class_obj_or_id;
5415
+		} else {
5416
+			throw new EE_Error(sprintf(__("'%s' is neither an object of type %s, nor an ID! Its full value is '%s'",
5417
+				'event_espresso'), $base_class_obj_or_id, $this->_get_class_name(),
5418
+				print_r($base_class_obj_or_id, true)));
5419
+		}
5420
+		return $id;
5421
+	}
5422
+
5423
+
5424
+
5425
+	/**
5426
+	 * Sets whether the values passed to the model (eg, values in WHERE, values in INSERT, UPDATE, etc)
5427
+	 * have already been ran through the appropriate model field's prepare_for_use_in_db method. IE, they have
5428
+	 * been sanitized and converted into the appropriate domain.
5429
+	 * Usually the only place you'll want to change the default (which is to assume values have NOT been sanitized by
5430
+	 * the model object/model field) is when making a method call from WITHIN a model object, which has direct access
5431
+	 * to its sanitized values. Note: after changing this setting, you should set it back to its previous value (using
5432
+	 * get_assumption_concerning_values_already_prepared_by_model_object()) eg.
5433
+	 * $EVT = EEM_Event::instance(); $old_setting =
5434
+	 * $EVT->get_assumption_concerning_values_already_prepared_by_model_object();
5435
+	 * $EVT->assume_values_already_prepared_by_model_object(true);
5436
+	 * $EVT->update(array('foo'=>'bar'),array(array('foo'=>'monkey')));
5437
+	 * $EVT->assume_values_already_prepared_by_model_object($old_setting);
5438
+	 *
5439
+	 * @param int $values_already_prepared like one of the constants on EEM_Base
5440
+	 * @return void
5441
+	 */
5442
+	public function assume_values_already_prepared_by_model_object(
5443
+		$values_already_prepared = self::not_prepared_by_model_object
5444
+	) {
5445
+		$this->_values_already_prepared_by_model_object = $values_already_prepared;
5446
+	}
5447
+
5448
+
5449
+
5450
+	/**
5451
+	 * Read comments for assume_values_already_prepared_by_model_object()
5452
+	 *
5453
+	 * @return int
5454
+	 */
5455
+	public function get_assumption_concerning_values_already_prepared_by_model_object()
5456
+	{
5457
+		return $this->_values_already_prepared_by_model_object;
5458
+	}
5459
+
5460
+
5461
+
5462
+	/**
5463
+	 * Gets all the indexes on this model
5464
+	 *
5465
+	 * @return EE_Index[]
5466
+	 */
5467
+	public function indexes()
5468
+	{
5469
+		return $this->_indexes;
5470
+	}
5471
+
5472
+
5473
+
5474
+	/**
5475
+	 * Gets all the Unique Indexes on this model
5476
+	 *
5477
+	 * @return EE_Unique_Index[]
5478
+	 */
5479
+	public function unique_indexes()
5480
+	{
5481
+		$unique_indexes = array();
5482
+		foreach ($this->_indexes as $name => $index) {
5483
+			if ($index instanceof EE_Unique_Index) {
5484
+				$unique_indexes [$name] = $index;
5485
+			}
5486
+		}
5487
+		return $unique_indexes;
5488
+	}
5489
+
5490
+
5491
+
5492
+	/**
5493
+	 * Gets all the fields which, when combined, make the primary key.
5494
+	 * This is usually just an array with 1 element (the primary key), but in cases
5495
+	 * where there is no primary key, it's a combination of fields as defined
5496
+	 * on a primary index
5497
+	 *
5498
+	 * @return EE_Model_Field_Base[] indexed by the field's name
5499
+	 * @throws EE_Error
5500
+	 */
5501
+	public function get_combined_primary_key_fields()
5502
+	{
5503
+		foreach ($this->indexes() as $index) {
5504
+			if ($index instanceof EE_Primary_Key_Index) {
5505
+				return $index->fields();
5506
+			}
5507
+		}
5508
+		return array($this->primary_key_name() => $this->get_primary_key_field());
5509
+	}
5510
+
5511
+
5512
+
5513
+	/**
5514
+	 * Used to build a primary key string (when the model has no primary key),
5515
+	 * which can be used a unique string to identify this model object.
5516
+	 *
5517
+	 * @param array $cols_n_values keys are field names, values are their values
5518
+	 * @return string
5519
+	 * @throws EE_Error
5520
+	 */
5521
+	public function get_index_primary_key_string($cols_n_values)
5522
+	{
5523
+		$cols_n_values_for_primary_key_index = array_intersect_key($cols_n_values,
5524
+			$this->get_combined_primary_key_fields());
5525
+		return http_build_query($cols_n_values_for_primary_key_index);
5526
+	}
5527
+
5528
+
5529
+
5530
+	/**
5531
+	 * Gets the field values from the primary key string
5532
+	 *
5533
+	 * @see EEM_Base::get_combined_primary_key_fields() and EEM_Base::get_index_primary_key_string()
5534
+	 * @param string $index_primary_key_string
5535
+	 * @return null|array
5536
+	 * @throws EE_Error
5537
+	 */
5538
+	public function parse_index_primary_key_string($index_primary_key_string)
5539
+	{
5540
+		$key_fields = $this->get_combined_primary_key_fields();
5541
+		//check all of them are in the $id
5542
+		$key_vals_in_combined_pk = array();
5543
+		parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5544
+		foreach ($key_fields as $key_field_name => $field_obj) {
5545
+			if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5546
+				return null;
5547
+			}
5548
+		}
5549
+		return $key_vals_in_combined_pk;
5550
+	}
5551
+
5552
+
5553
+
5554
+	/**
5555
+	 * verifies that an array of key-value pairs for model fields has a key
5556
+	 * for each field comprising the primary key index
5557
+	 *
5558
+	 * @param array $key_vals
5559
+	 * @return boolean
5560
+	 * @throws EE_Error
5561
+	 */
5562
+	public function has_all_combined_primary_key_fields($key_vals)
5563
+	{
5564
+		$keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5565
+		foreach ($keys_it_should_have as $key) {
5566
+			if (! isset($key_vals[$key])) {
5567
+				return false;
5568
+			}
5569
+		}
5570
+		return true;
5571
+	}
5572
+
5573
+
5574
+
5575
+	/**
5576
+	 * Finds all model objects in the DB that appear to be a copy of $model_object_or_attributes_array.
5577
+	 * We consider something to be a copy if all the attributes match (except the ID, of course).
5578
+	 *
5579
+	 * @param array|EE_Base_Class $model_object_or_attributes_array If its an array, it's field-value pairs
5580
+	 * @param array               $query_params                     like EEM_Base::get_all's query_params.
5581
+	 * @throws EE_Error
5582
+	 * @return \EE_Base_Class[] Array keys are object IDs (if there is a primary key on the model. if not, numerically
5583
+	 *                                                              indexed)
5584
+	 */
5585
+	public function get_all_copies($model_object_or_attributes_array, $query_params = array())
5586
+	{
5587
+		if ($model_object_or_attributes_array instanceof EE_Base_Class) {
5588
+			$attributes_array = $model_object_or_attributes_array->model_field_array();
5589
+		} elseif (is_array($model_object_or_attributes_array)) {
5590
+			$attributes_array = $model_object_or_attributes_array;
5591
+		} else {
5592
+			throw new EE_Error(sprintf(__("get_all_copies should be provided with either a model object or an array of field-value-pairs, but was given %s",
5593
+				"event_espresso"), $model_object_or_attributes_array));
5594
+		}
5595
+		//even copies obviously won't have the same ID, so remove the primary key
5596
+		//from the WHERE conditions for finding copies (if there is a primary key, of course)
5597
+		if ($this->has_primary_key_field() && isset($attributes_array[$this->primary_key_name()])) {
5598
+			unset($attributes_array[$this->primary_key_name()]);
5599
+		}
5600
+		if (isset($query_params[0])) {
5601
+			$query_params[0] = array_merge($attributes_array, $query_params);
5602
+		} else {
5603
+			$query_params[0] = $attributes_array;
5604
+		}
5605
+		return $this->get_all($query_params);
5606
+	}
5607
+
5608
+
5609
+
5610
+	/**
5611
+	 * Gets the first copy we find. See get_all_copies for more details
5612
+	 *
5613
+	 * @param       mixed EE_Base_Class | array        $model_object_or_attributes_array
5614
+	 * @param array $query_params
5615
+	 * @return EE_Base_Class
5616
+	 * @throws EE_Error
5617
+	 */
5618
+	public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5619
+	{
5620
+		if (! is_array($query_params)) {
5621
+			EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5622
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5623
+					gettype($query_params)), '4.6.0');
5624
+			$query_params = array();
5625
+		}
5626
+		$query_params['limit'] = 1;
5627
+		$copies = $this->get_all_copies($model_object_or_attributes_array, $query_params);
5628
+		if (is_array($copies)) {
5629
+			return array_shift($copies);
5630
+		}
5631
+		return null;
5632
+	}
5633
+
5634
+
5635
+
5636
+	/**
5637
+	 * Updates the item with the specified id. Ignores default query parameters because
5638
+	 * we have specified the ID, and its assumed we KNOW what we're doing
5639
+	 *
5640
+	 * @param array      $fields_n_values keys are field names, values are their new values
5641
+	 * @param int|string $id              the value of the primary key to update
5642
+	 * @return int number of rows updated
5643
+	 * @throws EE_Error
5644
+	 */
5645
+	public function update_by_ID($fields_n_values, $id)
5646
+	{
5647
+		$query_params = array(
5648
+			0                          => array($this->get_primary_key_field()->get_name() => $id),
5649
+			'default_where_conditions' => EEM_Base::default_where_conditions_others_only,
5650
+		);
5651
+		return $this->update($fields_n_values, $query_params);
5652
+	}
5653
+
5654
+
5655
+
5656
+	/**
5657
+	 * Changes an operator which was supplied to the models into one usable in SQL
5658
+	 *
5659
+	 * @param string $operator_supplied
5660
+	 * @return string an operator which can be used in SQL
5661
+	 * @throws EE_Error
5662
+	 */
5663
+	private function _prepare_operator_for_sql($operator_supplied)
5664
+	{
5665
+		$sql_operator = isset($this->_valid_operators[$operator_supplied]) ? $this->_valid_operators[$operator_supplied]
5666
+			: null;
5667
+		if ($sql_operator) {
5668
+			return $sql_operator;
5669
+		}
5670
+		throw new EE_Error(
5671
+			sprintf(
5672
+				__(
5673
+					"The operator '%s' is not in the list of valid operators: %s",
5674
+					"event_espresso"
5675
+				), $operator_supplied, implode(",", array_keys($this->_valid_operators))
5676
+			)
5677
+		);
5678
+	}
5679
+
5680
+
5681
+
5682
+	/**
5683
+	 * Gets the valid operators
5684
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5685
+	 */
5686
+	public function valid_operators(){
5687
+		return $this->_valid_operators;
5688
+	}
5689
+
5690
+
5691
+
5692
+	/**
5693
+	 * Gets the between-style operators (take 2 arguments).
5694
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5695
+	 */
5696
+	public function valid_between_style_operators()
5697
+	{
5698
+		return array_intersect(
5699
+			$this->valid_operators(),
5700
+			$this->_between_style_operators
5701
+		);
5702
+	}
5703
+
5704
+	/**
5705
+	 * Gets the "like"-style operators (take a single argument, but it may contain wildcards)
5706
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5707
+	 */
5708
+	public function valid_like_style_operators()
5709
+	{
5710
+		return array_intersect(
5711
+			$this->valid_operators(),
5712
+			$this->_like_style_operators
5713
+		);
5714
+	}
5715
+
5716
+	/**
5717
+	 * Gets the "in"-style operators
5718
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5719
+	 */
5720
+	public function valid_in_style_operators()
5721
+	{
5722
+		return array_intersect(
5723
+			$this->valid_operators(),
5724
+			$this->_in_style_operators
5725
+		);
5726
+	}
5727
+
5728
+	/**
5729
+	 * Gets the "null"-style operators (accept no arguments)
5730
+	 * @return array keys are accepted strings, values are the SQL they are converted to
5731
+	 */
5732
+	public function valid_null_style_operators()
5733
+	{
5734
+		return array_intersect(
5735
+			$this->valid_operators(),
5736
+			$this->_null_style_operators
5737
+		);
5738
+	}
5739
+
5740
+	/**
5741
+	 * Gets an array where keys are the primary keys and values are their 'names'
5742
+	 * (as determined by the model object's name() function, which is often overridden)
5743
+	 *
5744
+	 * @param array $query_params like get_all's
5745
+	 * @return string[]
5746
+	 * @throws EE_Error
5747
+	 */
5748
+	public function get_all_names($query_params = array())
5749
+	{
5750
+		$objs = $this->get_all($query_params);
5751
+		$names = array();
5752
+		foreach ($objs as $obj) {
5753
+			$names[$obj->ID()] = $obj->name();
5754
+		}
5755
+		return $names;
5756
+	}
5757
+
5758
+
5759
+
5760
+	/**
5761
+	 * Gets an array of primary keys from the model objects. If you acquired the model objects
5762
+	 * using EEM_Base::get_all() you don't need to call this (and probably shouldn't because
5763
+	 * this is duplicated effort and reduces efficiency) you would be better to use
5764
+	 * array_keys() on $model_objects.
5765
+	 *
5766
+	 * @param \EE_Base_Class[] $model_objects
5767
+	 * @param boolean          $filter_out_empty_ids if a model object has an ID of '' or 0, don't bother including it
5768
+	 *                                               in the returned array
5769
+	 * @return array
5770
+	 * @throws EE_Error
5771
+	 */
5772
+	public function get_IDs($model_objects, $filter_out_empty_ids = false)
5773
+	{
5774
+		if (! $this->has_primary_key_field()) {
5775
+			if (WP_DEBUG) {
5776
+				EE_Error::add_error(
5777
+					__('Trying to get IDs from a model than has no primary key', 'event_espresso'),
5778
+					__FILE__,
5779
+					__FUNCTION__,
5780
+					__LINE__
5781
+				);
5782
+			}
5783
+		}
5784
+		$IDs = array();
5785
+		foreach ($model_objects as $model_object) {
5786
+			$id = $model_object->ID();
5787
+			if (! $id) {
5788
+				if ($filter_out_empty_ids) {
5789
+					continue;
5790
+				}
5791
+				if (WP_DEBUG) {
5792
+					EE_Error::add_error(
5793
+						__(
5794
+							'Called %1$s on a model object that has no ID and so probably hasn\'t been saved to the database',
5795
+							'event_espresso'
5796
+						),
5797
+						__FILE__,
5798
+						__FUNCTION__,
5799
+						__LINE__
5800
+					);
5801
+				}
5802
+			}
5803
+			$IDs[] = $id;
5804
+		}
5805
+		return $IDs;
5806
+	}
5807
+
5808
+
5809
+
5810
+	/**
5811
+	 * Returns the string used in capabilities relating to this model. If there
5812
+	 * are no capabilities that relate to this model returns false
5813
+	 *
5814
+	 * @return string|false
5815
+	 */
5816
+	public function cap_slug()
5817
+	{
5818
+		return apply_filters('FHEE__EEM_Base__cap_slug', $this->_caps_slug, $this);
5819
+	}
5820
+
5821
+
5822
+
5823
+	/**
5824
+	 * Returns the capability-restrictions array (@see EEM_Base::_cap_restrictions).
5825
+	 * If $context is provided (which should be set to one of EEM_Base::valid_cap_contexts())
5826
+	 * only returns the cap restrictions array in that context (ie, the array
5827
+	 * at that key)
5828
+	 *
5829
+	 * @param string $context
5830
+	 * @return EE_Default_Where_Conditions[] indexed by associated capability
5831
+	 * @throws EE_Error
5832
+	 */
5833
+	public function cap_restrictions($context = EEM_Base::caps_read)
5834
+	{
5835
+		EEM_Base::verify_is_valid_cap_context($context);
5836
+		//check if we ought to run the restriction generator first
5837
+		if (
5838
+			isset($this->_cap_restriction_generators[$context])
5839
+			&& $this->_cap_restriction_generators[$context] instanceof EE_Restriction_Generator_Base
5840
+			&& ! $this->_cap_restriction_generators[$context]->has_generated_cap_restrictions()
5841
+		) {
5842
+			$this->_cap_restrictions[$context] = array_merge(
5843
+				$this->_cap_restrictions[$context],
5844
+				$this->_cap_restriction_generators[$context]->generate_restrictions()
5845
+			);
5846
+		}
5847
+		//and make sure we've finalized the construction of each restriction
5848
+		foreach ($this->_cap_restrictions[$context] as $where_conditions_obj) {
5849
+			if ($where_conditions_obj instanceof EE_Default_Where_Conditions) {
5850
+				$where_conditions_obj->_finalize_construct($this);
5851
+			}
5852
+		}
5853
+		return $this->_cap_restrictions[$context];
5854
+	}
5855
+
5856
+
5857
+
5858
+	/**
5859
+	 * Indicating whether or not this model thinks its a wp core model
5860
+	 *
5861
+	 * @return boolean
5862
+	 */
5863
+	public function is_wp_core_model()
5864
+	{
5865
+		return $this->_wp_core_model;
5866
+	}
5867
+
5868
+
5869
+
5870
+	/**
5871
+	 * Gets all the caps that are missing which impose a restriction on
5872
+	 * queries made in this context
5873
+	 *
5874
+	 * @param string $context one of EEM_Base::caps_ constants
5875
+	 * @return EE_Default_Where_Conditions[] indexed by capability name
5876
+	 * @throws EE_Error
5877
+	 */
5878
+	public function caps_missing($context = EEM_Base::caps_read)
5879
+	{
5880
+		$missing_caps = array();
5881
+		$cap_restrictions = $this->cap_restrictions($context);
5882
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5883
+			if (! EE_Capabilities::instance()
5884
+								 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5885
+			) {
5886
+				$missing_caps[$cap] = $restriction_if_no_cap;
5887
+			}
5888
+		}
5889
+		return $missing_caps;
5890
+	}
5891
+
5892
+
5893
+
5894
+	/**
5895
+	 * Gets the mapping from capability contexts to action strings used in capability names
5896
+	 *
5897
+	 * @return array keys are one of EEM_Base::valid_cap_contexts(), and values are usually
5898
+	 * one of 'read', 'edit', or 'delete'
5899
+	 */
5900
+	public function cap_contexts_to_cap_action_map()
5901
+	{
5902
+		return apply_filters('FHEE__EEM_Base__cap_contexts_to_cap_action_map', $this->_cap_contexts_to_cap_action_map,
5903
+			$this);
5904
+	}
5905
+
5906
+
5907
+
5908
+	/**
5909
+	 * Gets the action string for the specified capability context
5910
+	 *
5911
+	 * @param string $context
5912
+	 * @return string one of EEM_Base::cap_contexts_to_cap_action_map() values
5913
+	 * @throws EE_Error
5914
+	 */
5915
+	public function cap_action_for_context($context)
5916
+	{
5917
+		$mapping = $this->cap_contexts_to_cap_action_map();
5918
+		if (isset($mapping[$context])) {
5919
+			return $mapping[$context];
5920
+		}
5921
+		if ($action = apply_filters('FHEE__EEM_Base__cap_action_for_context', null, $this, $mapping, $context)) {
5922
+			return $action;
5923
+		}
5924
+		throw new EE_Error(
5925
+			sprintf(
5926
+				__('Cannot find capability restrictions for context "%1$s", allowed values are:%2$s', 'event_espresso'),
5927
+				$context,
5928
+				implode(',', array_keys($this->cap_contexts_to_cap_action_map()))
5929
+			)
5930
+		);
5931
+	}
5932
+
5933
+
5934
+
5935
+	/**
5936
+	 * Returns all the capability contexts which are valid when querying models
5937
+	 *
5938
+	 * @return array
5939
+	 */
5940
+	public static function valid_cap_contexts()
5941
+	{
5942
+		return apply_filters('FHEE__EEM_Base__valid_cap_contexts', array(
5943
+			self::caps_read,
5944
+			self::caps_read_admin,
5945
+			self::caps_edit,
5946
+			self::caps_delete,
5947
+		));
5948
+	}
5949
+
5950
+
5951
+
5952
+	/**
5953
+	 * Returns all valid options for 'default_where_conditions'
5954
+	 *
5955
+	 * @return array
5956
+	 */
5957
+	public static function valid_default_where_conditions()
5958
+	{
5959
+		return array(
5960
+			EEM_Base::default_where_conditions_all,
5961
+			EEM_Base::default_where_conditions_this_only,
5962
+			EEM_Base::default_where_conditions_others_only,
5963
+			EEM_Base::default_where_conditions_minimum_all,
5964
+			EEM_Base::default_where_conditions_minimum_others,
5965
+			EEM_Base::default_where_conditions_none
5966
+		);
5967
+	}
5968
+
5969
+	// public static function default_where_conditions_full
5970
+	/**
5971
+	 * Verifies $context is one of EEM_Base::valid_cap_contexts(), if not it throws an exception
5972
+	 *
5973
+	 * @param string $context
5974
+	 * @return bool
5975
+	 * @throws EE_Error
5976
+	 */
5977
+	static public function verify_is_valid_cap_context($context)
5978
+	{
5979
+		$valid_cap_contexts = EEM_Base::valid_cap_contexts();
5980
+		if (in_array($context, $valid_cap_contexts)) {
5981
+			return true;
5982
+		}
5983
+		throw new EE_Error(
5984
+			sprintf(
5985
+				__(
5986
+					'Context "%1$s" passed into model "%2$s" is not a valid context. They are: %3$s',
5987
+					'event_espresso'
5988
+				),
5989
+				$context,
5990
+				'EEM_Base',
5991
+				implode(',', $valid_cap_contexts)
5992
+			)
5993
+		);
5994
+	}
5995
+
5996
+
5997
+
5998
+	/**
5999
+	 * Clears all the models field caches. This is only useful when a sub-class
6000
+	 * might have added a field or something and these caches might be invalidated
6001
+	 */
6002
+	protected function _invalidate_field_caches()
6003
+	{
6004
+		$this->_cache_foreign_key_to_fields = array();
6005
+		$this->_cached_fields = null;
6006
+		$this->_cached_fields_non_db_only = null;
6007
+	}
6008
+
6009
+
6010
+
6011
+	/**
6012
+	 * Gets the list of all the where query param keys that relate to logic instead of field names
6013
+	 * (eg "and", "or", "not").
6014
+	 *
6015
+	 * @return array
6016
+	 */
6017
+	public function logic_query_param_keys()
6018
+	{
6019
+		return $this->_logic_query_param_keys;
6020
+	}
6021
+
6022
+
6023
+
6024
+	/**
6025
+	 * Determines whether or not the where query param array key is for a logic query param.
6026
+	 * Eg 'OR', 'not*', and 'and*because-i-say-so' should all return true, whereas
6027
+	 * 'ATT_fname', 'EVT_name*not-you-or-me', and 'ORG_name' should return false
6028
+	 *
6029
+	 * @param $query_param_key
6030
+	 * @return bool
6031
+	 */
6032
+	public function is_logic_query_param_key($query_param_key)
6033
+	{
6034
+		foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6035
+			if ($query_param_key === $logic_query_param_key
6036
+				|| strpos($query_param_key, $logic_query_param_key . '*') === 0
6037
+			) {
6038
+				return true;
6039
+			}
6040
+		}
6041
+		return false;
6042
+	}
6043 6043
 
6044 6044
 
6045 6045
 
Please login to merge, or discard this patch.
Spacing   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -511,8 +511,8 @@  discard block
 block discarded – undo
511 511
     protected function __construct($timezone = null)
512 512
     {
513 513
         // check that the model has not been loaded too soon
514
-        if (! did_action('AHEE__EE_System__load_espresso_addons')) {
515
-            throw new EE_Error (
514
+        if ( ! did_action('AHEE__EE_System__load_espresso_addons')) {
515
+            throw new EE_Error(
516 516
                 sprintf(
517 517
                     __('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.',
518 518
                         'event_espresso'),
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
          *
533 533
          * @var EE_Table_Base[] $_tables
534 534
          */
535
-        $this->_tables = (array)apply_filters('FHEE__' . get_class($this) . '__construct__tables', $this->_tables);
535
+        $this->_tables = (array) apply_filters('FHEE__'.get_class($this).'__construct__tables', $this->_tables);
536 536
         foreach ($this->_tables as $table_alias => $table_obj) {
537 537
             /** @var $table_obj EE_Table_Base */
538 538
             $table_obj->_construct_finalize_with_alias($table_alias);
@@ -547,10 +547,10 @@  discard block
 block discarded – undo
547 547
          *
548 548
          * @param EE_Model_Field_Base[] $_fields
549 549
          */
550
-        $this->_fields = (array)apply_filters('FHEE__' . get_class($this) . '__construct__fields', $this->_fields);
550
+        $this->_fields = (array) apply_filters('FHEE__'.get_class($this).'__construct__fields', $this->_fields);
551 551
         $this->_invalidate_field_caches();
552 552
         foreach ($this->_fields as $table_alias => $fields_for_table) {
553
-            if (! array_key_exists($table_alias, $this->_tables)) {
553
+            if ( ! array_key_exists($table_alias, $this->_tables)) {
554 554
                 throw new EE_Error(sprintf(__("Table alias %s does not exist in EEM_Base child's _tables array. Only tables defined are %s",
555 555
                     'event_espresso'), $table_alias, implode(",", $this->_fields)));
556 556
             }
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
          *
579 579
          * @param EE_Model_Relation_Base[] $_model_relations
580 580
          */
581
-        $this->_model_relations = (array)apply_filters('FHEE__' . get_class($this) . '__construct__model_relations',
581
+        $this->_model_relations = (array) apply_filters('FHEE__'.get_class($this).'__construct__model_relations',
582 582
             $this->_model_relations);
583 583
         foreach ($this->_model_relations as $model_name => $relation_obj) {
584 584
             /** @var $relation_obj EE_Model_Relation_Base */
@@ -590,12 +590,12 @@  discard block
 block discarded – undo
590 590
         }
591 591
         $this->set_timezone($timezone);
592 592
         //finalize default where condition strategy, or set default
593
-        if (! $this->_default_where_conditions_strategy) {
593
+        if ( ! $this->_default_where_conditions_strategy) {
594 594
             //nothing was set during child constructor, so set default
595 595
             $this->_default_where_conditions_strategy = new EE_Default_Where_Conditions();
596 596
         }
597 597
         $this->_default_where_conditions_strategy->_finalize_construct($this);
598
-        if (! $this->_minimum_where_conditions_strategy) {
598
+        if ( ! $this->_minimum_where_conditions_strategy) {
599 599
             //nothing was set during child constructor, so set default
600 600
             $this->_minimum_where_conditions_strategy = new EE_Default_Where_Conditions();
601 601
         }
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
         //initialize the standard cap restriction generators if none were specified by the child constructor
609 609
         if ($this->_cap_restriction_generators !== false) {
610 610
             foreach ($this->cap_contexts_to_cap_action_map() as $cap_context => $action) {
611
-                if (! isset($this->_cap_restriction_generators[$cap_context])) {
611
+                if ( ! isset($this->_cap_restriction_generators[$cap_context])) {
612 612
                     $this->_cap_restriction_generators[$cap_context] = apply_filters(
613 613
                         'FHEE__EEM_Base___construct__standard_cap_restriction_generator',
614 614
                         new EE_Restriction_Generator_Protected(),
@@ -621,10 +621,10 @@  discard block
 block discarded – undo
621 621
         //if there are cap restriction generators, use them to make the default cap restrictions
622 622
         if ($this->_cap_restriction_generators !== false) {
623 623
             foreach ($this->_cap_restriction_generators as $context => $generator_object) {
624
-                if (! $generator_object) {
624
+                if ( ! $generator_object) {
625 625
                     continue;
626 626
                 }
627
-                if (! $generator_object instanceof EE_Restriction_Generator_Base) {
627
+                if ( ! $generator_object instanceof EE_Restriction_Generator_Base) {
628 628
                     throw new EE_Error(
629 629
                         sprintf(
630 630
                             __('Index "%1$s" in the model %2$s\'s _cap_restriction_generators is not a child of EE_Restriction_Generator_Base. It should be that or NULL.',
@@ -635,12 +635,12 @@  discard block
 block discarded – undo
635 635
                     );
636 636
                 }
637 637
                 $action = $this->cap_action_for_context($context);
638
-                if (! $generator_object->construction_finalized()) {
638
+                if ( ! $generator_object->construction_finalized()) {
639 639
                     $generator_object->_construct_finalize($this, $action);
640 640
                 }
641 641
             }
642 642
         }
643
-        do_action('AHEE__' . get_class($this) . '__construct__end');
643
+        do_action('AHEE__'.get_class($this).'__construct__end');
644 644
     }
645 645
 
646 646
 
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
      */
654 654
     public static function set_model_query_blog_id($blog_id = 0)
655 655
     {
656
-        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int)$blog_id : get_current_blog_id();
656
+        EEM_Base::$_model_query_blog_id = $blog_id > 0 ? (int) $blog_id : get_current_blog_id();
657 657
     }
658 658
 
659 659
 
@@ -687,7 +687,7 @@  discard block
 block discarded – undo
687 687
     public static function instance($timezone = null)
688 688
     {
689 689
         // check if instance of Espresso_model already exists
690
-        if (! static::$_instance instanceof static) {
690
+        if ( ! static::$_instance instanceof static) {
691 691
             // instantiate Espresso_model
692 692
             static::$_instance = new static(
693 693
                 $timezone,
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
             foreach ($r->getDefaultProperties() as $property => $value) {
727 727
                 //don't set instance to null like it was originally,
728 728
                 //but it's static anyways, and we're ignoring static properties (for now at least)
729
-                if (! isset($static_properties[$property])) {
729
+                if ( ! isset($static_properties[$property])) {
730 730
                     static::$_instance->{$property} = $value;
731 731
                 }
732 732
             }
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
      */
751 751
     private static function getLoader()
752 752
     {
753
-        if(! EEM_Base::$loader instanceof LoaderInterface) {
753
+        if ( ! EEM_Base::$loader instanceof LoaderInterface) {
754 754
             EEM_Base::$loader = LoaderFactory::getLoader();
755 755
         }
756 756
         return EEM_Base::$loader;
@@ -770,7 +770,7 @@  discard block
 block discarded – undo
770 770
      */
771 771
     public function status_array($translated = false)
772 772
     {
773
-        if (! array_key_exists('Status', $this->_model_relations)) {
773
+        if ( ! array_key_exists('Status', $this->_model_relations)) {
774 774
             return array();
775 775
         }
776 776
         $model_name = $this->get_this_model_name();
@@ -973,17 +973,17 @@  discard block
 block discarded – undo
973 973
     public function wp_user_field_name()
974 974
     {
975 975
         try {
976
-            if (! empty($this->_model_chain_to_wp_user)) {
976
+            if ( ! empty($this->_model_chain_to_wp_user)) {
977 977
                 $models_to_follow_to_wp_users = explode('.', $this->_model_chain_to_wp_user);
978 978
                 $last_model_name = end($models_to_follow_to_wp_users);
979 979
                 $model_with_fk_to_wp_users = EE_Registry::instance()->load_model($last_model_name);
980
-                $model_chain_to_wp_user = $this->_model_chain_to_wp_user . '.';
980
+                $model_chain_to_wp_user = $this->_model_chain_to_wp_user.'.';
981 981
             } else {
982 982
                 $model_with_fk_to_wp_users = $this;
983 983
                 $model_chain_to_wp_user = '';
984 984
             }
985 985
             $wp_user_field = $model_with_fk_to_wp_users->get_foreign_key_to('WP_User');
986
-            return $model_chain_to_wp_user . $wp_user_field->get_name();
986
+            return $model_chain_to_wp_user.$wp_user_field->get_name();
987 987
         } catch (EE_Error $e) {
988 988
             return false;
989 989
         }
@@ -1054,12 +1054,12 @@  discard block
 block discarded – undo
1054 1054
         // remember the custom selections, if any, and type cast as array
1055 1055
         // (unless $columns_to_select is an object, then just set as an empty array)
1056 1056
         // Note: (array) 'some string' === array( 'some string' )
1057
-        $this->_custom_selections = ! is_object($columns_to_select) ? (array)$columns_to_select : array();
1057
+        $this->_custom_selections = ! is_object($columns_to_select) ? (array) $columns_to_select : array();
1058 1058
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1059 1059
         $select_expressions = $columns_to_select !== null
1060 1060
             ? $this->_construct_select_from_input($columns_to_select)
1061 1061
             : $this->_construct_default_select_sql($model_query_info);
1062
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1062
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1063 1063
         return $this->_do_wpdb_query('get_results', array($SQL, $output));
1064 1064
     }
1065 1065
 
@@ -1104,7 +1104,7 @@  discard block
 block discarded – undo
1104 1104
         if (is_array($columns_to_select)) {
1105 1105
             $select_sql_array = array();
1106 1106
             foreach ($columns_to_select as $alias => $selection_and_datatype) {
1107
-                if (! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1107
+                if ( ! is_array($selection_and_datatype) || ! isset($selection_and_datatype[1])) {
1108 1108
                     throw new EE_Error(
1109 1109
                         sprintf(
1110 1110
                             __(
@@ -1116,7 +1116,7 @@  discard block
 block discarded – undo
1116 1116
                         )
1117 1117
                     );
1118 1118
                 }
1119
-                if (! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1119
+                if ( ! in_array($selection_and_datatype[1], $this->_valid_wpdb_data_types, true)) {
1120 1120
                     throw new EE_Error(
1121 1121
                         sprintf(
1122 1122
                             esc_html__(
@@ -1188,7 +1188,7 @@  discard block
 block discarded – undo
1188 1188
      */
1189 1189
     public function alter_query_params_to_restrict_by_ID($id, $query_params = array())
1190 1190
     {
1191
-        if (! isset($query_params[0])) {
1191
+        if ( ! isset($query_params[0])) {
1192 1192
             $query_params[0] = array();
1193 1193
         }
1194 1194
         $conditions_from_id = $this->parse_index_primary_key_string($id);
@@ -1213,7 +1213,7 @@  discard block
 block discarded – undo
1213 1213
      */
1214 1214
     public function get_one($query_params = array())
1215 1215
     {
1216
-        if (! is_array($query_params)) {
1216
+        if ( ! is_array($query_params)) {
1217 1217
             EE_Error::doing_it_wrong('EEM_Base::get_one',
1218 1218
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1219 1219
                     gettype($query_params)), '4.6.0');
@@ -1404,7 +1404,7 @@  discard block
 block discarded – undo
1404 1404
                 return array();
1405 1405
             }
1406 1406
         }
1407
-        if (! is_array($query_params)) {
1407
+        if ( ! is_array($query_params)) {
1408 1408
             EE_Error::doing_it_wrong('EEM_Base::_get_consecutive',
1409 1409
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1410 1410
                     gettype($query_params)), '4.6.0');
@@ -1414,7 +1414,7 @@  discard block
 block discarded – undo
1414 1414
         $query_params[0][$field_to_order_by] = array($operand, $current_field_value);
1415 1415
         $query_params['limit'] = $limit;
1416 1416
         //set direction
1417
-        $incoming_orderby = isset($query_params['order_by']) ? (array)$query_params['order_by'] : array();
1417
+        $incoming_orderby = isset($query_params['order_by']) ? (array) $query_params['order_by'] : array();
1418 1418
         $query_params['order_by'] = $operand === '>'
1419 1419
             ? array($field_to_order_by => 'ASC') + $incoming_orderby
1420 1420
             : array($field_to_order_by => 'DESC') + $incoming_orderby;
@@ -1492,7 +1492,7 @@  discard block
 block discarded – undo
1492 1492
     {
1493 1493
         $field_settings = $this->field_settings_for($field_name);
1494 1494
         //if not a valid EE_Datetime_Field then throw error
1495
-        if (! $field_settings instanceof EE_Datetime_Field) {
1495
+        if ( ! $field_settings instanceof EE_Datetime_Field) {
1496 1496
             throw new EE_Error(sprintf(__('The field sent into EEM_Base::get_formats_for (%s) is not registered as a EE_Datetime_Field. Please check the spelling and make sure you are submitting the right field name to retrieve date_formats for.',
1497 1497
                 'event_espresso'), $field_name));
1498 1498
         }
@@ -1571,7 +1571,7 @@  discard block
 block discarded – undo
1571 1571
         //load EEH_DTT_Helper
1572 1572
         $set_timezone = empty($timezone) ? EEH_DTT_Helper::get_timezone() : $timezone;
1573 1573
         $incomingDateTime = date_create_from_format($incoming_format, $timestring, new DateTimeZone($set_timezone));
1574
-        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime( $incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)) );
1574
+        return \EventEspresso\core\domain\entities\DbSafeDateTime::createFromDateTime($incomingDateTime->setTimezone(new DateTimeZone($this->_timezone)));
1575 1575
     }
1576 1576
 
1577 1577
 
@@ -1639,7 +1639,7 @@  discard block
 block discarded – undo
1639 1639
      */
1640 1640
     public function update($fields_n_values, $query_params, $keep_model_objs_in_sync = true)
1641 1641
     {
1642
-        if (! is_array($query_params)) {
1642
+        if ( ! is_array($query_params)) {
1643 1643
             EE_Error::doing_it_wrong('EEM_Base::update',
1644 1644
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
1645 1645
                     gettype($query_params)), '4.6.0');
@@ -1661,7 +1661,7 @@  discard block
 block discarded – undo
1661 1661
          * @param EEM_Base $model           the model being queried
1662 1662
          * @param array    $query_params    see EEM_Base::get_all()
1663 1663
          */
1664
-        $fields_n_values = (array)apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1664
+        $fields_n_values = (array) apply_filters('FHEE__EEM_Base__update__fields_n_values', $fields_n_values, $this,
1665 1665
             $query_params);
1666 1666
         //need to verify that, for any entry we want to update, there are entries in each secondary table.
1667 1667
         //to do that, for each table, verify that it's PK isn't null.
@@ -1675,7 +1675,7 @@  discard block
 block discarded – undo
1675 1675
         $wpdb_select_results = $this->_get_all_wpdb_results($query_params);
1676 1676
         foreach ($wpdb_select_results as $wpdb_result) {
1677 1677
             // type cast stdClass as array
1678
-            $wpdb_result = (array)$wpdb_result;
1678
+            $wpdb_result = (array) $wpdb_result;
1679 1679
             //get the model object's PK, as we'll want this if we need to insert a row into secondary tables
1680 1680
             if ($this->has_primary_key_field()) {
1681 1681
                 $main_table_pk_value = $wpdb_result[$this->get_primary_key_field()->get_qualified_column()];
@@ -1692,13 +1692,13 @@  discard block
 block discarded – undo
1692 1692
                     $this_table_pk_column = $table_obj->get_fully_qualified_pk_column();
1693 1693
                     //if there is no private key for this table on the results, it means there's no entry
1694 1694
                     //in this table, right? so insert a row in the current table, using any fields available
1695
-                    if (! (array_key_exists($this_table_pk_column, $wpdb_result)
1695
+                    if ( ! (array_key_exists($this_table_pk_column, $wpdb_result)
1696 1696
                            && $wpdb_result[$this_table_pk_column])
1697 1697
                     ) {
1698 1698
                         $success = $this->_insert_into_specific_table($table_obj, $fields_n_values,
1699 1699
                             $main_table_pk_value);
1700 1700
                         //if we died here, report the error
1701
-                        if (! $success) {
1701
+                        if ( ! $success) {
1702 1702
                             return false;
1703 1703
                         }
1704 1704
                     }
@@ -1729,7 +1729,7 @@  discard block
 block discarded – undo
1729 1729
                     $model_objs_affected_ids[$combined_index_key] = $combined_index_key;
1730 1730
                 }
1731 1731
             }
1732
-            if (! $model_objs_affected_ids) {
1732
+            if ( ! $model_objs_affected_ids) {
1733 1733
                 //wait wait wait- if nothing was affected let's stop here
1734 1734
                 return 0;
1735 1735
             }
@@ -1756,7 +1756,7 @@  discard block
 block discarded – undo
1756 1756
                . $model_query_info->get_full_join_sql()
1757 1757
                . " SET "
1758 1758
                . $this->_construct_update_sql($fields_n_values)
1759
-               . $model_query_info->get_where_sql();//note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1759
+               . $model_query_info->get_where_sql(); //note: doesn't use _construct_2nd_half_of_select_query() because doesn't accept LIMIT, ORDER BY, etc.
1760 1760
         $rows_affected = $this->_do_wpdb_query('query', array($SQL));
1761 1761
         /**
1762 1762
          * Action called after a model update call has been made.
@@ -1767,7 +1767,7 @@  discard block
 block discarded – undo
1767 1767
          * @param int      $rows_affected
1768 1768
          */
1769 1769
         do_action('AHEE__EEM_Base__update__end', $this, $fields_n_values, $query_params, $rows_affected);
1770
-        return $rows_affected;//how many supposedly got updated
1770
+        return $rows_affected; //how many supposedly got updated
1771 1771
     }
1772 1772
 
1773 1773
 
@@ -1795,7 +1795,7 @@  discard block
 block discarded – undo
1795 1795
         }
1796 1796
         $model_query_info = $this->_create_model_query_info_carrier($query_params);
1797 1797
         $select_expressions = $field->get_qualified_column();
1798
-        $SQL = "SELECT $select_expressions " . $this->_construct_2nd_half_of_select_query($model_query_info);
1798
+        $SQL = "SELECT $select_expressions ".$this->_construct_2nd_half_of_select_query($model_query_info);
1799 1799
         return $this->_do_wpdb_query('get_col', array($SQL));
1800 1800
     }
1801 1801
 
@@ -1813,7 +1813,7 @@  discard block
 block discarded – undo
1813 1813
     {
1814 1814
         $query_params['limit'] = 1;
1815 1815
         $col = $this->get_col($query_params, $field_to_select);
1816
-        if (! empty($col)) {
1816
+        if ( ! empty($col)) {
1817 1817
             return reset($col);
1818 1818
         }
1819 1819
         return null;
@@ -1844,7 +1844,7 @@  discard block
 block discarded – undo
1844 1844
             $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
1845 1845
             $value_sql = $prepared_value === null ? 'NULL'
1846 1846
                 : $wpdb->prepare($field_obj->get_wpdb_data_type(), $prepared_value);
1847
-            $cols_n_values[] = $field_obj->get_qualified_column() . "=" . $value_sql;
1847
+            $cols_n_values[] = $field_obj->get_qualified_column()."=".$value_sql;
1848 1848
         }
1849 1849
         return implode(",", $cols_n_values);
1850 1850
     }
@@ -2026,7 +2026,7 @@  discard block
 block discarded – undo
2026 2026
          * @param int      $rows_deleted
2027 2027
          */
2028 2028
         do_action('AHEE__EEM_Base__delete__end', $this, $query_params, $rows_deleted, $columns_and_ids_for_deleting);
2029
-        return $rows_deleted;//how many supposedly got deleted
2029
+        return $rows_deleted; //how many supposedly got deleted
2030 2030
     }
2031 2031
 
2032 2032
 
@@ -2176,7 +2176,7 @@  discard block
 block discarded – undo
2176 2176
             foreach ($ids_to_delete_indexed_by_column as $column => $ids) {
2177 2177
                 //make sure we have unique $ids
2178 2178
                 $ids = array_unique($ids);
2179
-                $query[] = $column . ' IN(' . implode(',', $ids) . ')';
2179
+                $query[] = $column.' IN('.implode(',', $ids).')';
2180 2180
             }
2181 2181
             $query_part = ! empty($query) ? implode(' AND ', $query) : $query_part;
2182 2182
         } elseif (count($this->get_combined_primary_key_fields()) > 1) {
@@ -2184,7 +2184,7 @@  discard block
 block discarded – undo
2184 2184
             foreach ($ids_to_delete_indexed_by_column as $ids_to_delete_indexed_by_column_for_each_row) {
2185 2185
                 $values_for_each_combined_primary_key_for_a_row = array();
2186 2186
                 foreach ($ids_to_delete_indexed_by_column_for_each_row as $column => $id) {
2187
-                    $values_for_each_combined_primary_key_for_a_row[] = $column . '=' . $id;
2187
+                    $values_for_each_combined_primary_key_for_a_row[] = $column.'='.$id;
2188 2188
                 }
2189 2189
                 $ways_to_identify_a_row[] = '('
2190 2190
                                             . implode(' AND ', $values_for_each_combined_primary_key_for_a_row)
@@ -2204,8 +2204,8 @@  discard block
 block discarded – undo
2204 2204
      */
2205 2205
     public function get_field_by_column($qualified_column_name)
2206 2206
     {
2207
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2208
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2207
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2208
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2209 2209
                return $field_obj;
2210 2210
            }
2211 2211
        }
@@ -2256,9 +2256,9 @@  discard block
 block discarded – undo
2256 2256
                 $column_to_count = '*';
2257 2257
             }
2258 2258
         }
2259
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2260
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2261
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2259
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2260
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2261
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2262 2262
     }
2263 2263
 
2264 2264
 
@@ -2280,14 +2280,14 @@  discard block
 block discarded – undo
2280 2280
             $field_obj = $this->get_primary_key_field();
2281 2281
         }
2282 2282
         $column_to_count = $field_obj->get_qualified_column();
2283
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2283
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2284 2284
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2285 2285
         $data_type = $field_obj->get_wpdb_data_type();
2286 2286
         if ($data_type === '%d' || $data_type === '%s') {
2287
-            return (float)$return_value;
2287
+            return (float) $return_value;
2288 2288
         }
2289 2289
         //must be %f
2290
-        return (float)$return_value;
2290
+        return (float) $return_value;
2291 2291
     }
2292 2292
 
2293 2293
 
@@ -2307,13 +2307,13 @@  discard block
 block discarded – undo
2307 2307
         //if we're in maintenance mode level 2, DON'T run any queries
2308 2308
         //because level 2 indicates the database needs updating and
2309 2309
         //is probably out of sync with the code
2310
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2310
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2311 2311
             throw new EE_Error(sprintf(__("Event Espresso Level 2 Maintenance mode is active. That means EE can not run ANY database queries until the necessary migration scripts have run which will take EE out of maintenance mode level 2. Please inform support of this error.",
2312 2312
                 "event_espresso")));
2313 2313
         }
2314 2314
         /** @type WPDB $wpdb */
2315 2315
         global $wpdb;
2316
-        if (! method_exists($wpdb, $wpdb_method)) {
2316
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2317 2317
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2318 2318
                 'event_espresso'), $wpdb_method));
2319 2319
         }
@@ -2325,7 +2325,7 @@  discard block
 block discarded – undo
2325 2325
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2326 2326
         if (WP_DEBUG) {
2327 2327
             $wpdb->show_errors($old_show_errors_value);
2328
-            if (! empty($wpdb->last_error)) {
2328
+            if ( ! empty($wpdb->last_error)) {
2329 2329
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2330 2330
             }
2331 2331
             if ($result === false) {
@@ -2386,7 +2386,7 @@  discard block
 block discarded – undo
2386 2386
                     return $result;
2387 2387
                     break;
2388 2388
             }
2389
-            if (! empty($error_message)) {
2389
+            if ( ! empty($error_message)) {
2390 2390
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2391 2391
                 trigger_error($error_message);
2392 2392
             }
@@ -2462,11 +2462,11 @@  discard block
 block discarded – undo
2462 2462
      */
2463 2463
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2464 2464
     {
2465
-        return " FROM " . $model_query_info->get_full_join_sql() .
2466
-               $model_query_info->get_where_sql() .
2467
-               $model_query_info->get_group_by_sql() .
2468
-               $model_query_info->get_having_sql() .
2469
-               $model_query_info->get_order_by_sql() .
2465
+        return " FROM ".$model_query_info->get_full_join_sql().
2466
+               $model_query_info->get_where_sql().
2467
+               $model_query_info->get_group_by_sql().
2468
+               $model_query_info->get_having_sql().
2469
+               $model_query_info->get_order_by_sql().
2470 2470
                $model_query_info->get_limit_sql();
2471 2471
     }
2472 2472
 
@@ -2662,12 +2662,12 @@  discard block
 block discarded – undo
2662 2662
         $related_model = $this->get_related_model_obj($model_name);
2663 2663
         //we're just going to use the query params on the related model's normal get_all query,
2664 2664
         //except add a condition to say to match the current mod
2665
-        if (! isset($query_params['default_where_conditions'])) {
2665
+        if ( ! isset($query_params['default_where_conditions'])) {
2666 2666
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2667 2667
         }
2668 2668
         $this_model_name = $this->get_this_model_name();
2669 2669
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2670
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2670
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2671 2671
         return $related_model->count($query_params, $field_to_count, $distinct);
2672 2672
     }
2673 2673
 
@@ -2687,7 +2687,7 @@  discard block
 block discarded – undo
2687 2687
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2688 2688
     {
2689 2689
         $related_model = $this->get_related_model_obj($model_name);
2690
-        if (! is_array($query_params)) {
2690
+        if ( ! is_array($query_params)) {
2691 2691
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2692 2692
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2693 2693
                     gettype($query_params)), '4.6.0');
@@ -2695,12 +2695,12 @@  discard block
 block discarded – undo
2695 2695
         }
2696 2696
         //we're just going to use the query params on the related model's normal get_all query,
2697 2697
         //except add a condition to say to match the current mod
2698
-        if (! isset($query_params['default_where_conditions'])) {
2698
+        if ( ! isset($query_params['default_where_conditions'])) {
2699 2699
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2700 2700
         }
2701 2701
         $this_model_name = $this->get_this_model_name();
2702 2702
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2703
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2703
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2704 2704
         return $related_model->sum($query_params, $field_to_sum);
2705 2705
     }
2706 2706
 
@@ -2753,7 +2753,7 @@  discard block
 block discarded – undo
2753 2753
                 $field_with_model_name = $field;
2754 2754
             }
2755 2755
         }
2756
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2756
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2757 2757
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2758 2758
                 $this->get_this_model_name()));
2759 2759
         }
@@ -2786,7 +2786,7 @@  discard block
 block discarded – undo
2786 2786
          * @param array    $fields_n_values keys are the fields and values are their new values
2787 2787
          * @param EEM_Base $model           the model used
2788 2788
          */
2789
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2789
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2790 2790
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2791 2791
             $main_table = $this->_get_main_table();
2792 2792
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2893,7 +2893,7 @@  discard block
 block discarded – undo
2893 2893
         }
2894 2894
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2895 2895
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2896
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2896
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2897 2897
         }
2898 2898
         //if there is nothing to base this search on, then we shouldn't find anything
2899 2899
         if (empty($query_params)) {
@@ -2979,7 +2979,7 @@  discard block
 block discarded – undo
2979 2979
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2980 2980
             //so add the fk to the main table as a column
2981 2981
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2982
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2982
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2983 2983
         }
2984 2984
         //insert the new entry
2985 2985
         $result = $this->_do_wpdb_query('insert',
@@ -3183,7 +3183,7 @@  discard block
 block discarded – undo
3183 3183
                     $query_info_carrier,
3184 3184
                     'group_by'
3185 3185
                 );
3186
-            } elseif (! empty ($query_params['group_by'])) {
3186
+            } elseif ( ! empty ($query_params['group_by'])) {
3187 3187
                 $this->_extract_related_model_info_from_query_param(
3188 3188
                     $query_params['group_by'],
3189 3189
                     $query_info_carrier,
@@ -3205,7 +3205,7 @@  discard block
 block discarded – undo
3205 3205
                     $query_info_carrier,
3206 3206
                     'order_by'
3207 3207
                 );
3208
-            } elseif (! empty($query_params['order_by'])) {
3208
+            } elseif ( ! empty($query_params['order_by'])) {
3209 3209
                 $this->_extract_related_model_info_from_query_param(
3210 3210
                     $query_params['order_by'],
3211 3211
                     $query_info_carrier,
@@ -3240,8 +3240,8 @@  discard block
 block discarded – undo
3240 3240
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3241 3241
         $query_param_type
3242 3242
     ) {
3243
-        if (! empty($sub_query_params)) {
3244
-            $sub_query_params = (array)$sub_query_params;
3243
+        if ( ! empty($sub_query_params)) {
3244
+            $sub_query_params = (array) $sub_query_params;
3245 3245
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3246 3246
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3247 3247
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3252,7 +3252,7 @@  discard block
 block discarded – undo
3252 3252
                 //of array('Registration.TXN_ID'=>23)
3253 3253
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3254 3254
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3255
-                    if (! is_array($possibly_array_of_params)) {
3255
+                    if ( ! is_array($possibly_array_of_params)) {
3256 3256
                         throw new EE_Error(sprintf(__("You used a special where query param %s, but the value isn't an array of where query params, it's just %s'. It should be an array, eg array('EVT_ID'=>23,'OR'=>array('Venue.VNU_ID'=>32,'Venue.VNU_name'=>'monkey_land'))",
3257 3257
                             "event_espresso"),
3258 3258
                             $param, $possibly_array_of_params));
@@ -3269,7 +3269,7 @@  discard block
 block discarded – undo
3269 3269
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3270 3270
                     //indicating that $possible_array_of_params[1] is actually a field name,
3271 3271
                     //from which we should extract query parameters!
3272
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3272
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3273 3273
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3274 3274
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3275 3275
                     }
@@ -3299,8 +3299,8 @@  discard block
 block discarded – undo
3299 3299
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3300 3300
         $query_param_type
3301 3301
     ) {
3302
-        if (! empty($sub_query_params)) {
3303
-            if (! is_array($sub_query_params)) {
3302
+        if ( ! empty($sub_query_params)) {
3303
+            if ( ! is_array($sub_query_params)) {
3304 3304
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3305 3305
                     $sub_query_params));
3306 3306
             }
@@ -3329,7 +3329,7 @@  discard block
 block discarded – undo
3329 3329
      */
3330 3330
     public function _create_model_query_info_carrier($query_params)
3331 3331
     {
3332
-        if (! is_array($query_params)) {
3332
+        if ( ! is_array($query_params)) {
3333 3333
             EE_Error::doing_it_wrong(
3334 3334
                 'EEM_Base::_create_model_query_info_carrier',
3335 3335
                 sprintf(
@@ -3405,7 +3405,7 @@  discard block
 block discarded – undo
3405 3405
         //set limit
3406 3406
         if (array_key_exists('limit', $query_params)) {
3407 3407
             if (is_array($query_params['limit'])) {
3408
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3408
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3409 3409
                     $e = sprintf(
3410 3410
                         __(
3411 3411
                             "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)",
@@ -3413,12 +3413,12 @@  discard block
 block discarded – undo
3413 3413
                         ),
3414 3414
                         http_build_query($query_params['limit'])
3415 3415
                     );
3416
-                    throw new EE_Error($e . "|" . $e);
3416
+                    throw new EE_Error($e."|".$e);
3417 3417
                 }
3418 3418
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3419
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3420
-            } elseif (! empty ($query_params['limit'])) {
3421
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3419
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3420
+            } elseif ( ! empty ($query_params['limit'])) {
3421
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3422 3422
             }
3423 3423
         }
3424 3424
         //set order by
@@ -3450,10 +3450,10 @@  discard block
 block discarded – undo
3450 3450
                 $order_array = array();
3451 3451
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3452 3452
                     $order = $this->_extract_order($order);
3453
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3453
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3454 3454
                 }
3455
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3456
-            } elseif (! empty ($query_params['order_by'])) {
3455
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3456
+            } elseif ( ! empty ($query_params['order_by'])) {
3457 3457
                 $this->_extract_related_model_info_from_query_param(
3458 3458
                     $query_params['order_by'],
3459 3459
                     $query_object,
@@ -3464,18 +3464,18 @@  discard block
 block discarded – undo
3464 3464
                     ? $this->_extract_order($query_params['order'])
3465 3465
                     : 'DESC';
3466 3466
                 $query_object->set_order_by_sql(
3467
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3467
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3468 3468
                 );
3469 3469
             }
3470 3470
         }
3471 3471
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3472
-        if (! array_key_exists('order_by', $query_params)
3472
+        if ( ! array_key_exists('order_by', $query_params)
3473 3473
             && array_key_exists('order', $query_params)
3474 3474
             && ! empty($query_params['order'])
3475 3475
         ) {
3476 3476
             $pk_field = $this->get_primary_key_field();
3477 3477
             $order = $this->_extract_order($query_params['order']);
3478
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3478
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3479 3479
         }
3480 3480
         //set group by
3481 3481
         if (array_key_exists('group_by', $query_params)) {
@@ -3485,10 +3485,10 @@  discard block
 block discarded – undo
3485 3485
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3486 3486
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3487 3487
                 }
3488
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3489
-            } elseif (! empty ($query_params['group_by'])) {
3488
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3489
+            } elseif ( ! empty ($query_params['group_by'])) {
3490 3490
                 $query_object->set_group_by_sql(
3491
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3491
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3492 3492
                 );
3493 3493
             }
3494 3494
         }
@@ -3498,7 +3498,7 @@  discard block
 block discarded – undo
3498 3498
         }
3499 3499
         //now, just verify they didn't pass anything wack
3500 3500
         foreach ($query_params as $query_key => $query_value) {
3501
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3501
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3502 3502
                 throw new EE_Error(
3503 3503
                     sprintf(
3504 3504
                         __(
@@ -3597,22 +3597,22 @@  discard block
 block discarded – undo
3597 3597
         $where_query_params = array()
3598 3598
     ) {
3599 3599
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3600
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3600
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3601 3601
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3602 3602
                 "event_espresso"), $use_default_where_conditions,
3603 3603
                 implode(", ", $allowed_used_default_where_conditions_values)));
3604 3604
         }
3605 3605
         $universal_query_params = array();
3606
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3606
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3607 3607
             $universal_query_params = $this->_get_default_where_conditions();
3608
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3608
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3609 3609
             $universal_query_params = $this->_get_minimum_where_conditions();
3610 3610
         }
3611 3611
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3612 3612
             $related_model = $this->get_related_model_obj($model_name);
3613
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3613
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3614 3614
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3615
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3615
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3616 3616
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3617 3617
             } else {
3618 3618
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3645,7 +3645,7 @@  discard block
 block discarded – undo
3645 3645
      * @param bool $for_this_model false means this is for OTHER related models
3646 3646
      * @return bool
3647 3647
      */
3648
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3648
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3649 3649
     {
3650 3650
         return (
3651 3651
                    $for_this_model
@@ -3724,7 +3724,7 @@  discard block
 block discarded – undo
3724 3724
     ) {
3725 3725
         $null_friendly_where_conditions = array();
3726 3726
         $none_overridden = true;
3727
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3727
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3728 3728
         foreach ($default_where_conditions as $key => $val) {
3729 3729
             if (isset($provided_where_conditions[$key])) {
3730 3730
                 $none_overridden = false;
@@ -3842,7 +3842,7 @@  discard block
 block discarded – undo
3842 3842
             foreach ($tables as $table_obj) {
3843 3843
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3844 3844
                                        . $table_obj->get_fully_qualified_pk_column();
3845
-                if (! in_array($qualified_pk_column, $selects)) {
3845
+                if ( ! in_array($qualified_pk_column, $selects)) {
3846 3846
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3847 3847
                 }
3848 3848
             }
@@ -3936,9 +3936,9 @@  discard block
 block discarded – undo
3936 3936
         //and
3937 3937
         //check if it's a field on a related model
3938 3938
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3939
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3939
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3940 3940
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3941
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3941
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3942 3942
                 if ($query_param === '') {
3943 3943
                     //nothing left to $query_param
3944 3944
                     //we should actually end in a field name, not a model like this!
@@ -4030,7 +4030,7 @@  discard block
 block discarded – undo
4030 4030
     {
4031 4031
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4032 4032
         if ($SQL) {
4033
-            return " WHERE " . $SQL;
4033
+            return " WHERE ".$SQL;
4034 4034
         }
4035 4035
         return '';
4036 4036
     }
@@ -4049,7 +4049,7 @@  discard block
 block discarded – undo
4049 4049
     {
4050 4050
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4051 4051
         if ($SQL) {
4052
-            return " HAVING " . $SQL;
4052
+            return " HAVING ".$SQL;
4053 4053
         }
4054 4054
         return '';
4055 4055
     }
@@ -4068,7 +4068,7 @@  discard block
 block discarded – undo
4068 4068
     {
4069 4069
         $where_clauses = array();
4070 4070
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4071
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4071
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4072 4072
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4073 4073
                 switch ($query_param) {
4074 4074
                     case 'not':
@@ -4096,7 +4096,7 @@  discard block
 block discarded – undo
4096 4096
             } else {
4097 4097
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4098 4098
                 //if it's not a normal field, maybe it's a custom selection?
4099
-                if (! $field_obj) {
4099
+                if ( ! $field_obj) {
4100 4100
                     if (isset($this->_custom_selections[$query_param][1])) {
4101 4101
                         $field_obj = $this->_custom_selections[$query_param][1];
4102 4102
                     } else {
@@ -4105,7 +4105,7 @@  discard block
 block discarded – undo
4105 4105
                     }
4106 4106
                 }
4107 4107
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4108
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4108
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4109 4109
             }
4110 4110
         }
4111 4111
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4126,7 +4126,7 @@  discard block
 block discarded – undo
4126 4126
         if ($field) {
4127 4127
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4128 4128
                 $query_param);
4129
-            return $table_alias_prefix . $field->get_qualified_column();
4129
+            return $table_alias_prefix.$field->get_qualified_column();
4130 4130
         }
4131 4131
         if (array_key_exists($query_param, $this->_custom_selections)) {
4132 4132
             //maybe it's custom selection item?
@@ -4178,7 +4178,7 @@  discard block
 block discarded – undo
4178 4178
     {
4179 4179
         if (is_array($op_and_value)) {
4180 4180
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4181
-            if (! $operator) {
4181
+            if ( ! $operator) {
4182 4182
                 $php_array_like_string = array();
4183 4183
                 foreach ($op_and_value as $key => $value) {
4184 4184
                     $php_array_like_string[] = "$key=>$value";
@@ -4200,14 +4200,14 @@  discard block
 block discarded – undo
4200 4200
         }
4201 4201
         //check to see if the value is actually another field
4202 4202
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4203
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4203
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4204 4204
         }
4205 4205
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4206 4206
             //in this case, the value should be an array, or at least a comma-separated list
4207 4207
             //it will need to handle a little differently
4208 4208
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4209 4209
             //note: $cleaned_value has already been run through $wpdb->prepare()
4210
-            return $operator . SP . $cleaned_value;
4210
+            return $operator.SP.$cleaned_value;
4211 4211
         }
4212 4212
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4213 4213
             //the value should be an array with count of two.
@@ -4223,7 +4223,7 @@  discard block
 block discarded – undo
4223 4223
                 );
4224 4224
             }
4225 4225
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4226
-            return $operator . SP . $cleaned_value;
4226
+            return $operator.SP.$cleaned_value;
4227 4227
         }
4228 4228
         if (in_array($operator, $this->valid_null_style_operators())) {
4229 4229
             if ($value !== null) {
@@ -4243,10 +4243,10 @@  discard block
 block discarded – undo
4243 4243
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4244 4244
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4245 4245
             //remove other junk. So just treat it as a string.
4246
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4246
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4247 4247
         }
4248
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4249
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4248
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4249
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4250 4250
         }
4251 4251
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4252 4252
             throw new EE_Error(
@@ -4260,7 +4260,7 @@  discard block
 block discarded – undo
4260 4260
                 )
4261 4261
             );
4262 4262
         }
4263
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4263
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4264 4264
             throw new EE_Error(
4265 4265
                 sprintf(
4266 4266
                     __(
@@ -4300,7 +4300,7 @@  discard block
 block discarded – undo
4300 4300
         foreach ($values as $value) {
4301 4301
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4302 4302
         }
4303
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4303
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4304 4304
     }
4305 4305
 
4306 4306
 
@@ -4341,7 +4341,7 @@  discard block
 block discarded – undo
4341 4341
                                 . $main_table->get_table_name()
4342 4342
                                 . " WHERE FALSE";
4343 4343
         }
4344
-        return "(" . implode(",", $cleaned_values) . ")";
4344
+        return "(".implode(",", $cleaned_values).")";
4345 4345
     }
4346 4346
 
4347 4347
 
@@ -4360,7 +4360,7 @@  discard block
 block discarded – undo
4360 4360
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4361 4361
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4362 4362
         } //$field_obj should really just be a data type
4363
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4363
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4364 4364
             throw new EE_Error(
4365 4365
                 sprintf(
4366 4366
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4488,10 +4488,10 @@  discard block
 block discarded – undo
4488 4488
      */
4489 4489
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4490 4490
     {
4491
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4491
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4492 4492
         $qualified_columns = array();
4493 4493
         foreach ($this->field_settings() as $field_name => $field) {
4494
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4494
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4495 4495
         }
4496 4496
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4497 4497
     }
@@ -4515,11 +4515,11 @@  discard block
 block discarded – undo
4515 4515
             if ($table_obj instanceof EE_Primary_Table) {
4516 4516
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4517 4517
                     ? $table_obj->get_select_join_limit($limit)
4518
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4518
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4519 4519
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4520 4520
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4521 4521
                     ? $table_obj->get_select_join_limit_join($limit)
4522
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4522
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4523 4523
             }
4524 4524
         }
4525 4525
         return $SQL;
@@ -4607,12 +4607,12 @@  discard block
 block discarded – undo
4607 4607
      */
4608 4608
     public function get_related_model_obj($model_name)
4609 4609
     {
4610
-        $model_classname = "EEM_" . $model_name;
4611
-        if (! class_exists($model_classname)) {
4610
+        $model_classname = "EEM_".$model_name;
4611
+        if ( ! class_exists($model_classname)) {
4612 4612
             throw new EE_Error(sprintf(__("You specified a related model named %s in your query. No such model exists, if it did, it would have the classname %s",
4613 4613
                 'event_espresso'), $model_name, $model_classname));
4614 4614
         }
4615
-        return call_user_func($model_classname . "::instance");
4615
+        return call_user_func($model_classname."::instance");
4616 4616
     }
4617 4617
 
4618 4618
 
@@ -4659,7 +4659,7 @@  discard block
 block discarded – undo
4659 4659
     public function related_settings_for($relation_name)
4660 4660
     {
4661 4661
         $relatedModels = $this->relation_settings();
4662
-        if (! array_key_exists($relation_name, $relatedModels)) {
4662
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4663 4663
             throw new EE_Error(
4664 4664
                 sprintf(
4665 4665
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4687,7 +4687,7 @@  discard block
 block discarded – undo
4687 4687
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4688 4688
     {
4689 4689
         $fieldSettings = $this->field_settings($include_db_only_fields);
4690
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4690
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4691 4691
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4692 4692
                 get_class($this)));
4693 4693
         }
@@ -4760,7 +4760,7 @@  discard block
 block discarded – undo
4760 4760
                     break;
4761 4761
                 }
4762 4762
             }
4763
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4763
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4764 4764
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4765 4765
                     get_class($this)));
4766 4766
             }
@@ -4819,7 +4819,7 @@  discard block
 block discarded – undo
4819 4819
      */
4820 4820
     public function get_foreign_key_to($model_name)
4821 4821
     {
4822
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4822
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4823 4823
             foreach ($this->field_settings() as $field) {
4824 4824
                 if (
4825 4825
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4829,7 +4829,7 @@  discard block
 block discarded – undo
4829 4829
                     break;
4830 4830
                 }
4831 4831
             }
4832
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4832
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4833 4833
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4834 4834
                     'event_espresso'), $model_name, get_class($this)));
4835 4835
             }
@@ -4880,7 +4880,7 @@  discard block
 block discarded – undo
4880 4880
             foreach ($this->_fields as $fields_corresponding_to_table) {
4881 4881
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4882 4882
                     /** @var $field_obj EE_Model_Field_Base */
4883
-                    if (! $field_obj->is_db_only_field()) {
4883
+                    if ( ! $field_obj->is_db_only_field()) {
4884 4884
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4885 4885
                     }
4886 4886
                 }
@@ -4909,7 +4909,7 @@  discard block
 block discarded – undo
4909 4909
         $count_if_model_has_no_primary_key = 0;
4910 4910
         $has_primary_key = $this->has_primary_key_field();
4911 4911
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4912
-        foreach ((array)$rows as $row) {
4912
+        foreach ((array) $rows as $row) {
4913 4913
             if (empty($row)) {
4914 4914
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4915 4915
                 return array();
@@ -4927,7 +4927,7 @@  discard block
 block discarded – undo
4927 4927
                 }
4928 4928
             }
4929 4929
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4930
-            if (! $classInstance) {
4930
+            if ( ! $classInstance) {
4931 4931
                 throw new EE_Error(
4932 4932
                     sprintf(
4933 4933
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4996,7 +4996,7 @@  discard block
 block discarded – undo
4996 4996
      */
4997 4997
     public function instantiate_class_from_array_or_object($cols_n_values)
4998 4998
     {
4999
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4999
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
5000 5000
             $cols_n_values = get_object_vars($cols_n_values);
5001 5001
         }
5002 5002
         $primary_key = null;
@@ -5021,7 +5021,7 @@  discard block
 block discarded – undo
5021 5021
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5022 5022
         if ($primary_key) {
5023 5023
             $classInstance = $this->get_from_entity_map($primary_key);
5024
-            if (! $classInstance) {
5024
+            if ( ! $classInstance) {
5025 5025
                 $classInstance = EE_Registry::instance()
5026 5026
                                             ->load_class($className,
5027 5027
                                                 array($this_model_fields_n_values, $this->_timezone), true, false);
@@ -5070,12 +5070,12 @@  discard block
 block discarded – undo
5070 5070
     public function add_to_entity_map(EE_Base_Class $object)
5071 5071
     {
5072 5072
         $className = $this->_get_class_name();
5073
-        if (! $object instanceof $className) {
5073
+        if ( ! $object instanceof $className) {
5074 5074
             throw new EE_Error(sprintf(__("You tried adding a %s to a mapping of %ss", "event_espresso"),
5075 5075
                 is_object($object) ? get_class($object) : $object, $className));
5076 5076
         }
5077 5077
         /** @var $object EE_Base_Class */
5078
-        if (! $object->ID()) {
5078
+        if ( ! $object->ID()) {
5079 5079
             throw new EE_Error(sprintf(__("You tried storing a model object with NO ID in the %s entity mapper.",
5080 5080
                 "event_espresso"), get_class($this)));
5081 5081
         }
@@ -5144,7 +5144,7 @@  discard block
 block discarded – undo
5144 5144
             //there is a primary key on this table and its not set. Use defaults for all its columns
5145 5145
             if ($table_pk_value === null && $table_obj->get_pk_column()) {
5146 5146
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5147
-                    if (! $field_obj->is_db_only_field()) {
5147
+                    if ( ! $field_obj->is_db_only_field()) {
5148 5148
                         //prepare field as if its coming from db
5149 5149
                         $prepared_value = $field_obj->prepare_for_set($field_obj->get_default_value());
5150 5150
                         $this_model_fields_n_values[$field_name] = $field_obj->prepare_for_use_in_db($prepared_value);
@@ -5153,7 +5153,7 @@  discard block
 block discarded – undo
5153 5153
             } else {
5154 5154
                 //the table's rows existed. Use their values
5155 5155
                 foreach ($this->_get_fields_for_table($table_alias) as $field_name => $field_obj) {
5156
-                    if (! $field_obj->is_db_only_field()) {
5156
+                    if ( ! $field_obj->is_db_only_field()) {
5157 5157
                         $this_model_fields_n_values[$field_name] = $this->_get_column_value_with_table_alias_or_not(
5158 5158
                             $cols_n_values, $field_obj->get_qualified_column(),
5159 5159
                             $field_obj->get_table_column()
@@ -5268,7 +5268,7 @@  discard block
 block discarded – undo
5268 5268
      */
5269 5269
     private function _get_class_name()
5270 5270
     {
5271
-        return "EE_" . $this->get_this_model_name();
5271
+        return "EE_".$this->get_this_model_name();
5272 5272
     }
5273 5273
 
5274 5274
 
@@ -5283,7 +5283,7 @@  discard block
 block discarded – undo
5283 5283
      */
5284 5284
     public function item_name($quantity = 1)
5285 5285
     {
5286
-        return (int)$quantity === 1 ? $this->singular_item : $this->plural_item;
5286
+        return (int) $quantity === 1 ? $this->singular_item : $this->plural_item;
5287 5287
     }
5288 5288
 
5289 5289
 
@@ -5316,7 +5316,7 @@  discard block
 block discarded – undo
5316 5316
     {
5317 5317
         $className = get_class($this);
5318 5318
         $tagName = "FHEE__{$className}__{$methodName}";
5319
-        if (! has_filter($tagName)) {
5319
+        if ( ! has_filter($tagName)) {
5320 5320
             throw new EE_Error(
5321 5321
                 sprintf(
5322 5322
                     __('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 );',
@@ -5542,7 +5542,7 @@  discard block
 block discarded – undo
5542 5542
         $key_vals_in_combined_pk = array();
5543 5543
         parse_str($index_primary_key_string, $key_vals_in_combined_pk);
5544 5544
         foreach ($key_fields as $key_field_name => $field_obj) {
5545
-            if (! isset($key_vals_in_combined_pk[$key_field_name])) {
5545
+            if ( ! isset($key_vals_in_combined_pk[$key_field_name])) {
5546 5546
                 return null;
5547 5547
             }
5548 5548
         }
@@ -5563,7 +5563,7 @@  discard block
 block discarded – undo
5563 5563
     {
5564 5564
         $keys_it_should_have = array_keys($this->get_combined_primary_key_fields());
5565 5565
         foreach ($keys_it_should_have as $key) {
5566
-            if (! isset($key_vals[$key])) {
5566
+            if ( ! isset($key_vals[$key])) {
5567 5567
                 return false;
5568 5568
             }
5569 5569
         }
@@ -5617,7 +5617,7 @@  discard block
 block discarded – undo
5617 5617
      */
5618 5618
     public function get_one_copy($model_object_or_attributes_array, $query_params = array())
5619 5619
     {
5620
-        if (! is_array($query_params)) {
5620
+        if ( ! is_array($query_params)) {
5621 5621
             EE_Error::doing_it_wrong('EEM_Base::get_one_copy',
5622 5622
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
5623 5623
                     gettype($query_params)), '4.6.0');
@@ -5683,7 +5683,7 @@  discard block
 block discarded – undo
5683 5683
      * Gets the valid operators
5684 5684
      * @return array keys are accepted strings, values are the SQL they are converted to
5685 5685
      */
5686
-    public function valid_operators(){
5686
+    public function valid_operators() {
5687 5687
         return $this->_valid_operators;
5688 5688
     }
5689 5689
 
@@ -5771,7 +5771,7 @@  discard block
 block discarded – undo
5771 5771
      */
5772 5772
     public function get_IDs($model_objects, $filter_out_empty_ids = false)
5773 5773
     {
5774
-        if (! $this->has_primary_key_field()) {
5774
+        if ( ! $this->has_primary_key_field()) {
5775 5775
             if (WP_DEBUG) {
5776 5776
                 EE_Error::add_error(
5777 5777
                     __('Trying to get IDs from a model than has no primary key', 'event_espresso'),
@@ -5784,7 +5784,7 @@  discard block
 block discarded – undo
5784 5784
         $IDs = array();
5785 5785
         foreach ($model_objects as $model_object) {
5786 5786
             $id = $model_object->ID();
5787
-            if (! $id) {
5787
+            if ( ! $id) {
5788 5788
                 if ($filter_out_empty_ids) {
5789 5789
                     continue;
5790 5790
                 }
@@ -5880,8 +5880,8 @@  discard block
 block discarded – undo
5880 5880
         $missing_caps = array();
5881 5881
         $cap_restrictions = $this->cap_restrictions($context);
5882 5882
         foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
5883
-            if (! EE_Capabilities::instance()
5884
-                                 ->current_user_can($cap, $this->get_this_model_name() . '_model_applying_caps')
5883
+            if ( ! EE_Capabilities::instance()
5884
+                                 ->current_user_can($cap, $this->get_this_model_name().'_model_applying_caps')
5885 5885
             ) {
5886 5886
                 $missing_caps[$cap] = $restriction_if_no_cap;
5887 5887
             }
@@ -6033,7 +6033,7 @@  discard block
 block discarded – undo
6033 6033
     {
6034 6034
         foreach ($this->logic_query_param_keys() as $logic_query_param_key) {
6035 6035
             if ($query_param_key === $logic_query_param_key
6036
-                || strpos($query_param_key, $logic_query_param_key . '*') === 0
6036
+                || strpos($query_param_key, $logic_query_param_key.'*') === 0
6037 6037
             ) {
6038 6038
                 return true;
6039 6039
             }
Please login to merge, or discard this patch.
core/libraries/messages/EE_message_type.lib.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -825,7 +825,7 @@
 block discarded – undo
825 825
      * Takes care of setting up the addressee object(s) for the primary attendee.
826 826
      *
827 827
      * @access protected
828
-     * @return array of EE_Addressee objects
828
+     * @return EE_Messages_Addressee[] of EE_Addressee objects
829 829
      */
830 830
     protected function _primary_attendee_addressees()
831 831
     {
Please login to merge, or discard this patch.
Indentation   +895 added lines, -895 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2 2
 if (! defined('EVENT_ESPRESSO_VERSION')) {
3
-    exit('NO direct script access allowed');
3
+	exit('NO direct script access allowed');
4 4
 }
5 5
 
6 6
 
@@ -18,906 +18,906 @@  discard block
 block discarded – undo
18 18
 {
19 19
 
20 20
 
21
-    /**
22
-     * message type child classes will set what contexts are associated with the message type via this array.
23
-     * format:
24
-     * array(
25
-     * 'context' => array(
26
-     *        'label' => __('Context Label', 'event_espresso'),
27
-     *        'description' => __('Context description (for help popups)', 'event_espresso')
28
-     *    ));
29
-     *
30
-     * @var array
31
-     */
32
-    protected $_contexts = array();
33
-
34
-
35
-    /**
36
-     * This property is used to define what the display label will be for contexts (eg. "Recipients", "Themes" etc.)
37
-     * Format:
38
-     * array( 'label' => 'something', 'plural' => 'somethings', 'description' => 'something' );
39
-     *
40
-     * @var array
41
-     */
42
-    protected $_context_label;
43
-
44
-
45
-    /** MESSAGE ASSEMBLING PROPERTIES **/
46
-    /**
47
-     * This parameter simply holds all the message objects for retrieval by the controller and sending to the messenger.
48
-     *
49
-     * @var array of message objects.
50
-     */
51
-    public $messages = array();
52
-
53
-    /**
54
-     * The following holds the templates that will be used to assemble the message object for the messenger.
55
-     *
56
-     * @var array
57
-     */
58
-    protected $_templates;
59
-
60
-
61
-    /**
62
-     * If a specific template is being parsed, this will hold the message template group GRP_ID for that template.
63
-     *
64
-     * @var int.
65
-     */
66
-    protected $_GRP_ID;
67
-
68
-
69
-    /** OTHER INFO PROPERTIES **/
70
-    /**
71
-     * This will hold the count of the message objects in the messages array. This could be used for determining if
72
-     * batching/queueing is needed.
73
-     *
74
-     * @var int
75
-     */
76
-    public $count = 0;
77
-
78
-
79
-    /**
80
-     * This is set via the `do_messenger_hooks` method and contains the messenger being used to send the message of
81
-     * this message type at time of sending.
82
-     *
83
-     * @var EE_messenger
84
-     */
85
-    protected $_active_messenger;
86
-
87
-
88
-    /**
89
-     * This will hold the shortcode_replace instance for handling replacement of shortcodes in the various templates
90
-     *
91
-     * @var object
92
-     */
93
-    protected $_shortcode_replace;
94
-
95
-
96
-    /**
97
-     * The purpose for this property is to simply allow message types to indicate if the message generated is intended
98
-     * for only single context.  Child message types should redefine this variable (if necessary) in the
99
-     * _set_data_Handler() method.
100
-     *
101
-     * @var boolean
102
-     */
103
-    protected $_single_message = false;
104
-
105
-
106
-    /**
107
-     * This will hold an array of specific reg_ids that are receiving messages.
108
-     *
109
-     * @since 4.7.x
110
-     * @var array
111
-     */
112
-    protected $_regs_for_sending = array();
113
-
114
-
115
-    /**
116
-     * This holds the data passed to this class from the controller and also the final processed data.
117
-     *
118
-     * @var object
119
-     */
120
-    protected $_data;
121
-
122
-
123
-    /**
124
-     * this is just a flag indicating whether we're in preview mode or not.
125
-     *
126
-     * @var bool
127
-     */
128
-    protected $_preview = false;
129
-
130
-
131
-    /**
132
-     * This just holds defaults for addressee data that children merge with their data array setup
133
-     *
134
-     * @var array
135
-     */
136
-    protected $_default_addressee_data;
137
-
138
-
139
-    /**
140
-     * Child classes declare through this property what handler they want to use for the incoming data and this string
141
-     * is used to instantiate the EE_Messages_incoming_data child class for that handler.
142
-     *
143
-     * @var string
144
-     */
145
-    protected $_data_handler;
146
-
147
-
148
-    /**
149
-     * This holds any specific fields for holding any settings related to a message type (if any needed)
150
-     *
151
-     * @var array
152
-     */
153
-    protected $_admin_settings_fields = array();
154
-
155
-    /**
156
-     * this property will hold any existing setting that may have been set in the admin.
157
-     *
158
-     * @var array
159
-     */
160
-    protected $_existing_admin_settings = array();
161
-
162
-
163
-    /**
164
-     * This is used to designate the generating and alternative sending messengers for a message type.  It is set via
165
-     * set_with_messengers() on construct. Note, generating messenger also acts as a sending messenger for this message
166
-     * type.  However ONLY the generating messengers are used for creating templates for this message type. Should be
167
-     * in this format:
168
-     * {
169
-     *
170
-     * @type string $generating_messenger the name of the generating messenger.  Generating
171
-     *                                          messengers are used for generating templates,
172
-     *                                          doing validation and defining valid shortcodes.
173
-     *      {
174
-     * @type string $sending_messenger    values are the name(s) for the sending
175
-     *                                              messengers.  sending messengers are
176
-     *                                              just valid delivery vehicles that will utilize
177
-     *                                              the templates (and generated EE_message
178
-     *                                              objects from the generating messengers).
179
-     *      }
180
-     * }
181
-     * @since                             4.5.0
182
-     * @var array
183
-     */
184
-    protected $_with_messengers = array();
185
-
186
-
187
-    /**
188
-     * This holds the addressees in an array indexed by context for later retrieval when assembling the message objects.
189
-     *
190
-     * @access protected
191
-     * @var array
192
-     */
193
-    protected $_addressees = array();
194
-
195
-
196
-    /**
197
-     * This allows each message type to set what alternate messenger&message type combination can be used for fallback
198
-     * default templates if there are no specific ones defined for this messenger and message type.  Should be in the
199
-     * format:
200
-     * array(
201
-     *      'messenger' => 'message_type',
202
-     *      'another_messenger' => another_message_type
203
-     * );
204
-     * This is set in the message type constructor.
205
-     *
206
-     * @var array
207
-     */
208
-    protected $_master_templates = array();
209
-
210
-
211
-    /**
212
-     * This holds whatever the set template pack is for a message template group when generating messages.
213
-     *
214
-     * @since 4.5.0
215
-     * @var EE_Messages_Template_Pack
216
-     */
217
-    protected $_template_pack;
218
-
219
-
220
-    /**
221
-     * This holds whatever the set variation is for a message template group when generating messages.
222
-     *
223
-     * @since 4.5.0
224
-     * @var string
225
-     */
226
-    protected $_variation;
227
-
228
-
229
-    /**
230
-     * EE_message_type constructor.
231
-     */
232
-    public function __construct()
233
-    {
234
-        $this->_messages_item_type = 'message_type';
235
-        $this->_set_contexts();
236
-        $this->_set_with_messengers();
237
-        parent::__construct();
238
-    }
239
-
240
-
241
-    /**
242
-     * This sets the data handler for the message type.  It must be used to define the _data_handler property.  It is
243
-     * called when messages are setup.
244
-     *
245
-     * @abstract
246
-     * @access protected
247
-     * @return void
248
-     */
249
-    abstract protected function _set_data_handler();
250
-
251
-
252
-    /**
253
-     * This method should return a EE_Base_Class object (or array of EE_Base_Class objects) for the given context and
254
-     * ID (which should be the primary key id for the base class).  Client code doesn't have to know what a message
255
-     * type's data handler is.
256
-     *
257
-     * @since 4.5.0
258
-     * @param string          $context      This should be a string matching a valid context for the message type.
259
-     * @param EE_Registration $registration Need a registration to ensure that the data is valid (prevents people
260
-     *                                      guessing a url).
261
-     * @param int             $id           Optional. Integer corresponding to the value for the primary key of a
262
-     *                                      EE_Base_Class_Object
263
-     * @return mixed ( EE_Base_Class||EE_Base_Class[] )
264
-     */
265
-    abstract protected function _get_data_for_context($context, EE_Registration $registration, $id);
266
-
267
-
268
-    /**
269
-     * _set_contexts
270
-     * This sets up the contexts associated with the message_type
271
-     *
272
-     * @abstract
273
-     * @access  protected
274
-     * @return  void
275
-     */
276
-    abstract protected function _set_contexts();
277
-
278
-
279
-    /**
280
-     * This is used to get the "id" value fo the msg_trigger_url generated by get_url_trigger().
281
-     * In most cases, child classes don't need anything, (hence the default of 0), however if there is a specific
282
-     * EE_Base_Class that is required in generating a message for a message type recipient then the message
283
-     * type should override this method and use the given params to generate the correct ID.
284
-     *
285
-     * @param string          $context      The message type context.
286
-     * @param EE_Registration $registration Registration object
287
-     * @deprecated 4.9.0
288
-     * @return int
289
-     */
290
-    protected function _get_id_for_msg_url($context, EE_Registration $registration)
291
-    {
292
-        return 0;
293
-    }
294
-
295
-
296
-    /**
297
-     * This sets up any action/filter hooks this message type puts in place for a specific messenger.  Note that by
298
-     * default this does nothing.  Child classes will need to override if they want to add specific hooks for a
299
-     * messenger.
300
-     *
301
-     * @since 1.0.0
302
-     * @return void
303
-     */
304
-    protected function _do_messenger_hooks()
305
-    {
306
-        return;
307
-    }
308
-
309
-
310
-    /**
311
-     * This is a public wrapper for the protected _do_messenger_hooks() method.
312
-     * For backward compat reasons, this was done rather than making the protected method public.
313
-     *
314
-     * @param   EE_messenger $messenger This is used to set the $_active_messenger property, so message types are able
315
-     *                                  to know what messenger is being used to send the message at the time of
316
-     *                                  sending.
317
-     * @since 4.9.0
318
-     */
319
-    public function do_messenger_hooks($messenger = null)
320
-    {
321
-        $this->_active_messenger = $messenger;
322
-        $this->_do_messenger_hooks();
323
-    }
324
-
325
-
326
-    /**
327
-     * This method returns whether this message type should always generate a new copy
328
-     * when requested, or if links can be to the already generated copy.
329
-     * Note: this does NOT affect viewing/resending already generated messages in the EE_Message list table.
330
-     * Child classes should override this if different from the default of false.
331
-     *
332
-     * @return bool     false means can link to generated EE_Message.  true must regenerate.
333
-     */
334
-    public function always_generate()
335
-    {
336
-        return false;
337
-    }
338
-
339
-
340
-    /**
341
-     * Returns the priority for the message type.
342
-     * Priorities are defined as constants on EEM_Message.  Currently there are three priorities:
343
-     * - EEM_Message::priority_high
344
-     * - EEM_Message::priority_medium
345
-     * - EEM_Message::priority_low
346
-     * Priority is used to determine the weight the message type is given when queuing for generation and/or sending.
347
-     *
348
-     * @see    EEM_Message for more phpdocs on priority.
349
-     *         The default priority for all message_types is EEM_Message::priority_low.  Message Types wanting to give
350
-     *         a higher priority must override this method. Also note, messengers are able to override priorities
351
-     *         queuing instructions if their "send_now" flag is set to true. An example of this is the HTML messenger
352
-     *         which displays things in the browser.
353
-     * @since  4.9.0
354
-     * @return int
355
-     */
356
-    public function get_priority()
357
-    {
358
-        return EEM_Message::priority_low;
359
-    }
360
-
361
-
362
-    /**
363
-     * This runs the _set_data_handler() method for message types and then returns what got set.
364
-     *
365
-     * @param mixed $data This sets the data property for the message type with the incoming data used for generating.
366
-     * @return string (the reference for the data handler) (will be an empty string if could not be determined).
367
-     */
368
-    public function get_data_handler($data)
369
-    {
370
-        $this->_data = $data;
371
-        $this->_set_data_handler();
372
-        return apply_filters('FHEE__EE_message_type__get_data_handler', $this->_data_handler, $this);
373
-    }
374
-
375
-
376
-    /**
377
-     * This is called externally to reset the value of the $_data property for the message type.
378
-     * Please note the value of the _data is highly volatile.  It was added as an interim measure ensuring
379
-     * EE_Message_To_Generate objects have any changes to the _data property when `_set_data_handler` method is called
380
-     * (and for back compat reasons). This particular method is used in
381
-     * EE_Messages_Generator::_reset_current_properties to ensure that the internal _data on the message type is
382
-     * cleaned before subsequent EE_Message generation in the same request.
383
-     *
384
-     * @todo      This needs refactored along with the whole _set_data_handler() method in EE_message_types. Need to
385
-     *            ensure that there is no manipulation of the _data property during run time so there's a clear
386
-     *            expectation of what it is.  Likely we need to ensure that _data is not persisted IN the message type
387
-     *            at all.
388
-     * @internal  Plugin authors, do not implement this method, it is subject to change.
389
-     * @since     4.9
390
-     */
391
-    public function reset_data()
392
-    {
393
-        $this->_data = null;
394
-    }
395
-
396
-
397
-    /**
398
-     * This does some validation of incoming params gets the url trigger from the defined method in the specific child
399
-     * class and then filters the results.
400
-     *
401
-     * @param string          $context           The message type context
402
-     * @param string          $sending_messenger The sending messenger
403
-     * @param EE_Registration $registration      Registration object
404
-     * @throws EE_Error
405
-     * @deprecated  4.9.0  Likely 4.9.10 or 4.10.0 will remove this method completely
406
-     * @return string          generated url
407
-     */
408
-    public function get_url_trigger($context, $sending_messenger, EE_Registration $registration)
409
-    {
410
-        //validate context
411
-        //valid context?
412
-        if (! isset($this->_contexts[$context])) {
413
-            throw new EE_Error(
414
-                sprintf(
415
-                    __('The context %s is not a valid context for %s.', 'event_espresso'),
416
-                    $context,
417
-                    get_class($this)
418
-                )
419
-            );
420
-        }
421
-        //valid sending_messenger?
422
-        $not_valid_msgr = false;
423
-        foreach ($this->_with_messengers as $generating => $sendings) {
424
-            if (empty($sendings) || array_search($sending_messenger, $sendings) === false) {
425
-                $not_valid_msgr = true;
426
-            }
427
-        }
428
-        if ($not_valid_msgr) {
429
-            throw new EE_Error(
430
-                sprintf(
431
-                    __(
432
-                        'The given sending messenger string (%s) does not match a valid sending messenger with the %s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
433
-                        'event_espresso'
434
-                    ),
435
-                    $sending_messenger,
436
-                    get_class($this)
437
-                )
438
-            );
439
-        }
440
-        return EEH_MSG_Template::generate_url_trigger(
441
-            $sending_messenger,
442
-            $this->_active_messenger->name,
443
-            $context,
444
-            $this->name,
445
-            $registration,
446
-            $this->_GRP_ID,
447
-            $this->_get_id_for_msg_url($context, $registration)
448
-        );
449
-    }
450
-
451
-
452
-    /**
453
-     * Wrapper for _get_data_for_context() that handles some validation before calling the main class and also allows
454
-     * for filtering. This is (currently) called by the EED_Messages module.
455
-     *
456
-     * @since 4.5.0
457
-     * @throws EE_Error
458
-     * @param string          $context      This should be a string matching a valid context for the message type.
459
-     * @param EE_Registration $registration Need a registration to ensure that the data is valid (prevents people
460
-     *                                      guessing a url).
461
-     * @param int             $id           Optional. Integer corresponding to the value for the primary key of a
462
-     *                                      EE_Base_Class_Object
463
-     * @return mixed (EE_Base_Class||EE_Base_Class[])
464
-     */
465
-    public function get_data_for_context($context, EE_Registration $registration, $id = 0)
466
-    {
467
-        //valid context?
468
-        if (! isset($this->_contexts[$context])) {
469
-            throw new EE_Error(
470
-                sprintf(
471
-                    __('The context %s is not a valid context for %s.', 'event_espresso'),
472
-                    $context,
473
-                    get_class($this)
474
-                )
475
-            );
476
-        }
477
-        //get data and apply global and class specific filters on it.
478
-        $data = apply_filters(
479
-            'FHEE__EE_message_type__get_data_for_context__data',
480
-            $this->_get_data_for_context($context, $registration, $id),
481
-            $this
482
-        );
483
-        $data = apply_filters('FHEE__' . get_class($this) . '__get_data_for_context__data', $data, $this);
484
-        //if empty then something went wrong!
485
-        if (empty($data)) {
486
-            throw new EE_Error(
487
-                sprintf(
488
-                    __(
489
-                        'There is no data retrieved, it is possible that the id given (%d) does not match any value in the database for the corresponding EE_Base_Class used by the data handler for the %s message type.',
490
-                        'event_espresso'
491
-                    ),
492
-                    $id,
493
-                    $this->name
494
-                )
495
-            );
496
-        }
497
-        return $data;
498
-    }
499
-
500
-
501
-    /**
502
-     * This returns the contents of the _data property.
503
-     * Please note the value of the _data is highly volatile.  It was added as an interim measure ensuring
504
-     * EE_Message_To_Generate objects have any changes to the _data property when `_set_data_handler` method is called.
505
-     *
506
-     * @todo      This needs refactored along with the whole _set_data_handler() method in EE_message_types. Need to
507
-     *            ensure that there is no manipulation of the _data property during run time so there's a clear
508
-     *            expectation of what it is.
509
-     * @internal  Plugin authors, do not implement this method, it is subject to change.
510
-     * @return mixed
511
-     */
512
-    public function get_data()
513
-    {
514
-        return $this->_data;
515
-    }
516
-
517
-
518
-    /**
519
-     * used to set the $_with_messengers property. (this is a default, child classes SHOULD override)
520
-     *
521
-     * @see   property definition for description of setup.
522
-     * @since 4.5.0
523
-     * @abstract
524
-     * @return void
525
-     */
526
-    protected function _set_with_messengers()
527
-    {
528
-        $this->_with_messengers = array(
529
-            'email' => array('html'),
530
-        );
531
-    }
532
-
533
-
534
-    /**
535
-     * Return the value of the _with_messengers property
536
-     *
537
-     * @since 4.5.0
538
-     * @return array
539
-     */
540
-    public function with_messengers()
541
-    {
542
-        return apply_filters(
543
-            'FHEE__EE_message_type__get_with_messengers__with_messengers__' . get_class($this),
544
-            $this->_with_messengers
545
-        );
546
-    }
547
-
548
-
549
-    /**
550
-     * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class
551
-     * callback function if that page is registered via the `_admin_registered_page` property set by the child class.
552
-     * *
553
-     *
554
-     * @param string $page       the slug of the EE admin page
555
-     * @param array  $messengers an array of active messenger objects
556
-     * @param string $action     the page action (to allow for more specific handling - i.e. edit vs. add pages)
557
-     * @param array  $extra      This is just an extra argument that can be used to pass additional data for setting up
558
-     *                           page content.
559
-     * @access public
560
-     * @return string
561
-     */
562
-    public function get_message_type_admin_page_content(
563
-        $page,
564
-        $action = null,
565
-        $extra = array(),
566
-        $messengers = array()
567
-    ) {
568
-        //we can also further refine the context by action (if present).
569
-        return $this->_get_admin_page_content($page, $action, $extra, $messengers);
570
-    }
571
-
572
-
573
-    /**
574
-     * @return array
575
-     */
576
-    public function get_contexts()
577
-    {
578
-        return $this->_contexts;
579
-    }
580
-
581
-
582
-    /**
583
-     * This just returns the context label for a given context (as set in $_context_label property)
584
-     *
585
-     * @access public
586
-     * @return array
587
-     */
588
-    public function get_context_label()
589
-    {
590
-        return $this->_context_label;
591
-    }
592
-
593
-
594
-    /**
595
-     * This just returns the (filtered) _master_templates property.
596
-     *
597
-     * @see property definition for documentation.
598
-     * @return array
599
-     */
600
-    public function get_master_templates()
601
-    {
602
-        //first class specific filter then filter that by the global filter.
603
-        $master_templates = apply_filters(
604
-            'FHEE__' . get_class($this) . '__get_master_templates',
605
-            $this->_master_templates
606
-        );
607
-        return apply_filters('FHEE__EE_message_type__get_master_templates', $master_templates, $this);
608
-    }
609
-
610
-
611
-    /**
612
-     * Accepts an incoming data handler which contains data for processing, and returns an array of
613
-     * EE_Messages_Addressee objects.
614
-     *
615
-     * @param EE_Messages_incoming_data $data
616
-     * @param string                    $context Limit addressees to specific context.
617
-     * @return array   An array indexed by context where each context is an array of EE_Messages_Addressee objects for
618
-     *                                           that context
619
-     */
620
-    public function get_addressees(EE_Messages_incoming_data $data, $context = '')
621
-    {
622
-        //override _data
623
-        $this->_data       = $data;
624
-        $addressees        = array();
625
-        $original_contexts = $this->_contexts;
626
-        //if incoming context then limit to that context
627
-        if (! empty($context)) {
628
-            $cntxt = ! empty($this->_contexts[$context]) ? $this->_contexts[$context] : '';
629
-            if (! empty($cntxt)) {
630
-                $this->_contexts           = array();
631
-                $this->_contexts[$context] = $cntxt;
632
-            }
633
-        }
634
-        $this->_set_default_addressee_data();
635
-        if ($this->_process_data()) {
636
-            $addressees = $this->_addressees;
637
-        }
638
-
639
-        //reset contexts and addressees
640
-        $this->_contexts   = $original_contexts;
641
-        $this->_addressees = array();
642
-        return $addressees;
643
-    }
644
-
645
-
646
-    /**
647
-     * processes the data object so we get
648
-     *
649
-     * @throws EE_Error
650
-     * @return bool  true means data was processed successfully, false means not.
651
-     */
652
-    protected function _process_data()
653
-    {
654
-        //at a minimum, we NEED EE_Attendee objects.
655
-        if (empty($this->_data->attendees)) {
656
-            return false;  //there's no data to process!
657
-        }
658
-        // process addressees for each context.  Child classes will have to have methods for
659
-        // each context defined to handle the processing of the data object within them
660
-        foreach ($this->_contexts as $context => $details) {
661
-            $xpctd_method = '_' . $context . '_addressees';
662
-            if (! method_exists($this, $xpctd_method)) {
663
-                throw new EE_Error(
664
-                    sprintf(
665
-                        __(
666
-                            'The data for %1$s message type cannot be prepared because there is no set method for doing so.  The expected method name is "%2$s" please doublecheck the %1$s message type class and make sure that method is present',
667
-                            'event_espresso'
668
-                        ),
669
-                        $this->label['singular'],
670
-                        $xpctd_method
671
-                    )
672
-                );
673
-            }
674
-            $this->_addressees[$context] = call_user_func(array($this, $xpctd_method));
675
-        }
676
-        return true; //data was processed successfully.
677
-    }
678
-
679
-
680
-    /**
681
-     * sets the default_addressee_data property,
682
-     *
683
-     * @access private
684
-     * @return void
685
-     */
686
-    private function _set_default_addressee_data()
687
-    {
688
-        $this->_default_addressee_data = array(
689
-            'billing'                  => $this->_data->billing,
690
-            'taxes'                    => $this->_data->taxes,
691
-            'tax_line_items'           => $this->_data->tax_line_items,
692
-            'additional_line_items'    => $this->_data->additional_line_items,
693
-            'grand_total_line_item'    => $this->_data->grand_total_line_item,
694
-            'txn'                      => $this->_data->txn,
695
-            'payments'                 => $this->_data->payments,
696
-            'payment'                  => isset($this->_data->payment) && $this->_data->payment instanceof EE_Payment
697
-                ? $this->_data->payment
698
-                : null,
699
-            'reg_objs'                 => $this->_data->reg_objs,
700
-            'registrations'            => $this->_data->registrations,
701
-            'datetimes'                => $this->_data->datetimes,
702
-            'tickets'                  => $this->_data->tickets,
703
-            'line_items_with_children' => $this->_data->line_items_with_children,
704
-            'questions'                => $this->_data->questions,
705
-            'answers'                  => $this->_data->answers,
706
-            'txn_status'               => $this->_data->txn_status,
707
-            'total_ticket_count'       => $this->_data->total_ticket_count,
708
-        );
709
-        if (is_array($this->_data->primary_attendee_data)) {
710
-            $this->_default_addressee_data                    = array_merge(
711
-                $this->_default_addressee_data,
712
-                $this->_data->primary_attendee_data
713
-            );
714
-            $this->_default_addressee_data['primary_att_obj'] = $this->_data->primary_attendee_data['att_obj'];
715
-            $this->_default_addressee_data['primary_reg_obj'] = $this->_data->primary_attendee_data['reg_obj'];
716
-        }
717
-    }
718
-
719
-
720
-
721
-    /********************
21
+	/**
22
+	 * message type child classes will set what contexts are associated with the message type via this array.
23
+	 * format:
24
+	 * array(
25
+	 * 'context' => array(
26
+	 *        'label' => __('Context Label', 'event_espresso'),
27
+	 *        'description' => __('Context description (for help popups)', 'event_espresso')
28
+	 *    ));
29
+	 *
30
+	 * @var array
31
+	 */
32
+	protected $_contexts = array();
33
+
34
+
35
+	/**
36
+	 * This property is used to define what the display label will be for contexts (eg. "Recipients", "Themes" etc.)
37
+	 * Format:
38
+	 * array( 'label' => 'something', 'plural' => 'somethings', 'description' => 'something' );
39
+	 *
40
+	 * @var array
41
+	 */
42
+	protected $_context_label;
43
+
44
+
45
+	/** MESSAGE ASSEMBLING PROPERTIES **/
46
+	/**
47
+	 * This parameter simply holds all the message objects for retrieval by the controller and sending to the messenger.
48
+	 *
49
+	 * @var array of message objects.
50
+	 */
51
+	public $messages = array();
52
+
53
+	/**
54
+	 * The following holds the templates that will be used to assemble the message object for the messenger.
55
+	 *
56
+	 * @var array
57
+	 */
58
+	protected $_templates;
59
+
60
+
61
+	/**
62
+	 * If a specific template is being parsed, this will hold the message template group GRP_ID for that template.
63
+	 *
64
+	 * @var int.
65
+	 */
66
+	protected $_GRP_ID;
67
+
68
+
69
+	/** OTHER INFO PROPERTIES **/
70
+	/**
71
+	 * This will hold the count of the message objects in the messages array. This could be used for determining if
72
+	 * batching/queueing is needed.
73
+	 *
74
+	 * @var int
75
+	 */
76
+	public $count = 0;
77
+
78
+
79
+	/**
80
+	 * This is set via the `do_messenger_hooks` method and contains the messenger being used to send the message of
81
+	 * this message type at time of sending.
82
+	 *
83
+	 * @var EE_messenger
84
+	 */
85
+	protected $_active_messenger;
86
+
87
+
88
+	/**
89
+	 * This will hold the shortcode_replace instance for handling replacement of shortcodes in the various templates
90
+	 *
91
+	 * @var object
92
+	 */
93
+	protected $_shortcode_replace;
94
+
95
+
96
+	/**
97
+	 * The purpose for this property is to simply allow message types to indicate if the message generated is intended
98
+	 * for only single context.  Child message types should redefine this variable (if necessary) in the
99
+	 * _set_data_Handler() method.
100
+	 *
101
+	 * @var boolean
102
+	 */
103
+	protected $_single_message = false;
104
+
105
+
106
+	/**
107
+	 * This will hold an array of specific reg_ids that are receiving messages.
108
+	 *
109
+	 * @since 4.7.x
110
+	 * @var array
111
+	 */
112
+	protected $_regs_for_sending = array();
113
+
114
+
115
+	/**
116
+	 * This holds the data passed to this class from the controller and also the final processed data.
117
+	 *
118
+	 * @var object
119
+	 */
120
+	protected $_data;
121
+
122
+
123
+	/**
124
+	 * this is just a flag indicating whether we're in preview mode or not.
125
+	 *
126
+	 * @var bool
127
+	 */
128
+	protected $_preview = false;
129
+
130
+
131
+	/**
132
+	 * This just holds defaults for addressee data that children merge with their data array setup
133
+	 *
134
+	 * @var array
135
+	 */
136
+	protected $_default_addressee_data;
137
+
138
+
139
+	/**
140
+	 * Child classes declare through this property what handler they want to use for the incoming data and this string
141
+	 * is used to instantiate the EE_Messages_incoming_data child class for that handler.
142
+	 *
143
+	 * @var string
144
+	 */
145
+	protected $_data_handler;
146
+
147
+
148
+	/**
149
+	 * This holds any specific fields for holding any settings related to a message type (if any needed)
150
+	 *
151
+	 * @var array
152
+	 */
153
+	protected $_admin_settings_fields = array();
154
+
155
+	/**
156
+	 * this property will hold any existing setting that may have been set in the admin.
157
+	 *
158
+	 * @var array
159
+	 */
160
+	protected $_existing_admin_settings = array();
161
+
162
+
163
+	/**
164
+	 * This is used to designate the generating and alternative sending messengers for a message type.  It is set via
165
+	 * set_with_messengers() on construct. Note, generating messenger also acts as a sending messenger for this message
166
+	 * type.  However ONLY the generating messengers are used for creating templates for this message type. Should be
167
+	 * in this format:
168
+	 * {
169
+	 *
170
+	 * @type string $generating_messenger the name of the generating messenger.  Generating
171
+	 *                                          messengers are used for generating templates,
172
+	 *                                          doing validation and defining valid shortcodes.
173
+	 *      {
174
+	 * @type string $sending_messenger    values are the name(s) for the sending
175
+	 *                                              messengers.  sending messengers are
176
+	 *                                              just valid delivery vehicles that will utilize
177
+	 *                                              the templates (and generated EE_message
178
+	 *                                              objects from the generating messengers).
179
+	 *      }
180
+	 * }
181
+	 * @since                             4.5.0
182
+	 * @var array
183
+	 */
184
+	protected $_with_messengers = array();
185
+
186
+
187
+	/**
188
+	 * This holds the addressees in an array indexed by context for later retrieval when assembling the message objects.
189
+	 *
190
+	 * @access protected
191
+	 * @var array
192
+	 */
193
+	protected $_addressees = array();
194
+
195
+
196
+	/**
197
+	 * This allows each message type to set what alternate messenger&message type combination can be used for fallback
198
+	 * default templates if there are no specific ones defined for this messenger and message type.  Should be in the
199
+	 * format:
200
+	 * array(
201
+	 *      'messenger' => 'message_type',
202
+	 *      'another_messenger' => another_message_type
203
+	 * );
204
+	 * This is set in the message type constructor.
205
+	 *
206
+	 * @var array
207
+	 */
208
+	protected $_master_templates = array();
209
+
210
+
211
+	/**
212
+	 * This holds whatever the set template pack is for a message template group when generating messages.
213
+	 *
214
+	 * @since 4.5.0
215
+	 * @var EE_Messages_Template_Pack
216
+	 */
217
+	protected $_template_pack;
218
+
219
+
220
+	/**
221
+	 * This holds whatever the set variation is for a message template group when generating messages.
222
+	 *
223
+	 * @since 4.5.0
224
+	 * @var string
225
+	 */
226
+	protected $_variation;
227
+
228
+
229
+	/**
230
+	 * EE_message_type constructor.
231
+	 */
232
+	public function __construct()
233
+	{
234
+		$this->_messages_item_type = 'message_type';
235
+		$this->_set_contexts();
236
+		$this->_set_with_messengers();
237
+		parent::__construct();
238
+	}
239
+
240
+
241
+	/**
242
+	 * This sets the data handler for the message type.  It must be used to define the _data_handler property.  It is
243
+	 * called when messages are setup.
244
+	 *
245
+	 * @abstract
246
+	 * @access protected
247
+	 * @return void
248
+	 */
249
+	abstract protected function _set_data_handler();
250
+
251
+
252
+	/**
253
+	 * This method should return a EE_Base_Class object (or array of EE_Base_Class objects) for the given context and
254
+	 * ID (which should be the primary key id for the base class).  Client code doesn't have to know what a message
255
+	 * type's data handler is.
256
+	 *
257
+	 * @since 4.5.0
258
+	 * @param string          $context      This should be a string matching a valid context for the message type.
259
+	 * @param EE_Registration $registration Need a registration to ensure that the data is valid (prevents people
260
+	 *                                      guessing a url).
261
+	 * @param int             $id           Optional. Integer corresponding to the value for the primary key of a
262
+	 *                                      EE_Base_Class_Object
263
+	 * @return mixed ( EE_Base_Class||EE_Base_Class[] )
264
+	 */
265
+	abstract protected function _get_data_for_context($context, EE_Registration $registration, $id);
266
+
267
+
268
+	/**
269
+	 * _set_contexts
270
+	 * This sets up the contexts associated with the message_type
271
+	 *
272
+	 * @abstract
273
+	 * @access  protected
274
+	 * @return  void
275
+	 */
276
+	abstract protected function _set_contexts();
277
+
278
+
279
+	/**
280
+	 * This is used to get the "id" value fo the msg_trigger_url generated by get_url_trigger().
281
+	 * In most cases, child classes don't need anything, (hence the default of 0), however if there is a specific
282
+	 * EE_Base_Class that is required in generating a message for a message type recipient then the message
283
+	 * type should override this method and use the given params to generate the correct ID.
284
+	 *
285
+	 * @param string          $context      The message type context.
286
+	 * @param EE_Registration $registration Registration object
287
+	 * @deprecated 4.9.0
288
+	 * @return int
289
+	 */
290
+	protected function _get_id_for_msg_url($context, EE_Registration $registration)
291
+	{
292
+		return 0;
293
+	}
294
+
295
+
296
+	/**
297
+	 * This sets up any action/filter hooks this message type puts in place for a specific messenger.  Note that by
298
+	 * default this does nothing.  Child classes will need to override if they want to add specific hooks for a
299
+	 * messenger.
300
+	 *
301
+	 * @since 1.0.0
302
+	 * @return void
303
+	 */
304
+	protected function _do_messenger_hooks()
305
+	{
306
+		return;
307
+	}
308
+
309
+
310
+	/**
311
+	 * This is a public wrapper for the protected _do_messenger_hooks() method.
312
+	 * For backward compat reasons, this was done rather than making the protected method public.
313
+	 *
314
+	 * @param   EE_messenger $messenger This is used to set the $_active_messenger property, so message types are able
315
+	 *                                  to know what messenger is being used to send the message at the time of
316
+	 *                                  sending.
317
+	 * @since 4.9.0
318
+	 */
319
+	public function do_messenger_hooks($messenger = null)
320
+	{
321
+		$this->_active_messenger = $messenger;
322
+		$this->_do_messenger_hooks();
323
+	}
324
+
325
+
326
+	/**
327
+	 * This method returns whether this message type should always generate a new copy
328
+	 * when requested, or if links can be to the already generated copy.
329
+	 * Note: this does NOT affect viewing/resending already generated messages in the EE_Message list table.
330
+	 * Child classes should override this if different from the default of false.
331
+	 *
332
+	 * @return bool     false means can link to generated EE_Message.  true must regenerate.
333
+	 */
334
+	public function always_generate()
335
+	{
336
+		return false;
337
+	}
338
+
339
+
340
+	/**
341
+	 * Returns the priority for the message type.
342
+	 * Priorities are defined as constants on EEM_Message.  Currently there are three priorities:
343
+	 * - EEM_Message::priority_high
344
+	 * - EEM_Message::priority_medium
345
+	 * - EEM_Message::priority_low
346
+	 * Priority is used to determine the weight the message type is given when queuing for generation and/or sending.
347
+	 *
348
+	 * @see    EEM_Message for more phpdocs on priority.
349
+	 *         The default priority for all message_types is EEM_Message::priority_low.  Message Types wanting to give
350
+	 *         a higher priority must override this method. Also note, messengers are able to override priorities
351
+	 *         queuing instructions if their "send_now" flag is set to true. An example of this is the HTML messenger
352
+	 *         which displays things in the browser.
353
+	 * @since  4.9.0
354
+	 * @return int
355
+	 */
356
+	public function get_priority()
357
+	{
358
+		return EEM_Message::priority_low;
359
+	}
360
+
361
+
362
+	/**
363
+	 * This runs the _set_data_handler() method for message types and then returns what got set.
364
+	 *
365
+	 * @param mixed $data This sets the data property for the message type with the incoming data used for generating.
366
+	 * @return string (the reference for the data handler) (will be an empty string if could not be determined).
367
+	 */
368
+	public function get_data_handler($data)
369
+	{
370
+		$this->_data = $data;
371
+		$this->_set_data_handler();
372
+		return apply_filters('FHEE__EE_message_type__get_data_handler', $this->_data_handler, $this);
373
+	}
374
+
375
+
376
+	/**
377
+	 * This is called externally to reset the value of the $_data property for the message type.
378
+	 * Please note the value of the _data is highly volatile.  It was added as an interim measure ensuring
379
+	 * EE_Message_To_Generate objects have any changes to the _data property when `_set_data_handler` method is called
380
+	 * (and for back compat reasons). This particular method is used in
381
+	 * EE_Messages_Generator::_reset_current_properties to ensure that the internal _data on the message type is
382
+	 * cleaned before subsequent EE_Message generation in the same request.
383
+	 *
384
+	 * @todo      This needs refactored along with the whole _set_data_handler() method in EE_message_types. Need to
385
+	 *            ensure that there is no manipulation of the _data property during run time so there's a clear
386
+	 *            expectation of what it is.  Likely we need to ensure that _data is not persisted IN the message type
387
+	 *            at all.
388
+	 * @internal  Plugin authors, do not implement this method, it is subject to change.
389
+	 * @since     4.9
390
+	 */
391
+	public function reset_data()
392
+	{
393
+		$this->_data = null;
394
+	}
395
+
396
+
397
+	/**
398
+	 * This does some validation of incoming params gets the url trigger from the defined method in the specific child
399
+	 * class and then filters the results.
400
+	 *
401
+	 * @param string          $context           The message type context
402
+	 * @param string          $sending_messenger The sending messenger
403
+	 * @param EE_Registration $registration      Registration object
404
+	 * @throws EE_Error
405
+	 * @deprecated  4.9.0  Likely 4.9.10 or 4.10.0 will remove this method completely
406
+	 * @return string          generated url
407
+	 */
408
+	public function get_url_trigger($context, $sending_messenger, EE_Registration $registration)
409
+	{
410
+		//validate context
411
+		//valid context?
412
+		if (! isset($this->_contexts[$context])) {
413
+			throw new EE_Error(
414
+				sprintf(
415
+					__('The context %s is not a valid context for %s.', 'event_espresso'),
416
+					$context,
417
+					get_class($this)
418
+				)
419
+			);
420
+		}
421
+		//valid sending_messenger?
422
+		$not_valid_msgr = false;
423
+		foreach ($this->_with_messengers as $generating => $sendings) {
424
+			if (empty($sendings) || array_search($sending_messenger, $sendings) === false) {
425
+				$not_valid_msgr = true;
426
+			}
427
+		}
428
+		if ($not_valid_msgr) {
429
+			throw new EE_Error(
430
+				sprintf(
431
+					__(
432
+						'The given sending messenger string (%s) does not match a valid sending messenger with the %s.  If this is incorrect, make sure that the message type has defined this messenger as a sending messenger in its $_with_messengers array.',
433
+						'event_espresso'
434
+					),
435
+					$sending_messenger,
436
+					get_class($this)
437
+				)
438
+			);
439
+		}
440
+		return EEH_MSG_Template::generate_url_trigger(
441
+			$sending_messenger,
442
+			$this->_active_messenger->name,
443
+			$context,
444
+			$this->name,
445
+			$registration,
446
+			$this->_GRP_ID,
447
+			$this->_get_id_for_msg_url($context, $registration)
448
+		);
449
+	}
450
+
451
+
452
+	/**
453
+	 * Wrapper for _get_data_for_context() that handles some validation before calling the main class and also allows
454
+	 * for filtering. This is (currently) called by the EED_Messages module.
455
+	 *
456
+	 * @since 4.5.0
457
+	 * @throws EE_Error
458
+	 * @param string          $context      This should be a string matching a valid context for the message type.
459
+	 * @param EE_Registration $registration Need a registration to ensure that the data is valid (prevents people
460
+	 *                                      guessing a url).
461
+	 * @param int             $id           Optional. Integer corresponding to the value for the primary key of a
462
+	 *                                      EE_Base_Class_Object
463
+	 * @return mixed (EE_Base_Class||EE_Base_Class[])
464
+	 */
465
+	public function get_data_for_context($context, EE_Registration $registration, $id = 0)
466
+	{
467
+		//valid context?
468
+		if (! isset($this->_contexts[$context])) {
469
+			throw new EE_Error(
470
+				sprintf(
471
+					__('The context %s is not a valid context for %s.', 'event_espresso'),
472
+					$context,
473
+					get_class($this)
474
+				)
475
+			);
476
+		}
477
+		//get data and apply global and class specific filters on it.
478
+		$data = apply_filters(
479
+			'FHEE__EE_message_type__get_data_for_context__data',
480
+			$this->_get_data_for_context($context, $registration, $id),
481
+			$this
482
+		);
483
+		$data = apply_filters('FHEE__' . get_class($this) . '__get_data_for_context__data', $data, $this);
484
+		//if empty then something went wrong!
485
+		if (empty($data)) {
486
+			throw new EE_Error(
487
+				sprintf(
488
+					__(
489
+						'There is no data retrieved, it is possible that the id given (%d) does not match any value in the database for the corresponding EE_Base_Class used by the data handler for the %s message type.',
490
+						'event_espresso'
491
+					),
492
+					$id,
493
+					$this->name
494
+				)
495
+			);
496
+		}
497
+		return $data;
498
+	}
499
+
500
+
501
+	/**
502
+	 * This returns the contents of the _data property.
503
+	 * Please note the value of the _data is highly volatile.  It was added as an interim measure ensuring
504
+	 * EE_Message_To_Generate objects have any changes to the _data property when `_set_data_handler` method is called.
505
+	 *
506
+	 * @todo      This needs refactored along with the whole _set_data_handler() method in EE_message_types. Need to
507
+	 *            ensure that there is no manipulation of the _data property during run time so there's a clear
508
+	 *            expectation of what it is.
509
+	 * @internal  Plugin authors, do not implement this method, it is subject to change.
510
+	 * @return mixed
511
+	 */
512
+	public function get_data()
513
+	{
514
+		return $this->_data;
515
+	}
516
+
517
+
518
+	/**
519
+	 * used to set the $_with_messengers property. (this is a default, child classes SHOULD override)
520
+	 *
521
+	 * @see   property definition for description of setup.
522
+	 * @since 4.5.0
523
+	 * @abstract
524
+	 * @return void
525
+	 */
526
+	protected function _set_with_messengers()
527
+	{
528
+		$this->_with_messengers = array(
529
+			'email' => array('html'),
530
+		);
531
+	}
532
+
533
+
534
+	/**
535
+	 * Return the value of the _with_messengers property
536
+	 *
537
+	 * @since 4.5.0
538
+	 * @return array
539
+	 */
540
+	public function with_messengers()
541
+	{
542
+		return apply_filters(
543
+			'FHEE__EE_message_type__get_with_messengers__with_messengers__' . get_class($this),
544
+			$this->_with_messengers
545
+		);
546
+	}
547
+
548
+
549
+	/**
550
+	 * this public method accepts a page slug (for an EE_admin page) and will return the response from the child class
551
+	 * callback function if that page is registered via the `_admin_registered_page` property set by the child class.
552
+	 * *
553
+	 *
554
+	 * @param string $page       the slug of the EE admin page
555
+	 * @param array  $messengers an array of active messenger objects
556
+	 * @param string $action     the page action (to allow for more specific handling - i.e. edit vs. add pages)
557
+	 * @param array  $extra      This is just an extra argument that can be used to pass additional data for setting up
558
+	 *                           page content.
559
+	 * @access public
560
+	 * @return string
561
+	 */
562
+	public function get_message_type_admin_page_content(
563
+		$page,
564
+		$action = null,
565
+		$extra = array(),
566
+		$messengers = array()
567
+	) {
568
+		//we can also further refine the context by action (if present).
569
+		return $this->_get_admin_page_content($page, $action, $extra, $messengers);
570
+	}
571
+
572
+
573
+	/**
574
+	 * @return array
575
+	 */
576
+	public function get_contexts()
577
+	{
578
+		return $this->_contexts;
579
+	}
580
+
581
+
582
+	/**
583
+	 * This just returns the context label for a given context (as set in $_context_label property)
584
+	 *
585
+	 * @access public
586
+	 * @return array
587
+	 */
588
+	public function get_context_label()
589
+	{
590
+		return $this->_context_label;
591
+	}
592
+
593
+
594
+	/**
595
+	 * This just returns the (filtered) _master_templates property.
596
+	 *
597
+	 * @see property definition for documentation.
598
+	 * @return array
599
+	 */
600
+	public function get_master_templates()
601
+	{
602
+		//first class specific filter then filter that by the global filter.
603
+		$master_templates = apply_filters(
604
+			'FHEE__' . get_class($this) . '__get_master_templates',
605
+			$this->_master_templates
606
+		);
607
+		return apply_filters('FHEE__EE_message_type__get_master_templates', $master_templates, $this);
608
+	}
609
+
610
+
611
+	/**
612
+	 * Accepts an incoming data handler which contains data for processing, and returns an array of
613
+	 * EE_Messages_Addressee objects.
614
+	 *
615
+	 * @param EE_Messages_incoming_data $data
616
+	 * @param string                    $context Limit addressees to specific context.
617
+	 * @return array   An array indexed by context where each context is an array of EE_Messages_Addressee objects for
618
+	 *                                           that context
619
+	 */
620
+	public function get_addressees(EE_Messages_incoming_data $data, $context = '')
621
+	{
622
+		//override _data
623
+		$this->_data       = $data;
624
+		$addressees        = array();
625
+		$original_contexts = $this->_contexts;
626
+		//if incoming context then limit to that context
627
+		if (! empty($context)) {
628
+			$cntxt = ! empty($this->_contexts[$context]) ? $this->_contexts[$context] : '';
629
+			if (! empty($cntxt)) {
630
+				$this->_contexts           = array();
631
+				$this->_contexts[$context] = $cntxt;
632
+			}
633
+		}
634
+		$this->_set_default_addressee_data();
635
+		if ($this->_process_data()) {
636
+			$addressees = $this->_addressees;
637
+		}
638
+
639
+		//reset contexts and addressees
640
+		$this->_contexts   = $original_contexts;
641
+		$this->_addressees = array();
642
+		return $addressees;
643
+	}
644
+
645
+
646
+	/**
647
+	 * processes the data object so we get
648
+	 *
649
+	 * @throws EE_Error
650
+	 * @return bool  true means data was processed successfully, false means not.
651
+	 */
652
+	protected function _process_data()
653
+	{
654
+		//at a minimum, we NEED EE_Attendee objects.
655
+		if (empty($this->_data->attendees)) {
656
+			return false;  //there's no data to process!
657
+		}
658
+		// process addressees for each context.  Child classes will have to have methods for
659
+		// each context defined to handle the processing of the data object within them
660
+		foreach ($this->_contexts as $context => $details) {
661
+			$xpctd_method = '_' . $context . '_addressees';
662
+			if (! method_exists($this, $xpctd_method)) {
663
+				throw new EE_Error(
664
+					sprintf(
665
+						__(
666
+							'The data for %1$s message type cannot be prepared because there is no set method for doing so.  The expected method name is "%2$s" please doublecheck the %1$s message type class and make sure that method is present',
667
+							'event_espresso'
668
+						),
669
+						$this->label['singular'],
670
+						$xpctd_method
671
+					)
672
+				);
673
+			}
674
+			$this->_addressees[$context] = call_user_func(array($this, $xpctd_method));
675
+		}
676
+		return true; //data was processed successfully.
677
+	}
678
+
679
+
680
+	/**
681
+	 * sets the default_addressee_data property,
682
+	 *
683
+	 * @access private
684
+	 * @return void
685
+	 */
686
+	private function _set_default_addressee_data()
687
+	{
688
+		$this->_default_addressee_data = array(
689
+			'billing'                  => $this->_data->billing,
690
+			'taxes'                    => $this->_data->taxes,
691
+			'tax_line_items'           => $this->_data->tax_line_items,
692
+			'additional_line_items'    => $this->_data->additional_line_items,
693
+			'grand_total_line_item'    => $this->_data->grand_total_line_item,
694
+			'txn'                      => $this->_data->txn,
695
+			'payments'                 => $this->_data->payments,
696
+			'payment'                  => isset($this->_data->payment) && $this->_data->payment instanceof EE_Payment
697
+				? $this->_data->payment
698
+				: null,
699
+			'reg_objs'                 => $this->_data->reg_objs,
700
+			'registrations'            => $this->_data->registrations,
701
+			'datetimes'                => $this->_data->datetimes,
702
+			'tickets'                  => $this->_data->tickets,
703
+			'line_items_with_children' => $this->_data->line_items_with_children,
704
+			'questions'                => $this->_data->questions,
705
+			'answers'                  => $this->_data->answers,
706
+			'txn_status'               => $this->_data->txn_status,
707
+			'total_ticket_count'       => $this->_data->total_ticket_count,
708
+		);
709
+		if (is_array($this->_data->primary_attendee_data)) {
710
+			$this->_default_addressee_data                    = array_merge(
711
+				$this->_default_addressee_data,
712
+				$this->_data->primary_attendee_data
713
+			);
714
+			$this->_default_addressee_data['primary_att_obj'] = $this->_data->primary_attendee_data['att_obj'];
715
+			$this->_default_addressee_data['primary_reg_obj'] = $this->_data->primary_attendee_data['reg_obj'];
716
+		}
717
+	}
718
+
719
+
720
+
721
+	/********************
722 722
      * setup default shared addressee object/contexts
723 723
      * These can be utilized simply by defining the context in the child message type.
724 724
      * They can also be overridden if a specific message type needs to do something different for that context.
725 725
      ****************/
726
-    /**
727
-     * see abstract declaration in parent class for details, children message types can
728
-     * override these valid shortcodes if desired (we include all for all contexts by default).
729
-     */
730
-    protected function _set_valid_shortcodes()
731
-    {
732
-        $all_shortcodes = array(
733
-            'attendee_list',
734
-            'attendee',
735
-            'datetime_list',
736
-            'datetime',
737
-            'event_list',
738
-            'event_meta',
739
-            'event',
740
-            'organization',
741
-            'recipient_details',
742
-            'recipient_list',
743
-            'ticket_list',
744
-            'ticket',
745
-            'transaction',
746
-            'venue',
747
-            'primary_registration_details',
748
-            'primary_registration_list',
749
-            'event_author',
750
-            'email',
751
-            'messenger',
752
-        );
753
-        $contexts       = $this->get_contexts();
754
-        foreach ($contexts as $context => $details) {
755
-            $this->_valid_shortcodes[$context] = $all_shortcodes;
756
-            //make sure non admin context does not include the event_author shortcodes
757
-            if ($context != 'admin') {
758
-                if (($key = array_search('event_author', $this->_valid_shortcodes[$context])) !== false) {
759
-                    unset($this->_valid_shortcodes[$context][$key]);
760
-                }
761
-            }
762
-        }
763
-        // make sure admin context does not include the recipient_details shortcodes
764
-        // IF we have admin context hooked in message types might not have that context.
765
-        if (! empty($this->_valid_shortcodes['admin'])) {
766
-            if (($key = array_search('recipient_details', $this->_valid_shortcodes['admin'])) !== false) {
767
-                unset($this->_valid_shortcodes['admin'][$key]);
768
-            }
769
-            //make sure admin context does not include the recipient_details shortcodes
770
-            if (($key = array_search('recipient_list', $this->_valid_shortcodes['admin'])) !== false) {
771
-                unset($this->_valid_shortcodes['admin'][$key]);
772
-            }
773
-        }
774
-    }
775
-
776
-
777
-    /**
778
-     * Used by Validators to modify the valid shortcodes.
779
-     *
780
-     * @param  array $new_config array of valid shortcodes (by context)
781
-     * @return void               sets valid_shortcodes property
782
-     */
783
-    public function reset_valid_shortcodes_config($new_config)
784
-    {
785
-        foreach ($new_config as $context => $shortcodes) {
786
-            $this->_valid_shortcodes[$context] = $shortcodes;
787
-        }
788
-    }
789
-
790
-
791
-    /**
792
-     * returns an array of addressee objects for event_admins
793
-     *
794
-     * @access protected
795
-     * @return array array of EE_Messages_Addressee objects
796
-     */
797
-    protected function _admin_addressees()
798
-    {
799
-        $admin_events = array();
800
-        $addressees   = array();
801
-        // first we need to get the event admin user id for all the events
802
-        // and setup an addressee object for each unique admin user.
803
-        foreach ($this->_data->events as $line_ref => $event) {
804
-            $admin_id = $this->_get_event_admin_id($event['ID']);
805
-            //make sure we are just including the events that belong to this admin!
806
-            $admin_events[$admin_id][$line_ref] = $event;
807
-        }
808
-        //k now we can loop through the event_admins and setup the addressee data.
809
-        foreach ($admin_events as $admin_id => $event_details) {
810
-            $aee          = array(
811
-                'user_id'        => $admin_id,
812
-                'events'         => $event_details,
813
-                'attendees'      => $this->_data->attendees,
814
-                'recipient_id'   => $admin_id,
815
-                'recipient_type' => 'WP_User',
816
-            );
817
-            $aee          = array_merge($this->_default_addressee_data, $aee);
818
-            $addressees[] = new EE_Messages_Addressee($aee);
819
-        }
820
-        return $addressees;
821
-    }
822
-
823
-
824
-    /**
825
-     * Takes care of setting up the addressee object(s) for the primary attendee.
826
-     *
827
-     * @access protected
828
-     * @return array of EE_Addressee objects
829
-     */
830
-    protected function _primary_attendee_addressees()
831
-    {
832
-        $aee                   = $this->_default_addressee_data;
833
-        $aee['events']         = $this->_data->events;
834
-        $aee['attendees']      = $this->_data->attendees;
835
-        $aee['recipient_id']   = $aee['primary_att_obj'] instanceof EE_Attendee ? $aee['primary_att_obj']->ID() : 0;
836
-        $aee['recipient_type'] = 'Attendee';
837
-        //great now we can instantiate the $addressee object and return (as an array);
838
-        $add[] = new EE_Messages_Addressee($aee);
839
-        return $add;
840
-    }
841
-
842
-
843
-    /**
844
-     * Takes care of setting up the addressee object(s) for the registered attendees
845
-     *
846
-     * @access protected
847
-     * @return array of EE_Addressee objects
848
-     */
849
-    protected function _attendee_addressees()
850
-    {
851
-        $add = array();
852
-        //we just have to loop through the attendees.  We'll also set the attached events for each attendee.
853
-        //use to verify unique attendee emails... we don't want to sent multiple copies to the same attendee do we?
854
-        $already_processed = array();
855
-        foreach ($this->_data->attendees as $att_id => $details) {
856
-            //set the attendee array to blank on each loop;
857
-            $aee = array();
858
-            if (isset($this->_data->reg_obj)
859
-                && ($this->_data->reg_obj->attendee_ID() != $att_id)
860
-                && $this->_single_message
861
-            ) {
862
-                continue;
863
-            }
864
-            // is $this->_regs_for_sending present?
865
-            // If so, let's make sure we ONLY generate addressee for registrations in that array.
866
-            if (! empty($this->_regs_for_sending) && is_array($this->_regs_for_sending)) {
867
-                $regs_allowed = array_intersect_key(array_flip($this->_regs_for_sending), $details['reg_objs']);
868
-                if (empty($regs_allowed)) {
869
-                    continue;
870
-                }
871
-            }
872
-            if (
873
-                in_array($details['attendee_email'], $already_processed)
874
-                && apply_filters(
875
-                    'FHEE__EE_message_type___attendee_addressees__prevent_duplicate_email_sends',
876
-                    true,
877
-                    $this->_data,
878
-                    $this
879
-                )
880
-            ) {
881
-                continue;
882
-            }
883
-            $already_processed[] = $details['attendee_email'];
884
-            foreach ($details as $item => $value) {
885
-                $aee[$item] = $value;
886
-                if ($item == 'line_ref') {
887
-                    foreach ($value as $event_id) {
888
-                        $aee['events'][$event_id] = $this->_data->events[$event_id];
889
-                    }
890
-                }
891
-                if ($item == 'attendee_email') {
892
-                    $aee['attendee_email'] = $value;
893
-                }
894
-                /*if ( $item == 'registration_id' ) {
726
+	/**
727
+	 * see abstract declaration in parent class for details, children message types can
728
+	 * override these valid shortcodes if desired (we include all for all contexts by default).
729
+	 */
730
+	protected function _set_valid_shortcodes()
731
+	{
732
+		$all_shortcodes = array(
733
+			'attendee_list',
734
+			'attendee',
735
+			'datetime_list',
736
+			'datetime',
737
+			'event_list',
738
+			'event_meta',
739
+			'event',
740
+			'organization',
741
+			'recipient_details',
742
+			'recipient_list',
743
+			'ticket_list',
744
+			'ticket',
745
+			'transaction',
746
+			'venue',
747
+			'primary_registration_details',
748
+			'primary_registration_list',
749
+			'event_author',
750
+			'email',
751
+			'messenger',
752
+		);
753
+		$contexts       = $this->get_contexts();
754
+		foreach ($contexts as $context => $details) {
755
+			$this->_valid_shortcodes[$context] = $all_shortcodes;
756
+			//make sure non admin context does not include the event_author shortcodes
757
+			if ($context != 'admin') {
758
+				if (($key = array_search('event_author', $this->_valid_shortcodes[$context])) !== false) {
759
+					unset($this->_valid_shortcodes[$context][$key]);
760
+				}
761
+			}
762
+		}
763
+		// make sure admin context does not include the recipient_details shortcodes
764
+		// IF we have admin context hooked in message types might not have that context.
765
+		if (! empty($this->_valid_shortcodes['admin'])) {
766
+			if (($key = array_search('recipient_details', $this->_valid_shortcodes['admin'])) !== false) {
767
+				unset($this->_valid_shortcodes['admin'][$key]);
768
+			}
769
+			//make sure admin context does not include the recipient_details shortcodes
770
+			if (($key = array_search('recipient_list', $this->_valid_shortcodes['admin'])) !== false) {
771
+				unset($this->_valid_shortcodes['admin'][$key]);
772
+			}
773
+		}
774
+	}
775
+
776
+
777
+	/**
778
+	 * Used by Validators to modify the valid shortcodes.
779
+	 *
780
+	 * @param  array $new_config array of valid shortcodes (by context)
781
+	 * @return void               sets valid_shortcodes property
782
+	 */
783
+	public function reset_valid_shortcodes_config($new_config)
784
+	{
785
+		foreach ($new_config as $context => $shortcodes) {
786
+			$this->_valid_shortcodes[$context] = $shortcodes;
787
+		}
788
+	}
789
+
790
+
791
+	/**
792
+	 * returns an array of addressee objects for event_admins
793
+	 *
794
+	 * @access protected
795
+	 * @return array array of EE_Messages_Addressee objects
796
+	 */
797
+	protected function _admin_addressees()
798
+	{
799
+		$admin_events = array();
800
+		$addressees   = array();
801
+		// first we need to get the event admin user id for all the events
802
+		// and setup an addressee object for each unique admin user.
803
+		foreach ($this->_data->events as $line_ref => $event) {
804
+			$admin_id = $this->_get_event_admin_id($event['ID']);
805
+			//make sure we are just including the events that belong to this admin!
806
+			$admin_events[$admin_id][$line_ref] = $event;
807
+		}
808
+		//k now we can loop through the event_admins and setup the addressee data.
809
+		foreach ($admin_events as $admin_id => $event_details) {
810
+			$aee          = array(
811
+				'user_id'        => $admin_id,
812
+				'events'         => $event_details,
813
+				'attendees'      => $this->_data->attendees,
814
+				'recipient_id'   => $admin_id,
815
+				'recipient_type' => 'WP_User',
816
+			);
817
+			$aee          = array_merge($this->_default_addressee_data, $aee);
818
+			$addressees[] = new EE_Messages_Addressee($aee);
819
+		}
820
+		return $addressees;
821
+	}
822
+
823
+
824
+	/**
825
+	 * Takes care of setting up the addressee object(s) for the primary attendee.
826
+	 *
827
+	 * @access protected
828
+	 * @return array of EE_Addressee objects
829
+	 */
830
+	protected function _primary_attendee_addressees()
831
+	{
832
+		$aee                   = $this->_default_addressee_data;
833
+		$aee['events']         = $this->_data->events;
834
+		$aee['attendees']      = $this->_data->attendees;
835
+		$aee['recipient_id']   = $aee['primary_att_obj'] instanceof EE_Attendee ? $aee['primary_att_obj']->ID() : 0;
836
+		$aee['recipient_type'] = 'Attendee';
837
+		//great now we can instantiate the $addressee object and return (as an array);
838
+		$add[] = new EE_Messages_Addressee($aee);
839
+		return $add;
840
+	}
841
+
842
+
843
+	/**
844
+	 * Takes care of setting up the addressee object(s) for the registered attendees
845
+	 *
846
+	 * @access protected
847
+	 * @return array of EE_Addressee objects
848
+	 */
849
+	protected function _attendee_addressees()
850
+	{
851
+		$add = array();
852
+		//we just have to loop through the attendees.  We'll also set the attached events for each attendee.
853
+		//use to verify unique attendee emails... we don't want to sent multiple copies to the same attendee do we?
854
+		$already_processed = array();
855
+		foreach ($this->_data->attendees as $att_id => $details) {
856
+			//set the attendee array to blank on each loop;
857
+			$aee = array();
858
+			if (isset($this->_data->reg_obj)
859
+				&& ($this->_data->reg_obj->attendee_ID() != $att_id)
860
+				&& $this->_single_message
861
+			) {
862
+				continue;
863
+			}
864
+			// is $this->_regs_for_sending present?
865
+			// If so, let's make sure we ONLY generate addressee for registrations in that array.
866
+			if (! empty($this->_regs_for_sending) && is_array($this->_regs_for_sending)) {
867
+				$regs_allowed = array_intersect_key(array_flip($this->_regs_for_sending), $details['reg_objs']);
868
+				if (empty($regs_allowed)) {
869
+					continue;
870
+				}
871
+			}
872
+			if (
873
+				in_array($details['attendee_email'], $already_processed)
874
+				&& apply_filters(
875
+					'FHEE__EE_message_type___attendee_addressees__prevent_duplicate_email_sends',
876
+					true,
877
+					$this->_data,
878
+					$this
879
+				)
880
+			) {
881
+				continue;
882
+			}
883
+			$already_processed[] = $details['attendee_email'];
884
+			foreach ($details as $item => $value) {
885
+				$aee[$item] = $value;
886
+				if ($item == 'line_ref') {
887
+					foreach ($value as $event_id) {
888
+						$aee['events'][$event_id] = $this->_data->events[$event_id];
889
+					}
890
+				}
891
+				if ($item == 'attendee_email') {
892
+					$aee['attendee_email'] = $value;
893
+				}
894
+				/*if ( $item == 'registration_id' ) {
895 895
                     $aee['attendee_registration_id'] = $value;
896 896
                 }/**/
897
-            }
898
-            // note the FIRST reg object in this array is the one
899
-            // we'll use for this attendee as the primary registration for this attendee.
900
-            $aee['reg_obj']        = reset($this->_data->attendees[$att_id]['reg_objs']);
901
-            $aee['attendees']      = $this->_data->attendees;
902
-            $aee['recipient_id']   = $att_id;
903
-            $aee['recipient_type'] = 'Attendee';
904
-            //merge in the primary attendee data
905
-            $aee   = array_merge($this->_default_addressee_data, $aee);
906
-            $add[] = new EE_Messages_Addressee($aee);
907
-        }
908
-        return $add;
909
-    }
910
-
911
-
912
-    /**
913
-     * @param $event_id
914
-     * @return int
915
-     */
916
-    protected function _get_event_admin_id($event_id)
917
-    {
918
-        $event = EEM_Event::instance()->get_one_by_ID($event_id);
919
-        return $event instanceof EE_Event ? $event->wp_user() : 0;
920
-    }
897
+			}
898
+			// note the FIRST reg object in this array is the one
899
+			// we'll use for this attendee as the primary registration for this attendee.
900
+			$aee['reg_obj']        = reset($this->_data->attendees[$att_id]['reg_objs']);
901
+			$aee['attendees']      = $this->_data->attendees;
902
+			$aee['recipient_id']   = $att_id;
903
+			$aee['recipient_type'] = 'Attendee';
904
+			//merge in the primary attendee data
905
+			$aee   = array_merge($this->_default_addressee_data, $aee);
906
+			$add[] = new EE_Messages_Addressee($aee);
907
+		}
908
+		return $add;
909
+	}
910
+
911
+
912
+	/**
913
+	 * @param $event_id
914
+	 * @return int
915
+	 */
916
+	protected function _get_event_admin_id($event_id)
917
+	{
918
+		$event = EEM_Event::instance()->get_one_by_ID($event_id);
919
+		return $event instanceof EE_Event ? $event->wp_user() : 0;
920
+	}
921 921
 
922 922
 
923 923
 }
Please login to merge, or discard this patch.
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-if (! defined('EVENT_ESPRESSO_VERSION')) {
2
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
3 3
     exit('NO direct script access allowed');
4 4
 }
5 5
 
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
     {
410 410
         //validate context
411 411
         //valid context?
412
-        if (! isset($this->_contexts[$context])) {
412
+        if ( ! isset($this->_contexts[$context])) {
413 413
             throw new EE_Error(
414 414
                 sprintf(
415 415
                     __('The context %s is not a valid context for %s.', 'event_espresso'),
@@ -465,7 +465,7 @@  discard block
 block discarded – undo
465 465
     public function get_data_for_context($context, EE_Registration $registration, $id = 0)
466 466
     {
467 467
         //valid context?
468
-        if (! isset($this->_contexts[$context])) {
468
+        if ( ! isset($this->_contexts[$context])) {
469 469
             throw new EE_Error(
470 470
                 sprintf(
471 471
                     __('The context %s is not a valid context for %s.', 'event_espresso'),
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
             $this->_get_data_for_context($context, $registration, $id),
481 481
             $this
482 482
         );
483
-        $data = apply_filters('FHEE__' . get_class($this) . '__get_data_for_context__data', $data, $this);
483
+        $data = apply_filters('FHEE__'.get_class($this).'__get_data_for_context__data', $data, $this);
484 484
         //if empty then something went wrong!
485 485
         if (empty($data)) {
486 486
             throw new EE_Error(
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
     public function with_messengers()
541 541
     {
542 542
         return apply_filters(
543
-            'FHEE__EE_message_type__get_with_messengers__with_messengers__' . get_class($this),
543
+            'FHEE__EE_message_type__get_with_messengers__with_messengers__'.get_class($this),
544 544
             $this->_with_messengers
545 545
         );
546 546
     }
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
     {
602 602
         //first class specific filter then filter that by the global filter.
603 603
         $master_templates = apply_filters(
604
-            'FHEE__' . get_class($this) . '__get_master_templates',
604
+            'FHEE__'.get_class($this).'__get_master_templates',
605 605
             $this->_master_templates
606 606
         );
607 607
         return apply_filters('FHEE__EE_message_type__get_master_templates', $master_templates, $this);
@@ -624,9 +624,9 @@  discard block
 block discarded – undo
624 624
         $addressees        = array();
625 625
         $original_contexts = $this->_contexts;
626 626
         //if incoming context then limit to that context
627
-        if (! empty($context)) {
627
+        if ( ! empty($context)) {
628 628
             $cntxt = ! empty($this->_contexts[$context]) ? $this->_contexts[$context] : '';
629
-            if (! empty($cntxt)) {
629
+            if ( ! empty($cntxt)) {
630 630
                 $this->_contexts           = array();
631 631
                 $this->_contexts[$context] = $cntxt;
632 632
             }
@@ -653,13 +653,13 @@  discard block
 block discarded – undo
653 653
     {
654 654
         //at a minimum, we NEED EE_Attendee objects.
655 655
         if (empty($this->_data->attendees)) {
656
-            return false;  //there's no data to process!
656
+            return false; //there's no data to process!
657 657
         }
658 658
         // process addressees for each context.  Child classes will have to have methods for
659 659
         // each context defined to handle the processing of the data object within them
660 660
         foreach ($this->_contexts as $context => $details) {
661
-            $xpctd_method = '_' . $context . '_addressees';
662
-            if (! method_exists($this, $xpctd_method)) {
661
+            $xpctd_method = '_'.$context.'_addressees';
662
+            if ( ! method_exists($this, $xpctd_method)) {
663 663
                 throw new EE_Error(
664 664
                     sprintf(
665 665
                         __(
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
             'total_ticket_count'       => $this->_data->total_ticket_count,
708 708
         );
709 709
         if (is_array($this->_data->primary_attendee_data)) {
710
-            $this->_default_addressee_data                    = array_merge(
710
+            $this->_default_addressee_data = array_merge(
711 711
                 $this->_default_addressee_data,
712 712
                 $this->_data->primary_attendee_data
713 713
             );
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
             'email',
751 751
             'messenger',
752 752
         );
753
-        $contexts       = $this->get_contexts();
753
+        $contexts = $this->get_contexts();
754 754
         foreach ($contexts as $context => $details) {
755 755
             $this->_valid_shortcodes[$context] = $all_shortcodes;
756 756
             //make sure non admin context does not include the event_author shortcodes
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
         }
763 763
         // make sure admin context does not include the recipient_details shortcodes
764 764
         // IF we have admin context hooked in message types might not have that context.
765
-        if (! empty($this->_valid_shortcodes['admin'])) {
765
+        if ( ! empty($this->_valid_shortcodes['admin'])) {
766 766
             if (($key = array_search('recipient_details', $this->_valid_shortcodes['admin'])) !== false) {
767 767
                 unset($this->_valid_shortcodes['admin'][$key]);
768 768
             }
@@ -807,7 +807,7 @@  discard block
 block discarded – undo
807 807
         }
808 808
         //k now we can loop through the event_admins and setup the addressee data.
809 809
         foreach ($admin_events as $admin_id => $event_details) {
810
-            $aee          = array(
810
+            $aee = array(
811 811
                 'user_id'        => $admin_id,
812 812
                 'events'         => $event_details,
813 813
                 'attendees'      => $this->_data->attendees,
@@ -863,7 +863,7 @@  discard block
 block discarded – undo
863 863
             }
864 864
             // is $this->_regs_for_sending present?
865 865
             // If so, let's make sure we ONLY generate addressee for registrations in that array.
866
-            if (! empty($this->_regs_for_sending) && is_array($this->_regs_for_sending)) {
866
+            if ( ! empty($this->_regs_for_sending) && is_array($this->_regs_for_sending)) {
867 867
                 $regs_allowed = array_intersect_key(array_flip($this->_regs_for_sending), $details['reg_objs']);
868 868
                 if (empty($regs_allowed)) {
869 869
                     continue;
Please login to merge, or discard this patch.
espresso.php 1 patch
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php if ( ! defined('ABSPATH')) {
2
-    exit('No direct script access allowed');
2
+	exit('No direct script access allowed');
3 3
 }
4 4
 /*
5 5
   Plugin Name:		Event Espresso
@@ -40,243 +40,243 @@  discard block
 block discarded – undo
40 40
  * @since            4.0
41 41
  */
42 42
 if (function_exists('espresso_version')) {
43
-    /**
44
-     *    espresso_duplicate_plugin_error
45
-     *    displays if more than one version of EE is activated at the same time
46
-     */
47
-    function espresso_duplicate_plugin_error()
48
-    {
49
-        ?>
43
+	/**
44
+	 *    espresso_duplicate_plugin_error
45
+	 *    displays if more than one version of EE is activated at the same time
46
+	 */
47
+	function espresso_duplicate_plugin_error()
48
+	{
49
+		?>
50 50
         <div class="error">
51 51
             <p>
52 52
                 <?php echo esc_html__(
53
-                        'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
-                        'event_espresso'
55
-                ); ?>
53
+						'Can not run multiple versions of Event Espresso! One version has been automatically deactivated. Please verify that you have the correct version you want still active.',
54
+						'event_espresso'
55
+				); ?>
56 56
             </p>
57 57
         </div>
58 58
         <?php
59
-        espresso_deactivate_plugin(plugin_basename(__FILE__));
60
-    }
59
+		espresso_deactivate_plugin(plugin_basename(__FILE__));
60
+	}
61 61
 
62
-    add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
62
+	add_action('admin_notices', 'espresso_duplicate_plugin_error', 1);
63 63
 } else {
64
-    define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
-    if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
-        /**
67
-         * espresso_minimum_php_version_error
68
-         *
69
-         * @return void
70
-         */
71
-        function espresso_minimum_php_version_error()
72
-        {
73
-            ?>
64
+	define('EE_MIN_PHP_VER_REQUIRED', '5.3.9');
65
+	if ( ! version_compare(PHP_VERSION, EE_MIN_PHP_VER_REQUIRED, '>=')) {
66
+		/**
67
+		 * espresso_minimum_php_version_error
68
+		 *
69
+		 * @return void
70
+		 */
71
+		function espresso_minimum_php_version_error()
72
+		{
73
+			?>
74 74
             <div class="error">
75 75
                 <p>
76 76
                     <?php
77
-                    printf(
78
-                            esc_html__(
79
-                                    'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
-                                    'event_espresso'
81
-                            ),
82
-                            EE_MIN_PHP_VER_REQUIRED,
83
-                            PHP_VERSION,
84
-                            '<br/>',
85
-                            '<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
-                    );
87
-                    ?>
77
+					printf(
78
+							esc_html__(
79
+									'We\'re sorry, but Event Espresso requires PHP version %1$s or greater in order to operate. You are currently running version %2$s.%3$sIn order to update your version of PHP, you will need to contact your current hosting provider.%3$sFor information on stable PHP versions, please go to %4$s.',
80
+									'event_espresso'
81
+							),
82
+							EE_MIN_PHP_VER_REQUIRED,
83
+							PHP_VERSION,
84
+							'<br/>',
85
+							'<a href="http://php.net/downloads.php">http://php.net/downloads.php</a>'
86
+					);
87
+					?>
88 88
                 </p>
89 89
             </div>
90 90
             <?php
91
-            espresso_deactivate_plugin(plugin_basename(__FILE__));
92
-        }
91
+			espresso_deactivate_plugin(plugin_basename(__FILE__));
92
+		}
93 93
 
94
-        add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
-    } else {
96
-        /**
97
-         * espresso_version
98
-         * Returns the plugin version
99
-         *
100
-         * @return string
101
-         */
102
-        function espresso_version()
103
-        {
104
-            return apply_filters('FHEE__espresso__espresso_version', '4.9.47.rc.029');
105
-        }
94
+		add_action('admin_notices', 'espresso_minimum_php_version_error', 1);
95
+	} else {
96
+		/**
97
+		 * espresso_version
98
+		 * Returns the plugin version
99
+		 *
100
+		 * @return string
101
+		 */
102
+		function espresso_version()
103
+		{
104
+			return apply_filters('FHEE__espresso__espresso_version', '4.9.47.rc.029');
105
+		}
106 106
 
107
-        // define versions
108
-        define('EVENT_ESPRESSO_VERSION', espresso_version());
109
-        define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
-        define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
-        define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
-        define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
-        //used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
-        if ( ! defined('DS')) {
115
-            define('DS', '/');
116
-        }
117
-        if ( ! defined('PS')) {
118
-            define('PS', PATH_SEPARATOR);
119
-        }
120
-        if ( ! defined('SP')) {
121
-            define('SP', ' ');
122
-        }
123
-        if ( ! defined('EENL')) {
124
-            define('EENL', "\n");
125
-        }
126
-        define('EE_SUPPORT_EMAIL', '[email protected]');
127
-        // define the plugin directory and URL
128
-        define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
-        define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
-        define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
-        // main root folder paths
132
-        define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
-        define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
-        define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
-        define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
-        define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
-        define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
-        define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
-        define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
-        // core system paths
141
-        define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
-        define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
-        define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
-        define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
-        define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
-        define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
-        define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
-        define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
-        define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
-        define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
-        define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
-        define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
-        // gateways
154
-        define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
-        define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
-        // asset URL paths
157
-        define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
-        define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
-        define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
-        define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
-        define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
-        define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
-        // define upload paths
164
-        $uploads = wp_upload_dir();
165
-        // define the uploads directory and URL
166
-        define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
-        define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
-        // define the templates directory and URL
169
-        define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
-        define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
-        // define the gateway directory and URL
172
-        define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
-        define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
-        // languages folder/path
175
-        define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
-        define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
-        //check for dompdf fonts in uploads
178
-        if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
-            define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
-        }
181
-        //ajax constants
182
-        define(
183
-                'EE_FRONT_AJAX',
184
-                isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
-        );
186
-        define(
187
-                'EE_ADMIN_AJAX',
188
-                isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
-        );
190
-        //just a handy constant occasionally needed for finding values representing infinity in the DB
191
-        //you're better to use this than its straight value (currently -1) in case you ever
192
-        //want to change its default value! or find when -1 means infinity
193
-        define('EE_INF_IN_DB', -1);
194
-        define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
-        define('EE_DEBUG', false);
196
-        // for older WP versions
197
-        if ( ! defined('MONTH_IN_SECONDS')) {
198
-            define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
-        }
200
-        /**
201
-         *    espresso_plugin_activation
202
-         *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
-         */
204
-        function espresso_plugin_activation()
205
-        {
206
-            update_option('ee_espresso_activation', true);
207
-        }
107
+		// define versions
108
+		define('EVENT_ESPRESSO_VERSION', espresso_version());
109
+		define('EE_MIN_WP_VER_REQUIRED', '4.1');
110
+		define('EE_MIN_WP_VER_RECOMMENDED', '4.4.2');
111
+		define('EE_MIN_PHP_VER_RECOMMENDED', '5.4.44');
112
+		define('EVENT_ESPRESSO_MAIN_FILE', __FILE__);
113
+		//used to be DIRECTORY_SEPARATOR, but that caused issues on windows
114
+		if ( ! defined('DS')) {
115
+			define('DS', '/');
116
+		}
117
+		if ( ! defined('PS')) {
118
+			define('PS', PATH_SEPARATOR);
119
+		}
120
+		if ( ! defined('SP')) {
121
+			define('SP', ' ');
122
+		}
123
+		if ( ! defined('EENL')) {
124
+			define('EENL', "\n");
125
+		}
126
+		define('EE_SUPPORT_EMAIL', '[email protected]');
127
+		// define the plugin directory and URL
128
+		define('EE_PLUGIN_BASENAME', plugin_basename(EVENT_ESPRESSO_MAIN_FILE));
129
+		define('EE_PLUGIN_DIR_PATH', plugin_dir_path(EVENT_ESPRESSO_MAIN_FILE));
130
+		define('EE_PLUGIN_DIR_URL', plugin_dir_url(EVENT_ESPRESSO_MAIN_FILE));
131
+		// main root folder paths
132
+		define('EE_ADMIN_PAGES', EE_PLUGIN_DIR_PATH . 'admin_pages' . DS);
133
+		define('EE_CORE', EE_PLUGIN_DIR_PATH . 'core' . DS);
134
+		define('EE_MODULES', EE_PLUGIN_DIR_PATH . 'modules' . DS);
135
+		define('EE_PUBLIC', EE_PLUGIN_DIR_PATH . 'public' . DS);
136
+		define('EE_SHORTCODES', EE_PLUGIN_DIR_PATH . 'shortcodes' . DS);
137
+		define('EE_WIDGETS', EE_PLUGIN_DIR_PATH . 'widgets' . DS);
138
+		define('EE_PAYMENT_METHODS', EE_PLUGIN_DIR_PATH . 'payment_methods' . DS);
139
+		define('EE_CAFF_PATH', EE_PLUGIN_DIR_PATH . 'caffeinated' . DS);
140
+		// core system paths
141
+		define('EE_ADMIN', EE_CORE . 'admin' . DS);
142
+		define('EE_CPTS', EE_CORE . 'CPTs' . DS);
143
+		define('EE_CLASSES', EE_CORE . 'db_classes' . DS);
144
+		define('EE_INTERFACES', EE_CORE . 'interfaces' . DS);
145
+		define('EE_BUSINESS', EE_CORE . 'business' . DS);
146
+		define('EE_MODELS', EE_CORE . 'db_models' . DS);
147
+		define('EE_HELPERS', EE_CORE . 'helpers' . DS);
148
+		define('EE_LIBRARIES', EE_CORE . 'libraries' . DS);
149
+		define('EE_TEMPLATES', EE_CORE . 'templates' . DS);
150
+		define('EE_THIRD_PARTY', EE_CORE . 'third_party_libs' . DS);
151
+		define('EE_GLOBAL_ASSETS', EE_TEMPLATES . 'global_assets' . DS);
152
+		define('EE_FORM_SECTIONS', EE_LIBRARIES . 'form_sections' . DS);
153
+		// gateways
154
+		define('EE_GATEWAYS', EE_MODULES . 'gateways' . DS);
155
+		define('EE_GATEWAYS_URL', EE_PLUGIN_DIR_URL . 'modules' . DS . 'gateways' . DS);
156
+		// asset URL paths
157
+		define('EE_TEMPLATES_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'templates' . DS);
158
+		define('EE_GLOBAL_ASSETS_URL', EE_TEMPLATES_URL . 'global_assets' . DS);
159
+		define('EE_IMAGES_URL', EE_GLOBAL_ASSETS_URL . 'images' . DS);
160
+		define('EE_THIRD_PARTY_URL', EE_PLUGIN_DIR_URL . 'core' . DS . 'third_party_libs' . DS);
161
+		define('EE_HELPERS_ASSETS', EE_PLUGIN_DIR_URL . 'core/helpers/assets/');
162
+		define('EE_LIBRARIES_URL', EE_PLUGIN_DIR_URL . 'core/libraries/');
163
+		// define upload paths
164
+		$uploads = wp_upload_dir();
165
+		// define the uploads directory and URL
166
+		define('EVENT_ESPRESSO_UPLOAD_DIR', $uploads['basedir'] . DS . 'espresso' . DS);
167
+		define('EVENT_ESPRESSO_UPLOAD_URL', $uploads['baseurl'] . DS . 'espresso' . DS);
168
+		// define the templates directory and URL
169
+		define('EVENT_ESPRESSO_TEMPLATE_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'templates' . DS);
170
+		define('EVENT_ESPRESSO_TEMPLATE_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'templates' . DS);
171
+		// define the gateway directory and URL
172
+		define('EVENT_ESPRESSO_GATEWAY_DIR', $uploads['basedir'] . DS . 'espresso' . DS . 'gateways' . DS);
173
+		define('EVENT_ESPRESSO_GATEWAY_URL', $uploads['baseurl'] . DS . 'espresso' . DS . 'gateways' . DS);
174
+		// languages folder/path
175
+		define('EE_LANGUAGES_SAFE_LOC', '..' . DS . 'uploads' . DS . 'espresso' . DS . 'languages' . DS);
176
+		define('EE_LANGUAGES_SAFE_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'languages' . DS);
177
+		//check for dompdf fonts in uploads
178
+		if (file_exists(EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS)) {
179
+			define('DOMPDF_FONT_DIR', EVENT_ESPRESSO_UPLOAD_DIR . 'fonts' . DS);
180
+		}
181
+		//ajax constants
182
+		define(
183
+				'EE_FRONT_AJAX',
184
+				isset($_REQUEST['ee_front_ajax']) || isset($_REQUEST['data']['ee_front_ajax']) ? true : false
185
+		);
186
+		define(
187
+				'EE_ADMIN_AJAX',
188
+				isset($_REQUEST['ee_admin_ajax']) || isset($_REQUEST['data']['ee_admin_ajax']) ? true : false
189
+		);
190
+		//just a handy constant occasionally needed for finding values representing infinity in the DB
191
+		//you're better to use this than its straight value (currently -1) in case you ever
192
+		//want to change its default value! or find when -1 means infinity
193
+		define('EE_INF_IN_DB', -1);
194
+		define('EE_INF', INF > (float)PHP_INT_MAX ? INF : PHP_INT_MAX);
195
+		define('EE_DEBUG', false);
196
+		// for older WP versions
197
+		if ( ! defined('MONTH_IN_SECONDS')) {
198
+			define('MONTH_IN_SECONDS', DAY_IN_SECONDS * 30);
199
+		}
200
+		/**
201
+		 *    espresso_plugin_activation
202
+		 *    adds a wp-option to indicate that EE has been activated via the WP admin plugins page
203
+		 */
204
+		function espresso_plugin_activation()
205
+		{
206
+			update_option('ee_espresso_activation', true);
207
+		}
208 208
 
209
-        register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
-        /**
211
-         *    espresso_load_error_handling
212
-         *    this function loads EE's class for handling exceptions and errors
213
-         */
214
-        function espresso_load_error_handling()
215
-        {
216
-            // load debugging tools
217
-            if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
-                require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
-                EEH_Debug_Tools::instance();
220
-            }
221
-            // load error handling
222
-            if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
-                require_once(EE_CORE . 'EE_Error.core.php');
224
-            } else {
225
-                wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
-            }
227
-        }
209
+		register_activation_hook(EVENT_ESPRESSO_MAIN_FILE, 'espresso_plugin_activation');
210
+		/**
211
+		 *    espresso_load_error_handling
212
+		 *    this function loads EE's class for handling exceptions and errors
213
+		 */
214
+		function espresso_load_error_handling()
215
+		{
216
+			// load debugging tools
217
+			if (WP_DEBUG === true && is_readable(EE_HELPERS . 'EEH_Debug_Tools.helper.php')) {
218
+				require_once(EE_HELPERS . 'EEH_Debug_Tools.helper.php');
219
+				EEH_Debug_Tools::instance();
220
+			}
221
+			// load error handling
222
+			if (is_readable(EE_CORE . 'EE_Error.core.php')) {
223
+				require_once(EE_CORE . 'EE_Error.core.php');
224
+			} else {
225
+				wp_die(esc_html__('The EE_Error core class could not be loaded.', 'event_espresso'));
226
+			}
227
+		}
228 228
 
229
-        /**
230
-         *    espresso_load_required
231
-         *    given a class name and path, this function will load that file or throw an exception
232
-         *
233
-         * @param    string $classname
234
-         * @param    string $full_path_to_file
235
-         * @throws    EE_Error
236
-         */
237
-        function espresso_load_required($classname, $full_path_to_file)
238
-        {
239
-            static $error_handling_loaded = false;
240
-            if ( ! $error_handling_loaded) {
241
-                espresso_load_error_handling();
242
-                $error_handling_loaded = true;
243
-            }
244
-            if (is_readable($full_path_to_file)) {
245
-                require_once($full_path_to_file);
246
-            } else {
247
-                throw new EE_Error (
248
-                        sprintf(
249
-                                esc_html__(
250
-                                        'The %s class file could not be located or is not readable due to file permissions.',
251
-                                        'event_espresso'
252
-                                ),
253
-                                $classname
254
-                        )
255
-                );
256
-            }
257
-        }
229
+		/**
230
+		 *    espresso_load_required
231
+		 *    given a class name and path, this function will load that file or throw an exception
232
+		 *
233
+		 * @param    string $classname
234
+		 * @param    string $full_path_to_file
235
+		 * @throws    EE_Error
236
+		 */
237
+		function espresso_load_required($classname, $full_path_to_file)
238
+		{
239
+			static $error_handling_loaded = false;
240
+			if ( ! $error_handling_loaded) {
241
+				espresso_load_error_handling();
242
+				$error_handling_loaded = true;
243
+			}
244
+			if (is_readable($full_path_to_file)) {
245
+				require_once($full_path_to_file);
246
+			} else {
247
+				throw new EE_Error (
248
+						sprintf(
249
+								esc_html__(
250
+										'The %s class file could not be located or is not readable due to file permissions.',
251
+										'event_espresso'
252
+								),
253
+								$classname
254
+						)
255
+				);
256
+			}
257
+		}
258 258
 
259
-        espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
-        espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
-        espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
-        new EE_Bootstrap();
263
-    }
259
+		espresso_load_required('EEH_Base', EE_CORE . 'helpers' . DS . 'EEH_Base.helper.php');
260
+		espresso_load_required('EEH_File', EE_CORE . 'helpers' . DS . 'EEH_File.helper.php');
261
+		espresso_load_required('EE_Bootstrap', EE_CORE . 'EE_Bootstrap.core.php');
262
+		new EE_Bootstrap();
263
+	}
264 264
 }
265 265
 if ( ! function_exists('espresso_deactivate_plugin')) {
266
-    /**
267
-     *    deactivate_plugin
268
-     * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
-     *
270
-     * @access public
271
-     * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
-     * @return    void
273
-     */
274
-    function espresso_deactivate_plugin($plugin_basename = '')
275
-    {
276
-        if ( ! function_exists('deactivate_plugins')) {
277
-            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
-        }
279
-        unset($_GET['activate'], $_REQUEST['activate']);
280
-        deactivate_plugins($plugin_basename);
281
-    }
266
+	/**
267
+	 *    deactivate_plugin
268
+	 * usage:  espresso_deactivate_plugin( plugin_basename( __FILE__ ));
269
+	 *
270
+	 * @access public
271
+	 * @param string $plugin_basename - the results of plugin_basename( __FILE__ ) for the plugin's main file
272
+	 * @return    void
273
+	 */
274
+	function espresso_deactivate_plugin($plugin_basename = '')
275
+	{
276
+		if ( ! function_exists('deactivate_plugins')) {
277
+			require_once(ABSPATH . 'wp-admin/includes/plugin.php');
278
+		}
279
+		unset($_GET['activate'], $_REQUEST['activate']);
280
+		deactivate_plugins($plugin_basename);
281
+	}
282 282
 }
283 283
\ No newline at end of file
Please login to merge, or discard this patch.
modules/single_page_checkout/EED_Single_Page_Checkout.module.php 1 patch
Indentation   +1860 added lines, -1860 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\exceptions\InvalidEntityException;
6 6
 
7 7
 if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8
-    exit('No direct script access allowed');
8
+	exit('No direct script access allowed');
9 9
 }
10 10
 
11 11
 
@@ -20,1865 +20,1865 @@  discard block
 block discarded – undo
20 20
 class EED_Single_Page_Checkout extends EED_Module
21 21
 {
22 22
 
23
-    /**
24
-     * $_initialized - has the SPCO controller already been initialized ?
25
-     *
26
-     * @access private
27
-     * @var bool $_initialized
28
-     */
29
-    private static $_initialized = false;
30
-
31
-
32
-    /**
33
-     * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
34
-     *
35
-     * @access private
36
-     * @var bool $_valid_checkout
37
-     */
38
-    private static $_checkout_verified = true;
39
-
40
-    /**
41
-     *    $_reg_steps_array - holds initial array of reg steps
42
-     *
43
-     * @access private
44
-     * @var array $_reg_steps_array
45
-     */
46
-    private static $_reg_steps_array = array();
47
-
48
-    /**
49
-     *    $checkout - EE_Checkout object for handling the properties of the current checkout process
50
-     *
51
-     * @access public
52
-     * @var EE_Checkout $checkout
53
-     */
54
-    public $checkout;
55
-
56
-
57
-
58
-    /**
59
-     * @return EED_Module|EED_Single_Page_Checkout
60
-     */
61
-    public static function instance()
62
-    {
63
-        add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
64
-        return parent::get_instance(__CLASS__);
65
-    }
66
-
67
-
68
-
69
-    /**
70
-     * @return EE_CART
71
-     */
72
-    public function cart()
73
-    {
74
-        return $this->checkout->cart;
75
-    }
76
-
77
-
78
-
79
-    /**
80
-     * @return EE_Transaction
81
-     */
82
-    public function transaction()
83
-    {
84
-        return $this->checkout->transaction;
85
-    }
86
-
87
-
88
-
89
-    /**
90
-     *    set_hooks - for hooking into EE Core, other modules, etc
91
-     *
92
-     * @access    public
93
-     * @return    void
94
-     * @throws EE_Error
95
-     */
96
-    public static function set_hooks()
97
-    {
98
-        EED_Single_Page_Checkout::set_definitions();
99
-    }
100
-
101
-
102
-
103
-    /**
104
-     *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
105
-     *
106
-     * @access    public
107
-     * @return    void
108
-     * @throws EE_Error
109
-     */
110
-    public static function set_hooks_admin()
111
-    {
112
-        EED_Single_Page_Checkout::set_definitions();
113
-        if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
114
-            return;
115
-        }
116
-        // going to start an output buffer in case anything gets accidentally output
117
-        // that might disrupt our JSON response
118
-        ob_start();
119
-        EED_Single_Page_Checkout::load_request_handler();
120
-        EED_Single_Page_Checkout::load_reg_steps();
121
-        // set ajax hooks
122
-        add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
123
-        add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
124
-        add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
125
-        add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
126
-        add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
127
-        add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
128
-    }
129
-
130
-
131
-
132
-    /**
133
-     *    process ajax request
134
-     *
135
-     * @param string $ajax_action
136
-     * @throws EE_Error
137
-     */
138
-    public static function process_ajax_request($ajax_action)
139
-    {
140
-        EE_Registry::instance()->REQ->set('action', $ajax_action);
141
-        EED_Single_Page_Checkout::instance()->_initialize();
142
-    }
143
-
144
-
145
-
146
-    /**
147
-     *    ajax display registration step
148
-     *
149
-     * @throws EE_Error
150
-     */
151
-    public static function display_reg_step()
152
-    {
153
-        EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
154
-    }
155
-
156
-
157
-
158
-    /**
159
-     *    ajax process registration step
160
-     *
161
-     * @throws EE_Error
162
-     */
163
-    public static function process_reg_step()
164
-    {
165
-        EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
166
-    }
167
-
168
-
169
-
170
-    /**
171
-     *    ajax process registration step
172
-     *
173
-     * @throws EE_Error
174
-     */
175
-    public static function update_reg_step()
176
-    {
177
-        EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
178
-    }
179
-
180
-
181
-
182
-    /**
183
-     *   update_checkout
184
-     *
185
-     * @access public
186
-     * @return void
187
-     * @throws EE_Error
188
-     */
189
-    public static function update_checkout()
190
-    {
191
-        EED_Single_Page_Checkout::process_ajax_request('update_checkout');
192
-    }
193
-
194
-
195
-
196
-    /**
197
-     *    load_request_handler
198
-     *
199
-     * @access    public
200
-     * @return    void
201
-     */
202
-    public static function load_request_handler()
203
-    {
204
-        // load core Request_Handler class
205
-        if (EE_Registry::instance()->REQ !== null) {
206
-            EE_Registry::instance()->load_core('Request_Handler');
207
-        }
208
-    }
209
-
210
-
211
-
212
-    /**
213
-     *    set_definitions
214
-     *
215
-     * @access    public
216
-     * @return    void
217
-     * @throws EE_Error
218
-     */
219
-    public static function set_definitions()
220
-    {
221
-        if(defined('SPCO_BASE_PATH')) {
222
-            return;
223
-        }
224
-        define(
225
-            'SPCO_BASE_PATH',
226
-            rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS) . DS
227
-        );
228
-        define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css' . DS);
229
-        define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img' . DS);
230
-        define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js' . DS);
231
-        define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc' . DS);
232
-        define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps' . DS);
233
-        define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates' . DS);
234
-        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
235
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
236
-            __('%1$sWe\'re sorry, but you\'re registration time has expired.%2$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
237
-                'event_espresso'),
238
-            '<h4 class="important-notice">',
239
-            '</h4>',
240
-            '<br />',
241
-            '<p>',
242
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
243
-            '">',
244
-            '</a>',
245
-            '</p>'
246
-        );
247
-    }
248
-
249
-
250
-
251
-    /**
252
-     * load_reg_steps
253
-     * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
254
-     *
255
-     * @access    private
256
-     * @throws EE_Error
257
-     */
258
-    public static function load_reg_steps()
259
-    {
260
-        static $reg_steps_loaded = false;
261
-        if ($reg_steps_loaded) {
262
-            return;
263
-        }
264
-        // filter list of reg_steps
265
-        $reg_steps_to_load = (array)apply_filters(
266
-            'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
267
-            EED_Single_Page_Checkout::get_reg_steps()
268
-        );
269
-        // sort by key (order)
270
-        ksort($reg_steps_to_load);
271
-        // loop through folders
272
-        foreach ($reg_steps_to_load as $order => $reg_step) {
273
-            // we need a
274
-            if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
275
-                // copy over to the reg_steps_array
276
-                EED_Single_Page_Checkout::$_reg_steps_array[$order] = $reg_step;
277
-                // register custom key route for each reg step
278
-                // ie: step=>"slug" - this is the entire reason we load the reg steps array now
279
-                EE_Config::register_route(
280
-                    $reg_step['slug'],
281
-                    'EED_Single_Page_Checkout',
282
-                    'run',
283
-                    'step'
284
-                );
285
-                // add AJAX or other hooks
286
-                if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
287
-                    // setup autoloaders if necessary
288
-                    if ( ! class_exists($reg_step['class_name'])) {
289
-                        EEH_Autoloader::register_autoloaders_for_each_file_in_folder(
290
-                            $reg_step['file_path'],
291
-                            true
292
-                        );
293
-                    }
294
-                    if (is_callable($reg_step['class_name'], 'set_hooks')) {
295
-                        call_user_func(array($reg_step['class_name'], 'set_hooks'));
296
-                    }
297
-                }
298
-            }
299
-        }
300
-        $reg_steps_loaded = true;
301
-    }
302
-
303
-
304
-
305
-    /**
306
-     *    get_reg_steps
307
-     *
308
-     * @access    public
309
-     * @return    array
310
-     */
311
-    public static function get_reg_steps()
312
-    {
313
-        $reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
314
-        if (empty($reg_steps)) {
315
-            $reg_steps = array(
316
-                10  => array(
317
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
318
-                    'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
319
-                    'slug'       => 'attendee_information',
320
-                    'has_hooks'  => false,
321
-                ),
322
-                20  => array(
323
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'registration_confirmation',
324
-                    'class_name' => 'EE_SPCO_Reg_Step_Registration_Confirmation',
325
-                    'slug'       => 'registration_confirmation',
326
-                    'has_hooks'  => false,
327
-                ),
328
-                30  => array(
329
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
330
-                    'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
331
-                    'slug'       => 'payment_options',
332
-                    'has_hooks'  => true,
333
-                ),
334
-                999 => array(
335
-                    'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
336
-                    'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
337
-                    'slug'       => 'finalize_registration',
338
-                    'has_hooks'  => false,
339
-                ),
340
-            );
341
-        }
342
-        return $reg_steps;
343
-    }
344
-
345
-
346
-
347
-    /**
348
-     *    registration_checkout_for_admin
349
-     *
350
-     * @access    public
351
-     * @return    string
352
-     * @throws EE_Error
353
-     */
354
-    public static function registration_checkout_for_admin()
355
-    {
356
-        EED_Single_Page_Checkout::load_request_handler();
357
-        EE_Registry::instance()->REQ->set('step', 'attendee_information');
358
-        EE_Registry::instance()->REQ->set('action', 'display_spco_reg_step');
359
-        EE_Registry::instance()->REQ->set('process_form_submission', false);
360
-        EED_Single_Page_Checkout::instance()->_initialize();
361
-        EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
362
-        return EE_Registry::instance()->REQ->get_output();
363
-    }
364
-
365
-
366
-
367
-    /**
368
-     * process_registration_from_admin
369
-     *
370
-     * @access public
371
-     * @return \EE_Transaction
372
-     * @throws EE_Error
373
-     */
374
-    public static function process_registration_from_admin()
375
-    {
376
-        EED_Single_Page_Checkout::load_request_handler();
377
-        EE_Registry::instance()->REQ->set('step', 'attendee_information');
378
-        EE_Registry::instance()->REQ->set('action', 'process_reg_step');
379
-        EE_Registry::instance()->REQ->set('process_form_submission', true);
380
-        EED_Single_Page_Checkout::instance()->_initialize();
381
-        if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
382
-            $final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
383
-            if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
384
-                EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
385
-                if ($final_reg_step->process_reg_step()) {
386
-                    $final_reg_step->set_completed();
387
-                    EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
388
-                    return EED_Single_Page_Checkout::instance()->checkout->transaction;
389
-                }
390
-            }
391
-        }
392
-        return null;
393
-    }
394
-
395
-
396
-
397
-    /**
398
-     *    run
399
-     *
400
-     * @access    public
401
-     * @param WP_Query $WP_Query
402
-     * @return    void
403
-     * @throws EE_Error
404
-     */
405
-    public function run($WP_Query)
406
-    {
407
-        if (
408
-            $WP_Query instanceof WP_Query
409
-            && $WP_Query->is_main_query()
410
-            && apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
411
-            && $this->_is_reg_checkout()
412
-        ) {
413
-            $this->_initialize();
414
-        }
415
-    }
416
-
417
-
418
-
419
-    /**
420
-     * determines whether current url matches reg page url
421
-     *
422
-     * @return bool
423
-     */
424
-    protected function _is_reg_checkout()
425
-    {
426
-        // get current permalink for reg page without any extra query args
427
-        $reg_page_url = \get_permalink(EE_Config::instance()->core->reg_page_id);
428
-        // get request URI for current request, but without the scheme or host
429
-        $current_request_uri = \EEH_URL::filter_input_server_url('REQUEST_URI');
430
-        $current_request_uri = html_entity_decode($current_request_uri);
431
-        // get array of query args from the current request URI
432
-        $query_args = \EEH_URL::get_query_string($current_request_uri);
433
-        // grab page id if it is set
434
-        $page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
435
-        // and remove the page id from the query args (we will re-add it later)
436
-        unset($query_args['page_id']);
437
-        // now strip all query args from current request URI
438
-        $current_request_uri = remove_query_arg(array_keys($query_args), $current_request_uri);
439
-        // and re-add the page id if it was set
440
-        if ($page_id) {
441
-            $current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
442
-        }
443
-        // remove slashes and ?
444
-        $current_request_uri = trim($current_request_uri, '?/');
445
-        // is current request URI part of the known full reg page URL ?
446
-        return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
447
-    }
448
-
449
-
450
-
451
-    /**
452
-     * @param WP_Query $wp_query
453
-     * @return    void
454
-     * @throws EE_Error
455
-     */
456
-    public static function init($wp_query)
457
-    {
458
-        EED_Single_Page_Checkout::instance()->run($wp_query);
459
-    }
460
-
461
-
462
-
463
-    /**
464
-     *    _initialize - initial module setup
465
-     *
466
-     * @access    private
467
-     * @throws EE_Error
468
-     * @return    void
469
-     */
470
-    private function _initialize()
471
-    {
472
-        // ensure SPCO doesn't run twice
473
-        if (EED_Single_Page_Checkout::$_initialized) {
474
-            return;
475
-        }
476
-        try {
477
-            EED_Single_Page_Checkout::load_reg_steps();
478
-            $this->_verify_session();
479
-            // setup the EE_Checkout object
480
-            $this->checkout = $this->_initialize_checkout();
481
-            // filter checkout
482
-            $this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
483
-            // get the $_GET
484
-            $this->_get_request_vars();
485
-            if ($this->_block_bots()) {
486
-                return;
487
-            }
488
-            // filter continue_reg
489
-            $this->checkout->continue_reg = apply_filters(
490
-                'FHEE__EED_Single_Page_Checkout__init___continue_reg',
491
-                true,
492
-                $this->checkout
493
-            );
494
-            // load the reg steps array
495
-            if ( ! $this->_load_and_instantiate_reg_steps()) {
496
-                EED_Single_Page_Checkout::$_initialized = true;
497
-                return;
498
-            }
499
-            // set the current step
500
-            $this->checkout->set_current_step($this->checkout->step);
501
-            // and the next step
502
-            $this->checkout->set_next_step();
503
-            // verify that everything has been setup correctly
504
-            if ( ! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
505
-                EED_Single_Page_Checkout::$_initialized = true;
506
-                return;
507
-            }
508
-            // lock the transaction
509
-            $this->checkout->transaction->lock();
510
-            // make sure all of our cached objects are added to their respective model entity mappers
511
-            $this->checkout->refresh_all_entities();
512
-            // set amount owing
513
-            $this->checkout->amount_owing = $this->checkout->transaction->remaining();
514
-            // initialize each reg step, which gives them the chance to potentially alter the process
515
-            $this->_initialize_reg_steps();
516
-            // DEBUG LOG
517
-            //$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
518
-            // get reg form
519
-            if( ! $this->_check_form_submission()) {
520
-                EED_Single_Page_Checkout::$_initialized = true;
521
-                return;
522
-            }
523
-            // checkout the action!!!
524
-            $this->_process_form_action();
525
-            // add some style and make it dance
526
-            $this->add_styles_and_scripts();
527
-            // kk... SPCO has successfully run
528
-            EED_Single_Page_Checkout::$_initialized = true;
529
-            // set no cache headers and constants
530
-            EE_System::do_not_cache();
531
-            // add anchor
532
-            add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
533
-            // remove transaction lock
534
-            add_action('shutdown', array($this, 'unlock_transaction'), 1);
535
-        } catch (Exception $e) {
536
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
537
-        }
538
-    }
539
-
540
-
541
-
542
-    /**
543
-     *    _verify_session
544
-     * checks that the session is valid and not expired
545
-     *
546
-     * @access    private
547
-     * @throws EE_Error
548
-     */
549
-    private function _verify_session()
550
-    {
551
-        if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
552
-            throw new EE_Error(__('The EE_Session class could not be loaded.', 'event_espresso'));
553
-        }
554
-        $clear_session_requested = filter_var(
555
-            EE_Registry::instance()->REQ->get('clear_session', false),
556
-            FILTER_VALIDATE_BOOLEAN
557
-        );
558
-        // is session still valid ?
559
-        if ($clear_session_requested
560
-            || ( EE_Registry::instance()->SSN->expired()
561
-              && EE_Registry::instance()->REQ->get('e_reg_url_link', '') === ''
562
-            )
563
-        ) {
564
-            $this->checkout = new EE_Checkout();
565
-            EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
566
-            // EE_Registry::instance()->SSN->reset_cart();
567
-            // EE_Registry::instance()->SSN->reset_checkout();
568
-            // EE_Registry::instance()->SSN->reset_transaction();
569
-            if (! $clear_session_requested) {
570
-                EE_Error::add_attention(
571
-                    EE_Registry::$i18n_js_strings['registration_expiration_notice'],
572
-                    __FILE__, __FUNCTION__, __LINE__
573
-                );
574
-            }
575
-            // EE_Registry::instance()->SSN->reset_expired();
576
-        }
577
-    }
578
-
579
-
580
-
581
-    /**
582
-     *    _initialize_checkout
583
-     * loads and instantiates EE_Checkout
584
-     *
585
-     * @access    private
586
-     * @throws EE_Error
587
-     * @return EE_Checkout
588
-     */
589
-    private function _initialize_checkout()
590
-    {
591
-        // look in session for existing checkout
592
-        /** @type EE_Checkout $checkout */
593
-        $checkout = EE_Registry::instance()->SSN->checkout();
594
-        // verify
595
-        if ( ! $checkout instanceof EE_Checkout) {
596
-            // instantiate EE_Checkout object for handling the properties of the current checkout process
597
-            $checkout = EE_Registry::instance()->load_file(
598
-                SPCO_INC_PATH,
599
-                'EE_Checkout',
600
-                'class', array(),
601
-                false
602
-            );
603
-        } else {
604
-            if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
605
-                $this->unlock_transaction();
606
-                wp_safe_redirect($checkout->redirect_url);
607
-                exit();
608
-            }
609
-        }
610
-        $checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
611
-        // verify again
612
-        if ( ! $checkout instanceof EE_Checkout) {
613
-            throw new EE_Error(__('The EE_Checkout class could not be loaded.', 'event_espresso'));
614
-        }
615
-        // reset anything that needs a clean slate for each request
616
-        $checkout->reset_for_current_request();
617
-        return $checkout;
618
-    }
619
-
620
-
621
-
622
-    /**
623
-     *    _get_request_vars
624
-     *
625
-     * @access    private
626
-     * @return    void
627
-     * @throws EE_Error
628
-     */
629
-    private function _get_request_vars()
630
-    {
631
-        // load classes
632
-        EED_Single_Page_Checkout::load_request_handler();
633
-        //make sure this request is marked as belonging to EE
634
-        EE_Registry::instance()->REQ->set_espresso_page(true);
635
-        // which step is being requested ?
636
-        $this->checkout->step = EE_Registry::instance()->REQ->get('step', $this->_get_first_step());
637
-        // which step is being edited ?
638
-        $this->checkout->edit_step = EE_Registry::instance()->REQ->get('edit_step', '');
639
-        // and what we're doing on the current step
640
-        $this->checkout->action = EE_Registry::instance()->REQ->get('action', 'display_spco_reg_step');
641
-        // timestamp
642
-        $this->checkout->uts = EE_Registry::instance()->REQ->get('uts', 0);
643
-        // returning to edit ?
644
-        $this->checkout->reg_url_link = EE_Registry::instance()->REQ->get('e_reg_url_link', '');
645
-        // add reg url link to registration query params
646
-        if ($this->checkout->reg_url_link && strpos($this->checkout->reg_url_link, '1-') !== 0) {
647
-            $this->checkout->reg_cache_where_params[0]['REG_url_link'] = $this->checkout->reg_url_link;
648
-        }
649
-        // or some other kind of revisit ?
650
-        $this->checkout->revisit = filter_var(
651
-            EE_Registry::instance()->REQ->get('revisit', false),
652
-            FILTER_VALIDATE_BOOLEAN
653
-        );
654
-        // and whether or not to generate a reg form for this request
655
-        $this->checkout->generate_reg_form = filter_var(
656
-            EE_Registry::instance()->REQ->get('generate_reg_form', true),
657
-            FILTER_VALIDATE_BOOLEAN
658
-        );
659
-        // and whether or not to process a reg form submission for this request
660
-        $this->checkout->process_form_submission = filter_var(
661
-            EE_Registry::instance()->REQ->get(
662
-                'process_form_submission',
663
-                $this->checkout->action === 'process_reg_step'
664
-            ),
665
-            FILTER_VALIDATE_BOOLEAN
666
-        );
667
-        $this->checkout->process_form_submission = filter_var(
668
-            $this->checkout->action !== 'display_spco_reg_step'
669
-                ? $this->checkout->process_form_submission
670
-                : false,
671
-            FILTER_VALIDATE_BOOLEAN
672
-        );
673
-        // $this->_display_request_vars();
674
-    }
675
-
676
-
677
-
678
-    /**
679
-     *  _display_request_vars
680
-     *
681
-     * @access    protected
682
-     * @return    void
683
-     */
684
-    protected function _display_request_vars()
685
-    {
686
-        if ( ! WP_DEBUG) {
687
-            return;
688
-        }
689
-        EEH_Debug_Tools::printr($_REQUEST, '$_REQUEST', __FILE__, __LINE__);
690
-        EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
691
-        EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
692
-        EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
693
-        EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
694
-        EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
695
-        EEH_Debug_Tools::printr($this->checkout->generate_reg_form, '$this->checkout->generate_reg_form', __FILE__, __LINE__);
696
-        EEH_Debug_Tools::printr($this->checkout->process_form_submission, '$this->checkout->process_form_submission', __FILE__, __LINE__);
697
-    }
698
-
699
-
700
-
701
-    /**
702
-     * _block_bots
703
-     * checks that the incoming request has either of the following set:
704
-     *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
705
-     *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
706
-     * so if you're not coming from the Ticket Selector nor returning for a valid IP...
707
-     * then where you coming from man?
708
-     *
709
-     * @return boolean
710
-     */
711
-    private function _block_bots()
712
-    {
713
-        $invalid_checkout_access = EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
714
-        if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
715
-            return true;
716
-        }
717
-        return false;
718
-    }
719
-
720
-
721
-
722
-    /**
723
-     *    _get_first_step
724
-     *  gets slug for first step in $_reg_steps_array
725
-     *
726
-     * @access    private
727
-     * @throws EE_Error
728
-     * @return    string
729
-     */
730
-    private function _get_first_step()
731
-    {
732
-        $first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
733
-        return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
734
-    }
735
-
736
-
737
-
738
-    /**
739
-     *    _load_and_instantiate_reg_steps
740
-     *  instantiates each reg step based on the loaded reg_steps array
741
-     *
742
-     * @access    private
743
-     * @throws EE_Error
744
-     * @return    bool
745
-     */
746
-    private function _load_and_instantiate_reg_steps()
747
-    {
748
-        do_action('AHEE__Single_Page_Checkout___load_and_instantiate_reg_steps__start', $this->checkout);
749
-        // have reg_steps already been instantiated ?
750
-        if (
751
-            empty($this->checkout->reg_steps)
752
-            || apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
753
-        ) {
754
-            // if not, then loop through raw reg steps array
755
-            foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
756
-                if ( ! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
757
-                    return false;
758
-                }
759
-            }
760
-            EE_Registry::instance()->CFG->registration->skip_reg_confirmation = true;
761
-            EE_Registry::instance()->CFG->registration->reg_confirmation_last = true;
762
-            // skip the registration_confirmation page ?
763
-            if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
764
-                // just remove it from the reg steps array
765
-                $this->checkout->remove_reg_step('registration_confirmation', false);
766
-            } else if (
767
-                isset($this->checkout->reg_steps['registration_confirmation'])
768
-                && EE_Registry::instance()->CFG->registration->reg_confirmation_last
769
-            ) {
770
-                // set the order to something big like 100
771
-                $this->checkout->set_reg_step_order('registration_confirmation', 100);
772
-            }
773
-            // filter the array for good luck
774
-            $this->checkout->reg_steps = apply_filters(
775
-                'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
776
-                $this->checkout->reg_steps
777
-            );
778
-            // finally re-sort based on the reg step class order properties
779
-            $this->checkout->sort_reg_steps();
780
-        } else {
781
-            foreach ($this->checkout->reg_steps as $reg_step) {
782
-                // set all current step stati to FALSE
783
-                $reg_step->set_is_current_step(false);
784
-            }
785
-        }
786
-        if (empty($this->checkout->reg_steps)) {
787
-            EE_Error::add_error(
788
-                __('No Reg Steps were loaded..', 'event_espresso'),
789
-                __FILE__, __FUNCTION__, __LINE__
790
-            );
791
-            return false;
792
-        }
793
-        // make reg step details available to JS
794
-        $this->checkout->set_reg_step_JSON_info();
795
-        return true;
796
-    }
797
-
798
-
799
-
800
-    /**
801
-     *     _load_and_instantiate_reg_step
802
-     *
803
-     * @access    private
804
-     * @param array $reg_step
805
-     * @param int   $order
806
-     * @return bool
807
-     */
808
-    private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
809
-    {
810
-        // we need a file_path, class_name, and slug to add a reg step
811
-        if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
812
-            // if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
813
-            if (
814
-                $this->checkout->reg_url_link
815
-                && $this->checkout->step !== $reg_step['slug']
816
-                && $reg_step['slug'] !== 'finalize_registration'
817
-                // normally at this point we would NOT load the reg step, but this filter can change that
818
-                && apply_filters(
819
-                    'FHEE__Single_Page_Checkout___load_and_instantiate_reg_step__bypass_reg_step',
820
-                    true,
821
-                    $reg_step,
822
-                    $this->checkout
823
-                )
824
-            ) {
825
-                return true;
826
-            }
827
-            // instantiate step class using file path and class name
828
-            $reg_step_obj = EE_Registry::instance()->load_file(
829
-                $reg_step['file_path'],
830
-                $reg_step['class_name'],
831
-                'class',
832
-                $this->checkout,
833
-                false
834
-            );
835
-            // did we gets the goods ?
836
-            if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
837
-                // set reg step order based on config
838
-                $reg_step_obj->set_order($order);
839
-                // add instantiated reg step object to the master reg steps array
840
-                $this->checkout->add_reg_step($reg_step_obj);
841
-            } else {
842
-                EE_Error::add_error(
843
-                    __('The current step could not be set.', 'event_espresso'),
844
-                    __FILE__, __FUNCTION__, __LINE__
845
-                );
846
-                return false;
847
-            }
848
-        } else {
849
-            if (WP_DEBUG) {
850
-                EE_Error::add_error(
851
-                    sprintf(
852
-                        __(
853
-                            'A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s',
854
-                            'event_espresso'
855
-                        ),
856
-                        isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
857
-                        isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
858
-                        isset($reg_step['slug']) ? $reg_step['slug'] : '',
859
-                        '<ul>',
860
-                        '<li>',
861
-                        '</li>',
862
-                        '</ul>'
863
-                    ),
864
-                    __FILE__, __FUNCTION__, __LINE__
865
-                );
866
-            }
867
-            return false;
868
-        }
869
-        return true;
870
-    }
871
-
872
-
873
-    /**
874
-     * _verify_transaction_and_get_registrations
875
-     *
876
-     * @access private
877
-     * @return bool
878
-     * @throws InvalidDataTypeException
879
-     * @throws InvalidEntityException
880
-     * @throws EE_Error
881
-     */
882
-    private function _verify_transaction_and_get_registrations()
883
-    {
884
-        // was there already a valid transaction in the checkout from the session ?
885
-        if ( ! $this->checkout->transaction instanceof EE_Transaction) {
886
-            // get transaction from db or session
887
-            $this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
888
-                ? $this->_get_transaction_and_cart_for_previous_visit()
889
-                : $this->_get_cart_for_current_session_and_setup_new_transaction();
890
-            if ( ! $this->checkout->transaction instanceof EE_Transaction) {
891
-                EE_Error::add_error(
892
-                    __('Your Registration and Transaction information could not be retrieved from the db.',
893
-                        'event_espresso'),
894
-                    __FILE__, __FUNCTION__, __LINE__
895
-                );
896
-                $this->checkout->transaction = EE_Transaction::new_instance();
897
-                // add some style and make it dance
898
-                $this->add_styles_and_scripts();
899
-                EED_Single_Page_Checkout::$_initialized = true;
900
-                return false;
901
-            }
902
-            // and the registrations for the transaction
903
-            $this->_get_registrations($this->checkout->transaction);
904
-        }
905
-        return true;
906
-    }
907
-
908
-
909
-
910
-    /**
911
-     * _get_transaction_and_cart_for_previous_visit
912
-     *
913
-     * @access private
914
-     * @return mixed EE_Transaction|NULL
915
-     */
916
-    private function _get_transaction_and_cart_for_previous_visit()
917
-    {
918
-        /** @var $TXN_model EEM_Transaction */
919
-        $TXN_model = EE_Registry::instance()->load_model('Transaction');
920
-        // because the reg_url_link is present in the request,
921
-        // this is a return visit to SPCO, so we'll get the transaction data from the db
922
-        $transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
923
-        // verify transaction
924
-        if ($transaction instanceof EE_Transaction) {
925
-            // and get the cart that was used for that transaction
926
-            $this->checkout->cart = $this->_get_cart_for_transaction($transaction);
927
-            return $transaction;
928
-        }
929
-        EE_Error::add_error(
930
-            __('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'),
931
-            __FILE__, __FUNCTION__, __LINE__
932
-        );
933
-        return null;
934
-
935
-    }
936
-
937
-
938
-
939
-    /**
940
-     * _get_cart_for_transaction
941
-     *
942
-     * @access private
943
-     * @param EE_Transaction $transaction
944
-     * @return EE_Cart
945
-     */
946
-    private function _get_cart_for_transaction($transaction)
947
-    {
948
-        return $this->checkout->get_cart_for_transaction($transaction);
949
-    }
950
-
951
-
952
-
953
-    /**
954
-     * get_cart_for_transaction
955
-     *
956
-     * @access public
957
-     * @param EE_Transaction $transaction
958
-     * @return EE_Cart
959
-     */
960
-    public function get_cart_for_transaction(EE_Transaction $transaction)
961
-    {
962
-        return $this->checkout->get_cart_for_transaction($transaction);
963
-    }
964
-
965
-
966
-
967
-    /**
968
-     * _get_transaction_and_cart_for_current_session
969
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
970
-     *
971
-     * @access private
972
-     * @return EE_Transaction
973
-     * @throws EE_Error
974
-     */
975
-    private function _get_cart_for_current_session_and_setup_new_transaction()
976
-    {
977
-        //  if there's no transaction, then this is the FIRST visit to SPCO
978
-        // so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
979
-        $this->checkout->cart = $this->_get_cart_for_transaction(null);
980
-        // and then create a new transaction
981
-        $transaction = $this->_initialize_transaction();
982
-        // verify transaction
983
-        if ($transaction instanceof EE_Transaction) {
984
-            // save it so that we have an ID for other objects to use
985
-            $transaction->save();
986
-            // and save TXN data to the cart
987
-            $this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
988
-        } else {
989
-            EE_Error::add_error(
990
-                __('A Valid Transaction could not be initialized.', 'event_espresso'),
991
-                __FILE__, __FUNCTION__, __LINE__
992
-            );
993
-        }
994
-        return $transaction;
995
-    }
996
-
997
-
998
-
999
-    /**
1000
-     *    generates a new EE_Transaction object and adds it to the $_transaction property.
1001
-     *
1002
-     * @access private
1003
-     * @return mixed EE_Transaction|NULL
1004
-     */
1005
-    private function _initialize_transaction()
1006
-    {
1007
-        try {
1008
-            // ensure cart totals have been calculated
1009
-            $this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
1010
-            // grab the cart grand total
1011
-            $cart_total = $this->checkout->cart->get_cart_grand_total();
1012
-            // create new TXN
1013
-            $transaction = EE_Transaction::new_instance(
1014
-                array(
1015
-                    'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
1016
-                    'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
1017
-                    'TXN_paid'      => 0,
1018
-                    'STS_ID'        => EEM_Transaction::failed_status_code,
1019
-                )
1020
-            );
1021
-            // save it so that we have an ID for other objects to use
1022
-            $transaction->save();
1023
-            // set cron job for following up on TXNs after their session has expired
1024
-            EE_Cron_Tasks::schedule_expired_transaction_check(
1025
-                EE_Registry::instance()->SSN->expiration() + 1,
1026
-                $transaction->ID()
1027
-            );
1028
-            return $transaction;
1029
-        } catch (Exception $e) {
1030
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1031
-        }
1032
-        return null;
1033
-    }
1034
-
1035
-
1036
-    /**
1037
-     * _get_registrations
1038
-     *
1039
-     * @access private
1040
-     * @param EE_Transaction $transaction
1041
-     * @return void
1042
-     * @throws InvalidDataTypeException
1043
-     * @throws InvalidEntityException
1044
-     * @throws EE_Error
1045
-     */
1046
-    private function _get_registrations(EE_Transaction $transaction)
1047
-    {
1048
-        // first step: grab the registrants  { : o
1049
-        $registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
1050
-        $this->checkout->total_ticket_count = count($registrations);
1051
-        // verify registrations have been set
1052
-        if (empty($registrations)) {
1053
-            // if no cached registrations, then check the db
1054
-            $registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
1055
-            // still nothing ? well as long as this isn't a revisit
1056
-            if (empty($registrations) && ! $this->checkout->revisit) {
1057
-                // generate new registrations from scratch
1058
-                $registrations = $this->_initialize_registrations($transaction);
1059
-            }
1060
-        }
1061
-        // sort by their original registration order
1062
-        usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
1063
-        // then loop thru the array
1064
-        foreach ($registrations as $registration) {
1065
-            // verify each registration
1066
-            if ($registration instanceof EE_Registration) {
1067
-                // we display all attendee info for the primary registrant
1068
-                if ($this->checkout->reg_url_link === $registration->reg_url_link()
1069
-                    && $registration->is_primary_registrant()
1070
-                ) {
1071
-                    $this->checkout->primary_revisit = true;
1072
-                    break;
1073
-                }
1074
-                if ($this->checkout->revisit && $this->checkout->reg_url_link !== $registration->reg_url_link()) {
1075
-                    // but hide info if it doesn't belong to you
1076
-                    $transaction->clear_cache('Registration', $registration->ID());
1077
-                    $this->checkout->total_ticket_count--;
1078
-                }
1079
-                $this->checkout->set_reg_status_updated($registration->ID(), false);
1080
-            }
1081
-        }
1082
-    }
1083
-
1084
-
1085
-    /**
1086
-     *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1087
-     *
1088
-     * @access private
1089
-     * @param EE_Transaction $transaction
1090
-     * @return    array
1091
-     * @throws InvalidDataTypeException
1092
-     * @throws InvalidEntityException
1093
-     * @throws EE_Error
1094
-     */
1095
-    private function _initialize_registrations(EE_Transaction $transaction)
1096
-    {
1097
-        $att_nmbr = 0;
1098
-        $registrations = array();
1099
-        if ($transaction instanceof EE_Transaction) {
1100
-            /** @type EE_Registration_Processor $registration_processor */
1101
-            $registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1102
-            $this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1103
-            // now let's add the cart items to the $transaction
1104
-            foreach ($this->checkout->cart->get_tickets() as $line_item) {
1105
-                //do the following for each ticket of this type they selected
1106
-                for ($x = 1; $x <= $line_item->quantity(); $x++) {
1107
-                    $att_nmbr++;
1108
-                    /** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1109
-                    $CreateRegistrationCommand = EE_Registry::instance()->create(
1110
-                        'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1111
-                        array(
1112
-                            $transaction,
1113
-                            $line_item,
1114
-                            $att_nmbr,
1115
-                            $this->checkout->total_ticket_count,
1116
-                        )
1117
-                    );
1118
-                    // override capabilities for frontend registrations
1119
-                    if ( ! is_admin()) {
1120
-                        $CreateRegistrationCommand->setCapCheck(
1121
-                            new PublicCapabilities('', 'create_new_registration')
1122
-                        );
1123
-                    }
1124
-                    $registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1125
-                    if ( ! $registration instanceof EE_Registration) {
1126
-                        throw new InvalidEntityException($registration, 'EE_Registration');
1127
-                    }
1128
-                    $registrations[ $registration->ID() ] = $registration;
1129
-                }
1130
-            }
1131
-            $registration_processor->fix_reg_final_price_rounding_issue($transaction);
1132
-        }
1133
-        return $registrations;
1134
-    }
1135
-
1136
-
1137
-
1138
-    /**
1139
-     * sorts registrations by REG_count
1140
-     *
1141
-     * @access public
1142
-     * @param EE_Registration $reg_A
1143
-     * @param EE_Registration $reg_B
1144
-     * @return int
1145
-     */
1146
-    public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1147
-    {
1148
-        // this shouldn't ever happen within the same TXN, but oh well
1149
-        if ($reg_A->count() === $reg_B->count()) {
1150
-            return 0;
1151
-        }
1152
-        return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1153
-    }
1154
-
1155
-
1156
-
1157
-    /**
1158
-     *    _final_verifications
1159
-     * just makes sure that everything is set up correctly before proceeding
1160
-     *
1161
-     * @access    private
1162
-     * @return    bool
1163
-     * @throws EE_Error
1164
-     */
1165
-    private function _final_verifications()
1166
-    {
1167
-        // filter checkout
1168
-        $this->checkout = apply_filters(
1169
-            'FHEE__EED_Single_Page_Checkout___final_verifications__checkout',
1170
-            $this->checkout
1171
-        );
1172
-        //verify that current step is still set correctly
1173
-        if ( ! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1174
-            EE_Error::add_error(
1175
-                __('We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.', 'event_espresso'),
1176
-                __FILE__,
1177
-                __FUNCTION__,
1178
-                __LINE__
1179
-            );
1180
-            return false;
1181
-        }
1182
-        // if returning to SPCO, then verify that primary registrant is set
1183
-        if ( ! empty($this->checkout->reg_url_link)) {
1184
-            $valid_registrant = $this->checkout->transaction->primary_registration();
1185
-            if ( ! $valid_registrant instanceof EE_Registration) {
1186
-                EE_Error::add_error(
1187
-                    __('We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.', 'event_espresso'),
1188
-                    __FILE__,
1189
-                    __FUNCTION__,
1190
-                    __LINE__
1191
-                );
1192
-                return false;
1193
-            }
1194
-            $valid_registrant = null;
1195
-            foreach (
1196
-                $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration
1197
-            ) {
1198
-                if (
1199
-                    $registration instanceof EE_Registration
1200
-                    && $registration->reg_url_link() === $this->checkout->reg_url_link
1201
-                ) {
1202
-                    $valid_registrant = $registration;
1203
-                }
1204
-            }
1205
-            if ( ! $valid_registrant instanceof EE_Registration) {
1206
-                // hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1207
-                if (EED_Single_Page_Checkout::$_checkout_verified) {
1208
-                    // clear the session, mark the checkout as unverified, and try again
1209
-                    EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
1210
-                    EED_Single_Page_Checkout::$_initialized = false;
1211
-                    EED_Single_Page_Checkout::$_checkout_verified = false;
1212
-                    $this->_initialize();
1213
-                    EE_Error::reset_notices();
1214
-                    return false;
1215
-                }
1216
-                EE_Error::add_error(
1217
-                    __(
1218
-                        'We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.',
1219
-                        'event_espresso'
1220
-                    ),
1221
-                    __FILE__,
1222
-                    __FUNCTION__,
1223
-                    __LINE__
1224
-                );
1225
-                return false;
1226
-            }
1227
-        }
1228
-        // now that things have been kinda sufficiently verified,
1229
-        // let's add the checkout to the session so that it's available to other systems
1230
-        EE_Registry::instance()->SSN->set_checkout($this->checkout);
1231
-        return true;
1232
-    }
1233
-
1234
-
1235
-
1236
-    /**
1237
-     *    _initialize_reg_steps
1238
-     * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1239
-     * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1240
-     *
1241
-     * @access    private
1242
-     * @param bool $reinitializing
1243
-     * @throws EE_Error
1244
-     */
1245
-    private function _initialize_reg_steps($reinitializing = false)
1246
-    {
1247
-        $this->checkout->set_reg_step_initiated($this->checkout->current_step);
1248
-        // loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1249
-        foreach ($this->checkout->reg_steps as $reg_step) {
1250
-            if ( ! $reg_step->initialize_reg_step()) {
1251
-                // if not initialized then maybe this step is being removed...
1252
-                if ( ! $reinitializing && $reg_step->is_current_step()) {
1253
-                    // if it was the current step, then we need to start over here
1254
-                    $this->_initialize_reg_steps(true);
1255
-                    return;
1256
-                }
1257
-                continue;
1258
-            }
1259
-            // add css and JS for current step
1260
-            $reg_step->enqueue_styles_and_scripts();
1261
-            // i18n
1262
-            $reg_step->translate_js_strings();
1263
-            if ($reg_step->is_current_step()) {
1264
-                // the text that appears on the reg step form submit button
1265
-                $reg_step->set_submit_button_text();
1266
-            }
1267
-        }
1268
-        // dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1269
-        do_action(
1270
-            "AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}",
1271
-            $this->checkout->current_step
1272
-        );
1273
-    }
1274
-
1275
-
1276
-
1277
-    /**
1278
-     * _check_form_submission
1279
-     *
1280
-     * @access private
1281
-     * @return boolean
1282
-     */
1283
-    private function _check_form_submission()
1284
-    {
1285
-        //does this request require the reg form to be generated ?
1286
-        if ($this->checkout->generate_reg_form) {
1287
-            // ever heard that song by Blue Rodeo ?
1288
-            try {
1289
-                $this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1290
-                // if not displaying a form, then check for form submission
1291
-                if (
1292
-                    $this->checkout->process_form_submission
1293
-                    && $this->checkout->current_step->reg_form->was_submitted()
1294
-                ) {
1295
-                    // clear out any old data in case this step is being run again
1296
-                    $this->checkout->current_step->set_valid_data(array());
1297
-                    // capture submitted form data
1298
-                    $this->checkout->current_step->reg_form->receive_form_submission(
1299
-                        apply_filters(
1300
-                            'FHEE__Single_Page_Checkout___check_form_submission__request_params',
1301
-                            EE_Registry::instance()->REQ->params(),
1302
-                            $this->checkout
1303
-                        )
1304
-                    );
1305
-                    // validate submitted form data
1306
-                    if ( ! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1307
-                        // thou shall not pass !!!
1308
-                        $this->checkout->continue_reg = false;
1309
-                        // any form validation errors?
1310
-                        if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1311
-                            $submission_error_messages = array();
1312
-                            // bad, bad, bad registrant
1313
-                            foreach (
1314
-                                $this->checkout->current_step->reg_form->get_validation_errors_accumulated()
1315
-                                as $validation_error
1316
-                            ) {
1317
-                                if ($validation_error instanceof EE_Validation_Error) {
1318
-                                    $submission_error_messages[] = sprintf(
1319
-                                        __('%s : %s', 'event_espresso'),
1320
-                                        $validation_error->get_form_section()->html_label_text(),
1321
-                                        $validation_error->getMessage()
1322
-                                    );
1323
-                                }
1324
-                            }
1325
-                            EE_Error::add_error(
1326
-                                implode('<br />', $submission_error_messages),
1327
-                                __FILE__, __FUNCTION__, __LINE__
1328
-                            );
1329
-                        }
1330
-                        // well not really... what will happen is
1331
-                        // we'll just get redirected back to redo the current step
1332
-                        $this->go_to_next_step();
1333
-                        return false;
1334
-                    }
1335
-                }
1336
-            } catch (EE_Error $e) {
1337
-                $e->get_error();
1338
-            }
1339
-        }
1340
-        return true;
1341
-    }
1342
-
1343
-
1344
-
1345
-    /**
1346
-     * _process_action
1347
-     *
1348
-     * @access private
1349
-     * @return void
1350
-     * @throws EE_Error
1351
-     */
1352
-    private function _process_form_action()
1353
-    {
1354
-        // what cha wanna do?
1355
-        switch ($this->checkout->action) {
1356
-            // AJAX next step reg form
1357
-            case 'display_spco_reg_step' :
1358
-                $this->checkout->redirect = false;
1359
-                if (EE_Registry::instance()->REQ->ajax) {
1360
-                    $this->checkout->json_response->set_reg_step_html(
1361
-                        $this->checkout->current_step->display_reg_form()
1362
-                    );
1363
-                }
1364
-                break;
1365
-            default :
1366
-                // meh... do one of those other steps first
1367
-                if (
1368
-                    ! empty($this->checkout->action)
1369
-                    && is_callable(array($this->checkout->current_step, $this->checkout->action))
1370
-                ) {
1371
-                    // dynamically creates hook point like:
1372
-                    //   AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1373
-                    do_action(
1374
-                        "AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1375
-                        $this->checkout->current_step
1376
-                    );
1377
-                    // call action on current step
1378
-                    if (call_user_func(array($this->checkout->current_step, $this->checkout->action))) {
1379
-                        // good registrant, you get to proceed
1380
-                        if (
1381
-                            $this->checkout->current_step->success_message() !== ''
1382
-                            && apply_filters(
1383
-                                'FHEE__Single_Page_Checkout___process_form_action__display_success',
1384
-                                false
1385
-                            )
1386
-                        ) {
1387
-                            EE_Error::add_success(
1388
-                                $this->checkout->current_step->success_message()
1389
-                                . '<br />' . $this->checkout->next_step->_instructions()
1390
-                            );
1391
-                        }
1392
-                        // pack it up, pack it in...
1393
-                        $this->_setup_redirect();
1394
-                    }
1395
-                    // dynamically creates hook point like:
1396
-                    //  AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1397
-                    do_action(
1398
-                        "AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1399
-                        $this->checkout->current_step
1400
-                    );
1401
-                } else {
1402
-                    EE_Error::add_error(
1403
-                        sprintf(
1404
-                            __(
1405
-                                'The requested form action "%s" does not exist for the current "%s" registration step.',
1406
-                                'event_espresso'
1407
-                            ),
1408
-                            $this->checkout->action,
1409
-                            $this->checkout->current_step->name()
1410
-                        ),
1411
-                        __FILE__,
1412
-                        __FUNCTION__,
1413
-                        __LINE__
1414
-                    );
1415
-                }
1416
-            // end default
1417
-        }
1418
-        // store our progress so far
1419
-        $this->checkout->stash_transaction_and_checkout();
1420
-        // advance to the next step! If you pass GO, collect $200
1421
-        $this->go_to_next_step();
1422
-    }
1423
-
1424
-
1425
-
1426
-    /**
1427
-     *        add_styles_and_scripts
1428
-     *
1429
-     * @access        public
1430
-     * @return        void
1431
-     */
1432
-    public function add_styles_and_scripts()
1433
-    {
1434
-        // i18n
1435
-        $this->translate_js_strings();
1436
-        if ($this->checkout->admin_request) {
1437
-            add_action('admin_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1438
-        } else {
1439
-            add_action('wp_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1440
-        }
1441
-    }
1442
-
1443
-
1444
-
1445
-    /**
1446
-     *        translate_js_strings
1447
-     *
1448
-     * @access        public
1449
-     * @return        void
1450
-     */
1451
-    public function translate_js_strings()
1452
-    {
1453
-        EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1454
-        EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1455
-        EE_Registry::$i18n_js_strings['server_error'] = __(
1456
-            'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
1457
-            'event_espresso'
1458
-        );
1459
-        EE_Registry::$i18n_js_strings['invalid_json_response'] = __(
1460
-            'An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.',
1461
-            'event_espresso'
1462
-        );
1463
-        EE_Registry::$i18n_js_strings['validation_error'] = __(
1464
-            'There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.',
1465
-            'event_espresso'
1466
-        );
1467
-        EE_Registry::$i18n_js_strings['invalid_payment_method'] = __(
1468
-            'There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.',
1469
-            'event_espresso'
1470
-        );
1471
-        EE_Registry::$i18n_js_strings['reg_step_error'] = __(
1472
-            'This registration step could not be completed. Please refresh the page and try again.',
1473
-            'event_espresso'
1474
-        );
1475
-        EE_Registry::$i18n_js_strings['invalid_coupon'] = __(
1476
-            'We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.',
1477
-            'event_espresso'
1478
-        );
1479
-        EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1480
-            __(
1481
-                'Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.',
1482
-                'event_espresso'
1483
-            ),
1484
-            '<br/>',
1485
-            '<br/>'
1486
-        );
1487
-        EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1488
-        EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1489
-        EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1490
-        EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1491
-        EE_Registry::$i18n_js_strings['timer_years'] = __('years', 'event_espresso');
1492
-        EE_Registry::$i18n_js_strings['timer_months'] = __('months', 'event_espresso');
1493
-        EE_Registry::$i18n_js_strings['timer_weeks'] = __('weeks', 'event_espresso');
1494
-        EE_Registry::$i18n_js_strings['timer_days'] = __('days', 'event_espresso');
1495
-        EE_Registry::$i18n_js_strings['timer_hours'] = __('hours', 'event_espresso');
1496
-        EE_Registry::$i18n_js_strings['timer_minutes'] = __('minutes', 'event_espresso');
1497
-        EE_Registry::$i18n_js_strings['timer_seconds'] = __('seconds', 'event_espresso');
1498
-        EE_Registry::$i18n_js_strings['timer_year'] = __('year', 'event_espresso');
1499
-        EE_Registry::$i18n_js_strings['timer_month'] = __('month', 'event_espresso');
1500
-        EE_Registry::$i18n_js_strings['timer_week'] = __('week', 'event_espresso');
1501
-        EE_Registry::$i18n_js_strings['timer_day'] = __('day', 'event_espresso');
1502
-        EE_Registry::$i18n_js_strings['timer_hour'] = __('hour', 'event_espresso');
1503
-        EE_Registry::$i18n_js_strings['timer_minute'] = __('minute', 'event_espresso');
1504
-        EE_Registry::$i18n_js_strings['timer_second'] = __('second', 'event_espresso');
1505
-        EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
1506
-            __(
1507
-                '%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
1508
-                'event_espresso'
1509
-            ),
1510
-            '<h4 class="important-notice">',
1511
-            '</h4>',
1512
-            '<br />',
1513
-            '<p>',
1514
-            '<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1515
-            '">',
1516
-            '</a>',
1517
-            '</p>'
1518
-        );
1519
-        EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters(
1520
-            'FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit',
1521
-            true
1522
-        );
1523
-        EE_Registry::$i18n_js_strings['session_extension'] = absint(
1524
-            apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1525
-        );
1526
-        EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1527
-            'M d, Y H:i:s',
1528
-            EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1529
-        );
1530
-    }
1531
-
1532
-
1533
-
1534
-    /**
1535
-     *    enqueue_styles_and_scripts
1536
-     *
1537
-     * @access        public
1538
-     * @return        void
1539
-     * @throws EE_Error
1540
-     */
1541
-    public function enqueue_styles_and_scripts()
1542
-    {
1543
-        // load css
1544
-        wp_register_style(
1545
-            'single_page_checkout',
1546
-            SPCO_CSS_URL . 'single_page_checkout.css',
1547
-            array('espresso_default'),
1548
-            EVENT_ESPRESSO_VERSION
1549
-        );
1550
-        wp_enqueue_style('single_page_checkout');
1551
-        // load JS
1552
-        wp_register_script(
1553
-            'jquery_plugin',
1554
-            EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js',
1555
-            array('jquery'),
1556
-            '1.0.1',
1557
-            true
1558
-        );
1559
-        wp_register_script(
1560
-            'jquery_countdown',
1561
-            EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js',
1562
-            array('jquery_plugin'),
1563
-            '2.0.2',
1564
-            true
1565
-        );
1566
-        wp_register_script(
1567
-            'single_page_checkout',
1568
-            SPCO_JS_URL . 'single_page_checkout.js',
1569
-            array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'),
1570
-            EVENT_ESPRESSO_VERSION,
1571
-            true
1572
-        );
1573
-        if ($this->checkout->registration_form instanceof EE_Form_Section_Proper) {
1574
-            $this->checkout->registration_form->enqueue_js();
1575
-        }
1576
-        if ($this->checkout->current_step->reg_form instanceof EE_Form_Section_Proper) {
1577
-            $this->checkout->current_step->reg_form->enqueue_js();
1578
-        }
1579
-        wp_enqueue_script('single_page_checkout');
1580
-        /**
1581
-         * global action hook for enqueueing styles and scripts with
1582
-         * spco calls.
1583
-         */
1584
-        do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1585
-        /**
1586
-         * dynamic action hook for enqueueing styles and scripts with spco calls.
1587
-         * The hook will end up being something like:
1588
-         *      AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1589
-         */
1590
-        do_action(
1591
-            'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(),
1592
-            $this
1593
-        );
1594
-    }
1595
-
1596
-
1597
-
1598
-    /**
1599
-     *    display the Registration Single Page Checkout Form
1600
-     *
1601
-     * @access    private
1602
-     * @return    void
1603
-     * @throws EE_Error
1604
-     */
1605
-    private function _display_spco_reg_form()
1606
-    {
1607
-        // if registering via the admin, just display the reg form for the current step
1608
-        if ($this->checkout->admin_request) {
1609
-            EE_Registry::instance()->REQ->add_output($this->checkout->current_step->display_reg_form());
1610
-        } else {
1611
-            // add powered by EE msg
1612
-            add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1613
-            $empty_cart = count(
1614
-                $this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)
1615
-            ) < 1;
1616
-            EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1617
-            $cookies_not_set_msg = '';
1618
-            if ($empty_cart && ! isset($_COOKIE['ee_cookie_test'])) {
1619
-                $cookies_not_set_msg = apply_filters(
1620
-                    'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1621
-                    sprintf(
1622
-                        __(
1623
-                            '%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1624
-                            'event_espresso'
1625
-                        ),
1626
-                        '<div class="ee-attention">',
1627
-                        '</div>',
1628
-                        '<h6 class="important-notice">',
1629
-                        '</h6>',
1630
-                        '<p>',
1631
-                        '</p>',
1632
-                        '<br />',
1633
-                        '<a href="http://www.whatarecookies.com/enable.asp" target="_blank">',
1634
-                        '</a>'
1635
-                    )
1636
-                );
1637
-            }
1638
-            $this->checkout->registration_form = new EE_Form_Section_Proper(
1639
-                array(
1640
-                    'name'            => 'single-page-checkout',
1641
-                    'html_id'         => 'ee-single-page-checkout-dv',
1642
-                    'layout_strategy' =>
1643
-                        new EE_Template_Layout(
1644
-                            array(
1645
-                                'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1646
-                                'template_args'        => array(
1647
-                                    'empty_cart'              => $empty_cart,
1648
-                                    'revisit'                 => $this->checkout->revisit,
1649
-                                    'reg_steps'               => $this->checkout->reg_steps,
1650
-                                    'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1651
-                                        ? $this->checkout->next_step->slug()
1652
-                                        : '',
1653
-                                    'cancel_page_url'         => $this->checkout->cancel_page_url,
1654
-                                    'empty_msg'               => apply_filters(
1655
-                                        'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1656
-                                        sprintf(
1657
-                                            __(
1658
-                                                'You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1659
-                                                'event_espresso'
1660
-                                            ),
1661
-                                            '<a href="'
1662
-                                            . get_post_type_archive_link('espresso_events')
1663
-                                            . '" title="',
1664
-                                            '">',
1665
-                                            '</a>'
1666
-                                        )
1667
-                                    ),
1668
-                                    'cookies_not_set_msg'     => $cookies_not_set_msg,
1669
-                                    'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1670
-                                    'session_expiration'      => gmdate(
1671
-                                        'M d, Y H:i:s',
1672
-                                        EE_Registry::instance()->SSN->expiration()
1673
-                                        + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1674
-                                    ),
1675
-                                ),
1676
-                            )
1677
-                        ),
1678
-                )
1679
-            );
1680
-            // load template and add to output sent that gets filtered into the_content()
1681
-            EE_Registry::instance()->REQ->add_output($this->checkout->registration_form->get_html());
1682
-        }
1683
-    }
1684
-
1685
-
1686
-
1687
-    /**
1688
-     *    add_extra_finalize_registration_inputs
1689
-     *
1690
-     * @access    public
1691
-     * @param $next_step
1692
-     * @internal  param string $label
1693
-     * @return void
1694
-     */
1695
-    public function add_extra_finalize_registration_inputs($next_step)
1696
-    {
1697
-        if ($next_step === 'finalize_registration') {
1698
-            echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1699
-        }
1700
-    }
1701
-
1702
-
1703
-
1704
-    /**
1705
-     *    display_registration_footer
1706
-     *
1707
-     * @access    public
1708
-     * @return    string
1709
-     */
1710
-    public static function display_registration_footer()
1711
-    {
1712
-        if (
1713
-        apply_filters(
1714
-            'FHEE__EE_Front__Controller__show_reg_footer',
1715
-            EE_Registry::instance()->CFG->admin->show_reg_footer
1716
-        )
1717
-        ) {
1718
-            add_filter(
1719
-                'FHEE__EEH_Template__powered_by_event_espresso__url',
1720
-                function ($url) {
1721
-                    return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1722
-                }
1723
-            );
1724
-            echo apply_filters(
1725
-                'FHEE__EE_Front_Controller__display_registration_footer',
1726
-                \EEH_Template::powered_by_event_espresso(
1727
-                    '',
1728
-                    'espresso-registration-footer-dv',
1729
-                    array('utm_content' => 'registration_checkout')
1730
-                )
1731
-            );
1732
-        }
1733
-        return '';
1734
-    }
1735
-
1736
-
1737
-
1738
-    /**
1739
-     *    unlock_transaction
1740
-     *
1741
-     * @access    public
1742
-     * @return    void
1743
-     * @throws EE_Error
1744
-     */
1745
-    public function unlock_transaction()
1746
-    {
1747
-        if ($this->checkout->transaction instanceof EE_Transaction) {
1748
-            $this->checkout->transaction->unlock();
1749
-        }
1750
-    }
1751
-
1752
-
1753
-
1754
-    /**
1755
-     *        _setup_redirect
1756
-     *
1757
-     * @access    private
1758
-     * @return void
1759
-     */
1760
-    private function _setup_redirect()
1761
-    {
1762
-        if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1763
-            $this->checkout->redirect = true;
1764
-            if (empty($this->checkout->redirect_url)) {
1765
-                $this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1766
-            }
1767
-            $this->checkout->redirect_url = apply_filters(
1768
-                'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1769
-                $this->checkout->redirect_url,
1770
-                $this->checkout
1771
-            );
1772
-        }
1773
-    }
1774
-
1775
-
1776
-
1777
-    /**
1778
-     *   handle ajax message responses and redirects
1779
-     *
1780
-     * @access public
1781
-     * @return void
1782
-     * @throws EE_Error
1783
-     */
1784
-    public function go_to_next_step()
1785
-    {
1786
-        if (EE_Registry::instance()->REQ->ajax) {
1787
-            // capture contents of output buffer we started earlier in the request, and insert into JSON response
1788
-            $this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1789
-        }
1790
-        $this->unlock_transaction();
1791
-        // just return for these conditions
1792
-        if (
1793
-            $this->checkout->admin_request
1794
-            || $this->checkout->action === 'redirect_form'
1795
-            || $this->checkout->action === 'update_checkout'
1796
-        ) {
1797
-            return;
1798
-        }
1799
-        // AJAX response
1800
-        $this->_handle_json_response();
1801
-        // redirect to next step or the Thank You page
1802
-        $this->_handle_html_redirects();
1803
-        // hmmm... must be something wrong, so let's just display the form again !
1804
-        $this->_display_spco_reg_form();
1805
-    }
1806
-
1807
-
1808
-
1809
-    /**
1810
-     *   _handle_json_response
1811
-     *
1812
-     * @access protected
1813
-     * @return void
1814
-     */
1815
-    protected function _handle_json_response()
1816
-    {
1817
-        // if this is an ajax request
1818
-        if (EE_Registry::instance()->REQ->ajax) {
1819
-            // DEBUG LOG
1820
-            //$this->checkout->log(
1821
-            //	__CLASS__, __FUNCTION__, __LINE__,
1822
-            //	array(
1823
-            //		'json_response_redirect_url' => $this->checkout->json_response->redirect_url(),
1824
-            //		'redirect'                   => $this->checkout->redirect,
1825
-            //		'continue_reg'               => $this->checkout->continue_reg,
1826
-            //	)
1827
-            //);
1828
-            $this->checkout->json_response->set_registration_time_limit(
1829
-                $this->checkout->get_registration_time_limit()
1830
-            );
1831
-            $this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1832
-            // just send the ajax (
1833
-            $json_response = apply_filters(
1834
-                'FHEE__EE_Single_Page_Checkout__JSON_response',
1835
-                $this->checkout->json_response
1836
-            );
1837
-            echo $json_response;
1838
-            exit();
1839
-        }
1840
-    }
1841
-
1842
-
1843
-
1844
-    /**
1845
-     *   _handle_redirects
1846
-     *
1847
-     * @access protected
1848
-     * @return void
1849
-     */
1850
-    protected function _handle_html_redirects()
1851
-    {
1852
-        // going somewhere ?
1853
-        if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1854
-            // store notices in a transient
1855
-            EE_Error::get_notices(false, true, true);
1856
-            // DEBUG LOG
1857
-            //$this->checkout->log(
1858
-            //	__CLASS__, __FUNCTION__, __LINE__,
1859
-            //	array(
1860
-            //		'headers_sent' => headers_sent(),
1861
-            //		'redirect_url'     => $this->checkout->redirect_url,
1862
-            //		'headers_list'    => headers_list(),
1863
-            //	)
1864
-            //);
1865
-            wp_safe_redirect($this->checkout->redirect_url);
1866
-            exit();
1867
-        }
1868
-    }
1869
-
1870
-
1871
-
1872
-    /**
1873
-     *   set_checkout_anchor
1874
-     *
1875
-     * @access public
1876
-     * @return void
1877
-     */
1878
-    public function set_checkout_anchor()
1879
-    {
1880
-        echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1881
-    }
23
+	/**
24
+	 * $_initialized - has the SPCO controller already been initialized ?
25
+	 *
26
+	 * @access private
27
+	 * @var bool $_initialized
28
+	 */
29
+	private static $_initialized = false;
30
+
31
+
32
+	/**
33
+	 * $_checkout_verified - is the EE_Checkout verified as correct for this request ?
34
+	 *
35
+	 * @access private
36
+	 * @var bool $_valid_checkout
37
+	 */
38
+	private static $_checkout_verified = true;
39
+
40
+	/**
41
+	 *    $_reg_steps_array - holds initial array of reg steps
42
+	 *
43
+	 * @access private
44
+	 * @var array $_reg_steps_array
45
+	 */
46
+	private static $_reg_steps_array = array();
47
+
48
+	/**
49
+	 *    $checkout - EE_Checkout object for handling the properties of the current checkout process
50
+	 *
51
+	 * @access public
52
+	 * @var EE_Checkout $checkout
53
+	 */
54
+	public $checkout;
55
+
56
+
57
+
58
+	/**
59
+	 * @return EED_Module|EED_Single_Page_Checkout
60
+	 */
61
+	public static function instance()
62
+	{
63
+		add_filter('EED_Single_Page_Checkout__SPCO_active', '__return_true');
64
+		return parent::get_instance(__CLASS__);
65
+	}
66
+
67
+
68
+
69
+	/**
70
+	 * @return EE_CART
71
+	 */
72
+	public function cart()
73
+	{
74
+		return $this->checkout->cart;
75
+	}
76
+
77
+
78
+
79
+	/**
80
+	 * @return EE_Transaction
81
+	 */
82
+	public function transaction()
83
+	{
84
+		return $this->checkout->transaction;
85
+	}
86
+
87
+
88
+
89
+	/**
90
+	 *    set_hooks - for hooking into EE Core, other modules, etc
91
+	 *
92
+	 * @access    public
93
+	 * @return    void
94
+	 * @throws EE_Error
95
+	 */
96
+	public static function set_hooks()
97
+	{
98
+		EED_Single_Page_Checkout::set_definitions();
99
+	}
100
+
101
+
102
+
103
+	/**
104
+	 *    set_hooks_admin - for hooking into EE Admin Core, other modules, etc
105
+	 *
106
+	 * @access    public
107
+	 * @return    void
108
+	 * @throws EE_Error
109
+	 */
110
+	public static function set_hooks_admin()
111
+	{
112
+		EED_Single_Page_Checkout::set_definitions();
113
+		if ( ! (defined('DOING_AJAX') && DOING_AJAX)) {
114
+			return;
115
+		}
116
+		// going to start an output buffer in case anything gets accidentally output
117
+		// that might disrupt our JSON response
118
+		ob_start();
119
+		EED_Single_Page_Checkout::load_request_handler();
120
+		EED_Single_Page_Checkout::load_reg_steps();
121
+		// set ajax hooks
122
+		add_action('wp_ajax_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
123
+		add_action('wp_ajax_nopriv_process_reg_step', array('EED_Single_Page_Checkout', 'process_reg_step'));
124
+		add_action('wp_ajax_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
125
+		add_action('wp_ajax_nopriv_display_spco_reg_step', array('EED_Single_Page_Checkout', 'display_reg_step'));
126
+		add_action('wp_ajax_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
127
+		add_action('wp_ajax_nopriv_update_reg_step', array('EED_Single_Page_Checkout', 'update_reg_step'));
128
+	}
129
+
130
+
131
+
132
+	/**
133
+	 *    process ajax request
134
+	 *
135
+	 * @param string $ajax_action
136
+	 * @throws EE_Error
137
+	 */
138
+	public static function process_ajax_request($ajax_action)
139
+	{
140
+		EE_Registry::instance()->REQ->set('action', $ajax_action);
141
+		EED_Single_Page_Checkout::instance()->_initialize();
142
+	}
143
+
144
+
145
+
146
+	/**
147
+	 *    ajax display registration step
148
+	 *
149
+	 * @throws EE_Error
150
+	 */
151
+	public static function display_reg_step()
152
+	{
153
+		EED_Single_Page_Checkout::process_ajax_request('display_spco_reg_step');
154
+	}
155
+
156
+
157
+
158
+	/**
159
+	 *    ajax process registration step
160
+	 *
161
+	 * @throws EE_Error
162
+	 */
163
+	public static function process_reg_step()
164
+	{
165
+		EED_Single_Page_Checkout::process_ajax_request('process_reg_step');
166
+	}
167
+
168
+
169
+
170
+	/**
171
+	 *    ajax process registration step
172
+	 *
173
+	 * @throws EE_Error
174
+	 */
175
+	public static function update_reg_step()
176
+	{
177
+		EED_Single_Page_Checkout::process_ajax_request('update_reg_step');
178
+	}
179
+
180
+
181
+
182
+	/**
183
+	 *   update_checkout
184
+	 *
185
+	 * @access public
186
+	 * @return void
187
+	 * @throws EE_Error
188
+	 */
189
+	public static function update_checkout()
190
+	{
191
+		EED_Single_Page_Checkout::process_ajax_request('update_checkout');
192
+	}
193
+
194
+
195
+
196
+	/**
197
+	 *    load_request_handler
198
+	 *
199
+	 * @access    public
200
+	 * @return    void
201
+	 */
202
+	public static function load_request_handler()
203
+	{
204
+		// load core Request_Handler class
205
+		if (EE_Registry::instance()->REQ !== null) {
206
+			EE_Registry::instance()->load_core('Request_Handler');
207
+		}
208
+	}
209
+
210
+
211
+
212
+	/**
213
+	 *    set_definitions
214
+	 *
215
+	 * @access    public
216
+	 * @return    void
217
+	 * @throws EE_Error
218
+	 */
219
+	public static function set_definitions()
220
+	{
221
+		if(defined('SPCO_BASE_PATH')) {
222
+			return;
223
+		}
224
+		define(
225
+			'SPCO_BASE_PATH',
226
+			rtrim(str_replace(array('\\', '/'), DS, plugin_dir_path(__FILE__)), DS) . DS
227
+		);
228
+		define('SPCO_CSS_URL', plugin_dir_url(__FILE__) . 'css' . DS);
229
+		define('SPCO_IMG_URL', plugin_dir_url(__FILE__) . 'img' . DS);
230
+		define('SPCO_JS_URL', plugin_dir_url(__FILE__) . 'js' . DS);
231
+		define('SPCO_INC_PATH', SPCO_BASE_PATH . 'inc' . DS);
232
+		define('SPCO_REG_STEPS_PATH', SPCO_BASE_PATH . 'reg_steps' . DS);
233
+		define('SPCO_TEMPLATES_PATH', SPCO_BASE_PATH . 'templates' . DS);
234
+		EEH_Autoloader::register_autoloaders_for_each_file_in_folder(SPCO_BASE_PATH, true);
235
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
236
+			__('%1$sWe\'re sorry, but you\'re registration time has expired.%2$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
237
+				'event_espresso'),
238
+			'<h4 class="important-notice">',
239
+			'</h4>',
240
+			'<br />',
241
+			'<p>',
242
+			'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
243
+			'">',
244
+			'</a>',
245
+			'</p>'
246
+		);
247
+	}
248
+
249
+
250
+
251
+	/**
252
+	 * load_reg_steps
253
+	 * loads and instantiates each reg step based on the EE_Registry::instance()->CFG->registration->reg_steps array
254
+	 *
255
+	 * @access    private
256
+	 * @throws EE_Error
257
+	 */
258
+	public static function load_reg_steps()
259
+	{
260
+		static $reg_steps_loaded = false;
261
+		if ($reg_steps_loaded) {
262
+			return;
263
+		}
264
+		// filter list of reg_steps
265
+		$reg_steps_to_load = (array)apply_filters(
266
+			'AHEE__SPCO__load_reg_steps__reg_steps_to_load',
267
+			EED_Single_Page_Checkout::get_reg_steps()
268
+		);
269
+		// sort by key (order)
270
+		ksort($reg_steps_to_load);
271
+		// loop through folders
272
+		foreach ($reg_steps_to_load as $order => $reg_step) {
273
+			// we need a
274
+			if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
275
+				// copy over to the reg_steps_array
276
+				EED_Single_Page_Checkout::$_reg_steps_array[$order] = $reg_step;
277
+				// register custom key route for each reg step
278
+				// ie: step=>"slug" - this is the entire reason we load the reg steps array now
279
+				EE_Config::register_route(
280
+					$reg_step['slug'],
281
+					'EED_Single_Page_Checkout',
282
+					'run',
283
+					'step'
284
+				);
285
+				// add AJAX or other hooks
286
+				if (isset($reg_step['has_hooks']) && $reg_step['has_hooks']) {
287
+					// setup autoloaders if necessary
288
+					if ( ! class_exists($reg_step['class_name'])) {
289
+						EEH_Autoloader::register_autoloaders_for_each_file_in_folder(
290
+							$reg_step['file_path'],
291
+							true
292
+						);
293
+					}
294
+					if (is_callable($reg_step['class_name'], 'set_hooks')) {
295
+						call_user_func(array($reg_step['class_name'], 'set_hooks'));
296
+					}
297
+				}
298
+			}
299
+		}
300
+		$reg_steps_loaded = true;
301
+	}
302
+
303
+
304
+
305
+	/**
306
+	 *    get_reg_steps
307
+	 *
308
+	 * @access    public
309
+	 * @return    array
310
+	 */
311
+	public static function get_reg_steps()
312
+	{
313
+		$reg_steps = EE_Registry::instance()->CFG->registration->reg_steps;
314
+		if (empty($reg_steps)) {
315
+			$reg_steps = array(
316
+				10  => array(
317
+					'file_path'  => SPCO_REG_STEPS_PATH . 'attendee_information',
318
+					'class_name' => 'EE_SPCO_Reg_Step_Attendee_Information',
319
+					'slug'       => 'attendee_information',
320
+					'has_hooks'  => false,
321
+				),
322
+				20  => array(
323
+					'file_path'  => SPCO_REG_STEPS_PATH . 'registration_confirmation',
324
+					'class_name' => 'EE_SPCO_Reg_Step_Registration_Confirmation',
325
+					'slug'       => 'registration_confirmation',
326
+					'has_hooks'  => false,
327
+				),
328
+				30  => array(
329
+					'file_path'  => SPCO_REG_STEPS_PATH . 'payment_options',
330
+					'class_name' => 'EE_SPCO_Reg_Step_Payment_Options',
331
+					'slug'       => 'payment_options',
332
+					'has_hooks'  => true,
333
+				),
334
+				999 => array(
335
+					'file_path'  => SPCO_REG_STEPS_PATH . 'finalize_registration',
336
+					'class_name' => 'EE_SPCO_Reg_Step_Finalize_Registration',
337
+					'slug'       => 'finalize_registration',
338
+					'has_hooks'  => false,
339
+				),
340
+			);
341
+		}
342
+		return $reg_steps;
343
+	}
344
+
345
+
346
+
347
+	/**
348
+	 *    registration_checkout_for_admin
349
+	 *
350
+	 * @access    public
351
+	 * @return    string
352
+	 * @throws EE_Error
353
+	 */
354
+	public static function registration_checkout_for_admin()
355
+	{
356
+		EED_Single_Page_Checkout::load_request_handler();
357
+		EE_Registry::instance()->REQ->set('step', 'attendee_information');
358
+		EE_Registry::instance()->REQ->set('action', 'display_spco_reg_step');
359
+		EE_Registry::instance()->REQ->set('process_form_submission', false);
360
+		EED_Single_Page_Checkout::instance()->_initialize();
361
+		EED_Single_Page_Checkout::instance()->_display_spco_reg_form();
362
+		return EE_Registry::instance()->REQ->get_output();
363
+	}
364
+
365
+
366
+
367
+	/**
368
+	 * process_registration_from_admin
369
+	 *
370
+	 * @access public
371
+	 * @return \EE_Transaction
372
+	 * @throws EE_Error
373
+	 */
374
+	public static function process_registration_from_admin()
375
+	{
376
+		EED_Single_Page_Checkout::load_request_handler();
377
+		EE_Registry::instance()->REQ->set('step', 'attendee_information');
378
+		EE_Registry::instance()->REQ->set('action', 'process_reg_step');
379
+		EE_Registry::instance()->REQ->set('process_form_submission', true);
380
+		EED_Single_Page_Checkout::instance()->_initialize();
381
+		if (EED_Single_Page_Checkout::instance()->checkout->current_step->completed()) {
382
+			$final_reg_step = end(EED_Single_Page_Checkout::instance()->checkout->reg_steps);
383
+			if ($final_reg_step instanceof EE_SPCO_Reg_Step_Finalize_Registration) {
384
+				EED_Single_Page_Checkout::instance()->checkout->set_reg_step_initiated($final_reg_step);
385
+				if ($final_reg_step->process_reg_step()) {
386
+					$final_reg_step->set_completed();
387
+					EED_Single_Page_Checkout::instance()->checkout->update_txn_reg_steps_array();
388
+					return EED_Single_Page_Checkout::instance()->checkout->transaction;
389
+				}
390
+			}
391
+		}
392
+		return null;
393
+	}
394
+
395
+
396
+
397
+	/**
398
+	 *    run
399
+	 *
400
+	 * @access    public
401
+	 * @param WP_Query $WP_Query
402
+	 * @return    void
403
+	 * @throws EE_Error
404
+	 */
405
+	public function run($WP_Query)
406
+	{
407
+		if (
408
+			$WP_Query instanceof WP_Query
409
+			&& $WP_Query->is_main_query()
410
+			&& apply_filters('FHEE__EED_Single_Page_Checkout__run', true)
411
+			&& $this->_is_reg_checkout()
412
+		) {
413
+			$this->_initialize();
414
+		}
415
+	}
416
+
417
+
418
+
419
+	/**
420
+	 * determines whether current url matches reg page url
421
+	 *
422
+	 * @return bool
423
+	 */
424
+	protected function _is_reg_checkout()
425
+	{
426
+		// get current permalink for reg page without any extra query args
427
+		$reg_page_url = \get_permalink(EE_Config::instance()->core->reg_page_id);
428
+		// get request URI for current request, but without the scheme or host
429
+		$current_request_uri = \EEH_URL::filter_input_server_url('REQUEST_URI');
430
+		$current_request_uri = html_entity_decode($current_request_uri);
431
+		// get array of query args from the current request URI
432
+		$query_args = \EEH_URL::get_query_string($current_request_uri);
433
+		// grab page id if it is set
434
+		$page_id = isset($query_args['page_id']) ? absint($query_args['page_id']) : 0;
435
+		// and remove the page id from the query args (we will re-add it later)
436
+		unset($query_args['page_id']);
437
+		// now strip all query args from current request URI
438
+		$current_request_uri = remove_query_arg(array_keys($query_args), $current_request_uri);
439
+		// and re-add the page id if it was set
440
+		if ($page_id) {
441
+			$current_request_uri = add_query_arg('page_id', $page_id, $current_request_uri);
442
+		}
443
+		// remove slashes and ?
444
+		$current_request_uri = trim($current_request_uri, '?/');
445
+		// is current request URI part of the known full reg page URL ?
446
+		return ! empty($current_request_uri) && strpos($reg_page_url, $current_request_uri) !== false;
447
+	}
448
+
449
+
450
+
451
+	/**
452
+	 * @param WP_Query $wp_query
453
+	 * @return    void
454
+	 * @throws EE_Error
455
+	 */
456
+	public static function init($wp_query)
457
+	{
458
+		EED_Single_Page_Checkout::instance()->run($wp_query);
459
+	}
460
+
461
+
462
+
463
+	/**
464
+	 *    _initialize - initial module setup
465
+	 *
466
+	 * @access    private
467
+	 * @throws EE_Error
468
+	 * @return    void
469
+	 */
470
+	private function _initialize()
471
+	{
472
+		// ensure SPCO doesn't run twice
473
+		if (EED_Single_Page_Checkout::$_initialized) {
474
+			return;
475
+		}
476
+		try {
477
+			EED_Single_Page_Checkout::load_reg_steps();
478
+			$this->_verify_session();
479
+			// setup the EE_Checkout object
480
+			$this->checkout = $this->_initialize_checkout();
481
+			// filter checkout
482
+			$this->checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize__checkout', $this->checkout);
483
+			// get the $_GET
484
+			$this->_get_request_vars();
485
+			if ($this->_block_bots()) {
486
+				return;
487
+			}
488
+			// filter continue_reg
489
+			$this->checkout->continue_reg = apply_filters(
490
+				'FHEE__EED_Single_Page_Checkout__init___continue_reg',
491
+				true,
492
+				$this->checkout
493
+			);
494
+			// load the reg steps array
495
+			if ( ! $this->_load_and_instantiate_reg_steps()) {
496
+				EED_Single_Page_Checkout::$_initialized = true;
497
+				return;
498
+			}
499
+			// set the current step
500
+			$this->checkout->set_current_step($this->checkout->step);
501
+			// and the next step
502
+			$this->checkout->set_next_step();
503
+			// verify that everything has been setup correctly
504
+			if ( ! ($this->_verify_transaction_and_get_registrations() && $this->_final_verifications())) {
505
+				EED_Single_Page_Checkout::$_initialized = true;
506
+				return;
507
+			}
508
+			// lock the transaction
509
+			$this->checkout->transaction->lock();
510
+			// make sure all of our cached objects are added to their respective model entity mappers
511
+			$this->checkout->refresh_all_entities();
512
+			// set amount owing
513
+			$this->checkout->amount_owing = $this->checkout->transaction->remaining();
514
+			// initialize each reg step, which gives them the chance to potentially alter the process
515
+			$this->_initialize_reg_steps();
516
+			// DEBUG LOG
517
+			//$this->checkout->log( __CLASS__, __FUNCTION__, __LINE__ );
518
+			// get reg form
519
+			if( ! $this->_check_form_submission()) {
520
+				EED_Single_Page_Checkout::$_initialized = true;
521
+				return;
522
+			}
523
+			// checkout the action!!!
524
+			$this->_process_form_action();
525
+			// add some style and make it dance
526
+			$this->add_styles_and_scripts();
527
+			// kk... SPCO has successfully run
528
+			EED_Single_Page_Checkout::$_initialized = true;
529
+			// set no cache headers and constants
530
+			EE_System::do_not_cache();
531
+			// add anchor
532
+			add_action('loop_start', array($this, 'set_checkout_anchor'), 1);
533
+			// remove transaction lock
534
+			add_action('shutdown', array($this, 'unlock_transaction'), 1);
535
+		} catch (Exception $e) {
536
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
537
+		}
538
+	}
539
+
540
+
541
+
542
+	/**
543
+	 *    _verify_session
544
+	 * checks that the session is valid and not expired
545
+	 *
546
+	 * @access    private
547
+	 * @throws EE_Error
548
+	 */
549
+	private function _verify_session()
550
+	{
551
+		if ( ! EE_Registry::instance()->SSN instanceof EE_Session) {
552
+			throw new EE_Error(__('The EE_Session class could not be loaded.', 'event_espresso'));
553
+		}
554
+		$clear_session_requested = filter_var(
555
+			EE_Registry::instance()->REQ->get('clear_session', false),
556
+			FILTER_VALIDATE_BOOLEAN
557
+		);
558
+		// is session still valid ?
559
+		if ($clear_session_requested
560
+			|| ( EE_Registry::instance()->SSN->expired()
561
+			  && EE_Registry::instance()->REQ->get('e_reg_url_link', '') === ''
562
+			)
563
+		) {
564
+			$this->checkout = new EE_Checkout();
565
+			EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
566
+			// EE_Registry::instance()->SSN->reset_cart();
567
+			// EE_Registry::instance()->SSN->reset_checkout();
568
+			// EE_Registry::instance()->SSN->reset_transaction();
569
+			if (! $clear_session_requested) {
570
+				EE_Error::add_attention(
571
+					EE_Registry::$i18n_js_strings['registration_expiration_notice'],
572
+					__FILE__, __FUNCTION__, __LINE__
573
+				);
574
+			}
575
+			// EE_Registry::instance()->SSN->reset_expired();
576
+		}
577
+	}
578
+
579
+
580
+
581
+	/**
582
+	 *    _initialize_checkout
583
+	 * loads and instantiates EE_Checkout
584
+	 *
585
+	 * @access    private
586
+	 * @throws EE_Error
587
+	 * @return EE_Checkout
588
+	 */
589
+	private function _initialize_checkout()
590
+	{
591
+		// look in session for existing checkout
592
+		/** @type EE_Checkout $checkout */
593
+		$checkout = EE_Registry::instance()->SSN->checkout();
594
+		// verify
595
+		if ( ! $checkout instanceof EE_Checkout) {
596
+			// instantiate EE_Checkout object for handling the properties of the current checkout process
597
+			$checkout = EE_Registry::instance()->load_file(
598
+				SPCO_INC_PATH,
599
+				'EE_Checkout',
600
+				'class', array(),
601
+				false
602
+			);
603
+		} else {
604
+			if ($checkout->current_step->is_final_step() && $checkout->exit_spco() === true) {
605
+				$this->unlock_transaction();
606
+				wp_safe_redirect($checkout->redirect_url);
607
+				exit();
608
+			}
609
+		}
610
+		$checkout = apply_filters('FHEE__EED_Single_Page_Checkout___initialize_checkout__checkout', $checkout);
611
+		// verify again
612
+		if ( ! $checkout instanceof EE_Checkout) {
613
+			throw new EE_Error(__('The EE_Checkout class could not be loaded.', 'event_espresso'));
614
+		}
615
+		// reset anything that needs a clean slate for each request
616
+		$checkout->reset_for_current_request();
617
+		return $checkout;
618
+	}
619
+
620
+
621
+
622
+	/**
623
+	 *    _get_request_vars
624
+	 *
625
+	 * @access    private
626
+	 * @return    void
627
+	 * @throws EE_Error
628
+	 */
629
+	private function _get_request_vars()
630
+	{
631
+		// load classes
632
+		EED_Single_Page_Checkout::load_request_handler();
633
+		//make sure this request is marked as belonging to EE
634
+		EE_Registry::instance()->REQ->set_espresso_page(true);
635
+		// which step is being requested ?
636
+		$this->checkout->step = EE_Registry::instance()->REQ->get('step', $this->_get_first_step());
637
+		// which step is being edited ?
638
+		$this->checkout->edit_step = EE_Registry::instance()->REQ->get('edit_step', '');
639
+		// and what we're doing on the current step
640
+		$this->checkout->action = EE_Registry::instance()->REQ->get('action', 'display_spco_reg_step');
641
+		// timestamp
642
+		$this->checkout->uts = EE_Registry::instance()->REQ->get('uts', 0);
643
+		// returning to edit ?
644
+		$this->checkout->reg_url_link = EE_Registry::instance()->REQ->get('e_reg_url_link', '');
645
+		// add reg url link to registration query params
646
+		if ($this->checkout->reg_url_link && strpos($this->checkout->reg_url_link, '1-') !== 0) {
647
+			$this->checkout->reg_cache_where_params[0]['REG_url_link'] = $this->checkout->reg_url_link;
648
+		}
649
+		// or some other kind of revisit ?
650
+		$this->checkout->revisit = filter_var(
651
+			EE_Registry::instance()->REQ->get('revisit', false),
652
+			FILTER_VALIDATE_BOOLEAN
653
+		);
654
+		// and whether or not to generate a reg form for this request
655
+		$this->checkout->generate_reg_form = filter_var(
656
+			EE_Registry::instance()->REQ->get('generate_reg_form', true),
657
+			FILTER_VALIDATE_BOOLEAN
658
+		);
659
+		// and whether or not to process a reg form submission for this request
660
+		$this->checkout->process_form_submission = filter_var(
661
+			EE_Registry::instance()->REQ->get(
662
+				'process_form_submission',
663
+				$this->checkout->action === 'process_reg_step'
664
+			),
665
+			FILTER_VALIDATE_BOOLEAN
666
+		);
667
+		$this->checkout->process_form_submission = filter_var(
668
+			$this->checkout->action !== 'display_spco_reg_step'
669
+				? $this->checkout->process_form_submission
670
+				: false,
671
+			FILTER_VALIDATE_BOOLEAN
672
+		);
673
+		// $this->_display_request_vars();
674
+	}
675
+
676
+
677
+
678
+	/**
679
+	 *  _display_request_vars
680
+	 *
681
+	 * @access    protected
682
+	 * @return    void
683
+	 */
684
+	protected function _display_request_vars()
685
+	{
686
+		if ( ! WP_DEBUG) {
687
+			return;
688
+		}
689
+		EEH_Debug_Tools::printr($_REQUEST, '$_REQUEST', __FILE__, __LINE__);
690
+		EEH_Debug_Tools::printr($this->checkout->step, '$this->checkout->step', __FILE__, __LINE__);
691
+		EEH_Debug_Tools::printr($this->checkout->edit_step, '$this->checkout->edit_step', __FILE__, __LINE__);
692
+		EEH_Debug_Tools::printr($this->checkout->action, '$this->checkout->action', __FILE__, __LINE__);
693
+		EEH_Debug_Tools::printr($this->checkout->reg_url_link, '$this->checkout->reg_url_link', __FILE__, __LINE__);
694
+		EEH_Debug_Tools::printr($this->checkout->revisit, '$this->checkout->revisit', __FILE__, __LINE__);
695
+		EEH_Debug_Tools::printr($this->checkout->generate_reg_form, '$this->checkout->generate_reg_form', __FILE__, __LINE__);
696
+		EEH_Debug_Tools::printr($this->checkout->process_form_submission, '$this->checkout->process_form_submission', __FILE__, __LINE__);
697
+	}
698
+
699
+
700
+
701
+	/**
702
+	 * _block_bots
703
+	 * checks that the incoming request has either of the following set:
704
+	 *  a uts (unix timestamp) which indicates that the request was redirected from the Ticket Selector
705
+	 *  a REG URL Link, which indicates that the request is a return visit to SPCO for a valid TXN
706
+	 * so if you're not coming from the Ticket Selector nor returning for a valid IP...
707
+	 * then where you coming from man?
708
+	 *
709
+	 * @return boolean
710
+	 */
711
+	private function _block_bots()
712
+	{
713
+		$invalid_checkout_access = EED_Invalid_Checkout_Access::getInvalidCheckoutAccess();
714
+		if ($invalid_checkout_access->checkoutAccessIsInvalid($this->checkout)) {
715
+			return true;
716
+		}
717
+		return false;
718
+	}
719
+
720
+
721
+
722
+	/**
723
+	 *    _get_first_step
724
+	 *  gets slug for first step in $_reg_steps_array
725
+	 *
726
+	 * @access    private
727
+	 * @throws EE_Error
728
+	 * @return    string
729
+	 */
730
+	private function _get_first_step()
731
+	{
732
+		$first_step = reset(EED_Single_Page_Checkout::$_reg_steps_array);
733
+		return isset($first_step['slug']) ? $first_step['slug'] : 'attendee_information';
734
+	}
735
+
736
+
737
+
738
+	/**
739
+	 *    _load_and_instantiate_reg_steps
740
+	 *  instantiates each reg step based on the loaded reg_steps array
741
+	 *
742
+	 * @access    private
743
+	 * @throws EE_Error
744
+	 * @return    bool
745
+	 */
746
+	private function _load_and_instantiate_reg_steps()
747
+	{
748
+		do_action('AHEE__Single_Page_Checkout___load_and_instantiate_reg_steps__start', $this->checkout);
749
+		// have reg_steps already been instantiated ?
750
+		if (
751
+			empty($this->checkout->reg_steps)
752
+			|| apply_filters('FHEE__Single_Page_Checkout__load_reg_steps__reload_reg_steps', false, $this->checkout)
753
+		) {
754
+			// if not, then loop through raw reg steps array
755
+			foreach (EED_Single_Page_Checkout::$_reg_steps_array as $order => $reg_step) {
756
+				if ( ! $this->_load_and_instantiate_reg_step($reg_step, $order)) {
757
+					return false;
758
+				}
759
+			}
760
+			EE_Registry::instance()->CFG->registration->skip_reg_confirmation = true;
761
+			EE_Registry::instance()->CFG->registration->reg_confirmation_last = true;
762
+			// skip the registration_confirmation page ?
763
+			if (EE_Registry::instance()->CFG->registration->skip_reg_confirmation) {
764
+				// just remove it from the reg steps array
765
+				$this->checkout->remove_reg_step('registration_confirmation', false);
766
+			} else if (
767
+				isset($this->checkout->reg_steps['registration_confirmation'])
768
+				&& EE_Registry::instance()->CFG->registration->reg_confirmation_last
769
+			) {
770
+				// set the order to something big like 100
771
+				$this->checkout->set_reg_step_order('registration_confirmation', 100);
772
+			}
773
+			// filter the array for good luck
774
+			$this->checkout->reg_steps = apply_filters(
775
+				'FHEE__Single_Page_Checkout__load_reg_steps__reg_steps',
776
+				$this->checkout->reg_steps
777
+			);
778
+			// finally re-sort based on the reg step class order properties
779
+			$this->checkout->sort_reg_steps();
780
+		} else {
781
+			foreach ($this->checkout->reg_steps as $reg_step) {
782
+				// set all current step stati to FALSE
783
+				$reg_step->set_is_current_step(false);
784
+			}
785
+		}
786
+		if (empty($this->checkout->reg_steps)) {
787
+			EE_Error::add_error(
788
+				__('No Reg Steps were loaded..', 'event_espresso'),
789
+				__FILE__, __FUNCTION__, __LINE__
790
+			);
791
+			return false;
792
+		}
793
+		// make reg step details available to JS
794
+		$this->checkout->set_reg_step_JSON_info();
795
+		return true;
796
+	}
797
+
798
+
799
+
800
+	/**
801
+	 *     _load_and_instantiate_reg_step
802
+	 *
803
+	 * @access    private
804
+	 * @param array $reg_step
805
+	 * @param int   $order
806
+	 * @return bool
807
+	 */
808
+	private function _load_and_instantiate_reg_step($reg_step = array(), $order = 0)
809
+	{
810
+		// we need a file_path, class_name, and slug to add a reg step
811
+		if (isset($reg_step['file_path'], $reg_step['class_name'], $reg_step['slug'])) {
812
+			// if editing a specific step, but this is NOT that step... (and it's not the 'finalize_registration' step)
813
+			if (
814
+				$this->checkout->reg_url_link
815
+				&& $this->checkout->step !== $reg_step['slug']
816
+				&& $reg_step['slug'] !== 'finalize_registration'
817
+				// normally at this point we would NOT load the reg step, but this filter can change that
818
+				&& apply_filters(
819
+					'FHEE__Single_Page_Checkout___load_and_instantiate_reg_step__bypass_reg_step',
820
+					true,
821
+					$reg_step,
822
+					$this->checkout
823
+				)
824
+			) {
825
+				return true;
826
+			}
827
+			// instantiate step class using file path and class name
828
+			$reg_step_obj = EE_Registry::instance()->load_file(
829
+				$reg_step['file_path'],
830
+				$reg_step['class_name'],
831
+				'class',
832
+				$this->checkout,
833
+				false
834
+			);
835
+			// did we gets the goods ?
836
+			if ($reg_step_obj instanceof EE_SPCO_Reg_Step) {
837
+				// set reg step order based on config
838
+				$reg_step_obj->set_order($order);
839
+				// add instantiated reg step object to the master reg steps array
840
+				$this->checkout->add_reg_step($reg_step_obj);
841
+			} else {
842
+				EE_Error::add_error(
843
+					__('The current step could not be set.', 'event_espresso'),
844
+					__FILE__, __FUNCTION__, __LINE__
845
+				);
846
+				return false;
847
+			}
848
+		} else {
849
+			if (WP_DEBUG) {
850
+				EE_Error::add_error(
851
+					sprintf(
852
+						__(
853
+							'A registration step could not be loaded. One or more of the following data points is invalid:%4$s%5$sFile Path: %1$s%6$s%5$sClass Name: %2$s%6$s%5$sSlug: %3$s%6$s%7$s',
854
+							'event_espresso'
855
+						),
856
+						isset($reg_step['file_path']) ? $reg_step['file_path'] : '',
857
+						isset($reg_step['class_name']) ? $reg_step['class_name'] : '',
858
+						isset($reg_step['slug']) ? $reg_step['slug'] : '',
859
+						'<ul>',
860
+						'<li>',
861
+						'</li>',
862
+						'</ul>'
863
+					),
864
+					__FILE__, __FUNCTION__, __LINE__
865
+				);
866
+			}
867
+			return false;
868
+		}
869
+		return true;
870
+	}
871
+
872
+
873
+	/**
874
+	 * _verify_transaction_and_get_registrations
875
+	 *
876
+	 * @access private
877
+	 * @return bool
878
+	 * @throws InvalidDataTypeException
879
+	 * @throws InvalidEntityException
880
+	 * @throws EE_Error
881
+	 */
882
+	private function _verify_transaction_and_get_registrations()
883
+	{
884
+		// was there already a valid transaction in the checkout from the session ?
885
+		if ( ! $this->checkout->transaction instanceof EE_Transaction) {
886
+			// get transaction from db or session
887
+			$this->checkout->transaction = $this->checkout->reg_url_link && ! is_admin()
888
+				? $this->_get_transaction_and_cart_for_previous_visit()
889
+				: $this->_get_cart_for_current_session_and_setup_new_transaction();
890
+			if ( ! $this->checkout->transaction instanceof EE_Transaction) {
891
+				EE_Error::add_error(
892
+					__('Your Registration and Transaction information could not be retrieved from the db.',
893
+						'event_espresso'),
894
+					__FILE__, __FUNCTION__, __LINE__
895
+				);
896
+				$this->checkout->transaction = EE_Transaction::new_instance();
897
+				// add some style and make it dance
898
+				$this->add_styles_and_scripts();
899
+				EED_Single_Page_Checkout::$_initialized = true;
900
+				return false;
901
+			}
902
+			// and the registrations for the transaction
903
+			$this->_get_registrations($this->checkout->transaction);
904
+		}
905
+		return true;
906
+	}
907
+
908
+
909
+
910
+	/**
911
+	 * _get_transaction_and_cart_for_previous_visit
912
+	 *
913
+	 * @access private
914
+	 * @return mixed EE_Transaction|NULL
915
+	 */
916
+	private function _get_transaction_and_cart_for_previous_visit()
917
+	{
918
+		/** @var $TXN_model EEM_Transaction */
919
+		$TXN_model = EE_Registry::instance()->load_model('Transaction');
920
+		// because the reg_url_link is present in the request,
921
+		// this is a return visit to SPCO, so we'll get the transaction data from the db
922
+		$transaction = $TXN_model->get_transaction_from_reg_url_link($this->checkout->reg_url_link);
923
+		// verify transaction
924
+		if ($transaction instanceof EE_Transaction) {
925
+			// and get the cart that was used for that transaction
926
+			$this->checkout->cart = $this->_get_cart_for_transaction($transaction);
927
+			return $transaction;
928
+		}
929
+		EE_Error::add_error(
930
+			__('Your Registration and Transaction information could not be retrieved from the db.', 'event_espresso'),
931
+			__FILE__, __FUNCTION__, __LINE__
932
+		);
933
+		return null;
934
+
935
+	}
936
+
937
+
938
+
939
+	/**
940
+	 * _get_cart_for_transaction
941
+	 *
942
+	 * @access private
943
+	 * @param EE_Transaction $transaction
944
+	 * @return EE_Cart
945
+	 */
946
+	private function _get_cart_for_transaction($transaction)
947
+	{
948
+		return $this->checkout->get_cart_for_transaction($transaction);
949
+	}
950
+
951
+
952
+
953
+	/**
954
+	 * get_cart_for_transaction
955
+	 *
956
+	 * @access public
957
+	 * @param EE_Transaction $transaction
958
+	 * @return EE_Cart
959
+	 */
960
+	public function get_cart_for_transaction(EE_Transaction $transaction)
961
+	{
962
+		return $this->checkout->get_cart_for_transaction($transaction);
963
+	}
964
+
965
+
966
+
967
+	/**
968
+	 * _get_transaction_and_cart_for_current_session
969
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
970
+	 *
971
+	 * @access private
972
+	 * @return EE_Transaction
973
+	 * @throws EE_Error
974
+	 */
975
+	private function _get_cart_for_current_session_and_setup_new_transaction()
976
+	{
977
+		//  if there's no transaction, then this is the FIRST visit to SPCO
978
+		// so load up the cart ( passing nothing for the TXN because it doesn't exist yet )
979
+		$this->checkout->cart = $this->_get_cart_for_transaction(null);
980
+		// and then create a new transaction
981
+		$transaction = $this->_initialize_transaction();
982
+		// verify transaction
983
+		if ($transaction instanceof EE_Transaction) {
984
+			// save it so that we have an ID for other objects to use
985
+			$transaction->save();
986
+			// and save TXN data to the cart
987
+			$this->checkout->cart->get_grand_total()->save_this_and_descendants_to_txn($transaction->ID());
988
+		} else {
989
+			EE_Error::add_error(
990
+				__('A Valid Transaction could not be initialized.', 'event_espresso'),
991
+				__FILE__, __FUNCTION__, __LINE__
992
+			);
993
+		}
994
+		return $transaction;
995
+	}
996
+
997
+
998
+
999
+	/**
1000
+	 *    generates a new EE_Transaction object and adds it to the $_transaction property.
1001
+	 *
1002
+	 * @access private
1003
+	 * @return mixed EE_Transaction|NULL
1004
+	 */
1005
+	private function _initialize_transaction()
1006
+	{
1007
+		try {
1008
+			// ensure cart totals have been calculated
1009
+			$this->checkout->cart->get_grand_total()->recalculate_total_including_taxes();
1010
+			// grab the cart grand total
1011
+			$cart_total = $this->checkout->cart->get_cart_grand_total();
1012
+			// create new TXN
1013
+			$transaction = EE_Transaction::new_instance(
1014
+				array(
1015
+					'TXN_reg_steps' => $this->checkout->initialize_txn_reg_steps_array(),
1016
+					'TXN_total'     => $cart_total > 0 ? $cart_total : 0,
1017
+					'TXN_paid'      => 0,
1018
+					'STS_ID'        => EEM_Transaction::failed_status_code,
1019
+				)
1020
+			);
1021
+			// save it so that we have an ID for other objects to use
1022
+			$transaction->save();
1023
+			// set cron job for following up on TXNs after their session has expired
1024
+			EE_Cron_Tasks::schedule_expired_transaction_check(
1025
+				EE_Registry::instance()->SSN->expiration() + 1,
1026
+				$transaction->ID()
1027
+			);
1028
+			return $transaction;
1029
+		} catch (Exception $e) {
1030
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
1031
+		}
1032
+		return null;
1033
+	}
1034
+
1035
+
1036
+	/**
1037
+	 * _get_registrations
1038
+	 *
1039
+	 * @access private
1040
+	 * @param EE_Transaction $transaction
1041
+	 * @return void
1042
+	 * @throws InvalidDataTypeException
1043
+	 * @throws InvalidEntityException
1044
+	 * @throws EE_Error
1045
+	 */
1046
+	private function _get_registrations(EE_Transaction $transaction)
1047
+	{
1048
+		// first step: grab the registrants  { : o
1049
+		$registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
1050
+		$this->checkout->total_ticket_count = count($registrations);
1051
+		// verify registrations have been set
1052
+		if (empty($registrations)) {
1053
+			// if no cached registrations, then check the db
1054
+			$registrations = $transaction->registrations($this->checkout->reg_cache_where_params, false);
1055
+			// still nothing ? well as long as this isn't a revisit
1056
+			if (empty($registrations) && ! $this->checkout->revisit) {
1057
+				// generate new registrations from scratch
1058
+				$registrations = $this->_initialize_registrations($transaction);
1059
+			}
1060
+		}
1061
+		// sort by their original registration order
1062
+		usort($registrations, array('EED_Single_Page_Checkout', 'sort_registrations_by_REG_count'));
1063
+		// then loop thru the array
1064
+		foreach ($registrations as $registration) {
1065
+			// verify each registration
1066
+			if ($registration instanceof EE_Registration) {
1067
+				// we display all attendee info for the primary registrant
1068
+				if ($this->checkout->reg_url_link === $registration->reg_url_link()
1069
+					&& $registration->is_primary_registrant()
1070
+				) {
1071
+					$this->checkout->primary_revisit = true;
1072
+					break;
1073
+				}
1074
+				if ($this->checkout->revisit && $this->checkout->reg_url_link !== $registration->reg_url_link()) {
1075
+					// but hide info if it doesn't belong to you
1076
+					$transaction->clear_cache('Registration', $registration->ID());
1077
+					$this->checkout->total_ticket_count--;
1078
+				}
1079
+				$this->checkout->set_reg_status_updated($registration->ID(), false);
1080
+			}
1081
+		}
1082
+	}
1083
+
1084
+
1085
+	/**
1086
+	 *    adds related EE_Registration objects for each ticket in the cart to the current EE_Transaction object
1087
+	 *
1088
+	 * @access private
1089
+	 * @param EE_Transaction $transaction
1090
+	 * @return    array
1091
+	 * @throws InvalidDataTypeException
1092
+	 * @throws InvalidEntityException
1093
+	 * @throws EE_Error
1094
+	 */
1095
+	private function _initialize_registrations(EE_Transaction $transaction)
1096
+	{
1097
+		$att_nmbr = 0;
1098
+		$registrations = array();
1099
+		if ($transaction instanceof EE_Transaction) {
1100
+			/** @type EE_Registration_Processor $registration_processor */
1101
+			$registration_processor = EE_Registry::instance()->load_class('Registration_Processor');
1102
+			$this->checkout->total_ticket_count = $this->checkout->cart->all_ticket_quantity_count();
1103
+			// now let's add the cart items to the $transaction
1104
+			foreach ($this->checkout->cart->get_tickets() as $line_item) {
1105
+				//do the following for each ticket of this type they selected
1106
+				for ($x = 1; $x <= $line_item->quantity(); $x++) {
1107
+					$att_nmbr++;
1108
+					/** @var EventEspresso\core\services\commands\registration\CreateRegistrationCommand $CreateRegistrationCommand */
1109
+					$CreateRegistrationCommand = EE_Registry::instance()->create(
1110
+						'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
1111
+						array(
1112
+							$transaction,
1113
+							$line_item,
1114
+							$att_nmbr,
1115
+							$this->checkout->total_ticket_count,
1116
+						)
1117
+					);
1118
+					// override capabilities for frontend registrations
1119
+					if ( ! is_admin()) {
1120
+						$CreateRegistrationCommand->setCapCheck(
1121
+							new PublicCapabilities('', 'create_new_registration')
1122
+						);
1123
+					}
1124
+					$registration = EE_Registry::instance()->BUS->execute($CreateRegistrationCommand);
1125
+					if ( ! $registration instanceof EE_Registration) {
1126
+						throw new InvalidEntityException($registration, 'EE_Registration');
1127
+					}
1128
+					$registrations[ $registration->ID() ] = $registration;
1129
+				}
1130
+			}
1131
+			$registration_processor->fix_reg_final_price_rounding_issue($transaction);
1132
+		}
1133
+		return $registrations;
1134
+	}
1135
+
1136
+
1137
+
1138
+	/**
1139
+	 * sorts registrations by REG_count
1140
+	 *
1141
+	 * @access public
1142
+	 * @param EE_Registration $reg_A
1143
+	 * @param EE_Registration $reg_B
1144
+	 * @return int
1145
+	 */
1146
+	public static function sort_registrations_by_REG_count(EE_Registration $reg_A, EE_Registration $reg_B)
1147
+	{
1148
+		// this shouldn't ever happen within the same TXN, but oh well
1149
+		if ($reg_A->count() === $reg_B->count()) {
1150
+			return 0;
1151
+		}
1152
+		return ($reg_A->count() > $reg_B->count()) ? 1 : -1;
1153
+	}
1154
+
1155
+
1156
+
1157
+	/**
1158
+	 *    _final_verifications
1159
+	 * just makes sure that everything is set up correctly before proceeding
1160
+	 *
1161
+	 * @access    private
1162
+	 * @return    bool
1163
+	 * @throws EE_Error
1164
+	 */
1165
+	private function _final_verifications()
1166
+	{
1167
+		// filter checkout
1168
+		$this->checkout = apply_filters(
1169
+			'FHEE__EED_Single_Page_Checkout___final_verifications__checkout',
1170
+			$this->checkout
1171
+		);
1172
+		//verify that current step is still set correctly
1173
+		if ( ! $this->checkout->current_step instanceof EE_SPCO_Reg_Step) {
1174
+			EE_Error::add_error(
1175
+				__('We\'re sorry but the registration process can not proceed because one or more registration steps were not setup correctly. Please refresh the page and try again or contact support.', 'event_espresso'),
1176
+				__FILE__,
1177
+				__FUNCTION__,
1178
+				__LINE__
1179
+			);
1180
+			return false;
1181
+		}
1182
+		// if returning to SPCO, then verify that primary registrant is set
1183
+		if ( ! empty($this->checkout->reg_url_link)) {
1184
+			$valid_registrant = $this->checkout->transaction->primary_registration();
1185
+			if ( ! $valid_registrant instanceof EE_Registration) {
1186
+				EE_Error::add_error(
1187
+					__('We\'re sorry but there appears to be an error with the "reg_url_link" or the primary registrant for this transaction. Please refresh the page and try again or contact support.', 'event_espresso'),
1188
+					__FILE__,
1189
+					__FUNCTION__,
1190
+					__LINE__
1191
+				);
1192
+				return false;
1193
+			}
1194
+			$valid_registrant = null;
1195
+			foreach (
1196
+				$this->checkout->transaction->registrations($this->checkout->reg_cache_where_params) as $registration
1197
+			) {
1198
+				if (
1199
+					$registration instanceof EE_Registration
1200
+					&& $registration->reg_url_link() === $this->checkout->reg_url_link
1201
+				) {
1202
+					$valid_registrant = $registration;
1203
+				}
1204
+			}
1205
+			if ( ! $valid_registrant instanceof EE_Registration) {
1206
+				// hmmm... maybe we have the wrong session because the user is opening multiple tabs ?
1207
+				if (EED_Single_Page_Checkout::$_checkout_verified) {
1208
+					// clear the session, mark the checkout as unverified, and try again
1209
+					EE_Registry::instance()->SSN->clear_session(__CLASS__, __FUNCTION__);
1210
+					EED_Single_Page_Checkout::$_initialized = false;
1211
+					EED_Single_Page_Checkout::$_checkout_verified = false;
1212
+					$this->_initialize();
1213
+					EE_Error::reset_notices();
1214
+					return false;
1215
+				}
1216
+				EE_Error::add_error(
1217
+					__(
1218
+						'We\'re sorry but there appears to be an error with the "reg_url_link" or the transaction itself. Please refresh the page and try again or contact support.',
1219
+						'event_espresso'
1220
+					),
1221
+					__FILE__,
1222
+					__FUNCTION__,
1223
+					__LINE__
1224
+				);
1225
+				return false;
1226
+			}
1227
+		}
1228
+		// now that things have been kinda sufficiently verified,
1229
+		// let's add the checkout to the session so that it's available to other systems
1230
+		EE_Registry::instance()->SSN->set_checkout($this->checkout);
1231
+		return true;
1232
+	}
1233
+
1234
+
1235
+
1236
+	/**
1237
+	 *    _initialize_reg_steps
1238
+	 * first makes sure that EE_Transaction_Processor::set_reg_step_initiated() is called as required
1239
+	 * then loops thru all of the active reg steps and calls the initialize_reg_step() method
1240
+	 *
1241
+	 * @access    private
1242
+	 * @param bool $reinitializing
1243
+	 * @throws EE_Error
1244
+	 */
1245
+	private function _initialize_reg_steps($reinitializing = false)
1246
+	{
1247
+		$this->checkout->set_reg_step_initiated($this->checkout->current_step);
1248
+		// loop thru all steps to call their individual "initialize" methods and set i18n strings for JS
1249
+		foreach ($this->checkout->reg_steps as $reg_step) {
1250
+			if ( ! $reg_step->initialize_reg_step()) {
1251
+				// if not initialized then maybe this step is being removed...
1252
+				if ( ! $reinitializing && $reg_step->is_current_step()) {
1253
+					// if it was the current step, then we need to start over here
1254
+					$this->_initialize_reg_steps(true);
1255
+					return;
1256
+				}
1257
+				continue;
1258
+			}
1259
+			// add css and JS for current step
1260
+			$reg_step->enqueue_styles_and_scripts();
1261
+			// i18n
1262
+			$reg_step->translate_js_strings();
1263
+			if ($reg_step->is_current_step()) {
1264
+				// the text that appears on the reg step form submit button
1265
+				$reg_step->set_submit_button_text();
1266
+			}
1267
+		}
1268
+		// dynamically creates hook point like: AHEE__Single_Page_Checkout___initialize_reg_step__attendee_information
1269
+		do_action(
1270
+			"AHEE__Single_Page_Checkout___initialize_reg_step__{$this->checkout->current_step->slug()}",
1271
+			$this->checkout->current_step
1272
+		);
1273
+	}
1274
+
1275
+
1276
+
1277
+	/**
1278
+	 * _check_form_submission
1279
+	 *
1280
+	 * @access private
1281
+	 * @return boolean
1282
+	 */
1283
+	private function _check_form_submission()
1284
+	{
1285
+		//does this request require the reg form to be generated ?
1286
+		if ($this->checkout->generate_reg_form) {
1287
+			// ever heard that song by Blue Rodeo ?
1288
+			try {
1289
+				$this->checkout->current_step->reg_form = $this->checkout->current_step->generate_reg_form();
1290
+				// if not displaying a form, then check for form submission
1291
+				if (
1292
+					$this->checkout->process_form_submission
1293
+					&& $this->checkout->current_step->reg_form->was_submitted()
1294
+				) {
1295
+					// clear out any old data in case this step is being run again
1296
+					$this->checkout->current_step->set_valid_data(array());
1297
+					// capture submitted form data
1298
+					$this->checkout->current_step->reg_form->receive_form_submission(
1299
+						apply_filters(
1300
+							'FHEE__Single_Page_Checkout___check_form_submission__request_params',
1301
+							EE_Registry::instance()->REQ->params(),
1302
+							$this->checkout
1303
+						)
1304
+					);
1305
+					// validate submitted form data
1306
+					if ( ! $this->checkout->continue_reg || ! $this->checkout->current_step->reg_form->is_valid()) {
1307
+						// thou shall not pass !!!
1308
+						$this->checkout->continue_reg = false;
1309
+						// any form validation errors?
1310
+						if ($this->checkout->current_step->reg_form->submission_error_message() !== '') {
1311
+							$submission_error_messages = array();
1312
+							// bad, bad, bad registrant
1313
+							foreach (
1314
+								$this->checkout->current_step->reg_form->get_validation_errors_accumulated()
1315
+								as $validation_error
1316
+							) {
1317
+								if ($validation_error instanceof EE_Validation_Error) {
1318
+									$submission_error_messages[] = sprintf(
1319
+										__('%s : %s', 'event_espresso'),
1320
+										$validation_error->get_form_section()->html_label_text(),
1321
+										$validation_error->getMessage()
1322
+									);
1323
+								}
1324
+							}
1325
+							EE_Error::add_error(
1326
+								implode('<br />', $submission_error_messages),
1327
+								__FILE__, __FUNCTION__, __LINE__
1328
+							);
1329
+						}
1330
+						// well not really... what will happen is
1331
+						// we'll just get redirected back to redo the current step
1332
+						$this->go_to_next_step();
1333
+						return false;
1334
+					}
1335
+				}
1336
+			} catch (EE_Error $e) {
1337
+				$e->get_error();
1338
+			}
1339
+		}
1340
+		return true;
1341
+	}
1342
+
1343
+
1344
+
1345
+	/**
1346
+	 * _process_action
1347
+	 *
1348
+	 * @access private
1349
+	 * @return void
1350
+	 * @throws EE_Error
1351
+	 */
1352
+	private function _process_form_action()
1353
+	{
1354
+		// what cha wanna do?
1355
+		switch ($this->checkout->action) {
1356
+			// AJAX next step reg form
1357
+			case 'display_spco_reg_step' :
1358
+				$this->checkout->redirect = false;
1359
+				if (EE_Registry::instance()->REQ->ajax) {
1360
+					$this->checkout->json_response->set_reg_step_html(
1361
+						$this->checkout->current_step->display_reg_form()
1362
+					);
1363
+				}
1364
+				break;
1365
+			default :
1366
+				// meh... do one of those other steps first
1367
+				if (
1368
+					! empty($this->checkout->action)
1369
+					&& is_callable(array($this->checkout->current_step, $this->checkout->action))
1370
+				) {
1371
+					// dynamically creates hook point like:
1372
+					//   AHEE__Single_Page_Checkout__before_attendee_information__process_reg_step
1373
+					do_action(
1374
+						"AHEE__Single_Page_Checkout__before_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1375
+						$this->checkout->current_step
1376
+					);
1377
+					// call action on current step
1378
+					if (call_user_func(array($this->checkout->current_step, $this->checkout->action))) {
1379
+						// good registrant, you get to proceed
1380
+						if (
1381
+							$this->checkout->current_step->success_message() !== ''
1382
+							&& apply_filters(
1383
+								'FHEE__Single_Page_Checkout___process_form_action__display_success',
1384
+								false
1385
+							)
1386
+						) {
1387
+							EE_Error::add_success(
1388
+								$this->checkout->current_step->success_message()
1389
+								. '<br />' . $this->checkout->next_step->_instructions()
1390
+							);
1391
+						}
1392
+						// pack it up, pack it in...
1393
+						$this->_setup_redirect();
1394
+					}
1395
+					// dynamically creates hook point like:
1396
+					//  AHEE__Single_Page_Checkout__after_payment_options__process_reg_step
1397
+					do_action(
1398
+						"AHEE__Single_Page_Checkout__after_{$this->checkout->current_step->slug()}__{$this->checkout->action}",
1399
+						$this->checkout->current_step
1400
+					);
1401
+				} else {
1402
+					EE_Error::add_error(
1403
+						sprintf(
1404
+							__(
1405
+								'The requested form action "%s" does not exist for the current "%s" registration step.',
1406
+								'event_espresso'
1407
+							),
1408
+							$this->checkout->action,
1409
+							$this->checkout->current_step->name()
1410
+						),
1411
+						__FILE__,
1412
+						__FUNCTION__,
1413
+						__LINE__
1414
+					);
1415
+				}
1416
+			// end default
1417
+		}
1418
+		// store our progress so far
1419
+		$this->checkout->stash_transaction_and_checkout();
1420
+		// advance to the next step! If you pass GO, collect $200
1421
+		$this->go_to_next_step();
1422
+	}
1423
+
1424
+
1425
+
1426
+	/**
1427
+	 *        add_styles_and_scripts
1428
+	 *
1429
+	 * @access        public
1430
+	 * @return        void
1431
+	 */
1432
+	public function add_styles_and_scripts()
1433
+	{
1434
+		// i18n
1435
+		$this->translate_js_strings();
1436
+		if ($this->checkout->admin_request) {
1437
+			add_action('admin_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1438
+		} else {
1439
+			add_action('wp_enqueue_scripts', array($this, 'enqueue_styles_and_scripts'), 10);
1440
+		}
1441
+	}
1442
+
1443
+
1444
+
1445
+	/**
1446
+	 *        translate_js_strings
1447
+	 *
1448
+	 * @access        public
1449
+	 * @return        void
1450
+	 */
1451
+	public function translate_js_strings()
1452
+	{
1453
+		EE_Registry::$i18n_js_strings['revisit'] = $this->checkout->revisit;
1454
+		EE_Registry::$i18n_js_strings['e_reg_url_link'] = $this->checkout->reg_url_link;
1455
+		EE_Registry::$i18n_js_strings['server_error'] = __(
1456
+			'An unknown error occurred on the server while attempting to process your request. Please refresh the page and try again or contact support.',
1457
+			'event_espresso'
1458
+		);
1459
+		EE_Registry::$i18n_js_strings['invalid_json_response'] = __(
1460
+			'An invalid response was returned from the server while attempting to process your request. Please refresh the page and try again or contact support.',
1461
+			'event_espresso'
1462
+		);
1463
+		EE_Registry::$i18n_js_strings['validation_error'] = __(
1464
+			'There appears to be a problem with the form validation configuration! Please check the admin settings or contact support.',
1465
+			'event_espresso'
1466
+		);
1467
+		EE_Registry::$i18n_js_strings['invalid_payment_method'] = __(
1468
+			'There appears to be a problem with the payment method configuration! Please refresh the page and try again or contact support.',
1469
+			'event_espresso'
1470
+		);
1471
+		EE_Registry::$i18n_js_strings['reg_step_error'] = __(
1472
+			'This registration step could not be completed. Please refresh the page and try again.',
1473
+			'event_espresso'
1474
+		);
1475
+		EE_Registry::$i18n_js_strings['invalid_coupon'] = __(
1476
+			'We\'re sorry but that coupon code does not appear to be valid. If this is incorrect, please contact the site administrator.',
1477
+			'event_espresso'
1478
+		);
1479
+		EE_Registry::$i18n_js_strings['process_registration'] = sprintf(
1480
+			__(
1481
+				'Please wait while we process your registration.%sDo not refresh the page or navigate away while this is happening.%sThank you for your patience.',
1482
+				'event_espresso'
1483
+			),
1484
+			'<br/>',
1485
+			'<br/>'
1486
+		);
1487
+		EE_Registry::$i18n_js_strings['language'] = get_bloginfo('language');
1488
+		EE_Registry::$i18n_js_strings['EESID'] = EE_Registry::instance()->SSN->id();
1489
+		EE_Registry::$i18n_js_strings['currency'] = EE_Registry::instance()->CFG->currency;
1490
+		EE_Registry::$i18n_js_strings['datepicker_yearRange'] = '-150:+20';
1491
+		EE_Registry::$i18n_js_strings['timer_years'] = __('years', 'event_espresso');
1492
+		EE_Registry::$i18n_js_strings['timer_months'] = __('months', 'event_espresso');
1493
+		EE_Registry::$i18n_js_strings['timer_weeks'] = __('weeks', 'event_espresso');
1494
+		EE_Registry::$i18n_js_strings['timer_days'] = __('days', 'event_espresso');
1495
+		EE_Registry::$i18n_js_strings['timer_hours'] = __('hours', 'event_espresso');
1496
+		EE_Registry::$i18n_js_strings['timer_minutes'] = __('minutes', 'event_espresso');
1497
+		EE_Registry::$i18n_js_strings['timer_seconds'] = __('seconds', 'event_espresso');
1498
+		EE_Registry::$i18n_js_strings['timer_year'] = __('year', 'event_espresso');
1499
+		EE_Registry::$i18n_js_strings['timer_month'] = __('month', 'event_espresso');
1500
+		EE_Registry::$i18n_js_strings['timer_week'] = __('week', 'event_espresso');
1501
+		EE_Registry::$i18n_js_strings['timer_day'] = __('day', 'event_espresso');
1502
+		EE_Registry::$i18n_js_strings['timer_hour'] = __('hour', 'event_espresso');
1503
+		EE_Registry::$i18n_js_strings['timer_minute'] = __('minute', 'event_espresso');
1504
+		EE_Registry::$i18n_js_strings['timer_second'] = __('second', 'event_espresso');
1505
+		EE_Registry::$i18n_js_strings['registration_expiration_notice'] = sprintf(
1506
+			__(
1507
+				'%1$sWe\'re sorry, but your registration time has expired.%2$s%3$s%4$sIf you still wish to complete your registration, please return to the %5$sEvent List%6$sEvent List%7$s and reselect your tickets if available. Please except our apologies for any inconvenience this may have caused.%8$s',
1508
+				'event_espresso'
1509
+			),
1510
+			'<h4 class="important-notice">',
1511
+			'</h4>',
1512
+			'<br />',
1513
+			'<p>',
1514
+			'<a href="' . get_post_type_archive_link('espresso_events') . '" title="',
1515
+			'">',
1516
+			'</a>',
1517
+			'</p>'
1518
+		);
1519
+		EE_Registry::$i18n_js_strings['ajax_submit'] = apply_filters(
1520
+			'FHEE__Single_Page_Checkout__translate_js_strings__ajax_submit',
1521
+			true
1522
+		);
1523
+		EE_Registry::$i18n_js_strings['session_extension'] = absint(
1524
+			apply_filters('FHEE__EE_Session__extend_expiration__seconds_added', 10 * MINUTE_IN_SECONDS)
1525
+		);
1526
+		EE_Registry::$i18n_js_strings['session_expiration'] = gmdate(
1527
+			'M d, Y H:i:s',
1528
+			EE_Registry::instance()->SSN->expiration() + (get_option('gmt_offset') * HOUR_IN_SECONDS)
1529
+		);
1530
+	}
1531
+
1532
+
1533
+
1534
+	/**
1535
+	 *    enqueue_styles_and_scripts
1536
+	 *
1537
+	 * @access        public
1538
+	 * @return        void
1539
+	 * @throws EE_Error
1540
+	 */
1541
+	public function enqueue_styles_and_scripts()
1542
+	{
1543
+		// load css
1544
+		wp_register_style(
1545
+			'single_page_checkout',
1546
+			SPCO_CSS_URL . 'single_page_checkout.css',
1547
+			array('espresso_default'),
1548
+			EVENT_ESPRESSO_VERSION
1549
+		);
1550
+		wp_enqueue_style('single_page_checkout');
1551
+		// load JS
1552
+		wp_register_script(
1553
+			'jquery_plugin',
1554
+			EE_THIRD_PARTY_URL . 'jquery	.plugin.min.js',
1555
+			array('jquery'),
1556
+			'1.0.1',
1557
+			true
1558
+		);
1559
+		wp_register_script(
1560
+			'jquery_countdown',
1561
+			EE_THIRD_PARTY_URL . 'jquery	.countdown.min.js',
1562
+			array('jquery_plugin'),
1563
+			'2.0.2',
1564
+			true
1565
+		);
1566
+		wp_register_script(
1567
+			'single_page_checkout',
1568
+			SPCO_JS_URL . 'single_page_checkout.js',
1569
+			array('espresso_core', 'underscore', 'ee_form_section_validation', 'jquery_countdown'),
1570
+			EVENT_ESPRESSO_VERSION,
1571
+			true
1572
+		);
1573
+		if ($this->checkout->registration_form instanceof EE_Form_Section_Proper) {
1574
+			$this->checkout->registration_form->enqueue_js();
1575
+		}
1576
+		if ($this->checkout->current_step->reg_form instanceof EE_Form_Section_Proper) {
1577
+			$this->checkout->current_step->reg_form->enqueue_js();
1578
+		}
1579
+		wp_enqueue_script('single_page_checkout');
1580
+		/**
1581
+		 * global action hook for enqueueing styles and scripts with
1582
+		 * spco calls.
1583
+		 */
1584
+		do_action('AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts', $this);
1585
+		/**
1586
+		 * dynamic action hook for enqueueing styles and scripts with spco calls.
1587
+		 * The hook will end up being something like:
1588
+		 *      AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__attendee_information
1589
+		 */
1590
+		do_action(
1591
+			'AHEE__EED_Single_Page_Checkout__enqueue_styles_and_scripts__' . $this->checkout->current_step->slug(),
1592
+			$this
1593
+		);
1594
+	}
1595
+
1596
+
1597
+
1598
+	/**
1599
+	 *    display the Registration Single Page Checkout Form
1600
+	 *
1601
+	 * @access    private
1602
+	 * @return    void
1603
+	 * @throws EE_Error
1604
+	 */
1605
+	private function _display_spco_reg_form()
1606
+	{
1607
+		// if registering via the admin, just display the reg form for the current step
1608
+		if ($this->checkout->admin_request) {
1609
+			EE_Registry::instance()->REQ->add_output($this->checkout->current_step->display_reg_form());
1610
+		} else {
1611
+			// add powered by EE msg
1612
+			add_action('AHEE__SPCO__reg_form_footer', array('EED_Single_Page_Checkout', 'display_registration_footer'));
1613
+			$empty_cart = count(
1614
+				$this->checkout->transaction->registrations($this->checkout->reg_cache_where_params)
1615
+			) < 1;
1616
+			EE_Registry::$i18n_js_strings['empty_cart'] = $empty_cart;
1617
+			$cookies_not_set_msg = '';
1618
+			if ($empty_cart && ! isset($_COOKIE['ee_cookie_test'])) {
1619
+				$cookies_not_set_msg = apply_filters(
1620
+					'FHEE__Single_Page_Checkout__display_spco_reg_form__cookies_not_set_msg',
1621
+					sprintf(
1622
+						__(
1623
+							'%1$s%3$sIt appears your browser is not currently set to accept Cookies%4$s%5$sIn order to register for events, you need to enable cookies.%7$sIf you require assistance, then click the following link to learn how to %8$senable cookies%9$s%6$s%2$s',
1624
+							'event_espresso'
1625
+						),
1626
+						'<div class="ee-attention">',
1627
+						'</div>',
1628
+						'<h6 class="important-notice">',
1629
+						'</h6>',
1630
+						'<p>',
1631
+						'</p>',
1632
+						'<br />',
1633
+						'<a href="http://www.whatarecookies.com/enable.asp" target="_blank">',
1634
+						'</a>'
1635
+					)
1636
+				);
1637
+			}
1638
+			$this->checkout->registration_form = new EE_Form_Section_Proper(
1639
+				array(
1640
+					'name'            => 'single-page-checkout',
1641
+					'html_id'         => 'ee-single-page-checkout-dv',
1642
+					'layout_strategy' =>
1643
+						new EE_Template_Layout(
1644
+							array(
1645
+								'layout_template_file' => SPCO_TEMPLATES_PATH . 'registration_page_wrapper.template.php',
1646
+								'template_args'        => array(
1647
+									'empty_cart'              => $empty_cart,
1648
+									'revisit'                 => $this->checkout->revisit,
1649
+									'reg_steps'               => $this->checkout->reg_steps,
1650
+									'next_step'               => $this->checkout->next_step instanceof EE_SPCO_Reg_Step
1651
+										? $this->checkout->next_step->slug()
1652
+										: '',
1653
+									'cancel_page_url'         => $this->checkout->cancel_page_url,
1654
+									'empty_msg'               => apply_filters(
1655
+										'FHEE__Single_Page_Checkout__display_spco_reg_form__empty_msg',
1656
+										sprintf(
1657
+											__(
1658
+												'You need to %1$sReturn to Events list%2$sselect at least one event%3$s before you can proceed with the registration process.',
1659
+												'event_espresso'
1660
+											),
1661
+											'<a href="'
1662
+											. get_post_type_archive_link('espresso_events')
1663
+											. '" title="',
1664
+											'">',
1665
+											'</a>'
1666
+										)
1667
+									),
1668
+									'cookies_not_set_msg'     => $cookies_not_set_msg,
1669
+									'registration_time_limit' => $this->checkout->get_registration_time_limit(),
1670
+									'session_expiration'      => gmdate(
1671
+										'M d, Y H:i:s',
1672
+										EE_Registry::instance()->SSN->expiration()
1673
+										+ (get_option('gmt_offset') * HOUR_IN_SECONDS)
1674
+									),
1675
+								),
1676
+							)
1677
+						),
1678
+				)
1679
+			);
1680
+			// load template and add to output sent that gets filtered into the_content()
1681
+			EE_Registry::instance()->REQ->add_output($this->checkout->registration_form->get_html());
1682
+		}
1683
+	}
1684
+
1685
+
1686
+
1687
+	/**
1688
+	 *    add_extra_finalize_registration_inputs
1689
+	 *
1690
+	 * @access    public
1691
+	 * @param $next_step
1692
+	 * @internal  param string $label
1693
+	 * @return void
1694
+	 */
1695
+	public function add_extra_finalize_registration_inputs($next_step)
1696
+	{
1697
+		if ($next_step === 'finalize_registration') {
1698
+			echo '<div id="spco-extra-finalize_registration-inputs-dv"></div>';
1699
+		}
1700
+	}
1701
+
1702
+
1703
+
1704
+	/**
1705
+	 *    display_registration_footer
1706
+	 *
1707
+	 * @access    public
1708
+	 * @return    string
1709
+	 */
1710
+	public static function display_registration_footer()
1711
+	{
1712
+		if (
1713
+		apply_filters(
1714
+			'FHEE__EE_Front__Controller__show_reg_footer',
1715
+			EE_Registry::instance()->CFG->admin->show_reg_footer
1716
+		)
1717
+		) {
1718
+			add_filter(
1719
+				'FHEE__EEH_Template__powered_by_event_espresso__url',
1720
+				function ($url) {
1721
+					return apply_filters('FHEE__EE_Front_Controller__registration_footer__url', $url);
1722
+				}
1723
+			);
1724
+			echo apply_filters(
1725
+				'FHEE__EE_Front_Controller__display_registration_footer',
1726
+				\EEH_Template::powered_by_event_espresso(
1727
+					'',
1728
+					'espresso-registration-footer-dv',
1729
+					array('utm_content' => 'registration_checkout')
1730
+				)
1731
+			);
1732
+		}
1733
+		return '';
1734
+	}
1735
+
1736
+
1737
+
1738
+	/**
1739
+	 *    unlock_transaction
1740
+	 *
1741
+	 * @access    public
1742
+	 * @return    void
1743
+	 * @throws EE_Error
1744
+	 */
1745
+	public function unlock_transaction()
1746
+	{
1747
+		if ($this->checkout->transaction instanceof EE_Transaction) {
1748
+			$this->checkout->transaction->unlock();
1749
+		}
1750
+	}
1751
+
1752
+
1753
+
1754
+	/**
1755
+	 *        _setup_redirect
1756
+	 *
1757
+	 * @access    private
1758
+	 * @return void
1759
+	 */
1760
+	private function _setup_redirect()
1761
+	{
1762
+		if ($this->checkout->continue_reg && $this->checkout->next_step instanceof EE_SPCO_Reg_Step) {
1763
+			$this->checkout->redirect = true;
1764
+			if (empty($this->checkout->redirect_url)) {
1765
+				$this->checkout->redirect_url = $this->checkout->next_step->reg_step_url();
1766
+			}
1767
+			$this->checkout->redirect_url = apply_filters(
1768
+				'FHEE__EED_Single_Page_Checkout___setup_redirect__checkout_redirect_url',
1769
+				$this->checkout->redirect_url,
1770
+				$this->checkout
1771
+			);
1772
+		}
1773
+	}
1774
+
1775
+
1776
+
1777
+	/**
1778
+	 *   handle ajax message responses and redirects
1779
+	 *
1780
+	 * @access public
1781
+	 * @return void
1782
+	 * @throws EE_Error
1783
+	 */
1784
+	public function go_to_next_step()
1785
+	{
1786
+		if (EE_Registry::instance()->REQ->ajax) {
1787
+			// capture contents of output buffer we started earlier in the request, and insert into JSON response
1788
+			$this->checkout->json_response->set_unexpected_errors(ob_get_clean());
1789
+		}
1790
+		$this->unlock_transaction();
1791
+		// just return for these conditions
1792
+		if (
1793
+			$this->checkout->admin_request
1794
+			|| $this->checkout->action === 'redirect_form'
1795
+			|| $this->checkout->action === 'update_checkout'
1796
+		) {
1797
+			return;
1798
+		}
1799
+		// AJAX response
1800
+		$this->_handle_json_response();
1801
+		// redirect to next step or the Thank You page
1802
+		$this->_handle_html_redirects();
1803
+		// hmmm... must be something wrong, so let's just display the form again !
1804
+		$this->_display_spco_reg_form();
1805
+	}
1806
+
1807
+
1808
+
1809
+	/**
1810
+	 *   _handle_json_response
1811
+	 *
1812
+	 * @access protected
1813
+	 * @return void
1814
+	 */
1815
+	protected function _handle_json_response()
1816
+	{
1817
+		// if this is an ajax request
1818
+		if (EE_Registry::instance()->REQ->ajax) {
1819
+			// DEBUG LOG
1820
+			//$this->checkout->log(
1821
+			//	__CLASS__, __FUNCTION__, __LINE__,
1822
+			//	array(
1823
+			//		'json_response_redirect_url' => $this->checkout->json_response->redirect_url(),
1824
+			//		'redirect'                   => $this->checkout->redirect,
1825
+			//		'continue_reg'               => $this->checkout->continue_reg,
1826
+			//	)
1827
+			//);
1828
+			$this->checkout->json_response->set_registration_time_limit(
1829
+				$this->checkout->get_registration_time_limit()
1830
+			);
1831
+			$this->checkout->json_response->set_payment_amount($this->checkout->amount_owing);
1832
+			// just send the ajax (
1833
+			$json_response = apply_filters(
1834
+				'FHEE__EE_Single_Page_Checkout__JSON_response',
1835
+				$this->checkout->json_response
1836
+			);
1837
+			echo $json_response;
1838
+			exit();
1839
+		}
1840
+	}
1841
+
1842
+
1843
+
1844
+	/**
1845
+	 *   _handle_redirects
1846
+	 *
1847
+	 * @access protected
1848
+	 * @return void
1849
+	 */
1850
+	protected function _handle_html_redirects()
1851
+	{
1852
+		// going somewhere ?
1853
+		if ($this->checkout->redirect && ! empty($this->checkout->redirect_url)) {
1854
+			// store notices in a transient
1855
+			EE_Error::get_notices(false, true, true);
1856
+			// DEBUG LOG
1857
+			//$this->checkout->log(
1858
+			//	__CLASS__, __FUNCTION__, __LINE__,
1859
+			//	array(
1860
+			//		'headers_sent' => headers_sent(),
1861
+			//		'redirect_url'     => $this->checkout->redirect_url,
1862
+			//		'headers_list'    => headers_list(),
1863
+			//	)
1864
+			//);
1865
+			wp_safe_redirect($this->checkout->redirect_url);
1866
+			exit();
1867
+		}
1868
+	}
1869
+
1870
+
1871
+
1872
+	/**
1873
+	 *   set_checkout_anchor
1874
+	 *
1875
+	 * @access public
1876
+	 * @return void
1877
+	 */
1878
+	public function set_checkout_anchor()
1879
+	{
1880
+		echo '<a id="checkout" style="float: left; margin-left: -999em;"></a>';
1881
+	}
1882 1882
 
1883 1883
 
1884 1884
 
Please login to merge, or discard this patch.