Completed
Branch BUG-10878-event-spaces-remaini... (def5f8)
by
unknown
65:16 queued 53:59
created
core/db_models/EEM_Base.model.php 3 patches
Doc Comments   +15 added lines, -13 removed lines patch added patch discarded remove patch
@@ -967,7 +967,7 @@  discard block
 block discarded – undo
967 967
      *  on this model (or follows the _model_chain_to_wp_user and uses that model's
968 968
      * foreign key to the WP_User table)
969 969
      *
970
-     * @return string|boolean string on success, boolean false when there is no
970
+     * @return string|false string on success, boolean false when there is no
971 971
      * foreign key to the WP_User table
972 972
      */
973 973
     public function wp_user_field_name()
@@ -1072,7 +1072,7 @@  discard block
 block discarded – undo
1072 1072
      *
1073 1073
      * @param array  $query_params      like EEM_Base::get_all's $query_params
1074 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
1075
+     * @param string  $columns_to_select , What columns to select. By default, we select all columns specified by the
1076 1076
      *                                  fields on the model, and the models we joined to in the query. However, you can
1077 1077
      *                                  override this and set the select to "*", or a specific column name, like
1078 1078
      *                                  "ATT_ID", etc. If you would like to use these custom selections in WHERE,
@@ -1486,7 +1486,7 @@  discard block
 block discarded – undo
1486 1486
      * @param string $field_name The name of the field the formats are being retrieved for.
1487 1487
      * @param bool   $pretty     Whether to return the pretty formats (true) or not (false).
1488 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.
1489
+     * @return string[] formats in an array with the date format first, and the time format last.
1490 1490
      */
1491 1491
     public function get_formats_for($field_name, $pretty = false)
1492 1492
     {
@@ -1521,7 +1521,7 @@  discard block
 block discarded – undo
1521 1521
      *                                 be returned.
1522 1522
      * @param string $what             Whether to return the string in just the time format, the date format, or both.
1523 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
1524
+     * @return string|null  If the given field_name is not of the EE_Datetime_Field type, then an EE_Error
1525 1525
      *                                 exception is triggered.
1526 1526
      */
1527 1527
     public function current_time_for_query($field_name, $timestamp = false, $what = 'both')
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
      *                                the blog.  If this is not the case, then it can be specified here.  If incoming
1562 1562
      *                                format is
1563 1563
      *                                'U', this is ignored.
1564
-     * @return DateTime
1564
+     * @return string
1565 1565
      * @throws EE_Error
1566 1566
      */
1567 1567
     public function convert_datetime_for_query($field_name, $timestring, $incoming_format, $timezone = '')
@@ -2426,7 +2426,7 @@  discard block
 block discarded – undo
2426 2426
      * Verifies the EE addons' database is up-to-date and records that we've done it on
2427 2427
      * EEM_Base::$_db_verification_level
2428 2428
      *
2429
-     * @param $wpdb_method
2429
+     * @param string $wpdb_method
2430 2430
      * @param $arguments_to_provide
2431 2431
      * @return string
2432 2432
      */
@@ -2550,6 +2550,7 @@  discard block
 block discarded – undo
2550 2550
      *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2551 2551
      *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2552 2552
      *                             because these will be inserted in any new rows created as well.
2553
+     * @param EE_Base_Class $id_or_obj
2553 2554
      */
2554 2555
     public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2555 2556
     {
@@ -2560,7 +2561,7 @@  discard block
 block discarded – undo
2560 2561
 
2561 2562
 
2562 2563
     /**
2563
-     * @param mixed           $id_or_obj
2564
+     * @param EE_Base_Class           $id_or_obj
2564 2565
      * @param string          $relationName
2565 2566
      * @param array           $where_query_params
2566 2567
      * @param EE_Base_Class[] objects to which relations were removed
@@ -2601,7 +2602,7 @@  discard block
 block discarded – undo
2601 2602
      * However, if the model objects can't be deleted because of blocking related model objects, then
2602 2603
      * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2603 2604
      *
2604
-     * @param EE_Base_Class|int|string $id_or_obj
2605
+     * @param EE_Base_Class $id_or_obj
2605 2606
      * @param string                   $model_name
2606 2607
      * @param array                    $query_params
2607 2608
      * @return int how many deleted
@@ -2622,7 +2623,7 @@  discard block
 block discarded – undo
2622 2623
      * the model objects can't be hard deleted because of blocking related model objects,
2623 2624
      * just does a soft-delete on them instead.
2624 2625
      *
2625
-     * @param EE_Base_Class|int|string $id_or_obj
2626
+     * @param EE_Base_Class $id_or_obj
2626 2627
      * @param string                   $model_name
2627 2628
      * @param array                    $query_params
2628 2629
      * @return int how many deleted
@@ -2679,6 +2680,7 @@  discard block
 block discarded – undo
2679 2680
      * @param string $model_name   like 'Event', or 'Registration'
2680 2681
      * @param array  $query_params like EEM_Base::get_all's
2681 2682
      * @param string $field_to_sum name of field to count by. By default, uses primary key
2683
+     * @param EE_Base_Class $id_or_obj
2682 2684
      * @return float
2683 2685
      * @throws EE_Error
2684 2686
      */
@@ -3639,7 +3641,7 @@  discard block
 block discarded – undo
3639 3641
      * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3640 3642
      * We should use default where conditions on related models when they requested to use default where conditions
3641 3643
      * on all models, or specifically just on other related models
3642
-     * @param      $default_where_conditions_value
3644
+     * @param      string $default_where_conditions_value
3643 3645
      * @param bool $for_this_model false means this is for OTHER related models
3644 3646
      * @return bool
3645 3647
      */
@@ -3677,7 +3679,7 @@  discard block
 block discarded – undo
3677 3679
      * where conditions.
3678 3680
      * We should use minimum where conditions on related models if they requested to use minimum where conditions
3679 3681
      * on this model or others
3680
-     * @param      $default_where_conditions_value
3682
+     * @param      string $default_where_conditions_value
3681 3683
      * @param bool $for_this_model false means this is for OTHER related models
3682 3684
      * @return bool
3683 3685
      */
@@ -4732,7 +4734,7 @@  discard block
 block discarded – undo
4732 4734
      * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4733 4735
      * Eg, on EE_Answer that would be ANS_ID field object
4734 4736
      *
4735
-     * @param $field_obj
4737
+     * @param EE_Model_Field_Base $field_obj
4736 4738
      * @return boolean
4737 4739
      */
4738 4740
     public function is_primary_key_field($field_obj)
@@ -5450,7 +5452,7 @@  discard block
 block discarded – undo
5450 5452
     /**
5451 5453
      * Read comments for assume_values_already_prepared_by_model_object()
5452 5454
      *
5453
-     * @return int
5455
+     * @return boolean
5454 5456
      */
5455 5457
     public function get_assumption_concerning_values_already_prepared_by_model_object()
5456 5458
     {
Please login to merge, or discard this patch.
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[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2190
-            }
2191
-            $query_part = implode(' OR ', $ways_to_identify_a_row);
2192
-        }
2193
-        return $query_part;
2194
-    }
2195
-
2196
-
2197
-
2198
-    /**
2199
-     * Gets the model field by the fully qualified name
2200
-     * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2201
-     * @return EE_Model_Field_Base
2202
-     */
2203
-    public function get_field_by_column($qualified_column_name)
2204
-    {
2205
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2206
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2207
-               return $field_obj;
2208
-           }
2209
-       }
2210
-        throw new EE_Error(
2211
-            sprintf(
2212
-                esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2213
-                $this->get_this_model_name(),
2214
-                $qualified_column_name
2215
-            )
2216
-        );
2217
-    }
2218
-
2219
-
2220
-
2221
-    /**
2222
-     * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2223
-     * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2224
-     * column
2225
-     *
2226
-     * @param array  $query_params   like EEM_Base::get_all's
2227
-     * @param string $field_to_count field on model to count by (not column name)
2228
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2229
-     *                               that by the setting $distinct to TRUE;
2230
-     * @return int
2231
-     * @throws EE_Error
2232
-     */
2233
-    public function count($query_params = array(), $field_to_count = null, $distinct = false)
2234
-    {
2235
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2236
-        if ($field_to_count) {
2237
-            $field_obj = $this->field_settings_for($field_to_count);
2238
-            $column_to_count = $field_obj->get_qualified_column();
2239
-        } elseif ($this->has_primary_key_field()) {
2240
-            $pk_field_obj = $this->get_primary_key_field();
2241
-            $column_to_count = $pk_field_obj->get_qualified_column();
2242
-        } else {
2243
-            //there's no primary key
2244
-            //if we're counting distinct items, and there's no primary key,
2245
-            //we need to list out the columns for distinction;
2246
-            //otherwise we can just use star
2247
-            if ($distinct) {
2248
-                $columns_to_use = array();
2249
-                foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2250
-                    $columns_to_use[] = $field_obj->get_qualified_column();
2251
-                }
2252
-                $column_to_count = implode(',', $columns_to_use);
2253
-            } else {
2254
-                $column_to_count = '*';
2255
-            }
2256
-        }
2257
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2258
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2259
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2260
-    }
2261
-
2262
-
2263
-
2264
-    /**
2265
-     * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2266
-     *
2267
-     * @param array  $query_params like EEM_Base::get_all
2268
-     * @param string $field_to_sum name of field (array key in $_fields array)
2269
-     * @return float
2270
-     * @throws EE_Error
2271
-     */
2272
-    public function sum($query_params, $field_to_sum = null)
2273
-    {
2274
-        $model_query_info = $this->_create_model_query_info_carrier($query_params);
2275
-        if ($field_to_sum) {
2276
-            $field_obj = $this->field_settings_for($field_to_sum);
2277
-        } else {
2278
-            $field_obj = $this->get_primary_key_field();
2279
-        }
2280
-        $column_to_count = $field_obj->get_qualified_column();
2281
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2282
-        $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2283
-        $data_type = $field_obj->get_wpdb_data_type();
2284
-        if ($data_type === '%d' || $data_type === '%s') {
2285
-            return (float)$return_value;
2286
-        }
2287
-        //must be %f
2288
-        return (float)$return_value;
2289
-    }
2290
-
2291
-
2292
-
2293
-    /**
2294
-     * Just calls the specified method on $wpdb with the given arguments
2295
-     * Consolidates a little extra error handling code
2296
-     *
2297
-     * @param string $wpdb_method
2298
-     * @param array  $arguments_to_provide
2299
-     * @throws EE_Error
2300
-     * @global wpdb  $wpdb
2301
-     * @return mixed
2302
-     */
2303
-    protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2304
-    {
2305
-        //if we're in maintenance mode level 2, DON'T run any queries
2306
-        //because level 2 indicates the database needs updating and
2307
-        //is probably out of sync with the code
2308
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2309
-            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.",
2310
-                "event_espresso")));
2311
-        }
2312
-        /** @type WPDB $wpdb */
2313
-        global $wpdb;
2314
-        if (! method_exists($wpdb, $wpdb_method)) {
2315
-            throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2316
-                'event_espresso'), $wpdb_method));
2317
-        }
2318
-        if (WP_DEBUG) {
2319
-            $old_show_errors_value = $wpdb->show_errors;
2320
-            $wpdb->show_errors(false);
2321
-        }
2322
-        $result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2323
-        $this->show_db_query_if_previously_requested($wpdb->last_query);
2324
-        if (WP_DEBUG) {
2325
-            $wpdb->show_errors($old_show_errors_value);
2326
-            if (! empty($wpdb->last_error)) {
2327
-                throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2328
-            }
2329
-            if ($result === false) {
2330
-                throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2331
-                    'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2332
-            }
2333
-        } elseif ($result === false) {
2334
-            EE_Error::add_error(
2335
-                sprintf(
2336
-                    __('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"',
2337
-                        'event_espresso'),
2338
-                    $wpdb_method,
2339
-                    var_export($arguments_to_provide, true),
2340
-                    $wpdb->last_error
2341
-                ),
2342
-                __FILE__,
2343
-                __FUNCTION__,
2344
-                __LINE__
2345
-            );
2346
-        }
2347
-        return $result;
2348
-    }
2349
-
2350
-
2351
-
2352
-    /**
2353
-     * Attempts to run the indicated WPDB method with the provided arguments,
2354
-     * and if there's an error tries to verify the DB is correct. Uses
2355
-     * the static property EEM_Base::$_db_verification_level to determine whether
2356
-     * we should try to fix the EE core db, the addons, or just give up
2357
-     *
2358
-     * @param string $wpdb_method
2359
-     * @param array  $arguments_to_provide
2360
-     * @return mixed
2361
-     */
2362
-    private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2363
-    {
2364
-        /** @type WPDB $wpdb */
2365
-        global $wpdb;
2366
-        $wpdb->last_error = null;
2367
-        $result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2368
-        // was there an error running the query? but we don't care on new activations
2369
-        // (we're going to setup the DB anyway on new activations)
2370
-        if (($result === false || ! empty($wpdb->last_error))
2371
-            && EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2372
-        ) {
2373
-            switch (EEM_Base::$_db_verification_level) {
2374
-                case EEM_Base::db_verified_none :
2375
-                    // let's double-check core's DB
2376
-                    $error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2377
-                    break;
2378
-                case EEM_Base::db_verified_core :
2379
-                    // STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2380
-                    $error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2381
-                    break;
2382
-                case EEM_Base::db_verified_addons :
2383
-                    // ummmm... you in trouble
2384
-                    return $result;
2385
-                    break;
2386
-            }
2387
-            if (! empty($error_message)) {
2388
-                EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2389
-                trigger_error($error_message);
2390
-            }
2391
-            return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2392
-        }
2393
-        return $result;
2394
-    }
2395
-
2396
-
2397
-
2398
-    /**
2399
-     * Verifies the EE core database is up-to-date and records that we've done it on
2400
-     * EEM_Base::$_db_verification_level
2401
-     *
2402
-     * @param string $wpdb_method
2403
-     * @param array  $arguments_to_provide
2404
-     * @return string
2405
-     */
2406
-    private function _verify_core_db($wpdb_method, $arguments_to_provide)
2407
-    {
2408
-        /** @type WPDB $wpdb */
2409
-        global $wpdb;
2410
-        //ok remember that we've already attempted fixing the core db, in case the problem persists
2411
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2412
-        $error_message = sprintf(
2413
-            __('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2414
-                'event_espresso'),
2415
-            $wpdb->last_error,
2416
-            $wpdb_method,
2417
-            wp_json_encode($arguments_to_provide)
2418
-        );
2419
-        EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2420
-        return $error_message;
2421
-    }
2422
-
2423
-
2424
-
2425
-    /**
2426
-     * Verifies the EE addons' database is up-to-date and records that we've done it on
2427
-     * EEM_Base::$_db_verification_level
2428
-     *
2429
-     * @param $wpdb_method
2430
-     * @param $arguments_to_provide
2431
-     * @return string
2432
-     */
2433
-    private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2434
-    {
2435
-        /** @type WPDB $wpdb */
2436
-        global $wpdb;
2437
-        //ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2438
-        EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2439
-        $error_message = sprintf(
2440
-            __('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2441
-                'event_espresso'),
2442
-            $wpdb->last_error,
2443
-            $wpdb_method,
2444
-            wp_json_encode($arguments_to_provide)
2445
-        );
2446
-        EE_System::instance()->initialize_addons();
2447
-        return $error_message;
2448
-    }
2449
-
2450
-
2451
-
2452
-    /**
2453
-     * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2454
-     * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2455
-     * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2456
-     * ..."
2457
-     *
2458
-     * @param EE_Model_Query_Info_Carrier $model_query_info
2459
-     * @return string
2460
-     */
2461
-    private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2462
-    {
2463
-        return " FROM " . $model_query_info->get_full_join_sql() .
2464
-               $model_query_info->get_where_sql() .
2465
-               $model_query_info->get_group_by_sql() .
2466
-               $model_query_info->get_having_sql() .
2467
-               $model_query_info->get_order_by_sql() .
2468
-               $model_query_info->get_limit_sql();
2469
-    }
2470
-
2471
-
2472
-
2473
-    /**
2474
-     * Set to easily debug the next X queries ran from this model.
2475
-     *
2476
-     * @param int $count
2477
-     */
2478
-    public function show_next_x_db_queries($count = 1)
2479
-    {
2480
-        $this->_show_next_x_db_queries = $count;
2481
-    }
2482
-
2483
-
2484
-
2485
-    /**
2486
-     * @param $sql_query
2487
-     */
2488
-    public function show_db_query_if_previously_requested($sql_query)
2489
-    {
2490
-        if ($this->_show_next_x_db_queries > 0) {
2491
-            echo $sql_query;
2492
-            $this->_show_next_x_db_queries--;
2493
-        }
2494
-    }
2495
-
2496
-
2497
-
2498
-    /**
2499
-     * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2500
-     * There are the 3 cases:
2501
-     * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2502
-     * $otherModelObject has no ID, it is first saved.
2503
-     * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2504
-     * has no ID, it is first saved.
2505
-     * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2506
-     * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2507
-     * join table
2508
-     *
2509
-     * @param        EE_Base_Class                     /int $thisModelObject
2510
-     * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2511
-     * @param string $relationName                     , key in EEM_Base::_relations
2512
-     *                                                 an attendee to a group, you also want to specify which role they
2513
-     *                                                 will have in that group. So you would use this parameter to
2514
-     *                                                 specify array('role-column-name'=>'role-id')
2515
-     * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2516
-     *                                                 to for relation to methods that allow you to further specify
2517
-     *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2518
-     *                                                 only acceptable query_params is strict "col" => "value" pairs
2519
-     *                                                 because these will be inserted in any new rows created as well.
2520
-     * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2521
-     * @throws EE_Error
2522
-     */
2523
-    public function add_relationship_to(
2524
-        $id_or_obj,
2525
-        $other_model_id_or_obj,
2526
-        $relationName,
2527
-        $extra_join_model_fields_n_values = array()
2528
-    ) {
2529
-        $relation_obj = $this->related_settings_for($relationName);
2530
-        return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2531
-    }
2532
-
2533
-
2534
-
2535
-    /**
2536
-     * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2537
-     * There are the 3 cases:
2538
-     * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2539
-     * error
2540
-     * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2541
-     * an error
2542
-     * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2543
-     *
2544
-     * @param        EE_Base_Class /int $id_or_obj
2545
-     * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2546
-     * @param string $relationName key in EEM_Base::_relations
2547
-     * @return boolean of success
2548
-     * @throws EE_Error
2549
-     * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2550
-     *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2551
-     *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2552
-     *                             because these will be inserted in any new rows created as well.
2553
-     */
2554
-    public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2555
-    {
2556
-        $relation_obj = $this->related_settings_for($relationName);
2557
-        return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2558
-    }
2559
-
2560
-
2561
-
2562
-    /**
2563
-     * @param mixed           $id_or_obj
2564
-     * @param string          $relationName
2565
-     * @param array           $where_query_params
2566
-     * @param EE_Base_Class[] objects to which relations were removed
2567
-     * @return \EE_Base_Class[]
2568
-     * @throws EE_Error
2569
-     */
2570
-    public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2571
-    {
2572
-        $relation_obj = $this->related_settings_for($relationName);
2573
-        return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2574
-    }
2575
-
2576
-
2577
-
2578
-    /**
2579
-     * Gets all the related items of the specified $model_name, using $query_params.
2580
-     * Note: by default, we remove the "default query params"
2581
-     * because we want to get even deleted items etc.
2582
-     *
2583
-     * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2584
-     * @param string $model_name   like 'Event', 'Registration', etc. always singular
2585
-     * @param array  $query_params like EEM_Base::get_all
2586
-     * @return EE_Base_Class[]
2587
-     * @throws EE_Error
2588
-     */
2589
-    public function get_all_related($id_or_obj, $model_name, $query_params = null)
2590
-    {
2591
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2592
-        $relation_settings = $this->related_settings_for($model_name);
2593
-        return $relation_settings->get_all_related($model_obj, $query_params);
2594
-    }
2595
-
2596
-
2597
-
2598
-    /**
2599
-     * Deletes all the model objects across the relation indicated by $model_name
2600
-     * which are related to $id_or_obj which meet the criteria set in $query_params.
2601
-     * However, if the model objects can't be deleted because of blocking related model objects, then
2602
-     * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2603
-     *
2604
-     * @param EE_Base_Class|int|string $id_or_obj
2605
-     * @param string                   $model_name
2606
-     * @param array                    $query_params
2607
-     * @return int how many deleted
2608
-     * @throws EE_Error
2609
-     */
2610
-    public function delete_related($id_or_obj, $model_name, $query_params = array())
2611
-    {
2612
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2613
-        $relation_settings = $this->related_settings_for($model_name);
2614
-        return $relation_settings->delete_all_related($model_obj, $query_params);
2615
-    }
2616
-
2617
-
2618
-
2619
-    /**
2620
-     * Hard deletes all the model objects across the relation indicated by $model_name
2621
-     * which are related to $id_or_obj which meet the criteria set in $query_params. If
2622
-     * the model objects can't be hard deleted because of blocking related model objects,
2623
-     * just does a soft-delete on them instead.
2624
-     *
2625
-     * @param EE_Base_Class|int|string $id_or_obj
2626
-     * @param string                   $model_name
2627
-     * @param array                    $query_params
2628
-     * @return int how many deleted
2629
-     * @throws EE_Error
2630
-     */
2631
-    public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2632
-    {
2633
-        $model_obj = $this->ensure_is_obj($id_or_obj);
2634
-        $relation_settings = $this->related_settings_for($model_name);
2635
-        return $relation_settings->delete_related_permanently($model_obj, $query_params);
2636
-    }
2637
-
2638
-
2639
-
2640
-    /**
2641
-     * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2642
-     * unless otherwise specified in the $query_params
2643
-     *
2644
-     * @param        int             /EE_Base_Class $id_or_obj
2645
-     * @param string $model_name     like 'Event', or 'Registration'
2646
-     * @param array  $query_params   like EEM_Base::get_all's
2647
-     * @param string $field_to_count name of field to count by. By default, uses primary key
2648
-     * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2649
-     *                               that by the setting $distinct to TRUE;
2650
-     * @return int
2651
-     * @throws EE_Error
2652
-     */
2653
-    public function count_related(
2654
-        $id_or_obj,
2655
-        $model_name,
2656
-        $query_params = array(),
2657
-        $field_to_count = null,
2658
-        $distinct = false
2659
-    ) {
2660
-        $related_model = $this->get_related_model_obj($model_name);
2661
-        //we're just going to use the query params on the related model's normal get_all query,
2662
-        //except add a condition to say to match the current mod
2663
-        if (! isset($query_params['default_where_conditions'])) {
2664
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2665
-        }
2666
-        $this_model_name = $this->get_this_model_name();
2667
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2668
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2669
-        return $related_model->count($query_params, $field_to_count, $distinct);
2670
-    }
2671
-
2672
-
2673
-
2674
-    /**
2675
-     * Instead of getting the related model objects, simply sums up the values of the specified field.
2676
-     * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2677
-     *
2678
-     * @param        int           /EE_Base_Class $id_or_obj
2679
-     * @param string $model_name   like 'Event', or 'Registration'
2680
-     * @param array  $query_params like EEM_Base::get_all's
2681
-     * @param string $field_to_sum name of field to count by. By default, uses primary key
2682
-     * @return float
2683
-     * @throws EE_Error
2684
-     */
2685
-    public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2686
-    {
2687
-        $related_model = $this->get_related_model_obj($model_name);
2688
-        if (! is_array($query_params)) {
2689
-            EE_Error::doing_it_wrong('EEM_Base::sum_related',
2690
-                sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2691
-                    gettype($query_params)), '4.6.0');
2692
-            $query_params = array();
2693
-        }
2694
-        //we're just going to use the query params on the related model's normal get_all query,
2695
-        //except add a condition to say to match the current mod
2696
-        if (! isset($query_params['default_where_conditions'])) {
2697
-            $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2698
-        }
2699
-        $this_model_name = $this->get_this_model_name();
2700
-        $this_pk_field_name = $this->get_primary_key_field()->get_name();
2701
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2702
-        return $related_model->sum($query_params, $field_to_sum);
2703
-    }
2704
-
2705
-
2706
-
2707
-    /**
2708
-     * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2709
-     * $modelObject
2710
-     *
2711
-     * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2712
-     * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2713
-     * @param array               $query_params     like EEM_Base::get_all's
2714
-     * @return EE_Base_Class
2715
-     * @throws EE_Error
2716
-     */
2717
-    public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2718
-    {
2719
-        $query_params['limit'] = 1;
2720
-        $results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2721
-        if ($results) {
2722
-            return array_shift($results);
2723
-        }
2724
-        return null;
2725
-    }
2726
-
2727
-
2728
-
2729
-    /**
2730
-     * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2731
-     *
2732
-     * @return string
2733
-     */
2734
-    public function get_this_model_name()
2735
-    {
2736
-        return str_replace("EEM_", "", get_class($this));
2737
-    }
2738
-
2739
-
2740
-
2741
-    /**
2742
-     * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2743
-     *
2744
-     * @return EE_Any_Foreign_Model_Name_Field
2745
-     * @throws EE_Error
2746
-     */
2747
-    public function get_field_containing_related_model_name()
2748
-    {
2749
-        foreach ($this->field_settings(true) as $field) {
2750
-            if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2751
-                $field_with_model_name = $field;
2752
-            }
2753
-        }
2754
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2755
-            throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2756
-                $this->get_this_model_name()));
2757
-        }
2758
-        return $field_with_model_name;
2759
-    }
2760
-
2761
-
2762
-
2763
-    /**
2764
-     * Inserts a new entry into the database, for each table.
2765
-     * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2766
-     * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2767
-     * we also know there is no model object with the newly inserted item's ID at the moment (because
2768
-     * if there were, then they would already be in the DB and this would fail); and in the future if someone
2769
-     * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2770
-     * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2771
-     *
2772
-     * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2773
-     *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2774
-     *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2775
-     *                              of EEM_Base)
2776
-     * @return int new primary key on main table that got inserted
2777
-     * @throws EE_Error
2778
-     */
2779
-    public function insert($field_n_values)
2780
-    {
2781
-        /**
2782
-         * Filters the fields and their values before inserting an item using the models
2783
-         *
2784
-         * @param array    $fields_n_values keys are the fields and values are their new values
2785
-         * @param EEM_Base $model           the model used
2786
-         */
2787
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2788
-        if ($this->_satisfies_unique_indexes($field_n_values)) {
2789
-            $main_table = $this->_get_main_table();
2790
-            $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2791
-            if ($new_id !== false) {
2792
-                foreach ($this->_get_other_tables() as $other_table) {
2793
-                    $this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2794
-                }
2795
-            }
2796
-            /**
2797
-             * Done just after attempting to insert a new model object
2798
-             *
2799
-             * @param EEM_Base   $model           used
2800
-             * @param array      $fields_n_values fields and their values
2801
-             * @param int|string the              ID of the newly-inserted model object
2802
-             */
2803
-            do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2804
-            return $new_id;
2805
-        }
2806
-        return false;
2807
-    }
2808
-
2809
-
2810
-
2811
-    /**
2812
-     * Checks that the result would satisfy the unique indexes on this model
2813
-     *
2814
-     * @param array  $field_n_values
2815
-     * @param string $action
2816
-     * @return boolean
2817
-     * @throws EE_Error
2818
-     */
2819
-    protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2820
-    {
2821
-        foreach ($this->unique_indexes() as $index_name => $index) {
2822
-            $uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2823
-            if ($this->exists(array($uniqueness_where_params))) {
2824
-                EE_Error::add_error(
2825
-                    sprintf(
2826
-                        __(
2827
-                            "Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2828
-                            "event_espresso"
2829
-                        ),
2830
-                        $action,
2831
-                        $this->_get_class_name(),
2832
-                        $index_name,
2833
-                        implode(",", $index->field_names()),
2834
-                        http_build_query($uniqueness_where_params)
2835
-                    ),
2836
-                    __FILE__,
2837
-                    __FUNCTION__,
2838
-                    __LINE__
2839
-                );
2840
-                return false;
2841
-            }
2842
-        }
2843
-        return true;
2844
-    }
2845
-
2846
-
2847
-
2848
-    /**
2849
-     * Checks the database for an item that conflicts (ie, if this item were
2850
-     * saved to the DB would break some uniqueness requirement, like a primary key
2851
-     * or an index primary key set) with the item specified. $id_obj_or_fields_array
2852
-     * can be either an EE_Base_Class or an array of fields n values
2853
-     *
2854
-     * @param EE_Base_Class|array $obj_or_fields_array
2855
-     * @param boolean             $include_primary_key whether to use the model object's primary key
2856
-     *                                                 when looking for conflicts
2857
-     *                                                 (ie, if false, we ignore the model object's primary key
2858
-     *                                                 when finding "conflicts". If true, it's also considered).
2859
-     *                                                 Only works for INT primary key,
2860
-     *                                                 STRING primary keys cannot be ignored
2861
-     * @throws EE_Error
2862
-     * @return EE_Base_Class|array
2863
-     */
2864
-    public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2865
-    {
2866
-        if ($obj_or_fields_array instanceof EE_Base_Class) {
2867
-            $fields_n_values = $obj_or_fields_array->model_field_array();
2868
-        } elseif (is_array($obj_or_fields_array)) {
2869
-            $fields_n_values = $obj_or_fields_array;
2870
-        } else {
2871
-            throw new EE_Error(
2872
-                sprintf(
2873
-                    __(
2874
-                        "%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2875
-                        "event_espresso"
2876
-                    ),
2877
-                    get_class($this),
2878
-                    $obj_or_fields_array
2879
-                )
2880
-            );
2881
-        }
2882
-        $query_params = array();
2883
-        if ($this->has_primary_key_field()
2884
-            && ($include_primary_key
2885
-                || $this->get_primary_key_field()
2886
-                   instanceof
2887
-                   EE_Primary_Key_String_Field)
2888
-            && isset($fields_n_values[$this->primary_key_name()])
2889
-        ) {
2890
-            $query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2891
-        }
2892
-        foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2893
-            $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2894
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2895
-        }
2896
-        //if there is nothing to base this search on, then we shouldn't find anything
2897
-        if (empty($query_params)) {
2898
-            return array();
2899
-        }
2900
-        return $this->get_one($query_params);
2901
-    }
2902
-
2903
-
2904
-
2905
-    /**
2906
-     * Like count, but is optimized and returns a boolean instead of an int
2907
-     *
2908
-     * @param array $query_params
2909
-     * @return boolean
2910
-     * @throws EE_Error
2911
-     */
2912
-    public function exists($query_params)
2913
-    {
2914
-        $query_params['limit'] = 1;
2915
-        return $this->count($query_params) > 0;
2916
-    }
2917
-
2918
-
2919
-
2920
-    /**
2921
-     * Wrapper for exists, except ignores default query parameters so we're only considering ID
2922
-     *
2923
-     * @param int|string $id
2924
-     * @return boolean
2925
-     * @throws EE_Error
2926
-     */
2927
-    public function exists_by_ID($id)
2928
-    {
2929
-        return $this->exists(
2930
-            array(
2931
-                'default_where_conditions' => EEM_Base::default_where_conditions_none,
2932
-                array(
2933
-                    $this->primary_key_name() => $id,
2934
-                ),
2935
-            )
2936
-        );
2937
-    }
2938
-
2939
-
2940
-
2941
-    /**
2942
-     * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2943
-     * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2944
-     * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2945
-     * on the main table)
2946
-     * This is protected rather than private because private is not accessible to any child methods and there MAY be
2947
-     * cases where we want to call it directly rather than via insert().
2948
-     *
2949
-     * @access   protected
2950
-     * @param EE_Table_Base $table
2951
-     * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2952
-     *                                       float
2953
-     * @param int           $new_id          for now we assume only int keys
2954
-     * @throws EE_Error
2955
-     * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2956
-     * @return int ID of new row inserted, or FALSE on failure
2957
-     */
2958
-    protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2959
-    {
2960
-        global $wpdb;
2961
-        $insertion_col_n_values = array();
2962
-        $format_for_insertion = array();
2963
-        $fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2964
-        foreach ($fields_on_table as $field_name => $field_obj) {
2965
-            //check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2966
-            if ($field_obj->is_auto_increment()) {
2967
-                continue;
2968
-            }
2969
-            $prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2970
-            //if the value we want to assign it to is NULL, just don't mention it for the insertion
2971
-            if ($prepared_value !== null) {
2972
-                $insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2973
-                $format_for_insertion[] = $field_obj->get_wpdb_data_type();
2974
-            }
2975
-        }
2976
-        if ($table instanceof EE_Secondary_Table && $new_id) {
2977
-            //its not the main table, so we should have already saved the main table's PK which we just inserted
2978
-            //so add the fk to the main table as a column
2979
-            $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2980
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2981
-        }
2982
-        //insert the new entry
2983
-        $result = $this->_do_wpdb_query('insert',
2984
-            array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2985
-        if ($result === false) {
2986
-            return false;
2987
-        }
2988
-        //ok, now what do we return for the ID of the newly-inserted thing?
2989
-        if ($this->has_primary_key_field()) {
2990
-            if ($this->get_primary_key_field()->is_auto_increment()) {
2991
-                return $wpdb->insert_id;
2992
-            }
2993
-            //it's not an auto-increment primary key, so
2994
-            //it must have been supplied
2995
-            return $fields_n_values[$this->get_primary_key_field()->get_name()];
2996
-        }
2997
-        //we can't return a  primary key because there is none. instead return
2998
-        //a unique string indicating this model
2999
-        return $this->get_index_primary_key_string($fields_n_values);
3000
-    }
3001
-
3002
-
3003
-
3004
-    /**
3005
-     * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3006
-     * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3007
-     * and there is no default, we pass it along. WPDB will take care of it)
3008
-     *
3009
-     * @param EE_Model_Field_Base $field_obj
3010
-     * @param array               $fields_n_values
3011
-     * @return mixed string|int|float depending on what the table column will be expecting
3012
-     * @throws EE_Error
3013
-     */
3014
-    protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3015
-    {
3016
-        //if this field doesn't allow nullable, don't allow it
3017
-        if (
3018
-            ! $field_obj->is_nullable()
3019
-            && (
3020
-                ! isset($fields_n_values[$field_obj->get_name()])
3021
-                || $fields_n_values[$field_obj->get_name()] === null
3022
-            )
3023
-        ) {
3024
-            $fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3025
-        }
3026
-        $unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3027
-            ? $fields_n_values[$field_obj->get_name()]
3028
-            : null;
3029
-        return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3030
-    }
3031
-
3032
-
3033
-
3034
-    /**
3035
-     * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3036
-     * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3037
-     * the field's prepare_for_set() method.
3038
-     *
3039
-     * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3040
-     *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3041
-     *                                   top of file)
3042
-     * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3043
-     *                                   $value is a custom selection
3044
-     * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3045
-     */
3046
-    private function _prepare_value_for_use_in_db($value, $field)
3047
-    {
3048
-        if ($field && $field instanceof EE_Model_Field_Base) {
3049
-            switch ($this->_values_already_prepared_by_model_object) {
3050
-                /** @noinspection PhpMissingBreakStatementInspection */
3051
-                case self::not_prepared_by_model_object:
3052
-                    $value = $field->prepare_for_set($value);
3053
-                //purposefully left out "return"
3054
-                case self::prepared_by_model_object:
3055
-                    /** @noinspection SuspiciousAssignmentsInspection */
3056
-                    $value = $field->prepare_for_use_in_db($value);
3057
-                case self::prepared_for_use_in_db:
3058
-                    //leave the value alone
3059
-            }
3060
-            return $value;
3061
-        }
3062
-        return $value;
3063
-    }
3064
-
3065
-
3066
-
3067
-    /**
3068
-     * Returns the main table on this model
3069
-     *
3070
-     * @return EE_Primary_Table
3071
-     * @throws EE_Error
3072
-     */
3073
-    protected function _get_main_table()
3074
-    {
3075
-        foreach ($this->_tables as $table) {
3076
-            if ($table instanceof EE_Primary_Table) {
3077
-                return $table;
3078
-            }
3079
-        }
3080
-        throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3081
-            'event_espresso'), get_class($this)));
3082
-    }
3083
-
3084
-
3085
-
3086
-    /**
3087
-     * table
3088
-     * returns EE_Primary_Table table name
3089
-     *
3090
-     * @return string
3091
-     * @throws EE_Error
3092
-     */
3093
-    public function table()
3094
-    {
3095
-        return $this->_get_main_table()->get_table_name();
3096
-    }
3097
-
3098
-
3099
-
3100
-    /**
3101
-     * table
3102
-     * returns first EE_Secondary_Table table name
3103
-     *
3104
-     * @return string
3105
-     */
3106
-    public function second_table()
3107
-    {
3108
-        // grab second table from tables array
3109
-        $second_table = end($this->_tables);
3110
-        return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3111
-    }
3112
-
3113
-
3114
-
3115
-    /**
3116
-     * get_table_obj_by_alias
3117
-     * returns table name given it's alias
3118
-     *
3119
-     * @param string $table_alias
3120
-     * @return EE_Primary_Table | EE_Secondary_Table
3121
-     */
3122
-    public function get_table_obj_by_alias($table_alias = '')
3123
-    {
3124
-        return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3125
-    }
3126
-
3127
-
3128
-
3129
-    /**
3130
-     * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3131
-     *
3132
-     * @return EE_Secondary_Table[]
3133
-     */
3134
-    protected function _get_other_tables()
3135
-    {
3136
-        $other_tables = array();
3137
-        foreach ($this->_tables as $table_alias => $table) {
3138
-            if ($table instanceof EE_Secondary_Table) {
3139
-                $other_tables[$table_alias] = $table;
3140
-            }
3141
-        }
3142
-        return $other_tables;
3143
-    }
3144
-
3145
-
3146
-
3147
-    /**
3148
-     * Finds all the fields that correspond to the given table
3149
-     *
3150
-     * @param string $table_alias , array key in EEM_Base::_tables
3151
-     * @return EE_Model_Field_Base[]
3152
-     */
3153
-    public function _get_fields_for_table($table_alias)
3154
-    {
3155
-        return $this->_fields[$table_alias];
3156
-    }
3157
-
3158
-
3159
-
3160
-    /**
3161
-     * Recurses through all the where parameters, and finds all the related models we'll need
3162
-     * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3163
-     * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3164
-     * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3165
-     * related Registration, Transaction, and Payment models.
3166
-     *
3167
-     * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3168
-     * @return EE_Model_Query_Info_Carrier
3169
-     * @throws EE_Error
3170
-     */
3171
-    public function _extract_related_models_from_query($query_params)
3172
-    {
3173
-        $query_info_carrier = new EE_Model_Query_Info_Carrier();
3174
-        if (array_key_exists(0, $query_params)) {
3175
-            $this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3176
-        }
3177
-        if (array_key_exists('group_by', $query_params)) {
3178
-            if (is_array($query_params['group_by'])) {
3179
-                $this->_extract_related_models_from_sub_params_array_values(
3180
-                    $query_params['group_by'],
3181
-                    $query_info_carrier,
3182
-                    'group_by'
3183
-                );
3184
-            } elseif (! empty ($query_params['group_by'])) {
3185
-                $this->_extract_related_model_info_from_query_param(
3186
-                    $query_params['group_by'],
3187
-                    $query_info_carrier,
3188
-                    'group_by'
3189
-                );
3190
-            }
3191
-        }
3192
-        if (array_key_exists('having', $query_params)) {
3193
-            $this->_extract_related_models_from_sub_params_array_keys(
3194
-                $query_params[0],
3195
-                $query_info_carrier,
3196
-                'having'
3197
-            );
3198
-        }
3199
-        if (array_key_exists('order_by', $query_params)) {
3200
-            if (is_array($query_params['order_by'])) {
3201
-                $this->_extract_related_models_from_sub_params_array_keys(
3202
-                    $query_params['order_by'],
3203
-                    $query_info_carrier,
3204
-                    'order_by'
3205
-                );
3206
-            } elseif (! empty($query_params['order_by'])) {
3207
-                $this->_extract_related_model_info_from_query_param(
3208
-                    $query_params['order_by'],
3209
-                    $query_info_carrier,
3210
-                    'order_by'
3211
-                );
3212
-            }
3213
-        }
3214
-        if (array_key_exists('force_join', $query_params)) {
3215
-            $this->_extract_related_models_from_sub_params_array_values(
3216
-                $query_params['force_join'],
3217
-                $query_info_carrier,
3218
-                'force_join'
3219
-            );
3220
-        }
3221
-        return $query_info_carrier;
3222
-    }
3223
-
3224
-
3225
-
3226
-    /**
3227
-     * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3228
-     *
3229
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3230
-     *                                                      $query_params['having']
3231
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3232
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3233
-     * @throws EE_Error
3234
-     * @return \EE_Model_Query_Info_Carrier
3235
-     */
3236
-    private function _extract_related_models_from_sub_params_array_keys(
3237
-        $sub_query_params,
3238
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3239
-        $query_param_type
3240
-    ) {
3241
-        if (! empty($sub_query_params)) {
3242
-            $sub_query_params = (array)$sub_query_params;
3243
-            foreach ($sub_query_params as $param => $possibly_array_of_params) {
3244
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3245
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3246
-                    $query_param_type);
3247
-                //if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3248
-                //indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3249
-                //extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3250
-                //of array('Registration.TXN_ID'=>23)
3251
-                $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3252
-                if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3253
-                    if (! is_array($possibly_array_of_params)) {
3254
-                        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'))",
3255
-                            "event_espresso"),
3256
-                            $param, $possibly_array_of_params));
3257
-                    }
3258
-                    $this->_extract_related_models_from_sub_params_array_keys(
3259
-                        $possibly_array_of_params,
3260
-                        $model_query_info_carrier, $query_param_type
3261
-                    );
3262
-                } elseif ($query_param_type === 0 //ie WHERE
3263
-                          && is_array($possibly_array_of_params)
3264
-                          && isset($possibly_array_of_params[2])
3265
-                          && $possibly_array_of_params[2] == true
3266
-                ) {
3267
-                    //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3268
-                    //indicating that $possible_array_of_params[1] is actually a field name,
3269
-                    //from which we should extract query parameters!
3270
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3271
-                        throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3272
-                            "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3273
-                    }
3274
-                    $this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3275
-                        $model_query_info_carrier, $query_param_type);
3276
-                }
3277
-            }
3278
-        }
3279
-        return $model_query_info_carrier;
3280
-    }
3281
-
3282
-
3283
-
3284
-    /**
3285
-     * For extracting related models from forced_joins, where the array values contain the info about what
3286
-     * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3287
-     *
3288
-     * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3289
-     *                                                      $query_params['having']
3290
-     * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3291
-     * @param string                      $query_param_type one of $this->_allowed_query_params
3292
-     * @throws EE_Error
3293
-     * @return \EE_Model_Query_Info_Carrier
3294
-     */
3295
-    private function _extract_related_models_from_sub_params_array_values(
3296
-        $sub_query_params,
3297
-        EE_Model_Query_Info_Carrier $model_query_info_carrier,
3298
-        $query_param_type
3299
-    ) {
3300
-        if (! empty($sub_query_params)) {
3301
-            if (! is_array($sub_query_params)) {
3302
-                throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3303
-                    $sub_query_params));
3304
-            }
3305
-            foreach ($sub_query_params as $param) {
3306
-                //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3307
-                $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3308
-                    $query_param_type);
3309
-            }
3310
-        }
3311
-        return $model_query_info_carrier;
3312
-    }
3313
-
3314
-
3315
-
3316
-    /**
3317
-     * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3318
-     * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3319
-     * instead of directly constructing the SQL because often we need to extract info from the $query_params
3320
-     * but use them in a different order. Eg, we need to know what models we are querying
3321
-     * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3322
-     * other models before we can finalize the where clause SQL.
3323
-     *
3324
-     * @param array $query_params
3325
-     * @throws EE_Error
3326
-     * @return EE_Model_Query_Info_Carrier
3327
-     */
3328
-    public function _create_model_query_info_carrier($query_params)
3329
-    {
3330
-        if (! is_array($query_params)) {
3331
-            EE_Error::doing_it_wrong(
3332
-                'EEM_Base::_create_model_query_info_carrier',
3333
-                sprintf(
3334
-                    __(
3335
-                        '$query_params should be an array, you passed a variable of type %s',
3336
-                        'event_espresso'
3337
-                    ),
3338
-                    gettype($query_params)
3339
-                ),
3340
-                '4.6.0'
3341
-            );
3342
-            $query_params = array();
3343
-        }
3344
-        $where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3345
-        //first check if we should alter the query to account for caps or not
3346
-        //because the caps might require us to do extra joins
3347
-        if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3348
-            $query_params[0] = $where_query_params = array_replace_recursive(
3349
-                $where_query_params,
3350
-                $this->caps_where_conditions(
3351
-                    $query_params['caps']
3352
-                )
3353
-            );
3354
-        }
3355
-        $query_object = $this->_extract_related_models_from_query($query_params);
3356
-        //verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3357
-        foreach ($where_query_params as $key => $value) {
3358
-            if (is_int($key)) {
3359
-                throw new EE_Error(
3360
-                    sprintf(
3361
-                        __(
3362
-                            "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.",
3363
-                            "event_espresso"
3364
-                        ),
3365
-                        $key,
3366
-                        var_export($value, true),
3367
-                        var_export($query_params, true),
3368
-                        get_class($this)
3369
-                    )
3370
-                );
3371
-            }
3372
-        }
3373
-        if (
3374
-            array_key_exists('default_where_conditions', $query_params)
3375
-            && ! empty($query_params['default_where_conditions'])
3376
-        ) {
3377
-            $use_default_where_conditions = $query_params['default_where_conditions'];
3378
-        } else {
3379
-            $use_default_where_conditions = EEM_Base::default_where_conditions_all;
3380
-        }
3381
-        $where_query_params = array_merge(
3382
-            $this->_get_default_where_conditions_for_models_in_query(
3383
-                $query_object,
3384
-                $use_default_where_conditions,
3385
-                $where_query_params
3386
-            ),
3387
-            $where_query_params
3388
-        );
3389
-        $query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3390
-        // if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3391
-        // So we need to setup a subquery and use that for the main join.
3392
-        // Note for now this only works on the primary table for the model.
3393
-        // So for instance, you could set the limit array like this:
3394
-        // array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3395
-        if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3396
-            $query_object->set_main_model_join_sql(
3397
-                $this->_construct_limit_join_select(
3398
-                    $query_params['on_join_limit'][0],
3399
-                    $query_params['on_join_limit'][1]
3400
-                )
3401
-            );
3402
-        }
3403
-        //set limit
3404
-        if (array_key_exists('limit', $query_params)) {
3405
-            if (is_array($query_params['limit'])) {
3406
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3407
-                    $e = sprintf(
3408
-                        __(
3409
-                            "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)",
3410
-                            "event_espresso"
3411
-                        ),
3412
-                        http_build_query($query_params['limit'])
3413
-                    );
3414
-                    throw new EE_Error($e . "|" . $e);
3415
-                }
3416
-                //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3417
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3418
-            } elseif (! empty ($query_params['limit'])) {
3419
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3420
-            }
3421
-        }
3422
-        //set order by
3423
-        if (array_key_exists('order_by', $query_params)) {
3424
-            if (is_array($query_params['order_by'])) {
3425
-                //if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3426
-                //specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3427
-                //including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3428
-                if (array_key_exists('order', $query_params)) {
3429
-                    throw new EE_Error(
3430
-                        sprintf(
3431
-                            __(
3432
-                                "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 ",
3433
-                                "event_espresso"
3434
-                            ),
3435
-                            get_class($this),
3436
-                            implode(", ", array_keys($query_params['order_by'])),
3437
-                            implode(", ", $query_params['order_by']),
3438
-                            $query_params['order']
3439
-                        )
3440
-                    );
3441
-                }
3442
-                $this->_extract_related_models_from_sub_params_array_keys(
3443
-                    $query_params['order_by'],
3444
-                    $query_object,
3445
-                    'order_by'
3446
-                );
3447
-                //assume it's an array of fields to order by
3448
-                $order_array = array();
3449
-                foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3450
-                    $order = $this->_extract_order($order);
3451
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3452
-                }
3453
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3454
-            } elseif (! empty ($query_params['order_by'])) {
3455
-                $this->_extract_related_model_info_from_query_param(
3456
-                    $query_params['order_by'],
3457
-                    $query_object,
3458
-                    'order',
3459
-                    $query_params['order_by']
3460
-                );
3461
-                $order = isset($query_params['order'])
3462
-                    ? $this->_extract_order($query_params['order'])
3463
-                    : 'DESC';
3464
-                $query_object->set_order_by_sql(
3465
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3466
-                );
3467
-            }
3468
-        }
3469
-        //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3470
-        if (! array_key_exists('order_by', $query_params)
3471
-            && array_key_exists('order', $query_params)
3472
-            && ! empty($query_params['order'])
3473
-        ) {
3474
-            $pk_field = $this->get_primary_key_field();
3475
-            $order = $this->_extract_order($query_params['order']);
3476
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3477
-        }
3478
-        //set group by
3479
-        if (array_key_exists('group_by', $query_params)) {
3480
-            if (is_array($query_params['group_by'])) {
3481
-                //it's an array, so assume we'll be grouping by a bunch of stuff
3482
-                $group_by_array = array();
3483
-                foreach ($query_params['group_by'] as $field_name_to_group_by) {
3484
-                    $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3485
-                }
3486
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3487
-            } elseif (! empty ($query_params['group_by'])) {
3488
-                $query_object->set_group_by_sql(
3489
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3490
-                );
3491
-            }
3492
-        }
3493
-        //set having
3494
-        if (array_key_exists('having', $query_params) && $query_params['having']) {
3495
-            $query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3496
-        }
3497
-        //now, just verify they didn't pass anything wack
3498
-        foreach ($query_params as $query_key => $query_value) {
3499
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3500
-                throw new EE_Error(
3501
-                    sprintf(
3502
-                        __(
3503
-                            "You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3504
-                            'event_espresso'
3505
-                        ),
3506
-                        $query_key,
3507
-                        get_class($this),
3508
-                        //						print_r( $this->_allowed_query_params, TRUE )
3509
-                        implode(',', $this->_allowed_query_params)
3510
-                    )
3511
-                );
3512
-            }
3513
-        }
3514
-        $main_model_join_sql = $query_object->get_main_model_join_sql();
3515
-        if (empty($main_model_join_sql)) {
3516
-            $query_object->set_main_model_join_sql($this->_construct_internal_join());
3517
-        }
3518
-        return $query_object;
3519
-    }
3520
-
3521
-
3522
-
3523
-    /**
3524
-     * Gets the where conditions that should be imposed on the query based on the
3525
-     * context (eg reading frontend, backend, edit or delete).
3526
-     *
3527
-     * @param string $context one of EEM_Base::valid_cap_contexts()
3528
-     * @return array like EEM_Base::get_all() 's $query_params[0]
3529
-     * @throws EE_Error
3530
-     */
3531
-    public function caps_where_conditions($context = self::caps_read)
3532
-    {
3533
-        EEM_Base::verify_is_valid_cap_context($context);
3534
-        $cap_where_conditions = array();
3535
-        $cap_restrictions = $this->caps_missing($context);
3536
-        /**
3537
-         * @var $cap_restrictions EE_Default_Where_Conditions[]
3538
-         */
3539
-        foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3540
-            $cap_where_conditions = array_replace_recursive($cap_where_conditions,
3541
-                $restriction_if_no_cap->get_default_where_conditions());
3542
-        }
3543
-        return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3544
-            $cap_restrictions);
3545
-    }
3546
-
3547
-
3548
-
3549
-    /**
3550
-     * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3551
-     * otherwise throws an exception
3552
-     *
3553
-     * @param string $should_be_order_string
3554
-     * @return string either ASC, asc, DESC or desc
3555
-     * @throws EE_Error
3556
-     */
3557
-    private function _extract_order($should_be_order_string)
3558
-    {
3559
-        if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3560
-            return $should_be_order_string;
3561
-        }
3562
-        throw new EE_Error(
3563
-            sprintf(
3564
-                __(
3565
-                    "While performing a query on '%s', tried to use '%s' as an order parameter. ",
3566
-                    "event_espresso"
3567
-                ), get_class($this), $should_be_order_string
3568
-            )
3569
-        );
3570
-    }
3571
-
3572
-
3573
-
3574
-    /**
3575
-     * Looks at all the models which are included in this query, and asks each
3576
-     * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3577
-     * so they can be merged
3578
-     *
3579
-     * @param EE_Model_Query_Info_Carrier $query_info_carrier
3580
-     * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3581
-     *                                                                  'none' means NO default where conditions will
3582
-     *                                                                  be used AT ALL during this query.
3583
-     *                                                                  'other_models_only' means default where
3584
-     *                                                                  conditions from other models will be used, but
3585
-     *                                                                  not for this primary model. 'all', the default,
3586
-     *                                                                  means default where conditions will apply as
3587
-     *                                                                  normal
3588
-     * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3589
-     * @throws EE_Error
3590
-     * @return array like $query_params[0], see EEM_Base::get_all for documentation
3591
-     */
3592
-    private function _get_default_where_conditions_for_models_in_query(
3593
-        EE_Model_Query_Info_Carrier $query_info_carrier,
3594
-        $use_default_where_conditions = EEM_Base::default_where_conditions_all,
3595
-        $where_query_params = array()
3596
-    ) {
3597
-        $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3598
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3599
-            throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3600
-                "event_espresso"), $use_default_where_conditions,
3601
-                implode(", ", $allowed_used_default_where_conditions_values)));
3602
-        }
3603
-        $universal_query_params = array();
3604
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3605
-            $universal_query_params = $this->_get_default_where_conditions();
3606
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3607
-            $universal_query_params = $this->_get_minimum_where_conditions();
3608
-        }
3609
-        foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3610
-            $related_model = $this->get_related_model_obj($model_name);
3611
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3612
-                $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3613
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3614
-                $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3615
-            } else {
3616
-                //we don't want to add full or even minimum default where conditions from this model, so just continue
3617
-                continue;
3618
-            }
3619
-            $overrides = $this->_override_defaults_or_make_null_friendly(
3620
-                $related_model_universal_where_params,
3621
-                $where_query_params,
3622
-                $related_model,
3623
-                $model_relation_path
3624
-            );
3625
-            $universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3626
-                $universal_query_params,
3627
-                $overrides
3628
-            );
3629
-        }
3630
-        return $universal_query_params;
3631
-    }
3632
-
3633
-
3634
-
3635
-    /**
3636
-     * Determines whether or not we should use default where conditions for the model in question
3637
-     * (this model, or other related models).
3638
-     * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3639
-     * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3640
-     * We should use default where conditions on related models when they requested to use default where conditions
3641
-     * on all models, or specifically just on other related models
3642
-     * @param      $default_where_conditions_value
3643
-     * @param bool $for_this_model false means this is for OTHER related models
3644
-     * @return bool
3645
-     */
3646
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3647
-    {
3648
-        return (
3649
-                   $for_this_model
3650
-                   && in_array(
3651
-                       $default_where_conditions_value,
3652
-                       array(
3653
-                           EEM_Base::default_where_conditions_all,
3654
-                           EEM_Base::default_where_conditions_this_only,
3655
-                           EEM_Base::default_where_conditions_minimum_others,
3656
-                       ),
3657
-                       true
3658
-                   )
3659
-               )
3660
-               || (
3661
-                   ! $for_this_model
3662
-                   && in_array(
3663
-                       $default_where_conditions_value,
3664
-                       array(
3665
-                           EEM_Base::default_where_conditions_all,
3666
-                           EEM_Base::default_where_conditions_others_only,
3667
-                       ),
3668
-                       true
3669
-                   )
3670
-               );
3671
-    }
3672
-
3673
-    /**
3674
-     * Determines whether or not we should use default minimum conditions for the model in question
3675
-     * (this model, or other related models).
3676
-     * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3677
-     * where conditions.
3678
-     * We should use minimum where conditions on related models if they requested to use minimum where conditions
3679
-     * on this model or others
3680
-     * @param      $default_where_conditions_value
3681
-     * @param bool $for_this_model false means this is for OTHER related models
3682
-     * @return bool
3683
-     */
3684
-    private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3685
-    {
3686
-        return (
3687
-                   $for_this_model
3688
-                   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3689
-               )
3690
-               || (
3691
-                   ! $for_this_model
3692
-                   && in_array(
3693
-                       $default_where_conditions_value,
3694
-                       array(
3695
-                           EEM_Base::default_where_conditions_minimum_others,
3696
-                           EEM_Base::default_where_conditions_minimum_all,
3697
-                       ),
3698
-                       true
3699
-                   )
3700
-               );
3701
-    }
3702
-
3703
-
3704
-    /**
3705
-     * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3706
-     * then we also add a special where condition which allows for that model's primary key
3707
-     * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3708
-     * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3709
-     *
3710
-     * @param array    $default_where_conditions
3711
-     * @param array    $provided_where_conditions
3712
-     * @param EEM_Base $model
3713
-     * @param string   $model_relation_path like 'Transaction.Payment.'
3714
-     * @return array like EEM_Base::get_all's $query_params[0]
3715
-     * @throws EE_Error
3716
-     */
3717
-    private function _override_defaults_or_make_null_friendly(
3718
-        $default_where_conditions,
3719
-        $provided_where_conditions,
3720
-        $model,
3721
-        $model_relation_path
3722
-    ) {
3723
-        $null_friendly_where_conditions = array();
3724
-        $none_overridden = true;
3725
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3726
-        foreach ($default_where_conditions as $key => $val) {
3727
-            if (isset($provided_where_conditions[$key])) {
3728
-                $none_overridden = false;
3729
-            } else {
3730
-                $null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3731
-            }
3732
-        }
3733
-        if ($none_overridden && $default_where_conditions) {
3734
-            if ($model->has_primary_key_field()) {
3735
-                $null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3736
-                                                                                . "."
3737
-                                                                                . $model->primary_key_name()] = array('IS NULL');
3738
-            }/*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[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2190
+			}
2191
+			$query_part = implode(' OR ', $ways_to_identify_a_row);
2192
+		}
2193
+		return $query_part;
2194
+	}
2195
+
2196
+
2197
+
2198
+	/**
2199
+	 * Gets the model field by the fully qualified name
2200
+	 * @param string $qualified_column_name eg 'Event_CPT.post_name' or $field_obj->get_qualified_column()
2201
+	 * @return EE_Model_Field_Base
2202
+	 */
2203
+	public function get_field_by_column($qualified_column_name)
2204
+	{
2205
+	   foreach($this->field_settings(true) as $field_name => $field_obj){
2206
+		   if($field_obj->get_qualified_column() === $qualified_column_name){
2207
+			   return $field_obj;
2208
+		   }
2209
+	   }
2210
+		throw new EE_Error(
2211
+			sprintf(
2212
+				esc_html__('Could not find a field on the model "%1$s" for qualified column "%2$s"', 'event_espresso'),
2213
+				$this->get_this_model_name(),
2214
+				$qualified_column_name
2215
+			)
2216
+		);
2217
+	}
2218
+
2219
+
2220
+
2221
+	/**
2222
+	 * Count all the rows that match criteria expressed in $query_params (an array just like arg to EEM_Base::get_all).
2223
+	 * If $field_to_count isn't provided, the model's primary key is used. Otherwise, we count by field_to_count's
2224
+	 * column
2225
+	 *
2226
+	 * @param array  $query_params   like EEM_Base::get_all's
2227
+	 * @param string $field_to_count field on model to count by (not column name)
2228
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2229
+	 *                               that by the setting $distinct to TRUE;
2230
+	 * @return int
2231
+	 * @throws EE_Error
2232
+	 */
2233
+	public function count($query_params = array(), $field_to_count = null, $distinct = false)
2234
+	{
2235
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2236
+		if ($field_to_count) {
2237
+			$field_obj = $this->field_settings_for($field_to_count);
2238
+			$column_to_count = $field_obj->get_qualified_column();
2239
+		} elseif ($this->has_primary_key_field()) {
2240
+			$pk_field_obj = $this->get_primary_key_field();
2241
+			$column_to_count = $pk_field_obj->get_qualified_column();
2242
+		} else {
2243
+			//there's no primary key
2244
+			//if we're counting distinct items, and there's no primary key,
2245
+			//we need to list out the columns for distinction;
2246
+			//otherwise we can just use star
2247
+			if ($distinct) {
2248
+				$columns_to_use = array();
2249
+				foreach ($this->get_combined_primary_key_fields() as $field_obj) {
2250
+					$columns_to_use[] = $field_obj->get_qualified_column();
2251
+				}
2252
+				$column_to_count = implode(',', $columns_to_use);
2253
+			} else {
2254
+				$column_to_count = '*';
2255
+			}
2256
+		}
2257
+		$column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2258
+		$SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2259
+		return (int)$this->_do_wpdb_query('get_var', array($SQL));
2260
+	}
2261
+
2262
+
2263
+
2264
+	/**
2265
+	 * Sums up the value of the $field_to_sum (defaults to the primary key, which isn't terribly useful)
2266
+	 *
2267
+	 * @param array  $query_params like EEM_Base::get_all
2268
+	 * @param string $field_to_sum name of field (array key in $_fields array)
2269
+	 * @return float
2270
+	 * @throws EE_Error
2271
+	 */
2272
+	public function sum($query_params, $field_to_sum = null)
2273
+	{
2274
+		$model_query_info = $this->_create_model_query_info_carrier($query_params);
2275
+		if ($field_to_sum) {
2276
+			$field_obj = $this->field_settings_for($field_to_sum);
2277
+		} else {
2278
+			$field_obj = $this->get_primary_key_field();
2279
+		}
2280
+		$column_to_count = $field_obj->get_qualified_column();
2281
+		$SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2282
+		$return_value = $this->_do_wpdb_query('get_var', array($SQL));
2283
+		$data_type = $field_obj->get_wpdb_data_type();
2284
+		if ($data_type === '%d' || $data_type === '%s') {
2285
+			return (float)$return_value;
2286
+		}
2287
+		//must be %f
2288
+		return (float)$return_value;
2289
+	}
2290
+
2291
+
2292
+
2293
+	/**
2294
+	 * Just calls the specified method on $wpdb with the given arguments
2295
+	 * Consolidates a little extra error handling code
2296
+	 *
2297
+	 * @param string $wpdb_method
2298
+	 * @param array  $arguments_to_provide
2299
+	 * @throws EE_Error
2300
+	 * @global wpdb  $wpdb
2301
+	 * @return mixed
2302
+	 */
2303
+	protected function _do_wpdb_query($wpdb_method, $arguments_to_provide)
2304
+	{
2305
+		//if we're in maintenance mode level 2, DON'T run any queries
2306
+		//because level 2 indicates the database needs updating and
2307
+		//is probably out of sync with the code
2308
+		if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2309
+			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.",
2310
+				"event_espresso")));
2311
+		}
2312
+		/** @type WPDB $wpdb */
2313
+		global $wpdb;
2314
+		if (! method_exists($wpdb, $wpdb_method)) {
2315
+			throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2316
+				'event_espresso'), $wpdb_method));
2317
+		}
2318
+		if (WP_DEBUG) {
2319
+			$old_show_errors_value = $wpdb->show_errors;
2320
+			$wpdb->show_errors(false);
2321
+		}
2322
+		$result = $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2323
+		$this->show_db_query_if_previously_requested($wpdb->last_query);
2324
+		if (WP_DEBUG) {
2325
+			$wpdb->show_errors($old_show_errors_value);
2326
+			if (! empty($wpdb->last_error)) {
2327
+				throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2328
+			}
2329
+			if ($result === false) {
2330
+				throw new EE_Error(sprintf(__('WPDB Error occurred, but no error message was logged by wpdb! The wpdb method called was "%1$s" and the arguments were "%2$s"',
2331
+					'event_espresso'), $wpdb_method, var_export($arguments_to_provide, true)));
2332
+			}
2333
+		} elseif ($result === false) {
2334
+			EE_Error::add_error(
2335
+				sprintf(
2336
+					__('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"',
2337
+						'event_espresso'),
2338
+					$wpdb_method,
2339
+					var_export($arguments_to_provide, true),
2340
+					$wpdb->last_error
2341
+				),
2342
+				__FILE__,
2343
+				__FUNCTION__,
2344
+				__LINE__
2345
+			);
2346
+		}
2347
+		return $result;
2348
+	}
2349
+
2350
+
2351
+
2352
+	/**
2353
+	 * Attempts to run the indicated WPDB method with the provided arguments,
2354
+	 * and if there's an error tries to verify the DB is correct. Uses
2355
+	 * the static property EEM_Base::$_db_verification_level to determine whether
2356
+	 * we should try to fix the EE core db, the addons, or just give up
2357
+	 *
2358
+	 * @param string $wpdb_method
2359
+	 * @param array  $arguments_to_provide
2360
+	 * @return mixed
2361
+	 */
2362
+	private function _process_wpdb_query($wpdb_method, $arguments_to_provide)
2363
+	{
2364
+		/** @type WPDB $wpdb */
2365
+		global $wpdb;
2366
+		$wpdb->last_error = null;
2367
+		$result = call_user_func_array(array($wpdb, $wpdb_method), $arguments_to_provide);
2368
+		// was there an error running the query? but we don't care on new activations
2369
+		// (we're going to setup the DB anyway on new activations)
2370
+		if (($result === false || ! empty($wpdb->last_error))
2371
+			&& EE_System::instance()->detect_req_type() !== EE_System::req_type_new_activation
2372
+		) {
2373
+			switch (EEM_Base::$_db_verification_level) {
2374
+				case EEM_Base::db_verified_none :
2375
+					// let's double-check core's DB
2376
+					$error_message = $this->_verify_core_db($wpdb_method, $arguments_to_provide);
2377
+					break;
2378
+				case EEM_Base::db_verified_core :
2379
+					// STILL NO LOVE?? verify all the addons too. Maybe they need to be fixed
2380
+					$error_message = $this->_verify_addons_db($wpdb_method, $arguments_to_provide);
2381
+					break;
2382
+				case EEM_Base::db_verified_addons :
2383
+					// ummmm... you in trouble
2384
+					return $result;
2385
+					break;
2386
+			}
2387
+			if (! empty($error_message)) {
2388
+				EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2389
+				trigger_error($error_message);
2390
+			}
2391
+			return $this->_process_wpdb_query($wpdb_method, $arguments_to_provide);
2392
+		}
2393
+		return $result;
2394
+	}
2395
+
2396
+
2397
+
2398
+	/**
2399
+	 * Verifies the EE core database is up-to-date and records that we've done it on
2400
+	 * EEM_Base::$_db_verification_level
2401
+	 *
2402
+	 * @param string $wpdb_method
2403
+	 * @param array  $arguments_to_provide
2404
+	 * @return string
2405
+	 */
2406
+	private function _verify_core_db($wpdb_method, $arguments_to_provide)
2407
+	{
2408
+		/** @type WPDB $wpdb */
2409
+		global $wpdb;
2410
+		//ok remember that we've already attempted fixing the core db, in case the problem persists
2411
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_core;
2412
+		$error_message = sprintf(
2413
+			__('WPDB Error "%1$s" while running wpdb method "%2$s" with arguments %3$s. Automatically attempting to fix EE Core DB',
2414
+				'event_espresso'),
2415
+			$wpdb->last_error,
2416
+			$wpdb_method,
2417
+			wp_json_encode($arguments_to_provide)
2418
+		);
2419
+		EE_System::instance()->initialize_db_if_no_migrations_required(false, true);
2420
+		return $error_message;
2421
+	}
2422
+
2423
+
2424
+
2425
+	/**
2426
+	 * Verifies the EE addons' database is up-to-date and records that we've done it on
2427
+	 * EEM_Base::$_db_verification_level
2428
+	 *
2429
+	 * @param $wpdb_method
2430
+	 * @param $arguments_to_provide
2431
+	 * @return string
2432
+	 */
2433
+	private function _verify_addons_db($wpdb_method, $arguments_to_provide)
2434
+	{
2435
+		/** @type WPDB $wpdb */
2436
+		global $wpdb;
2437
+		//ok remember that we've already attempted fixing the addons dbs, in case the problem persists
2438
+		EEM_Base::$_db_verification_level = EEM_Base::db_verified_addons;
2439
+		$error_message = sprintf(
2440
+			__('WPDB AGAIN: Error "%1$s" while running the same method and arguments as before. Automatically attempting to fix EE Addons DB',
2441
+				'event_espresso'),
2442
+			$wpdb->last_error,
2443
+			$wpdb_method,
2444
+			wp_json_encode($arguments_to_provide)
2445
+		);
2446
+		EE_System::instance()->initialize_addons();
2447
+		return $error_message;
2448
+	}
2449
+
2450
+
2451
+
2452
+	/**
2453
+	 * In order to avoid repeating this code for the get_all, sum, and count functions, put the code parts
2454
+	 * that are identical in here. Returns a string of SQL of everything in a SELECT query except the beginning
2455
+	 * SELECT clause, eg " FROM wp_posts AS Event INNER JOIN ... WHERE ... ORDER BY ... LIMIT ... GROUP BY ... HAVING
2456
+	 * ..."
2457
+	 *
2458
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
2459
+	 * @return string
2460
+	 */
2461
+	private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2462
+	{
2463
+		return " FROM " . $model_query_info->get_full_join_sql() .
2464
+			   $model_query_info->get_where_sql() .
2465
+			   $model_query_info->get_group_by_sql() .
2466
+			   $model_query_info->get_having_sql() .
2467
+			   $model_query_info->get_order_by_sql() .
2468
+			   $model_query_info->get_limit_sql();
2469
+	}
2470
+
2471
+
2472
+
2473
+	/**
2474
+	 * Set to easily debug the next X queries ran from this model.
2475
+	 *
2476
+	 * @param int $count
2477
+	 */
2478
+	public function show_next_x_db_queries($count = 1)
2479
+	{
2480
+		$this->_show_next_x_db_queries = $count;
2481
+	}
2482
+
2483
+
2484
+
2485
+	/**
2486
+	 * @param $sql_query
2487
+	 */
2488
+	public function show_db_query_if_previously_requested($sql_query)
2489
+	{
2490
+		if ($this->_show_next_x_db_queries > 0) {
2491
+			echo $sql_query;
2492
+			$this->_show_next_x_db_queries--;
2493
+		}
2494
+	}
2495
+
2496
+
2497
+
2498
+	/**
2499
+	 * Adds a relationship of the correct type between $modelObject and $otherModelObject.
2500
+	 * There are the 3 cases:
2501
+	 * 'belongsTo' relationship: sets $id_or_obj's foreign_key to be $other_model_id_or_obj's primary_key. If
2502
+	 * $otherModelObject has no ID, it is first saved.
2503
+	 * 'hasMany' relationship: sets $other_model_id_or_obj's foreign_key to be $id_or_obj's primary_key. If $id_or_obj
2504
+	 * has no ID, it is first saved.
2505
+	 * 'hasAndBelongsToMany' relationships: checks that there isn't already an entry in the join table, and adds one.
2506
+	 * If one of the model Objects has not yet been saved to the database, it is saved before adding the entry in the
2507
+	 * join table
2508
+	 *
2509
+	 * @param        EE_Base_Class                     /int $thisModelObject
2510
+	 * @param        EE_Base_Class                     /int $id_or_obj EE_base_Class or ID of other Model Object
2511
+	 * @param string $relationName                     , key in EEM_Base::_relations
2512
+	 *                                                 an attendee to a group, you also want to specify which role they
2513
+	 *                                                 will have in that group. So you would use this parameter to
2514
+	 *                                                 specify array('role-column-name'=>'role-id')
2515
+	 * @param array  $extra_join_model_fields_n_values This allows you to enter further query params for the relation
2516
+	 *                                                 to for relation to methods that allow you to further specify
2517
+	 *                                                 extra columns to join by (such as HABTM).  Keep in mind that the
2518
+	 *                                                 only acceptable query_params is strict "col" => "value" pairs
2519
+	 *                                                 because these will be inserted in any new rows created as well.
2520
+	 * @return EE_Base_Class which was added as a relation. Object referred to by $other_model_id_or_obj
2521
+	 * @throws EE_Error
2522
+	 */
2523
+	public function add_relationship_to(
2524
+		$id_or_obj,
2525
+		$other_model_id_or_obj,
2526
+		$relationName,
2527
+		$extra_join_model_fields_n_values = array()
2528
+	) {
2529
+		$relation_obj = $this->related_settings_for($relationName);
2530
+		return $relation_obj->add_relation_to($id_or_obj, $other_model_id_or_obj, $extra_join_model_fields_n_values);
2531
+	}
2532
+
2533
+
2534
+
2535
+	/**
2536
+	 * Removes a relationship of the correct type between $modelObject and $otherModelObject.
2537
+	 * There are the 3 cases:
2538
+	 * 'belongsTo' relationship: sets $modelObject's foreign_key to null, if that field is nullable.Otherwise throws an
2539
+	 * error
2540
+	 * 'hasMany' relationship: sets $otherModelObject's foreign_key to null,if that field is nullable.Otherwise throws
2541
+	 * an error
2542
+	 * 'hasAndBelongsToMany' relationships:removes any existing entry in the join table between the two models.
2543
+	 *
2544
+	 * @param        EE_Base_Class /int $id_or_obj
2545
+	 * @param        EE_Base_Class /int $other_model_id_or_obj EE_Base_Class or ID of other Model Object
2546
+	 * @param string $relationName key in EEM_Base::_relations
2547
+	 * @return boolean of success
2548
+	 * @throws EE_Error
2549
+	 * @param array  $where_query  This allows you to enter further query params for the relation to for relation to
2550
+	 *                             methods that allow you to further specify extra columns to join by (such as HABTM).
2551
+	 *                             Keep in mind that the only acceptable query_params is strict "col" => "value" pairs
2552
+	 *                             because these will be inserted in any new rows created as well.
2553
+	 */
2554
+	public function remove_relationship_to($id_or_obj, $other_model_id_or_obj, $relationName, $where_query = array())
2555
+	{
2556
+		$relation_obj = $this->related_settings_for($relationName);
2557
+		return $relation_obj->remove_relation_to($id_or_obj, $other_model_id_or_obj, $where_query);
2558
+	}
2559
+
2560
+
2561
+
2562
+	/**
2563
+	 * @param mixed           $id_or_obj
2564
+	 * @param string          $relationName
2565
+	 * @param array           $where_query_params
2566
+	 * @param EE_Base_Class[] objects to which relations were removed
2567
+	 * @return \EE_Base_Class[]
2568
+	 * @throws EE_Error
2569
+	 */
2570
+	public function remove_relations($id_or_obj, $relationName, $where_query_params = array())
2571
+	{
2572
+		$relation_obj = $this->related_settings_for($relationName);
2573
+		return $relation_obj->remove_relations($id_or_obj, $where_query_params);
2574
+	}
2575
+
2576
+
2577
+
2578
+	/**
2579
+	 * Gets all the related items of the specified $model_name, using $query_params.
2580
+	 * Note: by default, we remove the "default query params"
2581
+	 * because we want to get even deleted items etc.
2582
+	 *
2583
+	 * @param mixed  $id_or_obj    EE_Base_Class child or its ID
2584
+	 * @param string $model_name   like 'Event', 'Registration', etc. always singular
2585
+	 * @param array  $query_params like EEM_Base::get_all
2586
+	 * @return EE_Base_Class[]
2587
+	 * @throws EE_Error
2588
+	 */
2589
+	public function get_all_related($id_or_obj, $model_name, $query_params = null)
2590
+	{
2591
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2592
+		$relation_settings = $this->related_settings_for($model_name);
2593
+		return $relation_settings->get_all_related($model_obj, $query_params);
2594
+	}
2595
+
2596
+
2597
+
2598
+	/**
2599
+	 * Deletes all the model objects across the relation indicated by $model_name
2600
+	 * which are related to $id_or_obj which meet the criteria set in $query_params.
2601
+	 * However, if the model objects can't be deleted because of blocking related model objects, then
2602
+	 * they aren't deleted. (Unless the thing that would have been deleted can be soft-deleted, that still happens).
2603
+	 *
2604
+	 * @param EE_Base_Class|int|string $id_or_obj
2605
+	 * @param string                   $model_name
2606
+	 * @param array                    $query_params
2607
+	 * @return int how many deleted
2608
+	 * @throws EE_Error
2609
+	 */
2610
+	public function delete_related($id_or_obj, $model_name, $query_params = array())
2611
+	{
2612
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2613
+		$relation_settings = $this->related_settings_for($model_name);
2614
+		return $relation_settings->delete_all_related($model_obj, $query_params);
2615
+	}
2616
+
2617
+
2618
+
2619
+	/**
2620
+	 * Hard deletes all the model objects across the relation indicated by $model_name
2621
+	 * which are related to $id_or_obj which meet the criteria set in $query_params. If
2622
+	 * the model objects can't be hard deleted because of blocking related model objects,
2623
+	 * just does a soft-delete on them instead.
2624
+	 *
2625
+	 * @param EE_Base_Class|int|string $id_or_obj
2626
+	 * @param string                   $model_name
2627
+	 * @param array                    $query_params
2628
+	 * @return int how many deleted
2629
+	 * @throws EE_Error
2630
+	 */
2631
+	public function delete_related_permanently($id_or_obj, $model_name, $query_params = array())
2632
+	{
2633
+		$model_obj = $this->ensure_is_obj($id_or_obj);
2634
+		$relation_settings = $this->related_settings_for($model_name);
2635
+		return $relation_settings->delete_related_permanently($model_obj, $query_params);
2636
+	}
2637
+
2638
+
2639
+
2640
+	/**
2641
+	 * Instead of getting the related model objects, simply counts them. Ignores default_where_conditions by default,
2642
+	 * unless otherwise specified in the $query_params
2643
+	 *
2644
+	 * @param        int             /EE_Base_Class $id_or_obj
2645
+	 * @param string $model_name     like 'Event', or 'Registration'
2646
+	 * @param array  $query_params   like EEM_Base::get_all's
2647
+	 * @param string $field_to_count name of field to count by. By default, uses primary key
2648
+	 * @param bool   $distinct       if we want to only count the distinct values for the column then you can trigger
2649
+	 *                               that by the setting $distinct to TRUE;
2650
+	 * @return int
2651
+	 * @throws EE_Error
2652
+	 */
2653
+	public function count_related(
2654
+		$id_or_obj,
2655
+		$model_name,
2656
+		$query_params = array(),
2657
+		$field_to_count = null,
2658
+		$distinct = false
2659
+	) {
2660
+		$related_model = $this->get_related_model_obj($model_name);
2661
+		//we're just going to use the query params on the related model's normal get_all query,
2662
+		//except add a condition to say to match the current mod
2663
+		if (! isset($query_params['default_where_conditions'])) {
2664
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2665
+		}
2666
+		$this_model_name = $this->get_this_model_name();
2667
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2668
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2669
+		return $related_model->count($query_params, $field_to_count, $distinct);
2670
+	}
2671
+
2672
+
2673
+
2674
+	/**
2675
+	 * Instead of getting the related model objects, simply sums up the values of the specified field.
2676
+	 * Note: ignores default_where_conditions by default, unless otherwise specified in the $query_params
2677
+	 *
2678
+	 * @param        int           /EE_Base_Class $id_or_obj
2679
+	 * @param string $model_name   like 'Event', or 'Registration'
2680
+	 * @param array  $query_params like EEM_Base::get_all's
2681
+	 * @param string $field_to_sum name of field to count by. By default, uses primary key
2682
+	 * @return float
2683
+	 * @throws EE_Error
2684
+	 */
2685
+	public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2686
+	{
2687
+		$related_model = $this->get_related_model_obj($model_name);
2688
+		if (! is_array($query_params)) {
2689
+			EE_Error::doing_it_wrong('EEM_Base::sum_related',
2690
+				sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2691
+					gettype($query_params)), '4.6.0');
2692
+			$query_params = array();
2693
+		}
2694
+		//we're just going to use the query params on the related model's normal get_all query,
2695
+		//except add a condition to say to match the current mod
2696
+		if (! isset($query_params['default_where_conditions'])) {
2697
+			$query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2698
+		}
2699
+		$this_model_name = $this->get_this_model_name();
2700
+		$this_pk_field_name = $this->get_primary_key_field()->get_name();
2701
+		$query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2702
+		return $related_model->sum($query_params, $field_to_sum);
2703
+	}
2704
+
2705
+
2706
+
2707
+	/**
2708
+	 * Uses $this->_relatedModels info to find the first related model object of relation $relationName to the given
2709
+	 * $modelObject
2710
+	 *
2711
+	 * @param int | EE_Base_Class $id_or_obj        EE_Base_Class child or its ID
2712
+	 * @param string              $other_model_name , key in $this->_relatedModels, eg 'Registration', or 'Events'
2713
+	 * @param array               $query_params     like EEM_Base::get_all's
2714
+	 * @return EE_Base_Class
2715
+	 * @throws EE_Error
2716
+	 */
2717
+	public function get_first_related(EE_Base_Class $id_or_obj, $other_model_name, $query_params)
2718
+	{
2719
+		$query_params['limit'] = 1;
2720
+		$results = $this->get_all_related($id_or_obj, $other_model_name, $query_params);
2721
+		if ($results) {
2722
+			return array_shift($results);
2723
+		}
2724
+		return null;
2725
+	}
2726
+
2727
+
2728
+
2729
+	/**
2730
+	 * Gets the model's name as it's expected in queries. For example, if this is EEM_Event model, that would be Event
2731
+	 *
2732
+	 * @return string
2733
+	 */
2734
+	public function get_this_model_name()
2735
+	{
2736
+		return str_replace("EEM_", "", get_class($this));
2737
+	}
2738
+
2739
+
2740
+
2741
+	/**
2742
+	 * Gets the model field on this model which is of type EE_Any_Foreign_Model_Name_Field
2743
+	 *
2744
+	 * @return EE_Any_Foreign_Model_Name_Field
2745
+	 * @throws EE_Error
2746
+	 */
2747
+	public function get_field_containing_related_model_name()
2748
+	{
2749
+		foreach ($this->field_settings(true) as $field) {
2750
+			if ($field instanceof EE_Any_Foreign_Model_Name_Field) {
2751
+				$field_with_model_name = $field;
2752
+			}
2753
+		}
2754
+		if (! isset($field_with_model_name) || ! $field_with_model_name) {
2755
+			throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2756
+				$this->get_this_model_name()));
2757
+		}
2758
+		return $field_with_model_name;
2759
+	}
2760
+
2761
+
2762
+
2763
+	/**
2764
+	 * Inserts a new entry into the database, for each table.
2765
+	 * Note: does not add the item to the entity map because that is done by EE_Base_Class::save() right after this.
2766
+	 * If client code uses EEM_Base::insert() directly, then although the item isn't in the entity map,
2767
+	 * we also know there is no model object with the newly inserted item's ID at the moment (because
2768
+	 * if there were, then they would already be in the DB and this would fail); and in the future if someone
2769
+	 * creates a model object with this ID (or grabs it from the DB) then it will be added to the
2770
+	 * entity map at that time anyways. SO, no need for EEM_Base::insert ot add to the entity map
2771
+	 *
2772
+	 * @param array $field_n_values keys are field names, values are their values (in the client code's domain if
2773
+	 *                              $values_already_prepared_by_model_object is false, in the model object's domain if
2774
+	 *                              $values_already_prepared_by_model_object is true. See comment about this at the top
2775
+	 *                              of EEM_Base)
2776
+	 * @return int new primary key on main table that got inserted
2777
+	 * @throws EE_Error
2778
+	 */
2779
+	public function insert($field_n_values)
2780
+	{
2781
+		/**
2782
+		 * Filters the fields and their values before inserting an item using the models
2783
+		 *
2784
+		 * @param array    $fields_n_values keys are the fields and values are their new values
2785
+		 * @param EEM_Base $model           the model used
2786
+		 */
2787
+		$field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2788
+		if ($this->_satisfies_unique_indexes($field_n_values)) {
2789
+			$main_table = $this->_get_main_table();
2790
+			$new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
2791
+			if ($new_id !== false) {
2792
+				foreach ($this->_get_other_tables() as $other_table) {
2793
+					$this->_insert_into_specific_table($other_table, $field_n_values, $new_id);
2794
+				}
2795
+			}
2796
+			/**
2797
+			 * Done just after attempting to insert a new model object
2798
+			 *
2799
+			 * @param EEM_Base   $model           used
2800
+			 * @param array      $fields_n_values fields and their values
2801
+			 * @param int|string the              ID of the newly-inserted model object
2802
+			 */
2803
+			do_action('AHEE__EEM_Base__insert__end', $this, $field_n_values, $new_id);
2804
+			return $new_id;
2805
+		}
2806
+		return false;
2807
+	}
2808
+
2809
+
2810
+
2811
+	/**
2812
+	 * Checks that the result would satisfy the unique indexes on this model
2813
+	 *
2814
+	 * @param array  $field_n_values
2815
+	 * @param string $action
2816
+	 * @return boolean
2817
+	 * @throws EE_Error
2818
+	 */
2819
+	protected function _satisfies_unique_indexes($field_n_values, $action = 'insert')
2820
+	{
2821
+		foreach ($this->unique_indexes() as $index_name => $index) {
2822
+			$uniqueness_where_params = array_intersect_key($field_n_values, $index->fields());
2823
+			if ($this->exists(array($uniqueness_where_params))) {
2824
+				EE_Error::add_error(
2825
+					sprintf(
2826
+						__(
2827
+							"Could not %s %s. %s uniqueness index failed. Fields %s must form a unique set, but an entry already exists with values %s.",
2828
+							"event_espresso"
2829
+						),
2830
+						$action,
2831
+						$this->_get_class_name(),
2832
+						$index_name,
2833
+						implode(",", $index->field_names()),
2834
+						http_build_query($uniqueness_where_params)
2835
+					),
2836
+					__FILE__,
2837
+					__FUNCTION__,
2838
+					__LINE__
2839
+				);
2840
+				return false;
2841
+			}
2842
+		}
2843
+		return true;
2844
+	}
2845
+
2846
+
2847
+
2848
+	/**
2849
+	 * Checks the database for an item that conflicts (ie, if this item were
2850
+	 * saved to the DB would break some uniqueness requirement, like a primary key
2851
+	 * or an index primary key set) with the item specified. $id_obj_or_fields_array
2852
+	 * can be either an EE_Base_Class or an array of fields n values
2853
+	 *
2854
+	 * @param EE_Base_Class|array $obj_or_fields_array
2855
+	 * @param boolean             $include_primary_key whether to use the model object's primary key
2856
+	 *                                                 when looking for conflicts
2857
+	 *                                                 (ie, if false, we ignore the model object's primary key
2858
+	 *                                                 when finding "conflicts". If true, it's also considered).
2859
+	 *                                                 Only works for INT primary key,
2860
+	 *                                                 STRING primary keys cannot be ignored
2861
+	 * @throws EE_Error
2862
+	 * @return EE_Base_Class|array
2863
+	 */
2864
+	public function get_one_conflicting($obj_or_fields_array, $include_primary_key = true)
2865
+	{
2866
+		if ($obj_or_fields_array instanceof EE_Base_Class) {
2867
+			$fields_n_values = $obj_or_fields_array->model_field_array();
2868
+		} elseif (is_array($obj_or_fields_array)) {
2869
+			$fields_n_values = $obj_or_fields_array;
2870
+		} else {
2871
+			throw new EE_Error(
2872
+				sprintf(
2873
+					__(
2874
+						"%s get_all_conflicting should be called with a model object or an array of field names and values, you provided %d",
2875
+						"event_espresso"
2876
+					),
2877
+					get_class($this),
2878
+					$obj_or_fields_array
2879
+				)
2880
+			);
2881
+		}
2882
+		$query_params = array();
2883
+		if ($this->has_primary_key_field()
2884
+			&& ($include_primary_key
2885
+				|| $this->get_primary_key_field()
2886
+				   instanceof
2887
+				   EE_Primary_Key_String_Field)
2888
+			&& isset($fields_n_values[$this->primary_key_name()])
2889
+		) {
2890
+			$query_params[0]['OR'][$this->primary_key_name()] = $fields_n_values[$this->primary_key_name()];
2891
+		}
2892
+		foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2893
+			$uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2894
+			$query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2895
+		}
2896
+		//if there is nothing to base this search on, then we shouldn't find anything
2897
+		if (empty($query_params)) {
2898
+			return array();
2899
+		}
2900
+		return $this->get_one($query_params);
2901
+	}
2902
+
2903
+
2904
+
2905
+	/**
2906
+	 * Like count, but is optimized and returns a boolean instead of an int
2907
+	 *
2908
+	 * @param array $query_params
2909
+	 * @return boolean
2910
+	 * @throws EE_Error
2911
+	 */
2912
+	public function exists($query_params)
2913
+	{
2914
+		$query_params['limit'] = 1;
2915
+		return $this->count($query_params) > 0;
2916
+	}
2917
+
2918
+
2919
+
2920
+	/**
2921
+	 * Wrapper for exists, except ignores default query parameters so we're only considering ID
2922
+	 *
2923
+	 * @param int|string $id
2924
+	 * @return boolean
2925
+	 * @throws EE_Error
2926
+	 */
2927
+	public function exists_by_ID($id)
2928
+	{
2929
+		return $this->exists(
2930
+			array(
2931
+				'default_where_conditions' => EEM_Base::default_where_conditions_none,
2932
+				array(
2933
+					$this->primary_key_name() => $id,
2934
+				),
2935
+			)
2936
+		);
2937
+	}
2938
+
2939
+
2940
+
2941
+	/**
2942
+	 * Inserts a new row in $table, using the $cols_n_values which apply to that table.
2943
+	 * If a $new_id is supplied and if $table is an EE_Other_Table, we assume
2944
+	 * we need to add a foreign key column to point to $new_id (which should be the primary key's value
2945
+	 * on the main table)
2946
+	 * This is protected rather than private because private is not accessible to any child methods and there MAY be
2947
+	 * cases where we want to call it directly rather than via insert().
2948
+	 *
2949
+	 * @access   protected
2950
+	 * @param EE_Table_Base $table
2951
+	 * @param array         $fields_n_values each key should be in field's keys, and value should be an int, string or
2952
+	 *                                       float
2953
+	 * @param int           $new_id          for now we assume only int keys
2954
+	 * @throws EE_Error
2955
+	 * @global WPDB         $wpdb            only used to get the $wpdb->insert_id after performing an insert
2956
+	 * @return int ID of new row inserted, or FALSE on failure
2957
+	 */
2958
+	protected function _insert_into_specific_table(EE_Table_Base $table, $fields_n_values, $new_id = 0)
2959
+	{
2960
+		global $wpdb;
2961
+		$insertion_col_n_values = array();
2962
+		$format_for_insertion = array();
2963
+		$fields_on_table = $this->_get_fields_for_table($table->get_table_alias());
2964
+		foreach ($fields_on_table as $field_name => $field_obj) {
2965
+			//check if its an auto-incrementing column, in which case we should just leave it to do its autoincrement thing
2966
+			if ($field_obj->is_auto_increment()) {
2967
+				continue;
2968
+			}
2969
+			$prepared_value = $this->_prepare_value_or_use_default($field_obj, $fields_n_values);
2970
+			//if the value we want to assign it to is NULL, just don't mention it for the insertion
2971
+			if ($prepared_value !== null) {
2972
+				$insertion_col_n_values[$field_obj->get_table_column()] = $prepared_value;
2973
+				$format_for_insertion[] = $field_obj->get_wpdb_data_type();
2974
+			}
2975
+		}
2976
+		if ($table instanceof EE_Secondary_Table && $new_id) {
2977
+			//its not the main table, so we should have already saved the main table's PK which we just inserted
2978
+			//so add the fk to the main table as a column
2979
+			$insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2980
+			$format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2981
+		}
2982
+		//insert the new entry
2983
+		$result = $this->_do_wpdb_query('insert',
2984
+			array($table->get_table_name(), $insertion_col_n_values, $format_for_insertion));
2985
+		if ($result === false) {
2986
+			return false;
2987
+		}
2988
+		//ok, now what do we return for the ID of the newly-inserted thing?
2989
+		if ($this->has_primary_key_field()) {
2990
+			if ($this->get_primary_key_field()->is_auto_increment()) {
2991
+				return $wpdb->insert_id;
2992
+			}
2993
+			//it's not an auto-increment primary key, so
2994
+			//it must have been supplied
2995
+			return $fields_n_values[$this->get_primary_key_field()->get_name()];
2996
+		}
2997
+		//we can't return a  primary key because there is none. instead return
2998
+		//a unique string indicating this model
2999
+		return $this->get_index_primary_key_string($fields_n_values);
3000
+	}
3001
+
3002
+
3003
+
3004
+	/**
3005
+	 * Prepare the $field_obj 's value in $fields_n_values for use in the database.
3006
+	 * If the field doesn't allow NULL, try to use its default. (If it doesn't allow NULL,
3007
+	 * and there is no default, we pass it along. WPDB will take care of it)
3008
+	 *
3009
+	 * @param EE_Model_Field_Base $field_obj
3010
+	 * @param array               $fields_n_values
3011
+	 * @return mixed string|int|float depending on what the table column will be expecting
3012
+	 * @throws EE_Error
3013
+	 */
3014
+	protected function _prepare_value_or_use_default($field_obj, $fields_n_values)
3015
+	{
3016
+		//if this field doesn't allow nullable, don't allow it
3017
+		if (
3018
+			! $field_obj->is_nullable()
3019
+			&& (
3020
+				! isset($fields_n_values[$field_obj->get_name()])
3021
+				|| $fields_n_values[$field_obj->get_name()] === null
3022
+			)
3023
+		) {
3024
+			$fields_n_values[$field_obj->get_name()] = $field_obj->get_default_value();
3025
+		}
3026
+		$unprepared_value = isset($fields_n_values[$field_obj->get_name()])
3027
+			? $fields_n_values[$field_obj->get_name()]
3028
+			: null;
3029
+		return $this->_prepare_value_for_use_in_db($unprepared_value, $field_obj);
3030
+	}
3031
+
3032
+
3033
+
3034
+	/**
3035
+	 * Consolidates code for preparing  a value supplied to the model for use int eh db. Calls the field's
3036
+	 * prepare_for_use_in_db method on the value, and depending on $value_already_prepare_by_model_obj, may also call
3037
+	 * the field's prepare_for_set() method.
3038
+	 *
3039
+	 * @param mixed               $value value in the client code domain if $value_already_prepared_by_model_object is
3040
+	 *                                   false, otherwise a value in the model object's domain (see lengthy comment at
3041
+	 *                                   top of file)
3042
+	 * @param EE_Model_Field_Base $field field which will be doing the preparing of the value. If null, we assume
3043
+	 *                                   $value is a custom selection
3044
+	 * @return mixed a value ready for use in the database for insertions, updating, or in a where clause
3045
+	 */
3046
+	private function _prepare_value_for_use_in_db($value, $field)
3047
+	{
3048
+		if ($field && $field instanceof EE_Model_Field_Base) {
3049
+			switch ($this->_values_already_prepared_by_model_object) {
3050
+				/** @noinspection PhpMissingBreakStatementInspection */
3051
+				case self::not_prepared_by_model_object:
3052
+					$value = $field->prepare_for_set($value);
3053
+				//purposefully left out "return"
3054
+				case self::prepared_by_model_object:
3055
+					/** @noinspection SuspiciousAssignmentsInspection */
3056
+					$value = $field->prepare_for_use_in_db($value);
3057
+				case self::prepared_for_use_in_db:
3058
+					//leave the value alone
3059
+			}
3060
+			return $value;
3061
+		}
3062
+		return $value;
3063
+	}
3064
+
3065
+
3066
+
3067
+	/**
3068
+	 * Returns the main table on this model
3069
+	 *
3070
+	 * @return EE_Primary_Table
3071
+	 * @throws EE_Error
3072
+	 */
3073
+	protected function _get_main_table()
3074
+	{
3075
+		foreach ($this->_tables as $table) {
3076
+			if ($table instanceof EE_Primary_Table) {
3077
+				return $table;
3078
+			}
3079
+		}
3080
+		throw new EE_Error(sprintf(__('There are no main tables on %s. They should be added to _tables array in the constructor',
3081
+			'event_espresso'), get_class($this)));
3082
+	}
3083
+
3084
+
3085
+
3086
+	/**
3087
+	 * table
3088
+	 * returns EE_Primary_Table table name
3089
+	 *
3090
+	 * @return string
3091
+	 * @throws EE_Error
3092
+	 */
3093
+	public function table()
3094
+	{
3095
+		return $this->_get_main_table()->get_table_name();
3096
+	}
3097
+
3098
+
3099
+
3100
+	/**
3101
+	 * table
3102
+	 * returns first EE_Secondary_Table table name
3103
+	 *
3104
+	 * @return string
3105
+	 */
3106
+	public function second_table()
3107
+	{
3108
+		// grab second table from tables array
3109
+		$second_table = end($this->_tables);
3110
+		return $second_table instanceof EE_Secondary_Table ? $second_table->get_table_name() : null;
3111
+	}
3112
+
3113
+
3114
+
3115
+	/**
3116
+	 * get_table_obj_by_alias
3117
+	 * returns table name given it's alias
3118
+	 *
3119
+	 * @param string $table_alias
3120
+	 * @return EE_Primary_Table | EE_Secondary_Table
3121
+	 */
3122
+	public function get_table_obj_by_alias($table_alias = '')
3123
+	{
3124
+		return isset($this->_tables[$table_alias]) ? $this->_tables[$table_alias] : null;
3125
+	}
3126
+
3127
+
3128
+
3129
+	/**
3130
+	 * Gets all the tables of type EE_Other_Table from EEM_CPT_Basel_Model::_tables
3131
+	 *
3132
+	 * @return EE_Secondary_Table[]
3133
+	 */
3134
+	protected function _get_other_tables()
3135
+	{
3136
+		$other_tables = array();
3137
+		foreach ($this->_tables as $table_alias => $table) {
3138
+			if ($table instanceof EE_Secondary_Table) {
3139
+				$other_tables[$table_alias] = $table;
3140
+			}
3141
+		}
3142
+		return $other_tables;
3143
+	}
3144
+
3145
+
3146
+
3147
+	/**
3148
+	 * Finds all the fields that correspond to the given table
3149
+	 *
3150
+	 * @param string $table_alias , array key in EEM_Base::_tables
3151
+	 * @return EE_Model_Field_Base[]
3152
+	 */
3153
+	public function _get_fields_for_table($table_alias)
3154
+	{
3155
+		return $this->_fields[$table_alias];
3156
+	}
3157
+
3158
+
3159
+
3160
+	/**
3161
+	 * Recurses through all the where parameters, and finds all the related models we'll need
3162
+	 * to complete this query. Eg, given where parameters like array('EVT_ID'=>3) from within Event model, we won't
3163
+	 * need any related models. But if the array were array('Registrations.REG_ID'=>3), we'd need the related
3164
+	 * Registration model. If it were array('Registrations.Transactions.Payments.PAY_ID'=>3), then we'd need the
3165
+	 * related Registration, Transaction, and Payment models.
3166
+	 *
3167
+	 * @param array $query_params like EEM_Base::get_all's $query_parameters['where']
3168
+	 * @return EE_Model_Query_Info_Carrier
3169
+	 * @throws EE_Error
3170
+	 */
3171
+	public function _extract_related_models_from_query($query_params)
3172
+	{
3173
+		$query_info_carrier = new EE_Model_Query_Info_Carrier();
3174
+		if (array_key_exists(0, $query_params)) {
3175
+			$this->_extract_related_models_from_sub_params_array_keys($query_params[0], $query_info_carrier, 0);
3176
+		}
3177
+		if (array_key_exists('group_by', $query_params)) {
3178
+			if (is_array($query_params['group_by'])) {
3179
+				$this->_extract_related_models_from_sub_params_array_values(
3180
+					$query_params['group_by'],
3181
+					$query_info_carrier,
3182
+					'group_by'
3183
+				);
3184
+			} elseif (! empty ($query_params['group_by'])) {
3185
+				$this->_extract_related_model_info_from_query_param(
3186
+					$query_params['group_by'],
3187
+					$query_info_carrier,
3188
+					'group_by'
3189
+				);
3190
+			}
3191
+		}
3192
+		if (array_key_exists('having', $query_params)) {
3193
+			$this->_extract_related_models_from_sub_params_array_keys(
3194
+				$query_params[0],
3195
+				$query_info_carrier,
3196
+				'having'
3197
+			);
3198
+		}
3199
+		if (array_key_exists('order_by', $query_params)) {
3200
+			if (is_array($query_params['order_by'])) {
3201
+				$this->_extract_related_models_from_sub_params_array_keys(
3202
+					$query_params['order_by'],
3203
+					$query_info_carrier,
3204
+					'order_by'
3205
+				);
3206
+			} elseif (! empty($query_params['order_by'])) {
3207
+				$this->_extract_related_model_info_from_query_param(
3208
+					$query_params['order_by'],
3209
+					$query_info_carrier,
3210
+					'order_by'
3211
+				);
3212
+			}
3213
+		}
3214
+		if (array_key_exists('force_join', $query_params)) {
3215
+			$this->_extract_related_models_from_sub_params_array_values(
3216
+				$query_params['force_join'],
3217
+				$query_info_carrier,
3218
+				'force_join'
3219
+			);
3220
+		}
3221
+		return $query_info_carrier;
3222
+	}
3223
+
3224
+
3225
+
3226
+	/**
3227
+	 * For extracting related models from WHERE (0), HAVING (having), ORDER BY (order_by) or forced joins (force_join)
3228
+	 *
3229
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3230
+	 *                                                      $query_params['having']
3231
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3232
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3233
+	 * @throws EE_Error
3234
+	 * @return \EE_Model_Query_Info_Carrier
3235
+	 */
3236
+	private function _extract_related_models_from_sub_params_array_keys(
3237
+		$sub_query_params,
3238
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3239
+		$query_param_type
3240
+	) {
3241
+		if (! empty($sub_query_params)) {
3242
+			$sub_query_params = (array)$sub_query_params;
3243
+			foreach ($sub_query_params as $param => $possibly_array_of_params) {
3244
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3245
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3246
+					$query_param_type);
3247
+				//if $possibly_array_of_params is an array, try recursing into it, searching for keys which
3248
+				//indicate needed joins. Eg, array('NOT'=>array('Registration.TXN_ID'=>23)). In this case, we tried
3249
+				//extracting models out of the 'NOT', which obviously wasn't successful, and then we recurse into the value
3250
+				//of array('Registration.TXN_ID'=>23)
3251
+				$query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3252
+				if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3253
+					if (! is_array($possibly_array_of_params)) {
3254
+						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'))",
3255
+							"event_espresso"),
3256
+							$param, $possibly_array_of_params));
3257
+					}
3258
+					$this->_extract_related_models_from_sub_params_array_keys(
3259
+						$possibly_array_of_params,
3260
+						$model_query_info_carrier, $query_param_type
3261
+					);
3262
+				} elseif ($query_param_type === 0 //ie WHERE
3263
+						  && is_array($possibly_array_of_params)
3264
+						  && isset($possibly_array_of_params[2])
3265
+						  && $possibly_array_of_params[2] == true
3266
+				) {
3267
+					//then $possible_array_of_params looks something like array('<','DTT_sold',true)
3268
+					//indicating that $possible_array_of_params[1] is actually a field name,
3269
+					//from which we should extract query parameters!
3270
+					if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3271
+						throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3272
+							"event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3273
+					}
3274
+					$this->_extract_related_model_info_from_query_param($possibly_array_of_params[1],
3275
+						$model_query_info_carrier, $query_param_type);
3276
+				}
3277
+			}
3278
+		}
3279
+		return $model_query_info_carrier;
3280
+	}
3281
+
3282
+
3283
+
3284
+	/**
3285
+	 * For extracting related models from forced_joins, where the array values contain the info about what
3286
+	 * models to join with. Eg an array like array('Attendee','Price.Price_Type');
3287
+	 *
3288
+	 * @param array                       $sub_query_params like EEM_Base::get_all's $query_params[0] or
3289
+	 *                                                      $query_params['having']
3290
+	 * @param EE_Model_Query_Info_Carrier $model_query_info_carrier
3291
+	 * @param string                      $query_param_type one of $this->_allowed_query_params
3292
+	 * @throws EE_Error
3293
+	 * @return \EE_Model_Query_Info_Carrier
3294
+	 */
3295
+	private function _extract_related_models_from_sub_params_array_values(
3296
+		$sub_query_params,
3297
+		EE_Model_Query_Info_Carrier $model_query_info_carrier,
3298
+		$query_param_type
3299
+	) {
3300
+		if (! empty($sub_query_params)) {
3301
+			if (! is_array($sub_query_params)) {
3302
+				throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3303
+					$sub_query_params));
3304
+			}
3305
+			foreach ($sub_query_params as $param) {
3306
+				//$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3307
+				$this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
3308
+					$query_param_type);
3309
+			}
3310
+		}
3311
+		return $model_query_info_carrier;
3312
+	}
3313
+
3314
+
3315
+
3316
+	/**
3317
+	 * Extract all the query parts from $query_params (an array like whats passed to EEM_Base::get_all)
3318
+	 * and put into a EEM_Related_Model_Info_Carrier for easy extraction into a query. We create this object
3319
+	 * instead of directly constructing the SQL because often we need to extract info from the $query_params
3320
+	 * but use them in a different order. Eg, we need to know what models we are querying
3321
+	 * before we know what joins to perform. However, we need to know what data types correspond to which fields on
3322
+	 * other models before we can finalize the where clause SQL.
3323
+	 *
3324
+	 * @param array $query_params
3325
+	 * @throws EE_Error
3326
+	 * @return EE_Model_Query_Info_Carrier
3327
+	 */
3328
+	public function _create_model_query_info_carrier($query_params)
3329
+	{
3330
+		if (! is_array($query_params)) {
3331
+			EE_Error::doing_it_wrong(
3332
+				'EEM_Base::_create_model_query_info_carrier',
3333
+				sprintf(
3334
+					__(
3335
+						'$query_params should be an array, you passed a variable of type %s',
3336
+						'event_espresso'
3337
+					),
3338
+					gettype($query_params)
3339
+				),
3340
+				'4.6.0'
3341
+			);
3342
+			$query_params = array();
3343
+		}
3344
+		$where_query_params = isset($query_params[0]) ? $query_params[0] : array();
3345
+		//first check if we should alter the query to account for caps or not
3346
+		//because the caps might require us to do extra joins
3347
+		if (isset($query_params['caps']) && $query_params['caps'] !== 'none') {
3348
+			$query_params[0] = $where_query_params = array_replace_recursive(
3349
+				$where_query_params,
3350
+				$this->caps_where_conditions(
3351
+					$query_params['caps']
3352
+				)
3353
+			);
3354
+		}
3355
+		$query_object = $this->_extract_related_models_from_query($query_params);
3356
+		//verify where_query_params has NO numeric indexes.... that's simply not how you use it!
3357
+		foreach ($where_query_params as $key => $value) {
3358
+			if (is_int($key)) {
3359
+				throw new EE_Error(
3360
+					sprintf(
3361
+						__(
3362
+							"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.",
3363
+							"event_espresso"
3364
+						),
3365
+						$key,
3366
+						var_export($value, true),
3367
+						var_export($query_params, true),
3368
+						get_class($this)
3369
+					)
3370
+				);
3371
+			}
3372
+		}
3373
+		if (
3374
+			array_key_exists('default_where_conditions', $query_params)
3375
+			&& ! empty($query_params['default_where_conditions'])
3376
+		) {
3377
+			$use_default_where_conditions = $query_params['default_where_conditions'];
3378
+		} else {
3379
+			$use_default_where_conditions = EEM_Base::default_where_conditions_all;
3380
+		}
3381
+		$where_query_params = array_merge(
3382
+			$this->_get_default_where_conditions_for_models_in_query(
3383
+				$query_object,
3384
+				$use_default_where_conditions,
3385
+				$where_query_params
3386
+			),
3387
+			$where_query_params
3388
+		);
3389
+		$query_object->set_where_sql($this->_construct_where_clause($where_query_params));
3390
+		// if this is a "on_join_limit" then we are limiting on on a specific table in a multi_table join.
3391
+		// So we need to setup a subquery and use that for the main join.
3392
+		// Note for now this only works on the primary table for the model.
3393
+		// So for instance, you could set the limit array like this:
3394
+		// array( 'on_join_limit' => array('Primary_Table_Alias', array(1,10) ) )
3395
+		if (array_key_exists('on_join_limit', $query_params) && ! empty($query_params['on_join_limit'])) {
3396
+			$query_object->set_main_model_join_sql(
3397
+				$this->_construct_limit_join_select(
3398
+					$query_params['on_join_limit'][0],
3399
+					$query_params['on_join_limit'][1]
3400
+				)
3401
+			);
3402
+		}
3403
+		//set limit
3404
+		if (array_key_exists('limit', $query_params)) {
3405
+			if (is_array($query_params['limit'])) {
3406
+				if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3407
+					$e = sprintf(
3408
+						__(
3409
+							"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)",
3410
+							"event_espresso"
3411
+						),
3412
+						http_build_query($query_params['limit'])
3413
+					);
3414
+					throw new EE_Error($e . "|" . $e);
3415
+				}
3416
+				//they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3417
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3418
+			} elseif (! empty ($query_params['limit'])) {
3419
+				$query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3420
+			}
3421
+		}
3422
+		//set order by
3423
+		if (array_key_exists('order_by', $query_params)) {
3424
+			if (is_array($query_params['order_by'])) {
3425
+				//if they're using 'order_by' as an array, they can't use 'order' (because 'order_by' must
3426
+				//specify whether to ascend or descend on each field. Eg 'order_by'=>array('EVT_ID'=>'ASC'). So
3427
+				//including 'order' wouldn't make any sense if 'order_by' has already specified which way to order!
3428
+				if (array_key_exists('order', $query_params)) {
3429
+					throw new EE_Error(
3430
+						sprintf(
3431
+							__(
3432
+								"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 ",
3433
+								"event_espresso"
3434
+							),
3435
+							get_class($this),
3436
+							implode(", ", array_keys($query_params['order_by'])),
3437
+							implode(", ", $query_params['order_by']),
3438
+							$query_params['order']
3439
+						)
3440
+					);
3441
+				}
3442
+				$this->_extract_related_models_from_sub_params_array_keys(
3443
+					$query_params['order_by'],
3444
+					$query_object,
3445
+					'order_by'
3446
+				);
3447
+				//assume it's an array of fields to order by
3448
+				$order_array = array();
3449
+				foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3450
+					$order = $this->_extract_order($order);
3451
+					$order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3452
+				}
3453
+				$query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3454
+			} elseif (! empty ($query_params['order_by'])) {
3455
+				$this->_extract_related_model_info_from_query_param(
3456
+					$query_params['order_by'],
3457
+					$query_object,
3458
+					'order',
3459
+					$query_params['order_by']
3460
+				);
3461
+				$order = isset($query_params['order'])
3462
+					? $this->_extract_order($query_params['order'])
3463
+					: 'DESC';
3464
+				$query_object->set_order_by_sql(
3465
+					" ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3466
+				);
3467
+			}
3468
+		}
3469
+		//if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3470
+		if (! array_key_exists('order_by', $query_params)
3471
+			&& array_key_exists('order', $query_params)
3472
+			&& ! empty($query_params['order'])
3473
+		) {
3474
+			$pk_field = $this->get_primary_key_field();
3475
+			$order = $this->_extract_order($query_params['order']);
3476
+			$query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3477
+		}
3478
+		//set group by
3479
+		if (array_key_exists('group_by', $query_params)) {
3480
+			if (is_array($query_params['group_by'])) {
3481
+				//it's an array, so assume we'll be grouping by a bunch of stuff
3482
+				$group_by_array = array();
3483
+				foreach ($query_params['group_by'] as $field_name_to_group_by) {
3484
+					$group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3485
+				}
3486
+				$query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3487
+			} elseif (! empty ($query_params['group_by'])) {
3488
+				$query_object->set_group_by_sql(
3489
+					" GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3490
+				);
3491
+			}
3492
+		}
3493
+		//set having
3494
+		if (array_key_exists('having', $query_params) && $query_params['having']) {
3495
+			$query_object->set_having_sql($this->_construct_having_clause($query_params['having']));
3496
+		}
3497
+		//now, just verify they didn't pass anything wack
3498
+		foreach ($query_params as $query_key => $query_value) {
3499
+			if (! in_array($query_key, $this->_allowed_query_params, true)) {
3500
+				throw new EE_Error(
3501
+					sprintf(
3502
+						__(
3503
+							"You passed %s as a query parameter to %s, which is illegal! The allowed query parameters are %s",
3504
+							'event_espresso'
3505
+						),
3506
+						$query_key,
3507
+						get_class($this),
3508
+						//						print_r( $this->_allowed_query_params, TRUE )
3509
+						implode(',', $this->_allowed_query_params)
3510
+					)
3511
+				);
3512
+			}
3513
+		}
3514
+		$main_model_join_sql = $query_object->get_main_model_join_sql();
3515
+		if (empty($main_model_join_sql)) {
3516
+			$query_object->set_main_model_join_sql($this->_construct_internal_join());
3517
+		}
3518
+		return $query_object;
3519
+	}
3520
+
3521
+
3522
+
3523
+	/**
3524
+	 * Gets the where conditions that should be imposed on the query based on the
3525
+	 * context (eg reading frontend, backend, edit or delete).
3526
+	 *
3527
+	 * @param string $context one of EEM_Base::valid_cap_contexts()
3528
+	 * @return array like EEM_Base::get_all() 's $query_params[0]
3529
+	 * @throws EE_Error
3530
+	 */
3531
+	public function caps_where_conditions($context = self::caps_read)
3532
+	{
3533
+		EEM_Base::verify_is_valid_cap_context($context);
3534
+		$cap_where_conditions = array();
3535
+		$cap_restrictions = $this->caps_missing($context);
3536
+		/**
3537
+		 * @var $cap_restrictions EE_Default_Where_Conditions[]
3538
+		 */
3539
+		foreach ($cap_restrictions as $cap => $restriction_if_no_cap) {
3540
+			$cap_where_conditions = array_replace_recursive($cap_where_conditions,
3541
+				$restriction_if_no_cap->get_default_where_conditions());
3542
+		}
3543
+		return apply_filters('FHEE__EEM_Base__caps_where_conditions__return', $cap_where_conditions, $this, $context,
3544
+			$cap_restrictions);
3545
+	}
3546
+
3547
+
3548
+
3549
+	/**
3550
+	 * Verifies that $should_be_order_string is in $this->_allowed_order_values,
3551
+	 * otherwise throws an exception
3552
+	 *
3553
+	 * @param string $should_be_order_string
3554
+	 * @return string either ASC, asc, DESC or desc
3555
+	 * @throws EE_Error
3556
+	 */
3557
+	private function _extract_order($should_be_order_string)
3558
+	{
3559
+		if (in_array($should_be_order_string, $this->_allowed_order_values)) {
3560
+			return $should_be_order_string;
3561
+		}
3562
+		throw new EE_Error(
3563
+			sprintf(
3564
+				__(
3565
+					"While performing a query on '%s', tried to use '%s' as an order parameter. ",
3566
+					"event_espresso"
3567
+				), get_class($this), $should_be_order_string
3568
+			)
3569
+		);
3570
+	}
3571
+
3572
+
3573
+
3574
+	/**
3575
+	 * Looks at all the models which are included in this query, and asks each
3576
+	 * for their universal_where_params, and returns them in the same format as $query_params[0] (where),
3577
+	 * so they can be merged
3578
+	 *
3579
+	 * @param EE_Model_Query_Info_Carrier $query_info_carrier
3580
+	 * @param string                      $use_default_where_conditions can be 'none','other_models_only', or 'all'.
3581
+	 *                                                                  'none' means NO default where conditions will
3582
+	 *                                                                  be used AT ALL during this query.
3583
+	 *                                                                  'other_models_only' means default where
3584
+	 *                                                                  conditions from other models will be used, but
3585
+	 *                                                                  not for this primary model. 'all', the default,
3586
+	 *                                                                  means default where conditions will apply as
3587
+	 *                                                                  normal
3588
+	 * @param array                       $where_query_params           like EEM_Base::get_all's $query_params[0]
3589
+	 * @throws EE_Error
3590
+	 * @return array like $query_params[0], see EEM_Base::get_all for documentation
3591
+	 */
3592
+	private function _get_default_where_conditions_for_models_in_query(
3593
+		EE_Model_Query_Info_Carrier $query_info_carrier,
3594
+		$use_default_where_conditions = EEM_Base::default_where_conditions_all,
3595
+		$where_query_params = array()
3596
+	) {
3597
+		$allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3598
+		if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3599
+			throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3600
+				"event_espresso"), $use_default_where_conditions,
3601
+				implode(", ", $allowed_used_default_where_conditions_values)));
3602
+		}
3603
+		$universal_query_params = array();
3604
+		if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3605
+			$universal_query_params = $this->_get_default_where_conditions();
3606
+		} else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3607
+			$universal_query_params = $this->_get_minimum_where_conditions();
3608
+		}
3609
+		foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3610
+			$related_model = $this->get_related_model_obj($model_name);
3611
+			if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3612
+				$related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3613
+			} elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3614
+				$related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3615
+			} else {
3616
+				//we don't want to add full or even minimum default where conditions from this model, so just continue
3617
+				continue;
3618
+			}
3619
+			$overrides = $this->_override_defaults_or_make_null_friendly(
3620
+				$related_model_universal_where_params,
3621
+				$where_query_params,
3622
+				$related_model,
3623
+				$model_relation_path
3624
+			);
3625
+			$universal_query_params = EEH_Array::merge_arrays_and_overwrite_keys(
3626
+				$universal_query_params,
3627
+				$overrides
3628
+			);
3629
+		}
3630
+		return $universal_query_params;
3631
+	}
3632
+
3633
+
3634
+
3635
+	/**
3636
+	 * Determines whether or not we should use default where conditions for the model in question
3637
+	 * (this model, or other related models).
3638
+	 * Basically, we should use default where conditions on this model if they have requested to use them on all models,
3639
+	 * this model only, or to use minimum where conditions on all other models and normal where conditions on this one.
3640
+	 * We should use default where conditions on related models when they requested to use default where conditions
3641
+	 * on all models, or specifically just on other related models
3642
+	 * @param      $default_where_conditions_value
3643
+	 * @param bool $for_this_model false means this is for OTHER related models
3644
+	 * @return bool
3645
+	 */
3646
+	private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3647
+	{
3648
+		return (
3649
+				   $for_this_model
3650
+				   && in_array(
3651
+					   $default_where_conditions_value,
3652
+					   array(
3653
+						   EEM_Base::default_where_conditions_all,
3654
+						   EEM_Base::default_where_conditions_this_only,
3655
+						   EEM_Base::default_where_conditions_minimum_others,
3656
+					   ),
3657
+					   true
3658
+				   )
3659
+			   )
3660
+			   || (
3661
+				   ! $for_this_model
3662
+				   && in_array(
3663
+					   $default_where_conditions_value,
3664
+					   array(
3665
+						   EEM_Base::default_where_conditions_all,
3666
+						   EEM_Base::default_where_conditions_others_only,
3667
+					   ),
3668
+					   true
3669
+				   )
3670
+			   );
3671
+	}
3672
+
3673
+	/**
3674
+	 * Determines whether or not we should use default minimum conditions for the model in question
3675
+	 * (this model, or other related models).
3676
+	 * Basically, we should use minimum where conditions on this model only if they requested all models to use minimum
3677
+	 * where conditions.
3678
+	 * We should use minimum where conditions on related models if they requested to use minimum where conditions
3679
+	 * on this model or others
3680
+	 * @param      $default_where_conditions_value
3681
+	 * @param bool $for_this_model false means this is for OTHER related models
3682
+	 * @return bool
3683
+	 */
3684
+	private function _should_use_minimum_where_conditions($default_where_conditions_value, $for_this_model = true)
3685
+	{
3686
+		return (
3687
+				   $for_this_model
3688
+				   && $default_where_conditions_value === EEM_Base::default_where_conditions_minimum_all
3689
+			   )
3690
+			   || (
3691
+				   ! $for_this_model
3692
+				   && in_array(
3693
+					   $default_where_conditions_value,
3694
+					   array(
3695
+						   EEM_Base::default_where_conditions_minimum_others,
3696
+						   EEM_Base::default_where_conditions_minimum_all,
3697
+					   ),
3698
+					   true
3699
+				   )
3700
+			   );
3701
+	}
3702
+
3703
+
3704
+	/**
3705
+	 * Checks if any of the defaults have been overridden. If there are any that AREN'T overridden,
3706
+	 * then we also add a special where condition which allows for that model's primary key
3707
+	 * to be null (which is important for JOINs. Eg, if you want to see all Events ordered by Venue's name,
3708
+	 * then Event's with NO Venue won't appear unless you allow VNU_ID to be NULL)
3709
+	 *
3710
+	 * @param array    $default_where_conditions
3711
+	 * @param array    $provided_where_conditions
3712
+	 * @param EEM_Base $model
3713
+	 * @param string   $model_relation_path like 'Transaction.Payment.'
3714
+	 * @return array like EEM_Base::get_all's $query_params[0]
3715
+	 * @throws EE_Error
3716
+	 */
3717
+	private function _override_defaults_or_make_null_friendly(
3718
+		$default_where_conditions,
3719
+		$provided_where_conditions,
3720
+		$model,
3721
+		$model_relation_path
3722
+	) {
3723
+		$null_friendly_where_conditions = array();
3724
+		$none_overridden = true;
3725
+		$or_condition_key_for_defaults = 'OR*' . get_class($model);
3726
+		foreach ($default_where_conditions as $key => $val) {
3727
+			if (isset($provided_where_conditions[$key])) {
3728
+				$none_overridden = false;
3729
+			} else {
3730
+				$null_friendly_where_conditions[$or_condition_key_for_defaults]['AND'][$key] = $val;
3731
+			}
3732
+		}
3733
+		if ($none_overridden && $default_where_conditions) {
3734
+			if ($model->has_primary_key_field()) {
3735
+				$null_friendly_where_conditions[$or_condition_key_for_defaults][$model_relation_path
3736
+																				. "."
3737
+																				. $model->primary_key_name()] = array('IS NULL');
3738
+			}/*else{
3739 3739
 				//@todo NO PK, use other defaults
3740 3740
 			}*/
3741
-        }
3742
-        return $null_friendly_where_conditions;
3743
-    }
3744
-
3745
-
3746
-
3747
-    /**
3748
-     * Uses the _default_where_conditions_strategy set during __construct() to get
3749
-     * default where conditions on all get_all, update, and delete queries done by this model.
3750
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3751
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3752
-     *
3753
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3754
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3755
-     */
3756
-    private function _get_default_where_conditions($model_relation_path = null)
3757
-    {
3758
-        if ($this->_ignore_where_strategy) {
3759
-            return array();
3760
-        }
3761
-        return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3762
-    }
3763
-
3764
-
3765
-
3766
-    /**
3767
-     * Uses the _minimum_where_conditions_strategy set during __construct() to get
3768
-     * minimum where conditions on all get_all, update, and delete queries done by this model.
3769
-     * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3770
-     * NOT array('Event_CPT.post_type'=>'esp_event').
3771
-     * Similar to _get_default_where_conditions
3772
-     *
3773
-     * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3774
-     * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3775
-     */
3776
-    protected function _get_minimum_where_conditions($model_relation_path = null)
3777
-    {
3778
-        if ($this->_ignore_where_strategy) {
3779
-            return array();
3780
-        }
3781
-        return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3782
-    }
3783
-
3784
-
3785
-
3786
-    /**
3787
-     * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3788
-     * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3789
-     *
3790
-     * @param EE_Model_Query_Info_Carrier $model_query_info
3791
-     * @return string
3792
-     * @throws EE_Error
3793
-     */
3794
-    private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3795
-    {
3796
-        $selects = $this->_get_columns_to_select_for_this_model();
3797
-        foreach (
3798
-            $model_query_info->get_model_names_included() as $model_relation_chain =>
3799
-            $name_of_other_model_included
3800
-        ) {
3801
-            $other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3802
-            $other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3803
-            foreach ($other_model_selects as $key => $value) {
3804
-                $selects[] = $value;
3805
-            }
3806
-        }
3807
-        return implode(", ", $selects);
3808
-    }
3809
-
3810
-
3811
-
3812
-    /**
3813
-     * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3814
-     * So that's going to be the columns for all the fields on the model
3815
-     *
3816
-     * @param string $model_relation_chain like 'Question.Question_Group.Event'
3817
-     * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3818
-     */
3819
-    public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3820
-    {
3821
-        $fields = $this->field_settings();
3822
-        $selects = array();
3823
-        $table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3824
-            $this->get_this_model_name());
3825
-        foreach ($fields as $field_obj) {
3826
-            $selects[] = $table_alias_with_model_relation_chain_prefix
3827
-                         . $field_obj->get_table_alias()
3828
-                         . "."
3829
-                         . $field_obj->get_table_column()
3830
-                         . " AS '"
3831
-                         . $table_alias_with_model_relation_chain_prefix
3832
-                         . $field_obj->get_table_alias()
3833
-                         . "."
3834
-                         . $field_obj->get_table_column()
3835
-                         . "'";
3836
-        }
3837
-        //make sure we are also getting the PKs of each table
3838
-        $tables = $this->get_tables();
3839
-        if (count($tables) > 1) {
3840
-            foreach ($tables as $table_obj) {
3841
-                $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3842
-                                       . $table_obj->get_fully_qualified_pk_column();
3843
-                if (! in_array($qualified_pk_column, $selects)) {
3844
-                    $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3845
-                }
3846
-            }
3847
-        }
3848
-        return $selects;
3849
-    }
3850
-
3851
-
3852
-
3853
-    /**
3854
-     * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3855
-     * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3856
-     * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3857
-     * SQL for joining, and the data types
3858
-     *
3859
-     * @param null|string                 $original_query_param
3860
-     * @param string                      $query_param          like Registration.Transaction.TXN_ID
3861
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3862
-     * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3863
-     *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3864
-     *                                                          column name. We only want model names, eg 'Event.Venue'
3865
-     *                                                          or 'Registration's
3866
-     * @param string                      $original_query_param what it originally was (eg
3867
-     *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3868
-     *                                                          matches $query_param
3869
-     * @throws EE_Error
3870
-     * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3871
-     */
3872
-    private function _extract_related_model_info_from_query_param(
3873
-        $query_param,
3874
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3875
-        $query_param_type,
3876
-        $original_query_param = null
3877
-    ) {
3878
-        if ($original_query_param === null) {
3879
-            $original_query_param = $query_param;
3880
-        }
3881
-        $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3882
-        /** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3883
-        $allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3884
-        $allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3885
-        //check to see if we have a field on this model
3886
-        $this_model_fields = $this->field_settings(true);
3887
-        if (array_key_exists($query_param, $this_model_fields)) {
3888
-            if ($allow_fields) {
3889
-                return;
3890
-            }
3891
-            throw new EE_Error(
3892
-                sprintf(
3893
-                    __(
3894
-                        "Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3895
-                        "event_espresso"
3896
-                    ),
3897
-                    $query_param, get_class($this), $query_param_type, $original_query_param
3898
-                )
3899
-            );
3900
-        }
3901
-        //check if this is a special logic query param
3902
-        if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3903
-            if ($allow_logic_query_params) {
3904
-                return;
3905
-            }
3906
-            throw new EE_Error(
3907
-                sprintf(
3908
-                    __(
3909
-                        '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',
3910
-                        'event_espresso'
3911
-                    ),
3912
-                    implode('", "', $this->_logic_query_param_keys),
3913
-                    $query_param,
3914
-                    get_class($this),
3915
-                    '<br />',
3916
-                    "\t"
3917
-                    . ' $passed_in_query_info = <pre>'
3918
-                    . print_r($passed_in_query_info, true)
3919
-                    . '</pre>'
3920
-                    . "\n\t"
3921
-                    . ' $query_param_type = '
3922
-                    . $query_param_type
3923
-                    . "\n\t"
3924
-                    . ' $original_query_param = '
3925
-                    . $original_query_param
3926
-                )
3927
-            );
3928
-        }
3929
-        //check if it's a custom selection
3930
-        if (array_key_exists($query_param, $this->_custom_selections)) {
3931
-            return;
3932
-        }
3933
-        //check if has a model name at the beginning
3934
-        //and
3935
-        //check if it's a field on a related model
3936
-        foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3937
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3938
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3939
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3940
-                if ($query_param === '') {
3941
-                    //nothing left to $query_param
3942
-                    //we should actually end in a field name, not a model like this!
3943
-                    throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3944
-                        "event_espresso"),
3945
-                        $query_param, $query_param_type, get_class($this), $valid_related_model_name));
3946
-                }
3947
-                $related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3948
-                $related_model_obj->_extract_related_model_info_from_query_param(
3949
-                    $query_param,
3950
-                    $passed_in_query_info, $query_param_type, $original_query_param
3951
-                );
3952
-                return;
3953
-            }
3954
-            if ($query_param === $valid_related_model_name) {
3955
-                $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3956
-                return;
3957
-            }
3958
-        }
3959
-        //ok so $query_param didn't start with a model name
3960
-        //and we previously confirmed it wasn't a logic query param or field on the current model
3961
-        //it's wack, that's what it is
3962
-        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",
3963
-            "event_espresso"),
3964
-            $query_param, get_class($this), $query_param_type, $original_query_param));
3965
-    }
3966
-
3967
-
3968
-
3969
-    /**
3970
-     * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3971
-     * and store it on $passed_in_query_info
3972
-     *
3973
-     * @param string                      $model_name
3974
-     * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3975
-     * @param string                      $original_query_param used to extract the relation chain between the queried
3976
-     *                                                          model and $model_name. Eg, if we are querying Event,
3977
-     *                                                          and are adding a join to 'Payment' with the original
3978
-     *                                                          query param key
3979
-     *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3980
-     *                                                          to extract 'Registration.Transaction.Payment', in case
3981
-     *                                                          Payment wants to add default query params so that it
3982
-     *                                                          will know what models to prepend onto its default query
3983
-     *                                                          params or in case it wants to rename tables (in case
3984
-     *                                                          there are multiple joins to the same table)
3985
-     * @return void
3986
-     * @throws EE_Error
3987
-     */
3988
-    private function _add_join_to_model(
3989
-        $model_name,
3990
-        EE_Model_Query_Info_Carrier $passed_in_query_info,
3991
-        $original_query_param
3992
-    ) {
3993
-        $relation_obj = $this->related_settings_for($model_name);
3994
-        $model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3995
-        //check if the relation is HABTM, because then we're essentially doing two joins
3996
-        //If so, join first to the JOIN table, and add its data types, and then continue as normal
3997
-        if ($relation_obj instanceof EE_HABTM_Relation) {
3998
-            $join_model_obj = $relation_obj->get_join_model();
3999
-            //replace the model specified with the join model for this relation chain, whi
4000
-            $relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4001
-                $join_model_obj->get_this_model_name(), $model_relation_chain);
4002
-            $passed_in_query_info->merge(
4003
-                new EE_Model_Query_Info_Carrier(
4004
-                    array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4005
-                    $relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4006
-                )
4007
-            );
4008
-        }
4009
-        //now just join to the other table pointed to by the relation object, and add its data types
4010
-        $passed_in_query_info->merge(
4011
-            new EE_Model_Query_Info_Carrier(
4012
-                array($model_relation_chain => $model_name),
4013
-                $relation_obj->get_join_statement($model_relation_chain)
4014
-            )
4015
-        );
4016
-    }
4017
-
4018
-
4019
-
4020
-    /**
4021
-     * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4022
-     *
4023
-     * @param array $where_params like EEM_Base::get_all
4024
-     * @return string of SQL
4025
-     * @throws EE_Error
4026
-     */
4027
-    private function _construct_where_clause($where_params)
4028
-    {
4029
-        $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4030
-        if ($SQL) {
4031
-            return " WHERE " . $SQL;
4032
-        }
4033
-        return '';
4034
-    }
4035
-
4036
-
4037
-
4038
-    /**
4039
-     * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4040
-     * and should be passed HAVING parameters, not WHERE parameters
4041
-     *
4042
-     * @param array $having_params
4043
-     * @return string
4044
-     * @throws EE_Error
4045
-     */
4046
-    private function _construct_having_clause($having_params)
4047
-    {
4048
-        $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4049
-        if ($SQL) {
4050
-            return " HAVING " . $SQL;
4051
-        }
4052
-        return '';
4053
-    }
4054
-
4055
-
4056
-    /**
4057
-     * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4058
-     * Event_Meta.meta_value = 'foo'))"
4059
-     *
4060
-     * @param array  $where_params see EEM_Base::get_all for documentation
4061
-     * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4062
-     * @throws EE_Error
4063
-     * @return string of SQL
4064
-     */
4065
-    private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4066
-    {
4067
-        $where_clauses = array();
4068
-        foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4069
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4070
-            if (in_array($query_param, $this->_logic_query_param_keys)) {
4071
-                switch ($query_param) {
4072
-                    case 'not':
4073
-                    case 'NOT':
4074
-                        $where_clauses[] = "! ("
4075
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4076
-                                $glue)
4077
-                                           . ")";
4078
-                        break;
4079
-                    case 'and':
4080
-                    case 'AND':
4081
-                        $where_clauses[] = " ("
4082
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4083
-                                ' AND ')
4084
-                                           . ")";
4085
-                        break;
4086
-                    case 'or':
4087
-                    case 'OR':
4088
-                        $where_clauses[] = " ("
4089
-                                           . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4090
-                                ' OR ')
4091
-                                           . ")";
4092
-                        break;
4093
-                }
4094
-            } else {
4095
-                $field_obj = $this->_deduce_field_from_query_param($query_param);
4096
-                //if it's not a normal field, maybe it's a custom selection?
4097
-                if (! $field_obj) {
4098
-                    if (isset($this->_custom_selections[$query_param][1])) {
4099
-                        $field_obj = $this->_custom_selections[$query_param][1];
4100
-                    } else {
4101
-                        throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4102
-                            "event_espresso"), $query_param));
4103
-                    }
4104
-                }
4105
-                $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4106
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4107
-            }
4108
-        }
4109
-        return $where_clauses ? implode($glue, $where_clauses) : '';
4110
-    }
4111
-
4112
-
4113
-
4114
-    /**
4115
-     * Takes the input parameter and extract the table name (alias) and column name
4116
-     *
4117
-     * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4118
-     * @throws EE_Error
4119
-     * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4120
-     */
4121
-    private function _deduce_column_name_from_query_param($query_param)
4122
-    {
4123
-        $field = $this->_deduce_field_from_query_param($query_param);
4124
-        if ($field) {
4125
-            $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4126
-                $query_param);
4127
-            return $table_alias_prefix . $field->get_qualified_column();
4128
-        }
4129
-        if (array_key_exists($query_param, $this->_custom_selections)) {
4130
-            //maybe it's custom selection item?
4131
-            //if so, just use it as the "column name"
4132
-            return $query_param;
4133
-        }
4134
-        throw new EE_Error(
4135
-            sprintf(
4136
-                __(
4137
-                    "%s is not a valid field on this model, nor a custom selection (%s)",
4138
-                    "event_espresso"
4139
-                ), $query_param, implode(",", $this->_custom_selections)
4140
-            )
4141
-        );
4142
-    }
4143
-
4144
-
4145
-
4146
-    /**
4147
-     * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4148
-     * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4149
-     * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4150
-     * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4151
-     *
4152
-     * @param string $condition_query_param_key
4153
-     * @return string
4154
-     */
4155
-    private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4156
-    {
4157
-        $pos_of_star = strpos($condition_query_param_key, '*');
4158
-        if ($pos_of_star === false) {
4159
-            return $condition_query_param_key;
4160
-        }
4161
-        $condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4162
-        return $condition_query_param_sans_star;
4163
-    }
4164
-
4165
-
4166
-
4167
-    /**
4168
-     * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4169
-     *
4170
-     * @param                            mixed      array | string    $op_and_value
4171
-     * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4172
-     * @throws EE_Error
4173
-     * @return string
4174
-     */
4175
-    private function _construct_op_and_value($op_and_value, $field_obj)
4176
-    {
4177
-        if (is_array($op_and_value)) {
4178
-            $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4179
-            if (! $operator) {
4180
-                $php_array_like_string = array();
4181
-                foreach ($op_and_value as $key => $value) {
4182
-                    $php_array_like_string[] = "$key=>$value";
4183
-                }
4184
-                throw new EE_Error(
4185
-                    sprintf(
4186
-                        __(
4187
-                            "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))",
4188
-                            "event_espresso"
4189
-                        ),
4190
-                        implode(",", $php_array_like_string)
4191
-                    )
4192
-                );
4193
-            }
4194
-            $value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4195
-        } else {
4196
-            $operator = '=';
4197
-            $value = $op_and_value;
4198
-        }
4199
-        //check to see if the value is actually another field
4200
-        if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4201
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4202
-        }
4203
-        if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4204
-            //in this case, the value should be an array, or at least a comma-separated list
4205
-            //it will need to handle a little differently
4206
-            $cleaned_value = $this->_construct_in_value($value, $field_obj);
4207
-            //note: $cleaned_value has already been run through $wpdb->prepare()
4208
-            return $operator . SP . $cleaned_value;
4209
-        }
4210
-        if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4211
-            //the value should be an array with count of two.
4212
-            if (count($value) !== 2) {
4213
-                throw new EE_Error(
4214
-                    sprintf(
4215
-                        __(
4216
-                            "The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4217
-                            'event_espresso'
4218
-                        ),
4219
-                        "BETWEEN"
4220
-                    )
4221
-                );
4222
-            }
4223
-            $cleaned_value = $this->_construct_between_value($value, $field_obj);
4224
-            return $operator . SP . $cleaned_value;
4225
-        }
4226
-        if (in_array($operator, $this->valid_null_style_operators())) {
4227
-            if ($value !== null) {
4228
-                throw new EE_Error(
4229
-                    sprintf(
4230
-                        __(
4231
-                            "You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4232
-                            "event_espresso"
4233
-                        ),
4234
-                        $value,
4235
-                        $operator
4236
-                    )
4237
-                );
4238
-            }
4239
-            return $operator;
4240
-        }
4241
-        if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4242
-            //if the operator is 'LIKE', we want to allow percent signs (%) and not
4243
-            //remove other junk. So just treat it as a string.
4244
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4245
-        }
4246
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4247
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4248
-        }
4249
-        if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4250
-            throw new EE_Error(
4251
-                sprintf(
4252
-                    __(
4253
-                        "Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4254
-                        'event_espresso'
4255
-                    ),
4256
-                    $operator,
4257
-                    $operator
4258
-                )
4259
-            );
4260
-        }
4261
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4262
-            throw new EE_Error(
4263
-                sprintf(
4264
-                    __(
4265
-                        "Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4266
-                        'event_espresso'
4267
-                    ),
4268
-                    $operator,
4269
-                    $operator
4270
-                )
4271
-            );
4272
-        }
4273
-        throw new EE_Error(
4274
-            sprintf(
4275
-                __(
4276
-                    "It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4277
-                    "event_espresso"
4278
-                ),
4279
-                http_build_query($op_and_value)
4280
-            )
4281
-        );
4282
-    }
4283
-
4284
-
4285
-
4286
-    /**
4287
-     * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4288
-     *
4289
-     * @param array                      $values
4290
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4291
-     *                                              '%s'
4292
-     * @return string
4293
-     * @throws EE_Error
4294
-     */
4295
-    public function _construct_between_value($values, $field_obj)
4296
-    {
4297
-        $cleaned_values = array();
4298
-        foreach ($values as $value) {
4299
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4300
-        }
4301
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4302
-    }
4303
-
4304
-
4305
-
4306
-    /**
4307
-     * Takes an array or a comma-separated list of $values and cleans them
4308
-     * according to $data_type using $wpdb->prepare, and then makes the list a
4309
-     * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4310
-     * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4311
-     * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4312
-     *
4313
-     * @param mixed                      $values    array or comma-separated string
4314
-     * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4315
-     * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4316
-     * @throws EE_Error
4317
-     */
4318
-    public function _construct_in_value($values, $field_obj)
4319
-    {
4320
-        //check if the value is a CSV list
4321
-        if (is_string($values)) {
4322
-            //in which case, turn it into an array
4323
-            $values = explode(",", $values);
4324
-        }
4325
-        $cleaned_values = array();
4326
-        foreach ($values as $value) {
4327
-            $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4328
-        }
4329
-        //we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4330
-        //but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4331
-        //which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4332
-        if (empty($cleaned_values)) {
4333
-            $all_fields = $this->field_settings();
4334
-            $a_field = array_shift($all_fields);
4335
-            $main_table = $this->_get_main_table();
4336
-            $cleaned_values[] = "SELECT "
4337
-                                . $a_field->get_table_column()
4338
-                                . " FROM "
4339
-                                . $main_table->get_table_name()
4340
-                                . " WHERE FALSE";
4341
-        }
4342
-        return "(" . implode(",", $cleaned_values) . ")";
4343
-    }
4344
-
4345
-
4346
-
4347
-    /**
4348
-     * @param mixed                      $value
4349
-     * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4350
-     * @throws EE_Error
4351
-     * @return false|null|string
4352
-     */
4353
-    private function _wpdb_prepare_using_field($value, $field_obj)
4354
-    {
4355
-        /** @type WPDB $wpdb */
4356
-        global $wpdb;
4357
-        if ($field_obj instanceof EE_Model_Field_Base) {
4358
-            return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4359
-                $this->_prepare_value_for_use_in_db($value, $field_obj));
4360
-        } //$field_obj should really just be a data type
4361
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4362
-            throw new EE_Error(
4363
-                sprintf(
4364
-                    __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4365
-                    $field_obj, implode(",", $this->_valid_wpdb_data_types)
4366
-                )
4367
-            );
4368
-        }
4369
-        return $wpdb->prepare($field_obj, $value);
4370
-    }
4371
-
4372
-
4373
-
4374
-    /**
4375
-     * Takes the input parameter and finds the model field that it indicates.
4376
-     *
4377
-     * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4378
-     * @throws EE_Error
4379
-     * @return EE_Model_Field_Base
4380
-     */
4381
-    protected function _deduce_field_from_query_param($query_param_name)
4382
-    {
4383
-        //ok, now proceed with deducing which part is the model's name, and which is the field's name
4384
-        //which will help us find the database table and column
4385
-        $query_param_parts = explode(".", $query_param_name);
4386
-        if (empty($query_param_parts)) {
4387
-            throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4388
-                'event_espresso'), $query_param_name));
4389
-        }
4390
-        $number_of_parts = count($query_param_parts);
4391
-        $last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4392
-        if ($number_of_parts === 1) {
4393
-            $field_name = $last_query_param_part;
4394
-            $model_obj = $this;
4395
-        } else {// $number_of_parts >= 2
4396
-            //the last part is the column name, and there are only 2parts. therefore...
4397
-            $field_name = $last_query_param_part;
4398
-            $model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4399
-        }
4400
-        try {
4401
-            return $model_obj->field_settings_for($field_name);
4402
-        } catch (EE_Error $e) {
4403
-            return null;
4404
-        }
4405
-    }
4406
-
4407
-
4408
-
4409
-    /**
4410
-     * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4411
-     * alias and column which corresponds to it
4412
-     *
4413
-     * @param string $field_name
4414
-     * @throws EE_Error
4415
-     * @return string
4416
-     */
4417
-    public function _get_qualified_column_for_field($field_name)
4418
-    {
4419
-        $all_fields = $this->field_settings();
4420
-        $field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4421
-        if ($field) {
4422
-            return $field->get_qualified_column();
4423
-        }
4424
-        throw new EE_Error(
4425
-            sprintf(
4426
-                __(
4427
-                    "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.",
4428
-                    'event_espresso'
4429
-                ), $field_name, get_class($this)
4430
-            )
4431
-        );
4432
-    }
4433
-
4434
-
4435
-
4436
-    /**
4437
-     * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4438
-     * Example usage:
4439
-     * EEM_Ticket::instance()->get_all_wpdb_results(
4440
-     *      array(),
4441
-     *      ARRAY_A,
4442
-     *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4443
-     *  );
4444
-     * is equivalent to
4445
-     *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4446
-     * and
4447
-     *  EEM_Event::instance()->get_all_wpdb_results(
4448
-     *      array(
4449
-     *          array(
4450
-     *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4451
-     *          ),
4452
-     *          ARRAY_A,
4453
-     *          implode(
4454
-     *              ', ',
4455
-     *              array_merge(
4456
-     *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4457
-     *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4458
-     *              )
4459
-     *          )
4460
-     *      )
4461
-     *  );
4462
-     * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4463
-     *
4464
-     * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4465
-     *                                            and the one whose fields you are selecting for example: when querying
4466
-     *                                            tickets model and selecting fields from the tickets model you would
4467
-     *                                            leave this parameter empty, because no models are needed to join
4468
-     *                                            between the queried model and the selected one. Likewise when
4469
-     *                                            querying the datetime model and selecting fields from the tickets
4470
-     *                                            model, it would also be left empty, because there is a direct
4471
-     *                                            relation from datetimes to tickets, so no model is needed to join
4472
-     *                                            them together. However, when querying from the event model and
4473
-     *                                            selecting fields from the ticket model, you should provide the string
4474
-     *                                            'Datetime', indicating that the event model must first join to the
4475
-     *                                            datetime model in order to find its relation to ticket model.
4476
-     *                                            Also, when querying from the venue model and selecting fields from
4477
-     *                                            the ticket model, you should provide the string 'Event.Datetime',
4478
-     *                                            indicating you need to join the venue model to the event model,
4479
-     *                                            to the datetime model, in order to find its relation to the ticket model.
4480
-     *                                            This string is used to deduce the prefix that gets added onto the
4481
-     *                                            models' tables qualified columns
4482
-     * @param bool   $return_string               if true, will return a string with qualified column names separated
4483
-     *                                            by ', ' if false, will simply return a numerically indexed array of
4484
-     *                                            qualified column names
4485
-     * @return array|string
4486
-     */
4487
-    public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4488
-    {
4489
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4490
-        $qualified_columns = array();
4491
-        foreach ($this->field_settings() as $field_name => $field) {
4492
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4493
-        }
4494
-        return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4495
-    }
4496
-
4497
-
4498
-
4499
-    /**
4500
-     * constructs the select use on special limit joins
4501
-     * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4502
-     * its setup so the select query will be setup on and just doing the special select join off of the primary table
4503
-     * (as that is typically where the limits would be set).
4504
-     *
4505
-     * @param  string       $table_alias The table the select is being built for
4506
-     * @param  mixed|string $limit       The limit for this select
4507
-     * @return string                The final select join element for the query.
4508
-     */
4509
-    public function _construct_limit_join_select($table_alias, $limit)
4510
-    {
4511
-        $SQL = '';
4512
-        foreach ($this->_tables as $table_obj) {
4513
-            if ($table_obj instanceof EE_Primary_Table) {
4514
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4515
-                    ? $table_obj->get_select_join_limit($limit)
4516
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4517
-            } elseif ($table_obj instanceof EE_Secondary_Table) {
4518
-                $SQL .= $table_alias === $table_obj->get_table_alias()
4519
-                    ? $table_obj->get_select_join_limit_join($limit)
4520
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4521
-            }
4522
-        }
4523
-        return $SQL;
4524
-    }
4525
-
4526
-
4527
-
4528
-    /**
4529
-     * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4530
-     * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4531
-     *
4532
-     * @return string SQL
4533
-     * @throws EE_Error
4534
-     */
4535
-    public function _construct_internal_join()
4536
-    {
4537
-        $SQL = $this->_get_main_table()->get_table_sql();
4538
-        $SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4539
-        return $SQL;
4540
-    }
4541
-
4542
-
4543
-
4544
-    /**
4545
-     * Constructs the SQL for joining all the tables on this model.
4546
-     * Normally $alias should be the primary table's alias, but in cases where
4547
-     * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4548
-     * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4549
-     * alias, this will construct SQL like:
4550
-     * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4551
-     * With $alias being a secondary table's alias, this will construct SQL like:
4552
-     * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4553
-     *
4554
-     * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4555
-     * @return string
4556
-     */
4557
-    public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4558
-    {
4559
-        $SQL = '';
4560
-        $alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4561
-        foreach ($this->_tables as $table_obj) {
4562
-            if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4563
-                if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4564
-                    //so we're joining to this table, meaning the table is already in
4565
-                    //the FROM statement, BUT the primary table isn't. So we want
4566
-                    //to add the inverse join sql
4567
-                    $SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4568
-                } else {
4569
-                    //just add a regular JOIN to this table from the primary table
4570
-                    $SQL .= $table_obj->get_join_sql($alias_prefixed);
4571
-                }
4572
-            }//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4573
-        }
4574
-        return $SQL;
4575
-    }
4576
-
4577
-
4578
-
4579
-    /**
4580
-     * Gets an array for storing all the data types on the next-to-be-executed-query.
4581
-     * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4582
-     * their data type (eg, '%s', '%d', etc)
4583
-     *
4584
-     * @return array
4585
-     */
4586
-    public function _get_data_types()
4587
-    {
4588
-        $data_types = array();
4589
-        foreach ($this->field_settings() as $field_obj) {
4590
-            //$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4591
-            /** @var $field_obj EE_Model_Field_Base */
4592
-            $data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4593
-        }
4594
-        return $data_types;
4595
-    }
4596
-
4597
-
4598
-
4599
-    /**
4600
-     * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4601
-     *
4602
-     * @param string $model_name
4603
-     * @throws EE_Error
4604
-     * @return EEM_Base
4605
-     */
4606
-    public function get_related_model_obj($model_name)
4607
-    {
4608
-        $model_classname = "EEM_" . $model_name;
4609
-        if (! class_exists($model_classname)) {
4610
-            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",
4611
-                'event_espresso'), $model_name, $model_classname));
4612
-        }
4613
-        return call_user_func($model_classname . "::instance");
4614
-    }
4615
-
4616
-
4617
-
4618
-    /**
4619
-     * Returns the array of EE_ModelRelations for this model.
4620
-     *
4621
-     * @return EE_Model_Relation_Base[]
4622
-     */
4623
-    public function relation_settings()
4624
-    {
4625
-        return $this->_model_relations;
4626
-    }
4627
-
4628
-
4629
-
4630
-    /**
4631
-     * Gets all related models that this model BELONGS TO. Handy to know sometimes
4632
-     * because without THOSE models, this model probably doesn't have much purpose.
4633
-     * (Eg, without an event, datetimes have little purpose.)
4634
-     *
4635
-     * @return EE_Belongs_To_Relation[]
4636
-     */
4637
-    public function belongs_to_relations()
4638
-    {
4639
-        $belongs_to_relations = array();
4640
-        foreach ($this->relation_settings() as $model_name => $relation_obj) {
4641
-            if ($relation_obj instanceof EE_Belongs_To_Relation) {
4642
-                $belongs_to_relations[$model_name] = $relation_obj;
4643
-            }
4644
-        }
4645
-        return $belongs_to_relations;
4646
-    }
4647
-
4648
-
4649
-
4650
-    /**
4651
-     * Returns the specified EE_Model_Relation, or throws an exception
4652
-     *
4653
-     * @param string $relation_name name of relation, key in $this->_relatedModels
4654
-     * @throws EE_Error
4655
-     * @return EE_Model_Relation_Base
4656
-     */
4657
-    public function related_settings_for($relation_name)
4658
-    {
4659
-        $relatedModels = $this->relation_settings();
4660
-        if (! array_key_exists($relation_name, $relatedModels)) {
4661
-            throw new EE_Error(
4662
-                sprintf(
4663
-                    __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4664
-                        'event_espresso'),
4665
-                    $relation_name,
4666
-                    $this->_get_class_name(),
4667
-                    implode(', ', array_keys($relatedModels))
4668
-                )
4669
-            );
4670
-        }
4671
-        return $relatedModels[$relation_name];
4672
-    }
4673
-
4674
-
4675
-
4676
-    /**
4677
-     * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4678
-     * fields
4679
-     *
4680
-     * @param string $fieldName
4681
-     * @param boolean $include_db_only_fields
4682
-     * @throws EE_Error
4683
-     * @return EE_Model_Field_Base
4684
-     */
4685
-    public function field_settings_for($fieldName, $include_db_only_fields = true)
4686
-    {
4687
-        $fieldSettings = $this->field_settings($include_db_only_fields);
4688
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4689
-            throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4690
-                get_class($this)));
4691
-        }
4692
-        return $fieldSettings[$fieldName];
4693
-    }
4694
-
4695
-
4696
-
4697
-    /**
4698
-     * Checks if this field exists on this model
4699
-     *
4700
-     * @param string $fieldName a key in the model's _field_settings array
4701
-     * @return boolean
4702
-     */
4703
-    public function has_field($fieldName)
4704
-    {
4705
-        $fieldSettings = $this->field_settings(true);
4706
-        if (isset($fieldSettings[$fieldName])) {
4707
-            return true;
4708
-        }
4709
-        return false;
4710
-    }
4711
-
4712
-
4713
-
4714
-    /**
4715
-     * Returns whether or not this model has a relation to the specified model
4716
-     *
4717
-     * @param string $relation_name possibly one of the keys in the relation_settings array
4718
-     * @return boolean
4719
-     */
4720
-    public function has_relation($relation_name)
4721
-    {
4722
-        $relations = $this->relation_settings();
4723
-        if (isset($relations[$relation_name])) {
4724
-            return true;
4725
-        }
4726
-        return false;
4727
-    }
4728
-
4729
-
4730
-
4731
-    /**
4732
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4733
-     * Eg, on EE_Answer that would be ANS_ID field object
4734
-     *
4735
-     * @param $field_obj
4736
-     * @return boolean
4737
-     */
4738
-    public function is_primary_key_field($field_obj)
4739
-    {
4740
-        return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4741
-    }
4742
-
4743
-
4744
-
4745
-    /**
4746
-     * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747
-     * Eg, on EE_Answer that would be ANS_ID field object
4748
-     *
4749
-     * @return EE_Model_Field_Base
4750
-     * @throws EE_Error
4751
-     */
4752
-    public function get_primary_key_field()
4753
-    {
4754
-        if ($this->_primary_key_field === null) {
4755
-            foreach ($this->field_settings(true) as $field_obj) {
4756
-                if ($this->is_primary_key_field($field_obj)) {
4757
-                    $this->_primary_key_field = $field_obj;
4758
-                    break;
4759
-                }
4760
-            }
4761
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4762
-                throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4763
-                    get_class($this)));
4764
-            }
4765
-        }
4766
-        return $this->_primary_key_field;
4767
-    }
4768
-
4769
-
4770
-
4771
-    /**
4772
-     * Returns whether or not not there is a primary key on this model.
4773
-     * Internally does some caching.
4774
-     *
4775
-     * @return boolean
4776
-     */
4777
-    public function has_primary_key_field()
4778
-    {
4779
-        if ($this->_has_primary_key_field === null) {
4780
-            try {
4781
-                $this->get_primary_key_field();
4782
-                $this->_has_primary_key_field = true;
4783
-            } catch (EE_Error $e) {
4784
-                $this->_has_primary_key_field = false;
4785
-            }
4786
-        }
4787
-        return $this->_has_primary_key_field;
4788
-    }
4789
-
4790
-
4791
-
4792
-    /**
4793
-     * Finds the first field of type $field_class_name.
4794
-     *
4795
-     * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4796
-     *                                 EE_Foreign_Key_Field, etc
4797
-     * @return EE_Model_Field_Base or null if none is found
4798
-     */
4799
-    public function get_a_field_of_type($field_class_name)
4800
-    {
4801
-        foreach ($this->field_settings() as $field) {
4802
-            if ($field instanceof $field_class_name) {
4803
-                return $field;
4804
-            }
4805
-        }
4806
-        return null;
4807
-    }
4808
-
4809
-
4810
-
4811
-    /**
4812
-     * Gets a foreign key field pointing to model.
4813
-     *
4814
-     * @param string $model_name eg Event, Registration, not EEM_Event
4815
-     * @return EE_Foreign_Key_Field_Base
4816
-     * @throws EE_Error
4817
-     */
4818
-    public function get_foreign_key_to($model_name)
4819
-    {
4820
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4821
-            foreach ($this->field_settings() as $field) {
4822
-                if (
4823
-                    $field instanceof EE_Foreign_Key_Field_Base
4824
-                    && in_array($model_name, $field->get_model_names_pointed_to())
4825
-                ) {
4826
-                    $this->_cache_foreign_key_to_fields[$model_name] = $field;
4827
-                    break;
4828
-                }
4829
-            }
4830
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4831
-                throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4832
-                    'event_espresso'), $model_name, get_class($this)));
4833
-            }
4834
-        }
4835
-        return $this->_cache_foreign_key_to_fields[$model_name];
4836
-    }
4837
-
4838
-
4839
-
4840
-    /**
4841
-     * Gets the table name (including $wpdb->prefix) for the table alias
4842
-     *
4843
-     * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4844
-     *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4845
-     *                            Either one works
4846
-     * @return string
4847
-     */
4848
-    public function get_table_for_alias($table_alias)
4849
-    {
4850
-        $table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4851
-        return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4852
-    }
4853
-
4854
-
4855
-
4856
-    /**
4857
-     * Returns a flat array of all field son this model, instead of organizing them
4858
-     * by table_alias as they are in the constructor.
4859
-     *
4860
-     * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4861
-     * @return EE_Model_Field_Base[] where the keys are the field's name
4862
-     */
4863
-    public function field_settings($include_db_only_fields = false)
4864
-    {
4865
-        if ($include_db_only_fields) {
4866
-            if ($this->_cached_fields === null) {
4867
-                $this->_cached_fields = array();
4868
-                foreach ($this->_fields as $fields_corresponding_to_table) {
4869
-                    foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4870
-                        $this->_cached_fields[$field_name] = $field_obj;
4871
-                    }
4872
-                }
4873
-            }
4874
-            return $this->_cached_fields;
4875
-        }
4876
-        if ($this->_cached_fields_non_db_only === null) {
4877
-            $this->_cached_fields_non_db_only = array();
4878
-            foreach ($this->_fields as $fields_corresponding_to_table) {
4879
-                foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4880
-                    /** @var $field_obj EE_Model_Field_Base */
4881
-                    if (! $field_obj->is_db_only_field()) {
4882
-                        $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4883
-                    }
4884
-                }
4885
-            }
4886
-        }
4887
-        return $this->_cached_fields_non_db_only;
4888
-    }
4889
-
4890
-
4891
-
4892
-    /**
4893
-     *        cycle though array of attendees and create objects out of each item
4894
-     *
4895
-     * @access        private
4896
-     * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4897
-     * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4898
-     *                           numerically indexed)
4899
-     * @throws EE_Error
4900
-     */
4901
-    protected function _create_objects($rows = array())
4902
-    {
4903
-        $array_of_objects = array();
4904
-        if (empty($rows)) {
4905
-            return array();
4906
-        }
4907
-        $count_if_model_has_no_primary_key = 0;
4908
-        $has_primary_key = $this->has_primary_key_field();
4909
-        $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4910
-        foreach ((array)$rows as $row) {
4911
-            if (empty($row)) {
4912
-                //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4913
-                return array();
4914
-            }
4915
-            //check if we've already set this object in the results array,
4916
-            //in which case there's no need to process it further (again)
4917
-            if ($has_primary_key) {
4918
-                $table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4919
-                    $row,
4920
-                    $primary_key_field->get_qualified_column(),
4921
-                    $primary_key_field->get_table_column()
4922
-                );
4923
-                if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4924
-                    continue;
4925
-                }
4926
-            }
4927
-            $classInstance = $this->instantiate_class_from_array_or_object($row);
4928
-            if (! $classInstance) {
4929
-                throw new EE_Error(
4930
-                    sprintf(
4931
-                        __('Could not create instance of class %s from row %s', 'event_espresso'),
4932
-                        $this->get_this_model_name(),
4933
-                        http_build_query($row)
4934
-                    )
4935
-                );
4936
-            }
4937
-            //set the timezone on the instantiated objects
4938
-            $classInstance->set_timezone($this->_timezone);
4939
-            //make sure if there is any timezone setting present that we set the timezone for the object
4940
-            $key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4941
-            $array_of_objects[$key] = $classInstance;
4942
-            //also, for all the relations of type BelongsTo, see if we can cache
4943
-            //those related models
4944
-            //(we could do this for other relations too, but if there are conditions
4945
-            //that filtered out some fo the results, then we'd be caching an incomplete set
4946
-            //so it requires a little more thought than just caching them immediately...)
4947
-            foreach ($this->_model_relations as $modelName => $relation_obj) {
4948
-                if ($relation_obj instanceof EE_Belongs_To_Relation) {
4949
-                    //check if this model's INFO is present. If so, cache it on the model
4950
-                    $other_model = $relation_obj->get_other_model();
4951
-                    $other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4952
-                    //if we managed to make a model object from the results, cache it on the main model object
4953
-                    if ($other_model_obj_maybe) {
4954
-                        //set timezone on these other model objects if they are present
4955
-                        $other_model_obj_maybe->set_timezone($this->_timezone);
4956
-                        $classInstance->cache($modelName, $other_model_obj_maybe);
4957
-                    }
4958
-                }
4959
-            }
4960
-        }
4961
-        return $array_of_objects;
4962
-    }
4963
-
4964
-
4965
-
4966
-    /**
4967
-     * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4968
-     * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4969
-     * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4970
-     * object (as set in the model_field!).
4971
-     *
4972
-     * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4973
-     */
4974
-    public function create_default_object()
4975
-    {
4976
-        $this_model_fields_and_values = array();
4977
-        //setup the row using default values;
4978
-        foreach ($this->field_settings() as $field_name => $field_obj) {
4979
-            $this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4980
-        }
4981
-        $className = $this->_get_class_name();
4982
-        $classInstance = EE_Registry::instance()
4983
-                                    ->load_class($className, array($this_model_fields_and_values), false, false);
4984
-        return $classInstance;
4985
-    }
4986
-
4987
-
4988
-
4989
-    /**
4990
-     * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4991
-     *                             or an stdClass where each property is the name of a column,
4992
-     * @return EE_Base_Class
4993
-     * @throws EE_Error
4994
-     */
4995
-    public function instantiate_class_from_array_or_object($cols_n_values)
4996
-    {
4997
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4998
-            $cols_n_values = get_object_vars($cols_n_values);
4999
-        }
5000
-        $primary_key = null;
5001
-        //make sure the array only has keys that are fields/columns on this model
5002
-        $this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5003
-        if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5004
-            $primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5005
-        }
5006
-        $className = $this->_get_class_name();
5007
-        //check we actually found results that we can use to build our model object
5008
-        //if not, return null
5009
-        if ($this->has_primary_key_field()) {
5010
-            if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5011
-                return null;
5012
-            }
5013
-        } else if ($this->unique_indexes()) {
5014
-            $first_column = reset($this_model_fields_n_values);
5015
-            if (empty($first_column)) {
5016
-                return null;
5017
-            }
5018
-        }
5019
-        // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5020
-        if ($primary_key) {
5021
-            $classInstance = $this->get_from_entity_map($primary_key);
5022
-            if (! $classInstance) {
5023
-                $classInstance = EE_Registry::instance()
5024
-                                            ->load_class($className,
5025
-                                                array($this_model_fields_n_values, $this->_timezone), true, false);
5026
-                // add this new object to the entity map
5027
-                $classInstance = $this->add_to_entity_map($classInstance);
5028
-            }
5029
-        } else {
5030
-            $classInstance = EE_Registry::instance()
5031
-                                        ->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5032
-                                            true, false);
5033
-        }
5034
-        //it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
5035
-        $this->set_timezone($classInstance->get_timezone());
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
-    }
3741
+		}
3742
+		return $null_friendly_where_conditions;
3743
+	}
3744
+
3745
+
3746
+
3747
+	/**
3748
+	 * Uses the _default_where_conditions_strategy set during __construct() to get
3749
+	 * default where conditions on all get_all, update, and delete queries done by this model.
3750
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3751
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3752
+	 *
3753
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3754
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3755
+	 */
3756
+	private function _get_default_where_conditions($model_relation_path = null)
3757
+	{
3758
+		if ($this->_ignore_where_strategy) {
3759
+			return array();
3760
+		}
3761
+		return $this->_default_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3762
+	}
3763
+
3764
+
3765
+
3766
+	/**
3767
+	 * Uses the _minimum_where_conditions_strategy set during __construct() to get
3768
+	 * minimum where conditions on all get_all, update, and delete queries done by this model.
3769
+	 * Use the same syntax as client code. Eg on the Event model, use array('Event.EVT_post_type'=>'esp_event'),
3770
+	 * NOT array('Event_CPT.post_type'=>'esp_event').
3771
+	 * Similar to _get_default_where_conditions
3772
+	 *
3773
+	 * @param string $model_relation_path eg, path from Event to Payment is "Registration.Transaction.Payment."
3774
+	 * @return array like EEM_Base::get_all's $query_params[0] (where conditions)
3775
+	 */
3776
+	protected function _get_minimum_where_conditions($model_relation_path = null)
3777
+	{
3778
+		if ($this->_ignore_where_strategy) {
3779
+			return array();
3780
+		}
3781
+		return $this->_minimum_where_conditions_strategy->get_default_where_conditions($model_relation_path);
3782
+	}
3783
+
3784
+
3785
+
3786
+	/**
3787
+	 * Creates the string of SQL for the select part of a select query, everything behind SELECT and before FROM.
3788
+	 * Eg, "Event.post_id, Event.post_name,Event_Detail.EVT_ID..."
3789
+	 *
3790
+	 * @param EE_Model_Query_Info_Carrier $model_query_info
3791
+	 * @return string
3792
+	 * @throws EE_Error
3793
+	 */
3794
+	private function _construct_default_select_sql(EE_Model_Query_Info_Carrier $model_query_info)
3795
+	{
3796
+		$selects = $this->_get_columns_to_select_for_this_model();
3797
+		foreach (
3798
+			$model_query_info->get_model_names_included() as $model_relation_chain =>
3799
+			$name_of_other_model_included
3800
+		) {
3801
+			$other_model_included = $this->get_related_model_obj($name_of_other_model_included);
3802
+			$other_model_selects = $other_model_included->_get_columns_to_select_for_this_model($model_relation_chain);
3803
+			foreach ($other_model_selects as $key => $value) {
3804
+				$selects[] = $value;
3805
+			}
3806
+		}
3807
+		return implode(", ", $selects);
3808
+	}
3809
+
3810
+
3811
+
3812
+	/**
3813
+	 * Gets an array of columns to select for this model, which are necessary for it to create its objects.
3814
+	 * So that's going to be the columns for all the fields on the model
3815
+	 *
3816
+	 * @param string $model_relation_chain like 'Question.Question_Group.Event'
3817
+	 * @return array numerically indexed, values are columns to select and rename, eg "Event.ID AS 'Event.ID'"
3818
+	 */
3819
+	public function _get_columns_to_select_for_this_model($model_relation_chain = '')
3820
+	{
3821
+		$fields = $this->field_settings();
3822
+		$selects = array();
3823
+		$table_alias_with_model_relation_chain_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_prefix($model_relation_chain,
3824
+			$this->get_this_model_name());
3825
+		foreach ($fields as $field_obj) {
3826
+			$selects[] = $table_alias_with_model_relation_chain_prefix
3827
+						 . $field_obj->get_table_alias()
3828
+						 . "."
3829
+						 . $field_obj->get_table_column()
3830
+						 . " AS '"
3831
+						 . $table_alias_with_model_relation_chain_prefix
3832
+						 . $field_obj->get_table_alias()
3833
+						 . "."
3834
+						 . $field_obj->get_table_column()
3835
+						 . "'";
3836
+		}
3837
+		//make sure we are also getting the PKs of each table
3838
+		$tables = $this->get_tables();
3839
+		if (count($tables) > 1) {
3840
+			foreach ($tables as $table_obj) {
3841
+				$qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3842
+									   . $table_obj->get_fully_qualified_pk_column();
3843
+				if (! in_array($qualified_pk_column, $selects)) {
3844
+					$selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3845
+				}
3846
+			}
3847
+		}
3848
+		return $selects;
3849
+	}
3850
+
3851
+
3852
+
3853
+	/**
3854
+	 * Given a $query_param like 'Registration.Transaction.TXN_ID', pops off 'Registration.',
3855
+	 * gets the join statement for it; gets the data types for it; and passes the remaining 'Transaction.TXN_ID'
3856
+	 * onto its related Transaction object to do the same. Returns an EE_Join_And_Data_Types object which contains the
3857
+	 * SQL for joining, and the data types
3858
+	 *
3859
+	 * @param null|string                 $original_query_param
3860
+	 * @param string                      $query_param          like Registration.Transaction.TXN_ID
3861
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3862
+	 * @param    string                   $query_param_type     like Registration.Transaction.TXN_ID
3863
+	 *                                                          or 'PAY_ID'. Otherwise, we don't expect there to be a
3864
+	 *                                                          column name. We only want model names, eg 'Event.Venue'
3865
+	 *                                                          or 'Registration's
3866
+	 * @param string                      $original_query_param what it originally was (eg
3867
+	 *                                                          Registration.Transaction.TXN_ID). If null, we assume it
3868
+	 *                                                          matches $query_param
3869
+	 * @throws EE_Error
3870
+	 * @return void only modifies the EEM_Related_Model_Info_Carrier passed into it
3871
+	 */
3872
+	private function _extract_related_model_info_from_query_param(
3873
+		$query_param,
3874
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3875
+		$query_param_type,
3876
+		$original_query_param = null
3877
+	) {
3878
+		if ($original_query_param === null) {
3879
+			$original_query_param = $query_param;
3880
+		}
3881
+		$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);
3882
+		/** @var $allow_logic_query_params bool whether or not to allow logic_query_params like 'NOT','OR', or 'AND' */
3883
+		$allow_logic_query_params = in_array($query_param_type, array('where', 'having'));
3884
+		$allow_fields = in_array($query_param_type, array('where', 'having', 'order_by', 'group_by', 'order'));
3885
+		//check to see if we have a field on this model
3886
+		$this_model_fields = $this->field_settings(true);
3887
+		if (array_key_exists($query_param, $this_model_fields)) {
3888
+			if ($allow_fields) {
3889
+				return;
3890
+			}
3891
+			throw new EE_Error(
3892
+				sprintf(
3893
+					__(
3894
+						"Using a field name (%s) on model %s is not allowed on this query param type '%s'. Original query param was %s",
3895
+						"event_espresso"
3896
+					),
3897
+					$query_param, get_class($this), $query_param_type, $original_query_param
3898
+				)
3899
+			);
3900
+		}
3901
+		//check if this is a special logic query param
3902
+		if (in_array($query_param, $this->_logic_query_param_keys, true)) {
3903
+			if ($allow_logic_query_params) {
3904
+				return;
3905
+			}
3906
+			throw new EE_Error(
3907
+				sprintf(
3908
+					__(
3909
+						'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',
3910
+						'event_espresso'
3911
+					),
3912
+					implode('", "', $this->_logic_query_param_keys),
3913
+					$query_param,
3914
+					get_class($this),
3915
+					'<br />',
3916
+					"\t"
3917
+					. ' $passed_in_query_info = <pre>'
3918
+					. print_r($passed_in_query_info, true)
3919
+					. '</pre>'
3920
+					. "\n\t"
3921
+					. ' $query_param_type = '
3922
+					. $query_param_type
3923
+					. "\n\t"
3924
+					. ' $original_query_param = '
3925
+					. $original_query_param
3926
+				)
3927
+			);
3928
+		}
3929
+		//check if it's a custom selection
3930
+		if (array_key_exists($query_param, $this->_custom_selections)) {
3931
+			return;
3932
+		}
3933
+		//check if has a model name at the beginning
3934
+		//and
3935
+		//check if it's a field on a related model
3936
+		foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3937
+			if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3938
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3939
+				$query_param = substr($query_param, strlen($valid_related_model_name . "."));
3940
+				if ($query_param === '') {
3941
+					//nothing left to $query_param
3942
+					//we should actually end in a field name, not a model like this!
3943
+					throw new EE_Error(sprintf(__("Query param '%s' (of type %s on model %s) shouldn't end on a period (.) ",
3944
+						"event_espresso"),
3945
+						$query_param, $query_param_type, get_class($this), $valid_related_model_name));
3946
+				}
3947
+				$related_model_obj = $this->get_related_model_obj($valid_related_model_name);
3948
+				$related_model_obj->_extract_related_model_info_from_query_param(
3949
+					$query_param,
3950
+					$passed_in_query_info, $query_param_type, $original_query_param
3951
+				);
3952
+				return;
3953
+			}
3954
+			if ($query_param === $valid_related_model_name) {
3955
+				$this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3956
+				return;
3957
+			}
3958
+		}
3959
+		//ok so $query_param didn't start with a model name
3960
+		//and we previously confirmed it wasn't a logic query param or field on the current model
3961
+		//it's wack, that's what it is
3962
+		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",
3963
+			"event_espresso"),
3964
+			$query_param, get_class($this), $query_param_type, $original_query_param));
3965
+	}
3966
+
3967
+
3968
+
3969
+	/**
3970
+	 * Privately used by _extract_related_model_info_from_query_param to add a join to $model_name
3971
+	 * and store it on $passed_in_query_info
3972
+	 *
3973
+	 * @param string                      $model_name
3974
+	 * @param EE_Model_Query_Info_Carrier $passed_in_query_info
3975
+	 * @param string                      $original_query_param used to extract the relation chain between the queried
3976
+	 *                                                          model and $model_name. Eg, if we are querying Event,
3977
+	 *                                                          and are adding a join to 'Payment' with the original
3978
+	 *                                                          query param key
3979
+	 *                                                          'Registration.Transaction.Payment.PAY_amount', we want
3980
+	 *                                                          to extract 'Registration.Transaction.Payment', in case
3981
+	 *                                                          Payment wants to add default query params so that it
3982
+	 *                                                          will know what models to prepend onto its default query
3983
+	 *                                                          params or in case it wants to rename tables (in case
3984
+	 *                                                          there are multiple joins to the same table)
3985
+	 * @return void
3986
+	 * @throws EE_Error
3987
+	 */
3988
+	private function _add_join_to_model(
3989
+		$model_name,
3990
+		EE_Model_Query_Info_Carrier $passed_in_query_info,
3991
+		$original_query_param
3992
+	) {
3993
+		$relation_obj = $this->related_settings_for($model_name);
3994
+		$model_relation_chain = EE_Model_Parser::extract_model_relation_chain($model_name, $original_query_param);
3995
+		//check if the relation is HABTM, because then we're essentially doing two joins
3996
+		//If so, join first to the JOIN table, and add its data types, and then continue as normal
3997
+		if ($relation_obj instanceof EE_HABTM_Relation) {
3998
+			$join_model_obj = $relation_obj->get_join_model();
3999
+			//replace the model specified with the join model for this relation chain, whi
4000
+			$relation_chain_to_join_model = EE_Model_Parser::replace_model_name_with_join_model_name_in_model_relation_chain($model_name,
4001
+				$join_model_obj->get_this_model_name(), $model_relation_chain);
4002
+			$passed_in_query_info->merge(
4003
+				new EE_Model_Query_Info_Carrier(
4004
+					array($relation_chain_to_join_model => $join_model_obj->get_this_model_name()),
4005
+					$relation_obj->get_join_to_intermediate_model_statement($relation_chain_to_join_model)
4006
+				)
4007
+			);
4008
+		}
4009
+		//now just join to the other table pointed to by the relation object, and add its data types
4010
+		$passed_in_query_info->merge(
4011
+			new EE_Model_Query_Info_Carrier(
4012
+				array($model_relation_chain => $model_name),
4013
+				$relation_obj->get_join_statement($model_relation_chain)
4014
+			)
4015
+		);
4016
+	}
4017
+
4018
+
4019
+
4020
+	/**
4021
+	 * Constructs SQL for where clause, like "WHERE Event.ID = 23 AND Transaction.amount > 100" etc.
4022
+	 *
4023
+	 * @param array $where_params like EEM_Base::get_all
4024
+	 * @return string of SQL
4025
+	 * @throws EE_Error
4026
+	 */
4027
+	private function _construct_where_clause($where_params)
4028
+	{
4029
+		$SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4030
+		if ($SQL) {
4031
+			return " WHERE " . $SQL;
4032
+		}
4033
+		return '';
4034
+	}
4035
+
4036
+
4037
+
4038
+	/**
4039
+	 * Just like the _construct_where_clause, except prepends 'HAVING' instead of 'WHERE',
4040
+	 * and should be passed HAVING parameters, not WHERE parameters
4041
+	 *
4042
+	 * @param array $having_params
4043
+	 * @return string
4044
+	 * @throws EE_Error
4045
+	 */
4046
+	private function _construct_having_clause($having_params)
4047
+	{
4048
+		$SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4049
+		if ($SQL) {
4050
+			return " HAVING " . $SQL;
4051
+		}
4052
+		return '';
4053
+	}
4054
+
4055
+
4056
+	/**
4057
+	 * Used for creating nested WHERE conditions. Eg "WHERE ! (Event.ID = 3 OR ( Event_Meta.meta_key = 'bob' AND
4058
+	 * Event_Meta.meta_value = 'foo'))"
4059
+	 *
4060
+	 * @param array  $where_params see EEM_Base::get_all for documentation
4061
+	 * @param string $glue         joins each subclause together. Should really only be " AND " or " OR "...
4062
+	 * @throws EE_Error
4063
+	 * @return string of SQL
4064
+	 */
4065
+	private function _construct_condition_clause_recursive($where_params, $glue = ' AND')
4066
+	{
4067
+		$where_clauses = array();
4068
+		foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4069
+			$query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4070
+			if (in_array($query_param, $this->_logic_query_param_keys)) {
4071
+				switch ($query_param) {
4072
+					case 'not':
4073
+					case 'NOT':
4074
+						$where_clauses[] = "! ("
4075
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4076
+								$glue)
4077
+										   . ")";
4078
+						break;
4079
+					case 'and':
4080
+					case 'AND':
4081
+						$where_clauses[] = " ("
4082
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4083
+								' AND ')
4084
+										   . ")";
4085
+						break;
4086
+					case 'or':
4087
+					case 'OR':
4088
+						$where_clauses[] = " ("
4089
+										   . $this->_construct_condition_clause_recursive($op_and_value_or_sub_condition,
4090
+								' OR ')
4091
+										   . ")";
4092
+						break;
4093
+				}
4094
+			} else {
4095
+				$field_obj = $this->_deduce_field_from_query_param($query_param);
4096
+				//if it's not a normal field, maybe it's a custom selection?
4097
+				if (! $field_obj) {
4098
+					if (isset($this->_custom_selections[$query_param][1])) {
4099
+						$field_obj = $this->_custom_selections[$query_param][1];
4100
+					} else {
4101
+						throw new EE_Error(sprintf(__("%s is neither a valid model field name, nor a custom selection",
4102
+							"event_espresso"), $query_param));
4103
+					}
4104
+				}
4105
+				$op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4106
+				$where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4107
+			}
4108
+		}
4109
+		return $where_clauses ? implode($glue, $where_clauses) : '';
4110
+	}
4111
+
4112
+
4113
+
4114
+	/**
4115
+	 * Takes the input parameter and extract the table name (alias) and column name
4116
+	 *
4117
+	 * @param string $query_param like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4118
+	 * @throws EE_Error
4119
+	 * @return string table alias and column name for SQL, eg "Transaction.TXN_ID"
4120
+	 */
4121
+	private function _deduce_column_name_from_query_param($query_param)
4122
+	{
4123
+		$field = $this->_deduce_field_from_query_param($query_param);
4124
+		if ($field) {
4125
+			$table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4126
+				$query_param);
4127
+			return $table_alias_prefix . $field->get_qualified_column();
4128
+		}
4129
+		if (array_key_exists($query_param, $this->_custom_selections)) {
4130
+			//maybe it's custom selection item?
4131
+			//if so, just use it as the "column name"
4132
+			return $query_param;
4133
+		}
4134
+		throw new EE_Error(
4135
+			sprintf(
4136
+				__(
4137
+					"%s is not a valid field on this model, nor a custom selection (%s)",
4138
+					"event_espresso"
4139
+				), $query_param, implode(",", $this->_custom_selections)
4140
+			)
4141
+		);
4142
+	}
4143
+
4144
+
4145
+
4146
+	/**
4147
+	 * Removes the * and anything after it from the condition query param key. It is useful to add the * to condition
4148
+	 * query param keys (eg, 'OR*', 'EVT_ID') in order for the array keys to still be unique, so that they don't get
4149
+	 * overwritten Takes a string like 'Event.EVT_ID*', 'TXN_total**', 'OR*1st', and 'DTT_reg_start*foobar' to
4150
+	 * 'Event.EVT_ID', 'TXN_total', 'OR', and 'DTT_reg_start', respectively.
4151
+	 *
4152
+	 * @param string $condition_query_param_key
4153
+	 * @return string
4154
+	 */
4155
+	private function _remove_stars_and_anything_after_from_condition_query_param_key($condition_query_param_key)
4156
+	{
4157
+		$pos_of_star = strpos($condition_query_param_key, '*');
4158
+		if ($pos_of_star === false) {
4159
+			return $condition_query_param_key;
4160
+		}
4161
+		$condition_query_param_sans_star = substr($condition_query_param_key, 0, $pos_of_star);
4162
+		return $condition_query_param_sans_star;
4163
+	}
4164
+
4165
+
4166
+
4167
+	/**
4168
+	 * creates the SQL for the operator and the value in a WHERE clause, eg "< 23" or "LIKE '%monkey%'"
4169
+	 *
4170
+	 * @param                            mixed      array | string    $op_and_value
4171
+	 * @param EE_Model_Field_Base|string $field_obj . If string, should be one of EEM_Base::_valid_wpdb_data_types
4172
+	 * @throws EE_Error
4173
+	 * @return string
4174
+	 */
4175
+	private function _construct_op_and_value($op_and_value, $field_obj)
4176
+	{
4177
+		if (is_array($op_and_value)) {
4178
+			$operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4179
+			if (! $operator) {
4180
+				$php_array_like_string = array();
4181
+				foreach ($op_and_value as $key => $value) {
4182
+					$php_array_like_string[] = "$key=>$value";
4183
+				}
4184
+				throw new EE_Error(
4185
+					sprintf(
4186
+						__(
4187
+							"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))",
4188
+							"event_espresso"
4189
+						),
4190
+						implode(",", $php_array_like_string)
4191
+					)
4192
+				);
4193
+			}
4194
+			$value = isset($op_and_value[1]) ? $op_and_value[1] : null;
4195
+		} else {
4196
+			$operator = '=';
4197
+			$value = $op_and_value;
4198
+		}
4199
+		//check to see if the value is actually another field
4200
+		if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4201
+			return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4202
+		}
4203
+		if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4204
+			//in this case, the value should be an array, or at least a comma-separated list
4205
+			//it will need to handle a little differently
4206
+			$cleaned_value = $this->_construct_in_value($value, $field_obj);
4207
+			//note: $cleaned_value has already been run through $wpdb->prepare()
4208
+			return $operator . SP . $cleaned_value;
4209
+		}
4210
+		if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4211
+			//the value should be an array with count of two.
4212
+			if (count($value) !== 2) {
4213
+				throw new EE_Error(
4214
+					sprintf(
4215
+						__(
4216
+							"The '%s' operator must be used with an array of values and there must be exactly TWO values in that array.",
4217
+							'event_espresso'
4218
+						),
4219
+						"BETWEEN"
4220
+					)
4221
+				);
4222
+			}
4223
+			$cleaned_value = $this->_construct_between_value($value, $field_obj);
4224
+			return $operator . SP . $cleaned_value;
4225
+		}
4226
+		if (in_array($operator, $this->valid_null_style_operators())) {
4227
+			if ($value !== null) {
4228
+				throw new EE_Error(
4229
+					sprintf(
4230
+						__(
4231
+							"You attempted to give a value  (%s) while using a NULL-style operator (%s). That isn't valid",
4232
+							"event_espresso"
4233
+						),
4234
+						$value,
4235
+						$operator
4236
+					)
4237
+				);
4238
+			}
4239
+			return $operator;
4240
+		}
4241
+		if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4242
+			//if the operator is 'LIKE', we want to allow percent signs (%) and not
4243
+			//remove other junk. So just treat it as a string.
4244
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4245
+		}
4246
+		if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4247
+			return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4248
+		}
4249
+		if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4250
+			throw new EE_Error(
4251
+				sprintf(
4252
+					__(
4253
+						"Operator '%s' must be used with an array of values, eg 'Registration.REG_ID' => array('%s',array(1,2,3))",
4254
+						'event_espresso'
4255
+					),
4256
+					$operator,
4257
+					$operator
4258
+				)
4259
+			);
4260
+		}
4261
+		if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4262
+			throw new EE_Error(
4263
+				sprintf(
4264
+					__(
4265
+						"Operator '%s' must be used with a single value, not an array. Eg 'Registration.REG_ID => array('%s',23))",
4266
+						'event_espresso'
4267
+					),
4268
+					$operator,
4269
+					$operator
4270
+				)
4271
+			);
4272
+		}
4273
+		throw new EE_Error(
4274
+			sprintf(
4275
+				__(
4276
+					"It appears you've provided some totally invalid query parameters. Operator and value were:'%s', which isn't right at all",
4277
+					"event_espresso"
4278
+				),
4279
+				http_build_query($op_and_value)
4280
+			)
4281
+		);
4282
+	}
4283
+
4284
+
4285
+
4286
+	/**
4287
+	 * Creates the operands to be used in a BETWEEN query, eg "'2014-12-31 20:23:33' AND '2015-01-23 12:32:54'"
4288
+	 *
4289
+	 * @param array                      $values
4290
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be the datatype to be used when querying, eg
4291
+	 *                                              '%s'
4292
+	 * @return string
4293
+	 * @throws EE_Error
4294
+	 */
4295
+	public function _construct_between_value($values, $field_obj)
4296
+	{
4297
+		$cleaned_values = array();
4298
+		foreach ($values as $value) {
4299
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4300
+		}
4301
+		return $cleaned_values[0] . " AND " . $cleaned_values[1];
4302
+	}
4303
+
4304
+
4305
+
4306
+	/**
4307
+	 * Takes an array or a comma-separated list of $values and cleans them
4308
+	 * according to $data_type using $wpdb->prepare, and then makes the list a
4309
+	 * string surrounded by ( and ). Eg, _construct_in_value(array(1,2,3),'%d') would
4310
+	 * return '(1,2,3)'; _construct_in_value("1,2,hack",'%d') would return '(1,2,1)' (assuming
4311
+	 * I'm right that a string, when interpreted as a digit, becomes a 1. It might become a 0)
4312
+	 *
4313
+	 * @param mixed                      $values    array or comma-separated string
4314
+	 * @param EE_Model_Field_Base|string $field_obj if string, it should be a wpdb data type like '%s', or '%d'
4315
+	 * @return string of SQL to follow an 'IN' or 'NOT IN' operator
4316
+	 * @throws EE_Error
4317
+	 */
4318
+	public function _construct_in_value($values, $field_obj)
4319
+	{
4320
+		//check if the value is a CSV list
4321
+		if (is_string($values)) {
4322
+			//in which case, turn it into an array
4323
+			$values = explode(",", $values);
4324
+		}
4325
+		$cleaned_values = array();
4326
+		foreach ($values as $value) {
4327
+			$cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4328
+		}
4329
+		//we would just LOVE to leave $cleaned_values as an empty array, and return the value as "()",
4330
+		//but unfortunately that's invalid SQL. So instead we return a string which we KNOW will evaluate to be the empty set
4331
+		//which is effectively equivalent to returning "()". We don't return "(0)" because that only works for auto-incrementing columns
4332
+		if (empty($cleaned_values)) {
4333
+			$all_fields = $this->field_settings();
4334
+			$a_field = array_shift($all_fields);
4335
+			$main_table = $this->_get_main_table();
4336
+			$cleaned_values[] = "SELECT "
4337
+								. $a_field->get_table_column()
4338
+								. " FROM "
4339
+								. $main_table->get_table_name()
4340
+								. " WHERE FALSE";
4341
+		}
4342
+		return "(" . implode(",", $cleaned_values) . ")";
4343
+	}
4344
+
4345
+
4346
+
4347
+	/**
4348
+	 * @param mixed                      $value
4349
+	 * @param EE_Model_Field_Base|string $field_obj if string it should be a wpdb data type like '%d'
4350
+	 * @throws EE_Error
4351
+	 * @return false|null|string
4352
+	 */
4353
+	private function _wpdb_prepare_using_field($value, $field_obj)
4354
+	{
4355
+		/** @type WPDB $wpdb */
4356
+		global $wpdb;
4357
+		if ($field_obj instanceof EE_Model_Field_Base) {
4358
+			return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4359
+				$this->_prepare_value_for_use_in_db($value, $field_obj));
4360
+		} //$field_obj should really just be a data type
4361
+		if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4362
+			throw new EE_Error(
4363
+				sprintf(
4364
+					__("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
4365
+					$field_obj, implode(",", $this->_valid_wpdb_data_types)
4366
+				)
4367
+			);
4368
+		}
4369
+		return $wpdb->prepare($field_obj, $value);
4370
+	}
4371
+
4372
+
4373
+
4374
+	/**
4375
+	 * Takes the input parameter and finds the model field that it indicates.
4376
+	 *
4377
+	 * @param string $query_param_name like Registration.Transaction.TXN_ID, Event.Datetime.start_time, or REG_ID
4378
+	 * @throws EE_Error
4379
+	 * @return EE_Model_Field_Base
4380
+	 */
4381
+	protected function _deduce_field_from_query_param($query_param_name)
4382
+	{
4383
+		//ok, now proceed with deducing which part is the model's name, and which is the field's name
4384
+		//which will help us find the database table and column
4385
+		$query_param_parts = explode(".", $query_param_name);
4386
+		if (empty($query_param_parts)) {
4387
+			throw new EE_Error(sprintf(__("_extract_column_name is empty when trying to extract column and table name from %s",
4388
+				'event_espresso'), $query_param_name));
4389
+		}
4390
+		$number_of_parts = count($query_param_parts);
4391
+		$last_query_param_part = $query_param_parts[count($query_param_parts) - 1];
4392
+		if ($number_of_parts === 1) {
4393
+			$field_name = $last_query_param_part;
4394
+			$model_obj = $this;
4395
+		} else {// $number_of_parts >= 2
4396
+			//the last part is the column name, and there are only 2parts. therefore...
4397
+			$field_name = $last_query_param_part;
4398
+			$model_obj = $this->get_related_model_obj($query_param_parts[$number_of_parts - 2]);
4399
+		}
4400
+		try {
4401
+			return $model_obj->field_settings_for($field_name);
4402
+		} catch (EE_Error $e) {
4403
+			return null;
4404
+		}
4405
+	}
4406
+
4407
+
4408
+
4409
+	/**
4410
+	 * Given a field's name (ie, a key in $this->field_settings()), uses the EE_Model_Field object to get the table's
4411
+	 * alias and column which corresponds to it
4412
+	 *
4413
+	 * @param string $field_name
4414
+	 * @throws EE_Error
4415
+	 * @return string
4416
+	 */
4417
+	public function _get_qualified_column_for_field($field_name)
4418
+	{
4419
+		$all_fields = $this->field_settings();
4420
+		$field = isset($all_fields[$field_name]) ? $all_fields[$field_name] : false;
4421
+		if ($field) {
4422
+			return $field->get_qualified_column();
4423
+		}
4424
+		throw new EE_Error(
4425
+			sprintf(
4426
+				__(
4427
+					"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.",
4428
+					'event_espresso'
4429
+				), $field_name, get_class($this)
4430
+			)
4431
+		);
4432
+	}
4433
+
4434
+
4435
+
4436
+	/**
4437
+	 * similar to \EEM_Base::_get_qualified_column_for_field() but returns an array with data for ALL fields.
4438
+	 * Example usage:
4439
+	 * EEM_Ticket::instance()->get_all_wpdb_results(
4440
+	 *      array(),
4441
+	 *      ARRAY_A,
4442
+	 *      EEM_Ticket::instance()->get_qualified_columns_for_all_fields()
4443
+	 *  );
4444
+	 * is equivalent to
4445
+	 *  EEM_Ticket::instance()->get_all_wpdb_results( array(), ARRAY_A, '*' );
4446
+	 * and
4447
+	 *  EEM_Event::instance()->get_all_wpdb_results(
4448
+	 *      array(
4449
+	 *          array(
4450
+	 *              'Datetime.Ticket.TKT_ID' => array( '<', 100 ),
4451
+	 *          ),
4452
+	 *          ARRAY_A,
4453
+	 *          implode(
4454
+	 *              ', ',
4455
+	 *              array_merge(
4456
+	 *                  EEM_Event::instance()->get_qualified_columns_for_all_fields( '', false ),
4457
+	 *                  EEM_Ticket::instance()->get_qualified_columns_for_all_fields( 'Datetime', false )
4458
+	 *              )
4459
+	 *          )
4460
+	 *      )
4461
+	 *  );
4462
+	 * selects rows from the database, selecting all the event and ticket columns, where the ticket ID is below 100
4463
+	 *
4464
+	 * @param string $model_relation_chain        the chain of models used to join between the model you want to query
4465
+	 *                                            and the one whose fields you are selecting for example: when querying
4466
+	 *                                            tickets model and selecting fields from the tickets model you would
4467
+	 *                                            leave this parameter empty, because no models are needed to join
4468
+	 *                                            between the queried model and the selected one. Likewise when
4469
+	 *                                            querying the datetime model and selecting fields from the tickets
4470
+	 *                                            model, it would also be left empty, because there is a direct
4471
+	 *                                            relation from datetimes to tickets, so no model is needed to join
4472
+	 *                                            them together. However, when querying from the event model and
4473
+	 *                                            selecting fields from the ticket model, you should provide the string
4474
+	 *                                            'Datetime', indicating that the event model must first join to the
4475
+	 *                                            datetime model in order to find its relation to ticket model.
4476
+	 *                                            Also, when querying from the venue model and selecting fields from
4477
+	 *                                            the ticket model, you should provide the string 'Event.Datetime',
4478
+	 *                                            indicating you need to join the venue model to the event model,
4479
+	 *                                            to the datetime model, in order to find its relation to the ticket model.
4480
+	 *                                            This string is used to deduce the prefix that gets added onto the
4481
+	 *                                            models' tables qualified columns
4482
+	 * @param bool   $return_string               if true, will return a string with qualified column names separated
4483
+	 *                                            by ', ' if false, will simply return a numerically indexed array of
4484
+	 *                                            qualified column names
4485
+	 * @return array|string
4486
+	 */
4487
+	public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4488
+	{
4489
+		$table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4490
+		$qualified_columns = array();
4491
+		foreach ($this->field_settings() as $field_name => $field) {
4492
+			$qualified_columns[] = $table_prefix . $field->get_qualified_column();
4493
+		}
4494
+		return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4495
+	}
4496
+
4497
+
4498
+
4499
+	/**
4500
+	 * constructs the select use on special limit joins
4501
+	 * NOTE: for now this has only been tested and will work when the  table alias is for the PRIMARY table. Although
4502
+	 * its setup so the select query will be setup on and just doing the special select join off of the primary table
4503
+	 * (as that is typically where the limits would be set).
4504
+	 *
4505
+	 * @param  string       $table_alias The table the select is being built for
4506
+	 * @param  mixed|string $limit       The limit for this select
4507
+	 * @return string                The final select join element for the query.
4508
+	 */
4509
+	public function _construct_limit_join_select($table_alias, $limit)
4510
+	{
4511
+		$SQL = '';
4512
+		foreach ($this->_tables as $table_obj) {
4513
+			if ($table_obj instanceof EE_Primary_Table) {
4514
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4515
+					? $table_obj->get_select_join_limit($limit)
4516
+					: SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4517
+			} elseif ($table_obj instanceof EE_Secondary_Table) {
4518
+				$SQL .= $table_alias === $table_obj->get_table_alias()
4519
+					? $table_obj->get_select_join_limit_join($limit)
4520
+					: SP . $table_obj->get_join_sql($table_alias) . SP;
4521
+			}
4522
+		}
4523
+		return $SQL;
4524
+	}
4525
+
4526
+
4527
+
4528
+	/**
4529
+	 * Constructs the internal join if there are multiple tables, or simply the table's name and alias
4530
+	 * Eg "wp_post AS Event" or "wp_post AS Event INNER JOIN wp_postmeta Event_Meta ON Event.ID = Event_Meta.post_id"
4531
+	 *
4532
+	 * @return string SQL
4533
+	 * @throws EE_Error
4534
+	 */
4535
+	public function _construct_internal_join()
4536
+	{
4537
+		$SQL = $this->_get_main_table()->get_table_sql();
4538
+		$SQL .= $this->_construct_internal_join_to_table_with_alias($this->_get_main_table()->get_table_alias());
4539
+		return $SQL;
4540
+	}
4541
+
4542
+
4543
+
4544
+	/**
4545
+	 * Constructs the SQL for joining all the tables on this model.
4546
+	 * Normally $alias should be the primary table's alias, but in cases where
4547
+	 * we have already joined to a secondary table (eg, the secondary table has a foreign key and is joined before the
4548
+	 * primary table) then we should provide that secondary table's alias. Eg, with $alias being the primary table's
4549
+	 * alias, this will construct SQL like:
4550
+	 * " INNER JOIN wp_esp_secondary_table AS Secondary_Table ON Primary_Table.pk = Secondary_Table.fk".
4551
+	 * With $alias being a secondary table's alias, this will construct SQL like:
4552
+	 * " INNER JOIN wp_esp_primary_table AS Primary_Table ON Primary_Table.pk = Secondary_Table.fk".
4553
+	 *
4554
+	 * @param string $alias_prefixed table alias to join to (this table should already be in the FROM SQL clause)
4555
+	 * @return string
4556
+	 */
4557
+	public function _construct_internal_join_to_table_with_alias($alias_prefixed)
4558
+	{
4559
+		$SQL = '';
4560
+		$alias_sans_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($alias_prefixed);
4561
+		foreach ($this->_tables as $table_obj) {
4562
+			if ($table_obj instanceof EE_Secondary_Table) {//table is secondary table
4563
+				if ($alias_sans_prefix === $table_obj->get_table_alias()) {
4564
+					//so we're joining to this table, meaning the table is already in
4565
+					//the FROM statement, BUT the primary table isn't. So we want
4566
+					//to add the inverse join sql
4567
+					$SQL .= $table_obj->get_inverse_join_sql($alias_prefixed);
4568
+				} else {
4569
+					//just add a regular JOIN to this table from the primary table
4570
+					$SQL .= $table_obj->get_join_sql($alias_prefixed);
4571
+				}
4572
+			}//if it's a primary table, dont add any SQL. it should already be in the FROM statement
4573
+		}
4574
+		return $SQL;
4575
+	}
4576
+
4577
+
4578
+
4579
+	/**
4580
+	 * Gets an array for storing all the data types on the next-to-be-executed-query.
4581
+	 * This should be a growing array of keys being table-columns (eg 'EVT_ID' and 'Event.EVT_ID'), and values being
4582
+	 * their data type (eg, '%s', '%d', etc)
4583
+	 *
4584
+	 * @return array
4585
+	 */
4586
+	public function _get_data_types()
4587
+	{
4588
+		$data_types = array();
4589
+		foreach ($this->field_settings() as $field_obj) {
4590
+			//$data_types[$field_obj->get_table_column()] = $field_obj->get_wpdb_data_type();
4591
+			/** @var $field_obj EE_Model_Field_Base */
4592
+			$data_types[$field_obj->get_qualified_column()] = $field_obj->get_wpdb_data_type();
4593
+		}
4594
+		return $data_types;
4595
+	}
4596
+
4597
+
4598
+
4599
+	/**
4600
+	 * Gets the model object given the relation's name / model's name (eg, 'Event', 'Registration',etc. Always singular)
4601
+	 *
4602
+	 * @param string $model_name
4603
+	 * @throws EE_Error
4604
+	 * @return EEM_Base
4605
+	 */
4606
+	public function get_related_model_obj($model_name)
4607
+	{
4608
+		$model_classname = "EEM_" . $model_name;
4609
+		if (! class_exists($model_classname)) {
4610
+			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",
4611
+				'event_espresso'), $model_name, $model_classname));
4612
+		}
4613
+		return call_user_func($model_classname . "::instance");
4614
+	}
4615
+
4616
+
4617
+
4618
+	/**
4619
+	 * Returns the array of EE_ModelRelations for this model.
4620
+	 *
4621
+	 * @return EE_Model_Relation_Base[]
4622
+	 */
4623
+	public function relation_settings()
4624
+	{
4625
+		return $this->_model_relations;
4626
+	}
4627
+
4628
+
4629
+
4630
+	/**
4631
+	 * Gets all related models that this model BELONGS TO. Handy to know sometimes
4632
+	 * because without THOSE models, this model probably doesn't have much purpose.
4633
+	 * (Eg, without an event, datetimes have little purpose.)
4634
+	 *
4635
+	 * @return EE_Belongs_To_Relation[]
4636
+	 */
4637
+	public function belongs_to_relations()
4638
+	{
4639
+		$belongs_to_relations = array();
4640
+		foreach ($this->relation_settings() as $model_name => $relation_obj) {
4641
+			if ($relation_obj instanceof EE_Belongs_To_Relation) {
4642
+				$belongs_to_relations[$model_name] = $relation_obj;
4643
+			}
4644
+		}
4645
+		return $belongs_to_relations;
4646
+	}
4647
+
4648
+
4649
+
4650
+	/**
4651
+	 * Returns the specified EE_Model_Relation, or throws an exception
4652
+	 *
4653
+	 * @param string $relation_name name of relation, key in $this->_relatedModels
4654
+	 * @throws EE_Error
4655
+	 * @return EE_Model_Relation_Base
4656
+	 */
4657
+	public function related_settings_for($relation_name)
4658
+	{
4659
+		$relatedModels = $this->relation_settings();
4660
+		if (! array_key_exists($relation_name, $relatedModels)) {
4661
+			throw new EE_Error(
4662
+				sprintf(
4663
+					__('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
4664
+						'event_espresso'),
4665
+					$relation_name,
4666
+					$this->_get_class_name(),
4667
+					implode(', ', array_keys($relatedModels))
4668
+				)
4669
+			);
4670
+		}
4671
+		return $relatedModels[$relation_name];
4672
+	}
4673
+
4674
+
4675
+
4676
+	/**
4677
+	 * A convenience method for getting a specific field's settings, instead of getting all field settings for all
4678
+	 * fields
4679
+	 *
4680
+	 * @param string $fieldName
4681
+	 * @param boolean $include_db_only_fields
4682
+	 * @throws EE_Error
4683
+	 * @return EE_Model_Field_Base
4684
+	 */
4685
+	public function field_settings_for($fieldName, $include_db_only_fields = true)
4686
+	{
4687
+		$fieldSettings = $this->field_settings($include_db_only_fields);
4688
+		if (! array_key_exists($fieldName, $fieldSettings)) {
4689
+			throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4690
+				get_class($this)));
4691
+		}
4692
+		return $fieldSettings[$fieldName];
4693
+	}
4694
+
4695
+
4696
+
4697
+	/**
4698
+	 * Checks if this field exists on this model
4699
+	 *
4700
+	 * @param string $fieldName a key in the model's _field_settings array
4701
+	 * @return boolean
4702
+	 */
4703
+	public function has_field($fieldName)
4704
+	{
4705
+		$fieldSettings = $this->field_settings(true);
4706
+		if (isset($fieldSettings[$fieldName])) {
4707
+			return true;
4708
+		}
4709
+		return false;
4710
+	}
4711
+
4712
+
4713
+
4714
+	/**
4715
+	 * Returns whether or not this model has a relation to the specified model
4716
+	 *
4717
+	 * @param string $relation_name possibly one of the keys in the relation_settings array
4718
+	 * @return boolean
4719
+	 */
4720
+	public function has_relation($relation_name)
4721
+	{
4722
+		$relations = $this->relation_settings();
4723
+		if (isset($relations[$relation_name])) {
4724
+			return true;
4725
+		}
4726
+		return false;
4727
+	}
4728
+
4729
+
4730
+
4731
+	/**
4732
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4733
+	 * Eg, on EE_Answer that would be ANS_ID field object
4734
+	 *
4735
+	 * @param $field_obj
4736
+	 * @return boolean
4737
+	 */
4738
+	public function is_primary_key_field($field_obj)
4739
+	{
4740
+		return $field_obj instanceof EE_Primary_Key_Field_Base ? true : false;
4741
+	}
4742
+
4743
+
4744
+
4745
+	/**
4746
+	 * gets the field object of type 'primary_key' from the fieldsSettings attribute.
4747
+	 * Eg, on EE_Answer that would be ANS_ID field object
4748
+	 *
4749
+	 * @return EE_Model_Field_Base
4750
+	 * @throws EE_Error
4751
+	 */
4752
+	public function get_primary_key_field()
4753
+	{
4754
+		if ($this->_primary_key_field === null) {
4755
+			foreach ($this->field_settings(true) as $field_obj) {
4756
+				if ($this->is_primary_key_field($field_obj)) {
4757
+					$this->_primary_key_field = $field_obj;
4758
+					break;
4759
+				}
4760
+			}
4761
+			if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4762
+				throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4763
+					get_class($this)));
4764
+			}
4765
+		}
4766
+		return $this->_primary_key_field;
4767
+	}
4768
+
4769
+
4770
+
4771
+	/**
4772
+	 * Returns whether or not not there is a primary key on this model.
4773
+	 * Internally does some caching.
4774
+	 *
4775
+	 * @return boolean
4776
+	 */
4777
+	public function has_primary_key_field()
4778
+	{
4779
+		if ($this->_has_primary_key_field === null) {
4780
+			try {
4781
+				$this->get_primary_key_field();
4782
+				$this->_has_primary_key_field = true;
4783
+			} catch (EE_Error $e) {
4784
+				$this->_has_primary_key_field = false;
4785
+			}
4786
+		}
4787
+		return $this->_has_primary_key_field;
4788
+	}
4789
+
4790
+
4791
+
4792
+	/**
4793
+	 * Finds the first field of type $field_class_name.
4794
+	 *
4795
+	 * @param string $field_class_name class name of field that you want to find. Eg, EE_Datetime_Field,
4796
+	 *                                 EE_Foreign_Key_Field, etc
4797
+	 * @return EE_Model_Field_Base or null if none is found
4798
+	 */
4799
+	public function get_a_field_of_type($field_class_name)
4800
+	{
4801
+		foreach ($this->field_settings() as $field) {
4802
+			if ($field instanceof $field_class_name) {
4803
+				return $field;
4804
+			}
4805
+		}
4806
+		return null;
4807
+	}
4808
+
4809
+
4810
+
4811
+	/**
4812
+	 * Gets a foreign key field pointing to model.
4813
+	 *
4814
+	 * @param string $model_name eg Event, Registration, not EEM_Event
4815
+	 * @return EE_Foreign_Key_Field_Base
4816
+	 * @throws EE_Error
4817
+	 */
4818
+	public function get_foreign_key_to($model_name)
4819
+	{
4820
+		if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4821
+			foreach ($this->field_settings() as $field) {
4822
+				if (
4823
+					$field instanceof EE_Foreign_Key_Field_Base
4824
+					&& in_array($model_name, $field->get_model_names_pointed_to())
4825
+				) {
4826
+					$this->_cache_foreign_key_to_fields[$model_name] = $field;
4827
+					break;
4828
+				}
4829
+			}
4830
+			if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4831
+				throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4832
+					'event_espresso'), $model_name, get_class($this)));
4833
+			}
4834
+		}
4835
+		return $this->_cache_foreign_key_to_fields[$model_name];
4836
+	}
4837
+
4838
+
4839
+
4840
+	/**
4841
+	 * Gets the table name (including $wpdb->prefix) for the table alias
4842
+	 *
4843
+	 * @param string $table_alias eg Event, Event_Meta, Registration, Transaction, but maybe
4844
+	 *                            a table alias with a model chain prefix, like 'Venue__Event_Venue___Event_Meta'.
4845
+	 *                            Either one works
4846
+	 * @return string
4847
+	 */
4848
+	public function get_table_for_alias($table_alias)
4849
+	{
4850
+		$table_alias_sans_model_relation_chain_prefix = EE_Model_Parser::remove_table_alias_model_relation_chain_prefix($table_alias);
4851
+		return $this->_tables[$table_alias_sans_model_relation_chain_prefix]->get_table_name();
4852
+	}
4853
+
4854
+
4855
+
4856
+	/**
4857
+	 * Returns a flat array of all field son this model, instead of organizing them
4858
+	 * by table_alias as they are in the constructor.
4859
+	 *
4860
+	 * @param bool $include_db_only_fields flag indicating whether or not to include the db-only fields
4861
+	 * @return EE_Model_Field_Base[] where the keys are the field's name
4862
+	 */
4863
+	public function field_settings($include_db_only_fields = false)
4864
+	{
4865
+		if ($include_db_only_fields) {
4866
+			if ($this->_cached_fields === null) {
4867
+				$this->_cached_fields = array();
4868
+				foreach ($this->_fields as $fields_corresponding_to_table) {
4869
+					foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4870
+						$this->_cached_fields[$field_name] = $field_obj;
4871
+					}
4872
+				}
4873
+			}
4874
+			return $this->_cached_fields;
4875
+		}
4876
+		if ($this->_cached_fields_non_db_only === null) {
4877
+			$this->_cached_fields_non_db_only = array();
4878
+			foreach ($this->_fields as $fields_corresponding_to_table) {
4879
+				foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4880
+					/** @var $field_obj EE_Model_Field_Base */
4881
+					if (! $field_obj->is_db_only_field()) {
4882
+						$this->_cached_fields_non_db_only[$field_name] = $field_obj;
4883
+					}
4884
+				}
4885
+			}
4886
+		}
4887
+		return $this->_cached_fields_non_db_only;
4888
+	}
4889
+
4890
+
4891
+
4892
+	/**
4893
+	 *        cycle though array of attendees and create objects out of each item
4894
+	 *
4895
+	 * @access        private
4896
+	 * @param        array $rows of results of $wpdb->get_results($query,ARRAY_A)
4897
+	 * @return \EE_Base_Class[] array keys are primary keys (if there is a primary key on the model. if not,
4898
+	 *                           numerically indexed)
4899
+	 * @throws EE_Error
4900
+	 */
4901
+	protected function _create_objects($rows = array())
4902
+	{
4903
+		$array_of_objects = array();
4904
+		if (empty($rows)) {
4905
+			return array();
4906
+		}
4907
+		$count_if_model_has_no_primary_key = 0;
4908
+		$has_primary_key = $this->has_primary_key_field();
4909
+		$primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4910
+		foreach ((array)$rows as $row) {
4911
+			if (empty($row)) {
4912
+				//wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4913
+				return array();
4914
+			}
4915
+			//check if we've already set this object in the results array,
4916
+			//in which case there's no need to process it further (again)
4917
+			if ($has_primary_key) {
4918
+				$table_pk_value = $this->_get_column_value_with_table_alias_or_not(
4919
+					$row,
4920
+					$primary_key_field->get_qualified_column(),
4921
+					$primary_key_field->get_table_column()
4922
+				);
4923
+				if ($table_pk_value && isset($array_of_objects[$table_pk_value])) {
4924
+					continue;
4925
+				}
4926
+			}
4927
+			$classInstance = $this->instantiate_class_from_array_or_object($row);
4928
+			if (! $classInstance) {
4929
+				throw new EE_Error(
4930
+					sprintf(
4931
+						__('Could not create instance of class %s from row %s', 'event_espresso'),
4932
+						$this->get_this_model_name(),
4933
+						http_build_query($row)
4934
+					)
4935
+				);
4936
+			}
4937
+			//set the timezone on the instantiated objects
4938
+			$classInstance->set_timezone($this->_timezone);
4939
+			//make sure if there is any timezone setting present that we set the timezone for the object
4940
+			$key = $has_primary_key ? $classInstance->ID() : $count_if_model_has_no_primary_key++;
4941
+			$array_of_objects[$key] = $classInstance;
4942
+			//also, for all the relations of type BelongsTo, see if we can cache
4943
+			//those related models
4944
+			//(we could do this for other relations too, but if there are conditions
4945
+			//that filtered out some fo the results, then we'd be caching an incomplete set
4946
+			//so it requires a little more thought than just caching them immediately...)
4947
+			foreach ($this->_model_relations as $modelName => $relation_obj) {
4948
+				if ($relation_obj instanceof EE_Belongs_To_Relation) {
4949
+					//check if this model's INFO is present. If so, cache it on the model
4950
+					$other_model = $relation_obj->get_other_model();
4951
+					$other_model_obj_maybe = $other_model->instantiate_class_from_array_or_object($row);
4952
+					//if we managed to make a model object from the results, cache it on the main model object
4953
+					if ($other_model_obj_maybe) {
4954
+						//set timezone on these other model objects if they are present
4955
+						$other_model_obj_maybe->set_timezone($this->_timezone);
4956
+						$classInstance->cache($modelName, $other_model_obj_maybe);
4957
+					}
4958
+				}
4959
+			}
4960
+		}
4961
+		return $array_of_objects;
4962
+	}
4963
+
4964
+
4965
+
4966
+	/**
4967
+	 * The purpose of this method is to allow us to create a model object that is not in the db that holds default
4968
+	 * values. A typical example of where this is used is when creating a new item and the initial load of a form.  We
4969
+	 * dont' necessarily want to test for if the object is present but just assume it is BUT load the defaults from the
4970
+	 * object (as set in the model_field!).
4971
+	 *
4972
+	 * @return EE_Base_Class single EE_Base_Class object with default values for the properties.
4973
+	 */
4974
+	public function create_default_object()
4975
+	{
4976
+		$this_model_fields_and_values = array();
4977
+		//setup the row using default values;
4978
+		foreach ($this->field_settings() as $field_name => $field_obj) {
4979
+			$this_model_fields_and_values[$field_name] = $field_obj->get_default_value();
4980
+		}
4981
+		$className = $this->_get_class_name();
4982
+		$classInstance = EE_Registry::instance()
4983
+									->load_class($className, array($this_model_fields_and_values), false, false);
4984
+		return $classInstance;
4985
+	}
4986
+
4987
+
4988
+
4989
+	/**
4990
+	 * @param mixed $cols_n_values either an array of where each key is the name of a field, and the value is its value
4991
+	 *                             or an stdClass where each property is the name of a column,
4992
+	 * @return EE_Base_Class
4993
+	 * @throws EE_Error
4994
+	 */
4995
+	public function instantiate_class_from_array_or_object($cols_n_values)
4996
+	{
4997
+		if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4998
+			$cols_n_values = get_object_vars($cols_n_values);
4999
+		}
5000
+		$primary_key = null;
5001
+		//make sure the array only has keys that are fields/columns on this model
5002
+		$this_model_fields_n_values = $this->_deduce_fields_n_values_from_cols_n_values($cols_n_values);
5003
+		if ($this->has_primary_key_field() && isset($this_model_fields_n_values[$this->primary_key_name()])) {
5004
+			$primary_key = $this_model_fields_n_values[$this->primary_key_name()];
5005
+		}
5006
+		$className = $this->_get_class_name();
5007
+		//check we actually found results that we can use to build our model object
5008
+		//if not, return null
5009
+		if ($this->has_primary_key_field()) {
5010
+			if (empty($this_model_fields_n_values[$this->primary_key_name()])) {
5011
+				return null;
5012
+			}
5013
+		} else if ($this->unique_indexes()) {
5014
+			$first_column = reset($this_model_fields_n_values);
5015
+			if (empty($first_column)) {
5016
+				return null;
5017
+			}
5018
+		}
5019
+		// if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5020
+		if ($primary_key) {
5021
+			$classInstance = $this->get_from_entity_map($primary_key);
5022
+			if (! $classInstance) {
5023
+				$classInstance = EE_Registry::instance()
5024
+											->load_class($className,
5025
+												array($this_model_fields_n_values, $this->_timezone), true, false);
5026
+				// add this new object to the entity map
5027
+				$classInstance = $this->add_to_entity_map($classInstance);
5028
+			}
5029
+		} else {
5030
+			$classInstance = EE_Registry::instance()
5031
+										->load_class($className, array($this_model_fields_n_values, $this->_timezone),
5032
+											true, false);
5033
+		}
5034
+		//it is entirely possible that the instantiated class object has a set timezone_string db field and has set it's internal _timezone property accordingly (see new_instance_from_db in model objects particularly EE_Event for example).  In this case, we want to make sure the model object doesn't have its timezone string overwritten by any timezone property currently set here on the model so, we intentionally override the model _timezone property with the model_object timezone property.
5035
+		$this->set_timezone($classInstance->get_timezone());
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   +156 added lines, -156 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,9 +2184,9 @@  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
-                $ways_to_identify_a_row[] = '(' . implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2189
+                $ways_to_identify_a_row[] = '('.implode(' AND ', $values_for_each_combined_primary_key_for_a_row);
2190 2190
             }
2191 2191
             $query_part = implode(' OR ', $ways_to_identify_a_row);
2192 2192
         }
@@ -2202,8 +2202,8 @@  discard block
 block discarded – undo
2202 2202
      */
2203 2203
     public function get_field_by_column($qualified_column_name)
2204 2204
     {
2205
-       foreach($this->field_settings(true) as $field_name => $field_obj){
2206
-           if($field_obj->get_qualified_column() === $qualified_column_name){
2205
+       foreach ($this->field_settings(true) as $field_name => $field_obj) {
2206
+           if ($field_obj->get_qualified_column() === $qualified_column_name) {
2207 2207
                return $field_obj;
2208 2208
            }
2209 2209
        }
@@ -2254,9 +2254,9 @@  discard block
 block discarded – undo
2254 2254
                 $column_to_count = '*';
2255 2255
             }
2256 2256
         }
2257
-        $column_to_count = $distinct ? "DISTINCT " . $column_to_count : $column_to_count;
2258
-        $SQL = "SELECT COUNT(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2259
-        return (int)$this->_do_wpdb_query('get_var', array($SQL));
2257
+        $column_to_count = $distinct ? "DISTINCT ".$column_to_count : $column_to_count;
2258
+        $SQL = "SELECT COUNT(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2259
+        return (int) $this->_do_wpdb_query('get_var', array($SQL));
2260 2260
     }
2261 2261
 
2262 2262
 
@@ -2278,14 +2278,14 @@  discard block
 block discarded – undo
2278 2278
             $field_obj = $this->get_primary_key_field();
2279 2279
         }
2280 2280
         $column_to_count = $field_obj->get_qualified_column();
2281
-        $SQL = "SELECT SUM(" . $column_to_count . ")" . $this->_construct_2nd_half_of_select_query($model_query_info);
2281
+        $SQL = "SELECT SUM(".$column_to_count.")".$this->_construct_2nd_half_of_select_query($model_query_info);
2282 2282
         $return_value = $this->_do_wpdb_query('get_var', array($SQL));
2283 2283
         $data_type = $field_obj->get_wpdb_data_type();
2284 2284
         if ($data_type === '%d' || $data_type === '%s') {
2285
-            return (float)$return_value;
2285
+            return (float) $return_value;
2286 2286
         }
2287 2287
         //must be %f
2288
-        return (float)$return_value;
2288
+        return (float) $return_value;
2289 2289
     }
2290 2290
 
2291 2291
 
@@ -2305,13 +2305,13 @@  discard block
 block discarded – undo
2305 2305
         //if we're in maintenance mode level 2, DON'T run any queries
2306 2306
         //because level 2 indicates the database needs updating and
2307 2307
         //is probably out of sync with the code
2308
-        if (! EE_Maintenance_Mode::instance()->models_can_query()) {
2308
+        if ( ! EE_Maintenance_Mode::instance()->models_can_query()) {
2309 2309
             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.",
2310 2310
                 "event_espresso")));
2311 2311
         }
2312 2312
         /** @type WPDB $wpdb */
2313 2313
         global $wpdb;
2314
-        if (! method_exists($wpdb, $wpdb_method)) {
2314
+        if ( ! method_exists($wpdb, $wpdb_method)) {
2315 2315
             throw new EE_Error(sprintf(__('There is no method named "%s" on Wordpress\' $wpdb object',
2316 2316
                 'event_espresso'), $wpdb_method));
2317 2317
         }
@@ -2323,7 +2323,7 @@  discard block
 block discarded – undo
2323 2323
         $this->show_db_query_if_previously_requested($wpdb->last_query);
2324 2324
         if (WP_DEBUG) {
2325 2325
             $wpdb->show_errors($old_show_errors_value);
2326
-            if (! empty($wpdb->last_error)) {
2326
+            if ( ! empty($wpdb->last_error)) {
2327 2327
                 throw new EE_Error(sprintf(__('WPDB Error: "%s"', 'event_espresso'), $wpdb->last_error));
2328 2328
             }
2329 2329
             if ($result === false) {
@@ -2384,7 +2384,7 @@  discard block
 block discarded – undo
2384 2384
                     return $result;
2385 2385
                     break;
2386 2386
             }
2387
-            if (! empty($error_message)) {
2387
+            if ( ! empty($error_message)) {
2388 2388
                 EE_Log::instance()->log(__FILE__, __FUNCTION__, $error_message, 'error');
2389 2389
                 trigger_error($error_message);
2390 2390
             }
@@ -2460,11 +2460,11 @@  discard block
 block discarded – undo
2460 2460
      */
2461 2461
     private function _construct_2nd_half_of_select_query(EE_Model_Query_Info_Carrier $model_query_info)
2462 2462
     {
2463
-        return " FROM " . $model_query_info->get_full_join_sql() .
2464
-               $model_query_info->get_where_sql() .
2465
-               $model_query_info->get_group_by_sql() .
2466
-               $model_query_info->get_having_sql() .
2467
-               $model_query_info->get_order_by_sql() .
2463
+        return " FROM ".$model_query_info->get_full_join_sql().
2464
+               $model_query_info->get_where_sql().
2465
+               $model_query_info->get_group_by_sql().
2466
+               $model_query_info->get_having_sql().
2467
+               $model_query_info->get_order_by_sql().
2468 2468
                $model_query_info->get_limit_sql();
2469 2469
     }
2470 2470
 
@@ -2660,12 +2660,12 @@  discard block
 block discarded – undo
2660 2660
         $related_model = $this->get_related_model_obj($model_name);
2661 2661
         //we're just going to use the query params on the related model's normal get_all query,
2662 2662
         //except add a condition to say to match the current mod
2663
-        if (! isset($query_params['default_where_conditions'])) {
2663
+        if ( ! isset($query_params['default_where_conditions'])) {
2664 2664
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2665 2665
         }
2666 2666
         $this_model_name = $this->get_this_model_name();
2667 2667
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2668
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2668
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2669 2669
         return $related_model->count($query_params, $field_to_count, $distinct);
2670 2670
     }
2671 2671
 
@@ -2685,7 +2685,7 @@  discard block
 block discarded – undo
2685 2685
     public function sum_related($id_or_obj, $model_name, $query_params, $field_to_sum = null)
2686 2686
     {
2687 2687
         $related_model = $this->get_related_model_obj($model_name);
2688
-        if (! is_array($query_params)) {
2688
+        if ( ! is_array($query_params)) {
2689 2689
             EE_Error::doing_it_wrong('EEM_Base::sum_related',
2690 2690
                 sprintf(__('$query_params should be an array, you passed a variable of type %s', 'event_espresso'),
2691 2691
                     gettype($query_params)), '4.6.0');
@@ -2693,12 +2693,12 @@  discard block
 block discarded – undo
2693 2693
         }
2694 2694
         //we're just going to use the query params on the related model's normal get_all query,
2695 2695
         //except add a condition to say to match the current mod
2696
-        if (! isset($query_params['default_where_conditions'])) {
2696
+        if ( ! isset($query_params['default_where_conditions'])) {
2697 2697
             $query_params['default_where_conditions'] = EEM_Base::default_where_conditions_none;
2698 2698
         }
2699 2699
         $this_model_name = $this->get_this_model_name();
2700 2700
         $this_pk_field_name = $this->get_primary_key_field()->get_name();
2701
-        $query_params[0][$this_model_name . "." . $this_pk_field_name] = $id_or_obj;
2701
+        $query_params[0][$this_model_name.".".$this_pk_field_name] = $id_or_obj;
2702 2702
         return $related_model->sum($query_params, $field_to_sum);
2703 2703
     }
2704 2704
 
@@ -2751,7 +2751,7 @@  discard block
 block discarded – undo
2751 2751
                 $field_with_model_name = $field;
2752 2752
             }
2753 2753
         }
2754
-        if (! isset($field_with_model_name) || ! $field_with_model_name) {
2754
+        if ( ! isset($field_with_model_name) || ! $field_with_model_name) {
2755 2755
             throw new EE_Error(sprintf(__("There is no EE_Any_Foreign_Model_Name field on model %s", "event_espresso"),
2756 2756
                 $this->get_this_model_name()));
2757 2757
         }
@@ -2784,7 +2784,7 @@  discard block
 block discarded – undo
2784 2784
          * @param array    $fields_n_values keys are the fields and values are their new values
2785 2785
          * @param EEM_Base $model           the model used
2786 2786
          */
2787
-        $field_n_values = (array)apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2787
+        $field_n_values = (array) apply_filters('FHEE__EEM_Base__insert__fields_n_values', $field_n_values, $this);
2788 2788
         if ($this->_satisfies_unique_indexes($field_n_values)) {
2789 2789
             $main_table = $this->_get_main_table();
2790 2790
             $new_id = $this->_insert_into_specific_table($main_table, $field_n_values, false);
@@ -2891,7 +2891,7 @@  discard block
 block discarded – undo
2891 2891
         }
2892 2892
         foreach ($this->unique_indexes() as $unique_index_name => $unique_index) {
2893 2893
             $uniqueness_where_params = array_intersect_key($fields_n_values, $unique_index->fields());
2894
-            $query_params[0]['OR']['AND*' . $unique_index_name] = $uniqueness_where_params;
2894
+            $query_params[0]['OR']['AND*'.$unique_index_name] = $uniqueness_where_params;
2895 2895
         }
2896 2896
         //if there is nothing to base this search on, then we shouldn't find anything
2897 2897
         if (empty($query_params)) {
@@ -2977,7 +2977,7 @@  discard block
 block discarded – undo
2977 2977
             //its not the main table, so we should have already saved the main table's PK which we just inserted
2978 2978
             //so add the fk to the main table as a column
2979 2979
             $insertion_col_n_values[$table->get_fk_on_table()] = $new_id;
2980
-            $format_for_insertion[] = '%d';//yes right now we're only allowing these foreign keys to be INTs
2980
+            $format_for_insertion[] = '%d'; //yes right now we're only allowing these foreign keys to be INTs
2981 2981
         }
2982 2982
         //insert the new entry
2983 2983
         $result = $this->_do_wpdb_query('insert',
@@ -3181,7 +3181,7 @@  discard block
 block discarded – undo
3181 3181
                     $query_info_carrier,
3182 3182
                     'group_by'
3183 3183
                 );
3184
-            } elseif (! empty ($query_params['group_by'])) {
3184
+            } elseif ( ! empty ($query_params['group_by'])) {
3185 3185
                 $this->_extract_related_model_info_from_query_param(
3186 3186
                     $query_params['group_by'],
3187 3187
                     $query_info_carrier,
@@ -3203,7 +3203,7 @@  discard block
 block discarded – undo
3203 3203
                     $query_info_carrier,
3204 3204
                     'order_by'
3205 3205
                 );
3206
-            } elseif (! empty($query_params['order_by'])) {
3206
+            } elseif ( ! empty($query_params['order_by'])) {
3207 3207
                 $this->_extract_related_model_info_from_query_param(
3208 3208
                     $query_params['order_by'],
3209 3209
                     $query_info_carrier,
@@ -3238,8 +3238,8 @@  discard block
 block discarded – undo
3238 3238
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3239 3239
         $query_param_type
3240 3240
     ) {
3241
-        if (! empty($sub_query_params)) {
3242
-            $sub_query_params = (array)$sub_query_params;
3241
+        if ( ! empty($sub_query_params)) {
3242
+            $sub_query_params = (array) $sub_query_params;
3243 3243
             foreach ($sub_query_params as $param => $possibly_array_of_params) {
3244 3244
                 //$param could be simply 'EVT_ID', or it could be 'Registrations.REG_ID', or even 'Registrations.Transactions.Payments.PAY_amount'
3245 3245
                 $this->_extract_related_model_info_from_query_param($param, $model_query_info_carrier,
@@ -3250,7 +3250,7 @@  discard block
 block discarded – undo
3250 3250
                 //of array('Registration.TXN_ID'=>23)
3251 3251
                 $query_param_sans_stars = $this->_remove_stars_and_anything_after_from_condition_query_param_key($param);
3252 3252
                 if (in_array($query_param_sans_stars, $this->_logic_query_param_keys, true)) {
3253
-                    if (! is_array($possibly_array_of_params)) {
3253
+                    if ( ! is_array($possibly_array_of_params)) {
3254 3254
                         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'))",
3255 3255
                             "event_espresso"),
3256 3256
                             $param, $possibly_array_of_params));
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
                     //then $possible_array_of_params looks something like array('<','DTT_sold',true)
3268 3268
                     //indicating that $possible_array_of_params[1] is actually a field name,
3269 3269
                     //from which we should extract query parameters!
3270
-                    if (! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3270
+                    if ( ! isset($possibly_array_of_params[0], $possibly_array_of_params[1])) {
3271 3271
                         throw new EE_Error(sprintf(__("Improperly formed query parameter %s. It should be numerically indexed like array('<','DTT_sold',true); but you provided %s",
3272 3272
                             "event_espresso"), $query_param_type, implode(",", $possibly_array_of_params)));
3273 3273
                     }
@@ -3297,8 +3297,8 @@  discard block
 block discarded – undo
3297 3297
         EE_Model_Query_Info_Carrier $model_query_info_carrier,
3298 3298
         $query_param_type
3299 3299
     ) {
3300
-        if (! empty($sub_query_params)) {
3301
-            if (! is_array($sub_query_params)) {
3300
+        if ( ! empty($sub_query_params)) {
3301
+            if ( ! is_array($sub_query_params)) {
3302 3302
                 throw new EE_Error(sprintf(__("Query parameter %s should be an array, but it isn't.", "event_espresso"),
3303 3303
                     $sub_query_params));
3304 3304
             }
@@ -3327,7 +3327,7 @@  discard block
 block discarded – undo
3327 3327
      */
3328 3328
     public function _create_model_query_info_carrier($query_params)
3329 3329
     {
3330
-        if (! is_array($query_params)) {
3330
+        if ( ! is_array($query_params)) {
3331 3331
             EE_Error::doing_it_wrong(
3332 3332
                 'EEM_Base::_create_model_query_info_carrier',
3333 3333
                 sprintf(
@@ -3403,7 +3403,7 @@  discard block
 block discarded – undo
3403 3403
         //set limit
3404 3404
         if (array_key_exists('limit', $query_params)) {
3405 3405
             if (is_array($query_params['limit'])) {
3406
-                if (! isset($query_params['limit'][0], $query_params['limit'][1])) {
3406
+                if ( ! isset($query_params['limit'][0], $query_params['limit'][1])) {
3407 3407
                     $e = sprintf(
3408 3408
                         __(
3409 3409
                             "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)",
@@ -3411,12 +3411,12 @@  discard block
 block discarded – undo
3411 3411
                         ),
3412 3412
                         http_build_query($query_params['limit'])
3413 3413
                     );
3414
-                    throw new EE_Error($e . "|" . $e);
3414
+                    throw new EE_Error($e."|".$e);
3415 3415
                 }
3416 3416
                 //they passed us an array for the limit. Assume it's like array(50,25), meaning offset by 50, and get 25
3417
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit'][0] . "," . $query_params['limit'][1]);
3418
-            } elseif (! empty ($query_params['limit'])) {
3419
-                $query_object->set_limit_sql(" LIMIT " . $query_params['limit']);
3417
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit'][0].",".$query_params['limit'][1]);
3418
+            } elseif ( ! empty ($query_params['limit'])) {
3419
+                $query_object->set_limit_sql(" LIMIT ".$query_params['limit']);
3420 3420
             }
3421 3421
         }
3422 3422
         //set order by
@@ -3448,10 +3448,10 @@  discard block
 block discarded – undo
3448 3448
                 $order_array = array();
3449 3449
                 foreach ($query_params['order_by'] as $field_name_to_order_by => $order) {
3450 3450
                     $order = $this->_extract_order($order);
3451
-                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by) . SP . $order;
3451
+                    $order_array[] = $this->_deduce_column_name_from_query_param($field_name_to_order_by).SP.$order;
3452 3452
                 }
3453
-                $query_object->set_order_by_sql(" ORDER BY " . implode(",", $order_array));
3454
-            } elseif (! empty ($query_params['order_by'])) {
3453
+                $query_object->set_order_by_sql(" ORDER BY ".implode(",", $order_array));
3454
+            } elseif ( ! empty ($query_params['order_by'])) {
3455 3455
                 $this->_extract_related_model_info_from_query_param(
3456 3456
                     $query_params['order_by'],
3457 3457
                     $query_object,
@@ -3462,18 +3462,18 @@  discard block
 block discarded – undo
3462 3462
                     ? $this->_extract_order($query_params['order'])
3463 3463
                     : 'DESC';
3464 3464
                 $query_object->set_order_by_sql(
3465
-                    " ORDER BY " . $this->_deduce_column_name_from_query_param($query_params['order_by']) . SP . $order
3465
+                    " ORDER BY ".$this->_deduce_column_name_from_query_param($query_params['order_by']).SP.$order
3466 3466
                 );
3467 3467
             }
3468 3468
         }
3469 3469
         //if 'order_by' wasn't set, maybe they are just using 'order' on its own?
3470
-        if (! array_key_exists('order_by', $query_params)
3470
+        if ( ! array_key_exists('order_by', $query_params)
3471 3471
             && array_key_exists('order', $query_params)
3472 3472
             && ! empty($query_params['order'])
3473 3473
         ) {
3474 3474
             $pk_field = $this->get_primary_key_field();
3475 3475
             $order = $this->_extract_order($query_params['order']);
3476
-            $query_object->set_order_by_sql(" ORDER BY " . $pk_field->get_qualified_column() . SP . $order);
3476
+            $query_object->set_order_by_sql(" ORDER BY ".$pk_field->get_qualified_column().SP.$order);
3477 3477
         }
3478 3478
         //set group by
3479 3479
         if (array_key_exists('group_by', $query_params)) {
@@ -3483,10 +3483,10 @@  discard block
 block discarded – undo
3483 3483
                 foreach ($query_params['group_by'] as $field_name_to_group_by) {
3484 3484
                     $group_by_array[] = $this->_deduce_column_name_from_query_param($field_name_to_group_by);
3485 3485
                 }
3486
-                $query_object->set_group_by_sql(" GROUP BY " . implode(", ", $group_by_array));
3487
-            } elseif (! empty ($query_params['group_by'])) {
3486
+                $query_object->set_group_by_sql(" GROUP BY ".implode(", ", $group_by_array));
3487
+            } elseif ( ! empty ($query_params['group_by'])) {
3488 3488
                 $query_object->set_group_by_sql(
3489
-                    " GROUP BY " . $this->_deduce_column_name_from_query_param($query_params['group_by'])
3489
+                    " GROUP BY ".$this->_deduce_column_name_from_query_param($query_params['group_by'])
3490 3490
                 );
3491 3491
             }
3492 3492
         }
@@ -3496,7 +3496,7 @@  discard block
 block discarded – undo
3496 3496
         }
3497 3497
         //now, just verify they didn't pass anything wack
3498 3498
         foreach ($query_params as $query_key => $query_value) {
3499
-            if (! in_array($query_key, $this->_allowed_query_params, true)) {
3499
+            if ( ! in_array($query_key, $this->_allowed_query_params, true)) {
3500 3500
                 throw new EE_Error(
3501 3501
                     sprintf(
3502 3502
                         __(
@@ -3595,22 +3595,22 @@  discard block
 block discarded – undo
3595 3595
         $where_query_params = array()
3596 3596
     ) {
3597 3597
         $allowed_used_default_where_conditions_values = EEM_Base::valid_default_where_conditions();
3598
-        if (! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3598
+        if ( ! in_array($use_default_where_conditions, $allowed_used_default_where_conditions_values)) {
3599 3599
             throw new EE_Error(sprintf(__("You passed an invalid value to the query parameter 'default_where_conditions' of '%s'. Allowed values are %s",
3600 3600
                 "event_espresso"), $use_default_where_conditions,
3601 3601
                 implode(", ", $allowed_used_default_where_conditions_values)));
3602 3602
         }
3603 3603
         $universal_query_params = array();
3604
-        if ($this->_should_use_default_where_conditions( $use_default_where_conditions, true)) {
3604
+        if ($this->_should_use_default_where_conditions($use_default_where_conditions, true)) {
3605 3605
             $universal_query_params = $this->_get_default_where_conditions();
3606
-        } else if ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, true)) {
3606
+        } else if ($this->_should_use_minimum_where_conditions($use_default_where_conditions, true)) {
3607 3607
             $universal_query_params = $this->_get_minimum_where_conditions();
3608 3608
         }
3609 3609
         foreach ($query_info_carrier->get_model_names_included() as $model_relation_path => $model_name) {
3610 3610
             $related_model = $this->get_related_model_obj($model_name);
3611
-            if ( $this->_should_use_default_where_conditions( $use_default_where_conditions, false)) {
3611
+            if ($this->_should_use_default_where_conditions($use_default_where_conditions, false)) {
3612 3612
                 $related_model_universal_where_params = $related_model->_get_default_where_conditions($model_relation_path);
3613
-            } elseif ($this->_should_use_minimum_where_conditions( $use_default_where_conditions, false)) {
3613
+            } elseif ($this->_should_use_minimum_where_conditions($use_default_where_conditions, false)) {
3614 3614
                 $related_model_universal_where_params = $related_model->_get_minimum_where_conditions($model_relation_path);
3615 3615
             } else {
3616 3616
                 //we don't want to add full or even minimum default where conditions from this model, so just continue
@@ -3643,7 +3643,7 @@  discard block
 block discarded – undo
3643 3643
      * @param bool $for_this_model false means this is for OTHER related models
3644 3644
      * @return bool
3645 3645
      */
3646
-    private function _should_use_default_where_conditions( $default_where_conditions_value, $for_this_model = true )
3646
+    private function _should_use_default_where_conditions($default_where_conditions_value, $for_this_model = true)
3647 3647
     {
3648 3648
         return (
3649 3649
                    $for_this_model
@@ -3722,7 +3722,7 @@  discard block
 block discarded – undo
3722 3722
     ) {
3723 3723
         $null_friendly_where_conditions = array();
3724 3724
         $none_overridden = true;
3725
-        $or_condition_key_for_defaults = 'OR*' . get_class($model);
3725
+        $or_condition_key_for_defaults = 'OR*'.get_class($model);
3726 3726
         foreach ($default_where_conditions as $key => $val) {
3727 3727
             if (isset($provided_where_conditions[$key])) {
3728 3728
                 $none_overridden = false;
@@ -3840,7 +3840,7 @@  discard block
 block discarded – undo
3840 3840
             foreach ($tables as $table_obj) {
3841 3841
                 $qualified_pk_column = $table_alias_with_model_relation_chain_prefix
3842 3842
                                        . $table_obj->get_fully_qualified_pk_column();
3843
-                if (! in_array($qualified_pk_column, $selects)) {
3843
+                if ( ! in_array($qualified_pk_column, $selects)) {
3844 3844
                     $selects[] = "$qualified_pk_column AS '$qualified_pk_column'";
3845 3845
                 }
3846 3846
             }
@@ -3934,9 +3934,9 @@  discard block
 block discarded – undo
3934 3934
         //and
3935 3935
         //check if it's a field on a related model
3936 3936
         foreach ($this->_model_relations as $valid_related_model_name => $relation_obj) {
3937
-            if (strpos($query_param, $valid_related_model_name . ".") === 0) {
3937
+            if (strpos($query_param, $valid_related_model_name.".") === 0) {
3938 3938
                 $this->_add_join_to_model($valid_related_model_name, $passed_in_query_info, $original_query_param);
3939
-                $query_param = substr($query_param, strlen($valid_related_model_name . "."));
3939
+                $query_param = substr($query_param, strlen($valid_related_model_name."."));
3940 3940
                 if ($query_param === '') {
3941 3941
                     //nothing left to $query_param
3942 3942
                     //we should actually end in a field name, not a model like this!
@@ -4028,7 +4028,7 @@  discard block
 block discarded – undo
4028 4028
     {
4029 4029
         $SQL = $this->_construct_condition_clause_recursive($where_params, ' AND ');
4030 4030
         if ($SQL) {
4031
-            return " WHERE " . $SQL;
4031
+            return " WHERE ".$SQL;
4032 4032
         }
4033 4033
         return '';
4034 4034
     }
@@ -4047,7 +4047,7 @@  discard block
 block discarded – undo
4047 4047
     {
4048 4048
         $SQL = $this->_construct_condition_clause_recursive($having_params, ' AND ');
4049 4049
         if ($SQL) {
4050
-            return " HAVING " . $SQL;
4050
+            return " HAVING ".$SQL;
4051 4051
         }
4052 4052
         return '';
4053 4053
     }
@@ -4066,7 +4066,7 @@  discard block
 block discarded – undo
4066 4066
     {
4067 4067
         $where_clauses = array();
4068 4068
         foreach ($where_params as $query_param => $op_and_value_or_sub_condition) {
4069
-            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param);//str_replace("*",'',$query_param);
4069
+            $query_param = $this->_remove_stars_and_anything_after_from_condition_query_param_key($query_param); //str_replace("*",'',$query_param);
4070 4070
             if (in_array($query_param, $this->_logic_query_param_keys)) {
4071 4071
                 switch ($query_param) {
4072 4072
                     case 'not':
@@ -4094,7 +4094,7 @@  discard block
 block discarded – undo
4094 4094
             } else {
4095 4095
                 $field_obj = $this->_deduce_field_from_query_param($query_param);
4096 4096
                 //if it's not a normal field, maybe it's a custom selection?
4097
-                if (! $field_obj) {
4097
+                if ( ! $field_obj) {
4098 4098
                     if (isset($this->_custom_selections[$query_param][1])) {
4099 4099
                         $field_obj = $this->_custom_selections[$query_param][1];
4100 4100
                     } else {
@@ -4103,7 +4103,7 @@  discard block
 block discarded – undo
4103 4103
                     }
4104 4104
                 }
4105 4105
                 $op_and_value_sql = $this->_construct_op_and_value($op_and_value_or_sub_condition, $field_obj);
4106
-                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param) . SP . $op_and_value_sql;
4106
+                $where_clauses[] = $this->_deduce_column_name_from_query_param($query_param).SP.$op_and_value_sql;
4107 4107
             }
4108 4108
         }
4109 4109
         return $where_clauses ? implode($glue, $where_clauses) : '';
@@ -4124,7 +4124,7 @@  discard block
 block discarded – undo
4124 4124
         if ($field) {
4125 4125
             $table_alias_prefix = EE_Model_Parser::extract_table_alias_model_relation_chain_from_query_param($field->get_model_name(),
4126 4126
                 $query_param);
4127
-            return $table_alias_prefix . $field->get_qualified_column();
4127
+            return $table_alias_prefix.$field->get_qualified_column();
4128 4128
         }
4129 4129
         if (array_key_exists($query_param, $this->_custom_selections)) {
4130 4130
             //maybe it's custom selection item?
@@ -4176,7 +4176,7 @@  discard block
 block discarded – undo
4176 4176
     {
4177 4177
         if (is_array($op_and_value)) {
4178 4178
             $operator = isset($op_and_value[0]) ? $this->_prepare_operator_for_sql($op_and_value[0]) : null;
4179
-            if (! $operator) {
4179
+            if ( ! $operator) {
4180 4180
                 $php_array_like_string = array();
4181 4181
                 foreach ($op_and_value as $key => $value) {
4182 4182
                     $php_array_like_string[] = "$key=>$value";
@@ -4198,14 +4198,14 @@  discard block
 block discarded – undo
4198 4198
         }
4199 4199
         //check to see if the value is actually another field
4200 4200
         if (is_array($op_and_value) && isset($op_and_value[2]) && $op_and_value[2] == true) {
4201
-            return $operator . SP . $this->_deduce_column_name_from_query_param($value);
4201
+            return $operator.SP.$this->_deduce_column_name_from_query_param($value);
4202 4202
         }
4203 4203
         if (in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4204 4204
             //in this case, the value should be an array, or at least a comma-separated list
4205 4205
             //it will need to handle a little differently
4206 4206
             $cleaned_value = $this->_construct_in_value($value, $field_obj);
4207 4207
             //note: $cleaned_value has already been run through $wpdb->prepare()
4208
-            return $operator . SP . $cleaned_value;
4208
+            return $operator.SP.$cleaned_value;
4209 4209
         }
4210 4210
         if (in_array($operator, $this->valid_between_style_operators()) && is_array($value)) {
4211 4211
             //the value should be an array with count of two.
@@ -4221,7 +4221,7 @@  discard block
 block discarded – undo
4221 4221
                 );
4222 4222
             }
4223 4223
             $cleaned_value = $this->_construct_between_value($value, $field_obj);
4224
-            return $operator . SP . $cleaned_value;
4224
+            return $operator.SP.$cleaned_value;
4225 4225
         }
4226 4226
         if (in_array($operator, $this->valid_null_style_operators())) {
4227 4227
             if ($value !== null) {
@@ -4241,10 +4241,10 @@  discard block
 block discarded – undo
4241 4241
         if (in_array($operator, $this->valid_like_style_operators()) && ! is_array($value)) {
4242 4242
             //if the operator is 'LIKE', we want to allow percent signs (%) and not
4243 4243
             //remove other junk. So just treat it as a string.
4244
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, '%s');
4244
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, '%s');
4245 4245
         }
4246
-        if (! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4247
-            return $operator . SP . $this->_wpdb_prepare_using_field($value, $field_obj);
4246
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4247
+            return $operator.SP.$this->_wpdb_prepare_using_field($value, $field_obj);
4248 4248
         }
4249 4249
         if (in_array($operator, $this->valid_in_style_operators()) && ! is_array($value)) {
4250 4250
             throw new EE_Error(
@@ -4258,7 +4258,7 @@  discard block
 block discarded – undo
4258 4258
                 )
4259 4259
             );
4260 4260
         }
4261
-        if (! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4261
+        if ( ! in_array($operator, $this->valid_in_style_operators()) && is_array($value)) {
4262 4262
             throw new EE_Error(
4263 4263
                 sprintf(
4264 4264
                     __(
@@ -4298,7 +4298,7 @@  discard block
 block discarded – undo
4298 4298
         foreach ($values as $value) {
4299 4299
             $cleaned_values[] = $this->_wpdb_prepare_using_field($value, $field_obj);
4300 4300
         }
4301
-        return $cleaned_values[0] . " AND " . $cleaned_values[1];
4301
+        return $cleaned_values[0]." AND ".$cleaned_values[1];
4302 4302
     }
4303 4303
 
4304 4304
 
@@ -4339,7 +4339,7 @@  discard block
 block discarded – undo
4339 4339
                                 . $main_table->get_table_name()
4340 4340
                                 . " WHERE FALSE";
4341 4341
         }
4342
-        return "(" . implode(",", $cleaned_values) . ")";
4342
+        return "(".implode(",", $cleaned_values).")";
4343 4343
     }
4344 4344
 
4345 4345
 
@@ -4358,7 +4358,7 @@  discard block
 block discarded – undo
4358 4358
             return $wpdb->prepare($field_obj->get_wpdb_data_type(),
4359 4359
                 $this->_prepare_value_for_use_in_db($value, $field_obj));
4360 4360
         } //$field_obj should really just be a data type
4361
-        if (! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4361
+        if ( ! in_array($field_obj, $this->_valid_wpdb_data_types)) {
4362 4362
             throw new EE_Error(
4363 4363
                 sprintf(
4364 4364
                     __("%s is not a valid wpdb datatype. Valid ones are %s", "event_espresso"),
@@ -4486,10 +4486,10 @@  discard block
 block discarded – undo
4486 4486
      */
4487 4487
     public function get_qualified_columns_for_all_fields($model_relation_chain = '', $return_string = true)
4488 4488
     {
4489
-        $table_prefix = str_replace('.', '__', $model_relation_chain) . (empty($model_relation_chain) ? '' : '__');
4489
+        $table_prefix = str_replace('.', '__', $model_relation_chain).(empty($model_relation_chain) ? '' : '__');
4490 4490
         $qualified_columns = array();
4491 4491
         foreach ($this->field_settings() as $field_name => $field) {
4492
-            $qualified_columns[] = $table_prefix . $field->get_qualified_column();
4492
+            $qualified_columns[] = $table_prefix.$field->get_qualified_column();
4493 4493
         }
4494 4494
         return $return_string ? implode(', ', $qualified_columns) : $qualified_columns;
4495 4495
     }
@@ -4513,11 +4513,11 @@  discard block
 block discarded – undo
4513 4513
             if ($table_obj instanceof EE_Primary_Table) {
4514 4514
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4515 4515
                     ? $table_obj->get_select_join_limit($limit)
4516
-                    : SP . $table_obj->get_table_name() . " AS " . $table_obj->get_table_alias() . SP;
4516
+                    : SP.$table_obj->get_table_name()." AS ".$table_obj->get_table_alias().SP;
4517 4517
             } elseif ($table_obj instanceof EE_Secondary_Table) {
4518 4518
                 $SQL .= $table_alias === $table_obj->get_table_alias()
4519 4519
                     ? $table_obj->get_select_join_limit_join($limit)
4520
-                    : SP . $table_obj->get_join_sql($table_alias) . SP;
4520
+                    : SP.$table_obj->get_join_sql($table_alias).SP;
4521 4521
             }
4522 4522
         }
4523 4523
         return $SQL;
@@ -4605,12 +4605,12 @@  discard block
 block discarded – undo
4605 4605
      */
4606 4606
     public function get_related_model_obj($model_name)
4607 4607
     {
4608
-        $model_classname = "EEM_" . $model_name;
4609
-        if (! class_exists($model_classname)) {
4608
+        $model_classname = "EEM_".$model_name;
4609
+        if ( ! class_exists($model_classname)) {
4610 4610
             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",
4611 4611
                 'event_espresso'), $model_name, $model_classname));
4612 4612
         }
4613
-        return call_user_func($model_classname . "::instance");
4613
+        return call_user_func($model_classname."::instance");
4614 4614
     }
4615 4615
 
4616 4616
 
@@ -4657,7 +4657,7 @@  discard block
 block discarded – undo
4657 4657
     public function related_settings_for($relation_name)
4658 4658
     {
4659 4659
         $relatedModels = $this->relation_settings();
4660
-        if (! array_key_exists($relation_name, $relatedModels)) {
4660
+        if ( ! array_key_exists($relation_name, $relatedModels)) {
4661 4661
             throw new EE_Error(
4662 4662
                 sprintf(
4663 4663
                     __('Cannot get %s related to %s. There is no model relation of that type. There is, however, %s...',
@@ -4685,7 +4685,7 @@  discard block
 block discarded – undo
4685 4685
     public function field_settings_for($fieldName, $include_db_only_fields = true)
4686 4686
     {
4687 4687
         $fieldSettings = $this->field_settings($include_db_only_fields);
4688
-        if (! array_key_exists($fieldName, $fieldSettings)) {
4688
+        if ( ! array_key_exists($fieldName, $fieldSettings)) {
4689 4689
             throw new EE_Error(sprintf(__("There is no field/column '%s' on '%s'", 'event_espresso'), $fieldName,
4690 4690
                 get_class($this)));
4691 4691
         }
@@ -4758,7 +4758,7 @@  discard block
 block discarded – undo
4758 4758
                     break;
4759 4759
                 }
4760 4760
             }
4761
-            if (! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4761
+            if ( ! $this->_primary_key_field instanceof EE_Primary_Key_Field_Base) {
4762 4762
                 throw new EE_Error(sprintf(__("There is no Primary Key defined on model %s", 'event_espresso'),
4763 4763
                     get_class($this)));
4764 4764
             }
@@ -4817,7 +4817,7 @@  discard block
 block discarded – undo
4817 4817
      */
4818 4818
     public function get_foreign_key_to($model_name)
4819 4819
     {
4820
-        if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4820
+        if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4821 4821
             foreach ($this->field_settings() as $field) {
4822 4822
                 if (
4823 4823
                     $field instanceof EE_Foreign_Key_Field_Base
@@ -4827,7 +4827,7 @@  discard block
 block discarded – undo
4827 4827
                     break;
4828 4828
                 }
4829 4829
             }
4830
-            if (! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4830
+            if ( ! isset($this->_cache_foreign_key_to_fields[$model_name])) {
4831 4831
                 throw new EE_Error(sprintf(__("There is no foreign key field pointing to model %s on model %s",
4832 4832
                     'event_espresso'), $model_name, get_class($this)));
4833 4833
             }
@@ -4878,7 +4878,7 @@  discard block
 block discarded – undo
4878 4878
             foreach ($this->_fields as $fields_corresponding_to_table) {
4879 4879
                 foreach ($fields_corresponding_to_table as $field_name => $field_obj) {
4880 4880
                     /** @var $field_obj EE_Model_Field_Base */
4881
-                    if (! $field_obj->is_db_only_field()) {
4881
+                    if ( ! $field_obj->is_db_only_field()) {
4882 4882
                         $this->_cached_fields_non_db_only[$field_name] = $field_obj;
4883 4883
                     }
4884 4884
                 }
@@ -4907,7 +4907,7 @@  discard block
 block discarded – undo
4907 4907
         $count_if_model_has_no_primary_key = 0;
4908 4908
         $has_primary_key = $this->has_primary_key_field();
4909 4909
         $primary_key_field = $has_primary_key ? $this->get_primary_key_field() : null;
4910
-        foreach ((array)$rows as $row) {
4910
+        foreach ((array) $rows as $row) {
4911 4911
             if (empty($row)) {
4912 4912
                 //wp did its weird thing where it returns an array like array(0=>null), which is totally not helpful...
4913 4913
                 return array();
@@ -4925,7 +4925,7 @@  discard block
 block discarded – undo
4925 4925
                 }
4926 4926
             }
4927 4927
             $classInstance = $this->instantiate_class_from_array_or_object($row);
4928
-            if (! $classInstance) {
4928
+            if ( ! $classInstance) {
4929 4929
                 throw new EE_Error(
4930 4930
                     sprintf(
4931 4931
                         __('Could not create instance of class %s from row %s', 'event_espresso'),
@@ -4994,7 +4994,7 @@  discard block
 block discarded – undo
4994 4994
      */
4995 4995
     public function instantiate_class_from_array_or_object($cols_n_values)
4996 4996
     {
4997
-        if (! is_array($cols_n_values) && is_object($cols_n_values)) {
4997
+        if ( ! is_array($cols_n_values) && is_object($cols_n_values)) {
4998 4998
             $cols_n_values = get_object_vars($cols_n_values);
4999 4999
         }
5000 5000
         $primary_key = null;
@@ -5019,7 +5019,7 @@  discard block
 block discarded – undo
5019 5019
         // if there is no primary key or the object doesn't already exist in the entity map, then create a new instance
5020 5020
         if ($primary_key) {
5021 5021
             $classInstance = $this->get_from_entity_map($primary_key);
5022
-            if (! $classInstance) {
5022
+            if ( ! $classInstance) {
5023 5023
                 $classInstance = EE_Registry::instance()
5024 5024
                                             ->load_class($className,
5025 5025
                                                 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/services/loaders/CachingLoader.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -21,146 +21,146 @@
 block discarded – undo
21 21
 class CachingLoader extends LoaderDecorator
22 22
 {
23 23
 
24
-    /**
25
-     * @var CollectionInterface $cache
26
-     */
27
-    protected $cache;
28
-
29
-    /**
30
-     * @var string $identifier
31
-     */
32
-    protected $identifier;
33
-
34
-
35
-
36
-    /**
37
-     * CachingLoader constructor.
38
-     *
39
-     * @param LoaderDecoratorInterface $loader
40
-     * @param CollectionInterface      $cache
41
-     * @param string                   $identifier
42
-     * @throws InvalidDataTypeException
43
-     */
44
-    public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
45
-    {
46
-        parent::__construct($loader);
47
-        $this->cache = $cache;
48
-        $this->setIdentifier($identifier);
49
-        if ($this->identifier !== '') {
50
-            // to only clear this cache, and assuming an identifier has been set, simply do the following:
51
-            // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
52
-            // where "IDENTIFIER" = the string that was set during construction
53
-            add_action(
54
-                "AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
55
-                array($this, 'reset')
56
-            );
57
-        }
58
-        // to clear ALL caches, simply do the following:
59
-        // do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
60
-        add_action(
61
-            'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
62
-            array($this, 'reset')
63
-        );
64
-    }
65
-
66
-
67
-
68
-    /**
69
-     * @return string
70
-     */
71
-    public function identifier()
72
-    {
73
-        return $this->identifier;
74
-    }
75
-
76
-
77
-
78
-    /**
79
-     * @param string $identifier
80
-     * @throws InvalidDataTypeException
81
-     */
82
-    private function setIdentifier($identifier)
83
-    {
84
-        if ( ! is_string($identifier)) {
85
-            throw new InvalidDataTypeException('$identifier', $identifier, 'string');
86
-        }
87
-        $this->identifier = $identifier;
88
-    }
89
-
90
-
91
-
92
-    /**
93
-     * @param string $fqcn
94
-     * @param array  $arguments
95
-     * @param bool   $shared
96
-     * @return mixed
97
-     */
98
-    public function load($fqcn, $arguments = array(), $shared = true)
99
-    {
100
-        $fqcn = ltrim($fqcn, '\\');
101
-        // caching can be turned off via the following code:
102
-        // add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
103
-        if(
104
-            apply_filters(
105
-                'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
106
-                false,
107
-                $this
108
-            )
109
-        ){
110
-            // even though $shared might be true, caching should be bypassed for whatever reason,
111
-            // so we don't want the core loader to cache anything, therefore caching is turned off
112
-            return $this->loader->load($fqcn, $arguments, false);
113
-        }
114
-        $identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
115
-        if($this->cache->has($identifier)){
116
-            return $this->cache->get($identifier);
117
-        }
118
-        $object = $this->loader->load($fqcn, $arguments, $shared);
119
-        if($object instanceof $fqcn){
120
-            $this->cache->add($object, $identifier);
121
-        }
122
-        return $object;
123
-    }
124
-
125
-
126
-
127
-    /**
128
-     * empties cache and calls reset() on loader if method exists
129
-     */
130
-    public function reset()
131
-    {
132
-        $this->cache->trashAndDetachAll();
133
-        $this->loader->reset();
134
-    }
135
-
136
-
137
-
138
-    /**
139
-     * build a string representation of a class' arguments
140
-     * (mostly because Closures can't be serialized)
141
-     *
142
-     * @param array $arguments
143
-     * @return string
144
-     */
145
-    private function getIdentifierForArgument(array $arguments)
146
-    {
147
-        $identifier = '';
148
-        foreach ($arguments as $argument) {
149
-            switch (true) {
150
-                case is_object($argument) :
151
-                case $argument instanceof Closure :
152
-                    $identifier .= spl_object_hash($argument);
153
-                    break;
154
-                case is_array($argument) :
155
-                    $identifier .= $this->getIdentifierForArgument($argument);
156
-                    break;
157
-                default :
158
-                    $identifier .= $argument;
159
-                    break;
160
-            }
161
-        }
162
-        return $identifier;
163
-    }
24
+	/**
25
+	 * @var CollectionInterface $cache
26
+	 */
27
+	protected $cache;
28
+
29
+	/**
30
+	 * @var string $identifier
31
+	 */
32
+	protected $identifier;
33
+
34
+
35
+
36
+	/**
37
+	 * CachingLoader constructor.
38
+	 *
39
+	 * @param LoaderDecoratorInterface $loader
40
+	 * @param CollectionInterface      $cache
41
+	 * @param string                   $identifier
42
+	 * @throws InvalidDataTypeException
43
+	 */
44
+	public function __construct(LoaderDecoratorInterface $loader, CollectionInterface $cache, $identifier = '')
45
+	{
46
+		parent::__construct($loader);
47
+		$this->cache = $cache;
48
+		$this->setIdentifier($identifier);
49
+		if ($this->identifier !== '') {
50
+			// to only clear this cache, and assuming an identifier has been set, simply do the following:
51
+			// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__IDENTIFIER');
52
+			// where "IDENTIFIER" = the string that was set during construction
53
+			add_action(
54
+				"AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache__{$identifier}",
55
+				array($this, 'reset')
56
+			);
57
+		}
58
+		// to clear ALL caches, simply do the following:
59
+		// do_action('AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache');
60
+		add_action(
61
+			'AHEE__EventEspresso_core_services_loaders_CachingLoader__resetCache',
62
+			array($this, 'reset')
63
+		);
64
+	}
65
+
66
+
67
+
68
+	/**
69
+	 * @return string
70
+	 */
71
+	public function identifier()
72
+	{
73
+		return $this->identifier;
74
+	}
75
+
76
+
77
+
78
+	/**
79
+	 * @param string $identifier
80
+	 * @throws InvalidDataTypeException
81
+	 */
82
+	private function setIdentifier($identifier)
83
+	{
84
+		if ( ! is_string($identifier)) {
85
+			throw new InvalidDataTypeException('$identifier', $identifier, 'string');
86
+		}
87
+		$this->identifier = $identifier;
88
+	}
89
+
90
+
91
+
92
+	/**
93
+	 * @param string $fqcn
94
+	 * @param array  $arguments
95
+	 * @param bool   $shared
96
+	 * @return mixed
97
+	 */
98
+	public function load($fqcn, $arguments = array(), $shared = true)
99
+	{
100
+		$fqcn = ltrim($fqcn, '\\');
101
+		// caching can be turned off via the following code:
102
+		// add_filter('FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache', '__return_true');
103
+		if(
104
+			apply_filters(
105
+				'FHEE__EventEspresso_core_services_loaders_CachingLoader__load__bypass_cache',
106
+				false,
107
+				$this
108
+			)
109
+		){
110
+			// even though $shared might be true, caching should be bypassed for whatever reason,
111
+			// so we don't want the core loader to cache anything, therefore caching is turned off
112
+			return $this->loader->load($fqcn, $arguments, false);
113
+		}
114
+		$identifier = md5($fqcn . $this->getIdentifierForArgument($arguments));
115
+		if($this->cache->has($identifier)){
116
+			return $this->cache->get($identifier);
117
+		}
118
+		$object = $this->loader->load($fqcn, $arguments, $shared);
119
+		if($object instanceof $fqcn){
120
+			$this->cache->add($object, $identifier);
121
+		}
122
+		return $object;
123
+	}
124
+
125
+
126
+
127
+	/**
128
+	 * empties cache and calls reset() on loader if method exists
129
+	 */
130
+	public function reset()
131
+	{
132
+		$this->cache->trashAndDetachAll();
133
+		$this->loader->reset();
134
+	}
135
+
136
+
137
+
138
+	/**
139
+	 * build a string representation of a class' arguments
140
+	 * (mostly because Closures can't be serialized)
141
+	 *
142
+	 * @param array $arguments
143
+	 * @return string
144
+	 */
145
+	private function getIdentifierForArgument(array $arguments)
146
+	{
147
+		$identifier = '';
148
+		foreach ($arguments as $argument) {
149
+			switch (true) {
150
+				case is_object($argument) :
151
+				case $argument instanceof Closure :
152
+					$identifier .= spl_object_hash($argument);
153
+					break;
154
+				case is_array($argument) :
155
+					$identifier .= $this->getIdentifierForArgument($argument);
156
+					break;
157
+				default :
158
+					$identifier .= $argument;
159
+					break;
160
+			}
161
+		}
162
+		return $identifier;
163
+	}
164 164
 
165 165
 
166 166
 }
Please login to merge, or discard this patch.
core/libraries/rest_api/controllers/model/Write.php 2 patches
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -18,7 +18,7 @@  discard block
 block discarded – undo
18 18
 use EE_Error;
19 19
 
20 20
 if (! defined('EVENT_ESPRESSO_VERSION')) {
21
-    exit('No direct script access allowed');
21
+	exit('No direct script access allowed');
22 22
 }
23 23
 
24 24
 
@@ -36,334 +36,334 @@  discard block
 block discarded – undo
36 36
 
37 37
 
38 38
 
39
-    public function __construct()
40
-    {
41
-        parent::__construct();
42
-        EE_Registry::instance()->load_helper('Inflector');
43
-    }
44
-
45
-
46
-
47
-    /**
48
-     * Handles requests to get all (or a filtered subset) of entities for a particular model
49
-     *
50
-     * @param WP_REST_Request $request
51
-     * @param string          $version
52
-     * @param string          $model_name
53
-     * @return WP_REST_Response|\WP_Error
54
-     */
55
-    public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
56
-    {
57
-        $controller = new Write();
58
-        try {
59
-            $controller->setRequestedVersion($version);
60
-            return $controller->sendResponse(
61
-                $controller->insert(
62
-                    $controller->getModelVersionInfo()->loadModel($model_name),
63
-                    $request
64
-                )
65
-            );
66
-        } catch (\Exception $e) {
67
-            return $controller->sendResponse($e);
68
-        }
69
-    }
70
-
71
-
72
-
73
-    /**
74
-     * Handles a request from \WP_REST_Server to update an EE model
75
-     *
76
-     * @param WP_REST_Request $request
77
-     * @param string          $version
78
-     * @param string          $model_name
79
-     * @return WP_REST_Response|\WP_Error
80
-     */
81
-    public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
82
-    {
83
-        $controller = new Write();
84
-        try {
85
-            $controller->setRequestedVersion($version);
86
-            return $controller->sendResponse(
87
-                $controller->update(
88
-                    $controller->getModelVersionInfo()->loadModel($model_name),
89
-                    $request
90
-                )
91
-            );
92
-        } catch (\Exception $e) {
93
-            return $controller->sendResponse($e);
94
-        }
95
-    }
96
-
97
-
98
-
99
-    /**
100
-     * Deletes a single model object and returns it. Unless
101
-     *
102
-     * @param WP_REST_Request $request
103
-     * @param string          $version
104
-     * @param string          $model_name
105
-     * @return WP_REST_Response|\WP_Error
106
-     */
107
-    public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
108
-    {
109
-        $controller = new Write();
110
-        try {
111
-            $controller->setRequestedVersion($version);
112
-            return $controller->sendResponse(
113
-                $controller->delete(
114
-                    $controller->getModelVersionInfo()->loadModel($model_name),
115
-                    $request
116
-                )
117
-            );
118
-        } catch (\Exception $e) {
119
-            return $controller->sendResponse($e);
120
-        }
121
-    }
122
-
123
-
124
-
125
-    /**
126
-     * Inserts a new model object according to the $request
127
-     *
128
-     * @param EEM_Base        $model
129
-     * @param WP_REST_Request $request
130
-     * @return array
131
-     * @throws EE_Error
132
-     * @throws RestException
133
-     */
134
-    public function insert(EEM_Base $model, WP_REST_Request $request)
135
-    {
136
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
-        if (! current_user_can($default_cap_to_check_for)) {
139
-            throw new RestException(
140
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141
-                sprintf(
142
-                    esc_html__(
143
-                        // @codingStandardsIgnoreStart
144
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
145
-                        // @codingStandardsIgnoreEnd
146
-                        'event_espresso'
147
-                    ),
148
-                    $default_cap_to_check_for
149
-                ),
150
-                array('status' => 403)
151
-            );
152
-        }
153
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
154
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155
-            $submitted_json_data,
156
-            $model,
157
-            $this->getModelVersionInfo()->requestedVersion(),
158
-            true
159
-        );
160
-        $model_obj = EE_Registry::instance()->load_class(
161
-            $model->get_this_model_name(),
162
-            array($model_data, $model->get_timezone()),
163
-            false,
164
-            false
165
-        );
166
-        $model_obj->save();
167
-        $new_id = $model_obj->ID();
168
-        if (! $new_id) {
169
-            throw new RestException(
170
-                'rest_insertion_failed',
171
-                sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
172
-            );
173
-        }
174
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
175
-    }
176
-
177
-
178
-
179
-    /**
180
-     * Updates an existing model object according to the $request
181
-     *
182
-     * @param EEM_Base        $model
183
-     * @param WP_REST_Request $request
184
-     * @return array
185
-     * @throws EE_Error
186
-     */
187
-    public function update(EEM_Base $model, WP_REST_Request $request)
188
-    {
189
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
-        if (! current_user_can($default_cap_to_check_for)) {
192
-            throw new RestException(
193
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194
-                sprintf(
195
-                    esc_html__(
196
-                        // @codingStandardsIgnoreStart
197
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
198
-                        // @codingStandardsIgnoreEnd
199
-                        'event_espresso'
200
-                    ),
201
-                    $default_cap_to_check_for
202
-                ),
203
-                array('status' => 403)
204
-            );
205
-        }
206
-        $obj_id = $request->get_param('id');
207
-        if (! $obj_id) {
208
-            throw new RestException(
209
-                'rest_edit_failed',
210
-                sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
211
-            );
212
-        }
213
-        $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
214
-            $this->getBodyParams($request),
215
-            $model,
216
-            $this->getModelVersionInfo()->requestedVersion(),
217
-            true
218
-        );
219
-        $model_obj = $model->get_one_by_ID($obj_id);
220
-        if (! $model_obj instanceof EE_Base_Class) {
221
-            $lowercase_model_name = strtolower($model->get_this_model_name());
222
-            throw new RestException(
223
-                sprintf('rest_%s_invalid_id', $lowercase_model_name),
224
-                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
225
-                array('status' => 404)
226
-            );
227
-        }
228
-        $model_obj->save($model_data);
229
-        return $this->returnModelObjAsJsonResponse($model_obj, $request);
230
-    }
231
-
232
-
233
-
234
-    /**
235
-     * Updates an existing model object according to the $request
236
-     *
237
-     * @param EEM_Base        $model
238
-     * @param WP_REST_Request $request
239
-     * @return array of either the soft-deleted item, or
240
-     * @throws EE_Error
241
-     */
242
-    public function delete(EEM_Base $model, WP_REST_Request $request)
243
-    {
244
-        Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
245
-        $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
246
-        if (! current_user_can($default_cap_to_check_for)) {
247
-            throw new RestException(
248
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
249
-                sprintf(
250
-                    esc_html__(
251
-                        // @codingStandardsIgnoreStart
252
-                        'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
253
-                        // @codingStandardsIgnoreEnd
254
-                        'event_espresso'
255
-                    ),
256
-                    $default_cap_to_check_for
257
-                ),
258
-                array('status' => 403)
259
-            );
260
-        }
261
-        $obj_id = $request->get_param('id');
262
-        //this is where we would apply more fine-grained caps
263
-        $model_obj = $model->get_one_by_ID($obj_id);
264
-        if (! $model_obj instanceof EE_Base_Class) {
265
-            $lowercase_model_name = strtolower($model->get_this_model_name());
266
-            throw new RestException(
267
-                sprintf('rest_%s_invalid_id', $lowercase_model_name),
268
-                sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
269
-                array('status' => 404)
270
-            );
271
-        }
272
-        $requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
273
-        $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
274
-        if ($requested_permanent_delete) {
275
-            $previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
276
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
277
-            return array(
278
-                'deleted'  => $deleted,
279
-                'previous' => $previous,
280
-            );
281
-        } else {
282
-            if ($model instanceof EEM_Soft_Delete_Base) {
283
-                $model->delete_by_ID($obj_id, $requested_allow_blocking);
284
-                return $this->returnModelObjAsJsonResponse($model_obj, $request);
285
-            } else {
286
-                throw new RestException(
287
-                    'rest_trash_not_supported',
288
-                    501,
289
-                    sprintf(
290
-                        esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
291
-                        EEH_Inflector::pluralize($model->get_this_model_name())
292
-                    )
293
-                );
294
-            }
295
-        }
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * Returns an array ready to be converted into a JSON response, based solely on the model object
302
-     *
303
-     * @param EE_Base_Class $model_obj
304
-     * @param WP_REST_Request $request
305
-     * @return array ready for a response
306
-     */
307
-    protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
308
-    {
309
-        $model = $model_obj->get_model();
310
-        //create an array exactly like the wpdb results row,
311
-        // so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
312
-        $simulated_db_row = array();
313
-        foreach ($model->field_settings(true) as $field_name => $field_obj) {
314
-            //we need to reconstruct the normal wpdb results, including the db-only fields
315
-            //like a secondary table's primary key. The models expect those (but don't care what value they have)
316
-            if( $field_obj instanceof EE_DB_Only_Field_Base){
317
-                $raw_value = true;
318
-            } elseif ($field_obj instanceof EE_Datetime_Field) {
319
-                $raw_value = $model_obj->get_DateTime_object($field_name);
320
-            } else {
321
-                $raw_value = $model_obj->get_raw($field_name);
322
-            }
323
-            $simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
324
-        }
325
-        $read_controller = new Read();
326
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
327
-        //the simulates request really doesn't need any info downstream
328
-        $simulated_request = new WP_REST_Request('GET');
329
-        return $read_controller->createEntityFromWpdbResult(
330
-            $model_obj->get_model(),
331
-            $simulated_db_row,
332
-            $simulated_request
333
-        );
334
-    }
335
-
336
-
337
-
338
-    /**
339
-     * Gets the item affected by this request
340
-     *
341
-     * @param EEM_Base        $model
342
-     * @param WP_REST_Request $request
343
-     * @param  int|string     $obj_id
344
-     * @return \WP_Error|array
345
-     */
346
-    protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
347
-    {
348
-        $requested_version = $this->getRequestedVersion($request->get_route());
349
-        $get_request = new WP_REST_Request(
350
-            'GET',
351
-            EED_Core_Rest_Api::ee_api_namespace
352
-            . $requested_version
353
-            . '/'
354
-            . EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
355
-            . '/'
356
-            . $obj_id
357
-        );
358
-        $get_request->set_url_params(
359
-            array(
360
-                'id'      => $obj_id,
361
-                'include' => $request->get_param('include'),
362
-            )
363
-        );
364
-        $read_controller = new Read();
365
-        $read_controller->setRequestedVersion($this->getRequestedVersion());
366
-        return $read_controller->getEntityFromModel($model, $get_request);
367
-    }
39
+	public function __construct()
40
+	{
41
+		parent::__construct();
42
+		EE_Registry::instance()->load_helper('Inflector');
43
+	}
44
+
45
+
46
+
47
+	/**
48
+	 * Handles requests to get all (or a filtered subset) of entities for a particular model
49
+	 *
50
+	 * @param WP_REST_Request $request
51
+	 * @param string          $version
52
+	 * @param string          $model_name
53
+	 * @return WP_REST_Response|\WP_Error
54
+	 */
55
+	public static function handleRequestInsert(WP_REST_Request $request, $version, $model_name)
56
+	{
57
+		$controller = new Write();
58
+		try {
59
+			$controller->setRequestedVersion($version);
60
+			return $controller->sendResponse(
61
+				$controller->insert(
62
+					$controller->getModelVersionInfo()->loadModel($model_name),
63
+					$request
64
+				)
65
+			);
66
+		} catch (\Exception $e) {
67
+			return $controller->sendResponse($e);
68
+		}
69
+	}
70
+
71
+
72
+
73
+	/**
74
+	 * Handles a request from \WP_REST_Server to update an EE model
75
+	 *
76
+	 * @param WP_REST_Request $request
77
+	 * @param string          $version
78
+	 * @param string          $model_name
79
+	 * @return WP_REST_Response|\WP_Error
80
+	 */
81
+	public static function handleRequestUpdate(WP_REST_Request $request, $version, $model_name)
82
+	{
83
+		$controller = new Write();
84
+		try {
85
+			$controller->setRequestedVersion($version);
86
+			return $controller->sendResponse(
87
+				$controller->update(
88
+					$controller->getModelVersionInfo()->loadModel($model_name),
89
+					$request
90
+				)
91
+			);
92
+		} catch (\Exception $e) {
93
+			return $controller->sendResponse($e);
94
+		}
95
+	}
96
+
97
+
98
+
99
+	/**
100
+	 * Deletes a single model object and returns it. Unless
101
+	 *
102
+	 * @param WP_REST_Request $request
103
+	 * @param string          $version
104
+	 * @param string          $model_name
105
+	 * @return WP_REST_Response|\WP_Error
106
+	 */
107
+	public static function handleRequestDelete(WP_REST_Request $request, $version, $model_name)
108
+	{
109
+		$controller = new Write();
110
+		try {
111
+			$controller->setRequestedVersion($version);
112
+			return $controller->sendResponse(
113
+				$controller->delete(
114
+					$controller->getModelVersionInfo()->loadModel($model_name),
115
+					$request
116
+				)
117
+			);
118
+		} catch (\Exception $e) {
119
+			return $controller->sendResponse($e);
120
+		}
121
+	}
122
+
123
+
124
+
125
+	/**
126
+	 * Inserts a new model object according to the $request
127
+	 *
128
+	 * @param EEM_Base        $model
129
+	 * @param WP_REST_Request $request
130
+	 * @return array
131
+	 * @throws EE_Error
132
+	 * @throws RestException
133
+	 */
134
+	public function insert(EEM_Base $model, WP_REST_Request $request)
135
+	{
136
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
+		if (! current_user_can($default_cap_to_check_for)) {
139
+			throw new RestException(
140
+				'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141
+				sprintf(
142
+					esc_html__(
143
+						// @codingStandardsIgnoreStart
144
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to insert data into Event Espresso.',
145
+						// @codingStandardsIgnoreEnd
146
+						'event_espresso'
147
+					),
148
+					$default_cap_to_check_for
149
+				),
150
+				array('status' => 403)
151
+			);
152
+		}
153
+		$submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
154
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155
+			$submitted_json_data,
156
+			$model,
157
+			$this->getModelVersionInfo()->requestedVersion(),
158
+			true
159
+		);
160
+		$model_obj = EE_Registry::instance()->load_class(
161
+			$model->get_this_model_name(),
162
+			array($model_data, $model->get_timezone()),
163
+			false,
164
+			false
165
+		);
166
+		$model_obj->save();
167
+		$new_id = $model_obj->ID();
168
+		if (! $new_id) {
169
+			throw new RestException(
170
+				'rest_insertion_failed',
171
+				sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
172
+			);
173
+		}
174
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
175
+	}
176
+
177
+
178
+
179
+	/**
180
+	 * Updates an existing model object according to the $request
181
+	 *
182
+	 * @param EEM_Base        $model
183
+	 * @param WP_REST_Request $request
184
+	 * @return array
185
+	 * @throws EE_Error
186
+	 */
187
+	public function update(EEM_Base $model, WP_REST_Request $request)
188
+	{
189
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
+		if (! current_user_can($default_cap_to_check_for)) {
192
+			throw new RestException(
193
+				'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194
+				sprintf(
195
+					esc_html__(
196
+						// @codingStandardsIgnoreStart
197
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to update data into Event Espresso.',
198
+						// @codingStandardsIgnoreEnd
199
+						'event_espresso'
200
+					),
201
+					$default_cap_to_check_for
202
+				),
203
+				array('status' => 403)
204
+			);
205
+		}
206
+		$obj_id = $request->get_param('id');
207
+		if (! $obj_id) {
208
+			throw new RestException(
209
+				'rest_edit_failed',
210
+				sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
211
+			);
212
+		}
213
+		$model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
214
+			$this->getBodyParams($request),
215
+			$model,
216
+			$this->getModelVersionInfo()->requestedVersion(),
217
+			true
218
+		);
219
+		$model_obj = $model->get_one_by_ID($obj_id);
220
+		if (! $model_obj instanceof EE_Base_Class) {
221
+			$lowercase_model_name = strtolower($model->get_this_model_name());
222
+			throw new RestException(
223
+				sprintf('rest_%s_invalid_id', $lowercase_model_name),
224
+				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
225
+				array('status' => 404)
226
+			);
227
+		}
228
+		$model_obj->save($model_data);
229
+		return $this->returnModelObjAsJsonResponse($model_obj, $request);
230
+	}
231
+
232
+
233
+
234
+	/**
235
+	 * Updates an existing model object according to the $request
236
+	 *
237
+	 * @param EEM_Base        $model
238
+	 * @param WP_REST_Request $request
239
+	 * @return array of either the soft-deleted item, or
240
+	 * @throws EE_Error
241
+	 */
242
+	public function delete(EEM_Base $model, WP_REST_Request $request)
243
+	{
244
+		Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
245
+		$default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
246
+		if (! current_user_can($default_cap_to_check_for)) {
247
+			throw new RestException(
248
+				'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
249
+				sprintf(
250
+					esc_html__(
251
+						// @codingStandardsIgnoreStart
252
+						'For now, only those with the admin capability to "%1$s" are allowed to use the REST API to delete data into Event Espresso.',
253
+						// @codingStandardsIgnoreEnd
254
+						'event_espresso'
255
+					),
256
+					$default_cap_to_check_for
257
+				),
258
+				array('status' => 403)
259
+			);
260
+		}
261
+		$obj_id = $request->get_param('id');
262
+		//this is where we would apply more fine-grained caps
263
+		$model_obj = $model->get_one_by_ID($obj_id);
264
+		if (! $model_obj instanceof EE_Base_Class) {
265
+			$lowercase_model_name = strtolower($model->get_this_model_name());
266
+			throw new RestException(
267
+				sprintf('rest_%s_invalid_id', $lowercase_model_name),
268
+				sprintf(__('Invalid %s ID.', 'event_espresso'), $lowercase_model_name),
269
+				array('status' => 404)
270
+			);
271
+		}
272
+		$requested_permanent_delete = filter_var($request->get_param('force'), FILTER_VALIDATE_BOOLEAN);
273
+		$requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
274
+		if ($requested_permanent_delete) {
275
+			$previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
276
+			$deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
277
+			return array(
278
+				'deleted'  => $deleted,
279
+				'previous' => $previous,
280
+			);
281
+		} else {
282
+			if ($model instanceof EEM_Soft_Delete_Base) {
283
+				$model->delete_by_ID($obj_id, $requested_allow_blocking);
284
+				return $this->returnModelObjAsJsonResponse($model_obj, $request);
285
+			} else {
286
+				throw new RestException(
287
+					'rest_trash_not_supported',
288
+					501,
289
+					sprintf(
290
+						esc_html__('%1$s do not support trashing. Set force=1 to delete.', 'event_espresso'),
291
+						EEH_Inflector::pluralize($model->get_this_model_name())
292
+					)
293
+				);
294
+			}
295
+		}
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * Returns an array ready to be converted into a JSON response, based solely on the model object
302
+	 *
303
+	 * @param EE_Base_Class $model_obj
304
+	 * @param WP_REST_Request $request
305
+	 * @return array ready for a response
306
+	 */
307
+	protected function returnModelObjAsJsonResponse(EE_Base_Class $model_obj, WP_REST_Request $request)
308
+	{
309
+		$model = $model_obj->get_model();
310
+		//create an array exactly like the wpdb results row,
311
+		// so we can pass it to controllers/model/Read::create_entity_from_wpdb_result()
312
+		$simulated_db_row = array();
313
+		foreach ($model->field_settings(true) as $field_name => $field_obj) {
314
+			//we need to reconstruct the normal wpdb results, including the db-only fields
315
+			//like a secondary table's primary key. The models expect those (but don't care what value they have)
316
+			if( $field_obj instanceof EE_DB_Only_Field_Base){
317
+				$raw_value = true;
318
+			} elseif ($field_obj instanceof EE_Datetime_Field) {
319
+				$raw_value = $model_obj->get_DateTime_object($field_name);
320
+			} else {
321
+				$raw_value = $model_obj->get_raw($field_name);
322
+			}
323
+			$simulated_db_row[$field_obj->get_qualified_column()] = $field_obj->prepare_for_use_in_db($raw_value);
324
+		}
325
+		$read_controller = new Read();
326
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
327
+		//the simulates request really doesn't need any info downstream
328
+		$simulated_request = new WP_REST_Request('GET');
329
+		return $read_controller->createEntityFromWpdbResult(
330
+			$model_obj->get_model(),
331
+			$simulated_db_row,
332
+			$simulated_request
333
+		);
334
+	}
335
+
336
+
337
+
338
+	/**
339
+	 * Gets the item affected by this request
340
+	 *
341
+	 * @param EEM_Base        $model
342
+	 * @param WP_REST_Request $request
343
+	 * @param  int|string     $obj_id
344
+	 * @return \WP_Error|array
345
+	 */
346
+	protected function getOneBasedOnRequest(EEM_Base $model, WP_REST_Request $request, $obj_id)
347
+	{
348
+		$requested_version = $this->getRequestedVersion($request->get_route());
349
+		$get_request = new WP_REST_Request(
350
+			'GET',
351
+			EED_Core_Rest_Api::ee_api_namespace
352
+			. $requested_version
353
+			. '/'
354
+			. EEH_Inflector::pluralize_and_lower($model->get_this_model_name())
355
+			. '/'
356
+			. $obj_id
357
+		);
358
+		$get_request->set_url_params(
359
+			array(
360
+				'id'      => $obj_id,
361
+				'include' => $request->get_param('include'),
362
+			)
363
+		);
364
+		$read_controller = new Read();
365
+		$read_controller->setRequestedVersion($this->getRequestedVersion());
366
+		return $read_controller->getEntityFromModel($model, $get_request);
367
+	}
368 368
 }
369 369
 // End of file Read.php
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -17,7 +17,7 @@  discard block
 block discarded – undo
17 17
 use EEH_Inflector;
18 18
 use EE_Error;
19 19
 
20
-if (! defined('EVENT_ESPRESSO_VERSION')) {
20
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
21 21
     exit('No direct script access allowed');
22 22
 }
23 23
 
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
     {
136 136
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'create');
137 137
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
138
-        if (! current_user_can($default_cap_to_check_for)) {
138
+        if ( ! current_user_can($default_cap_to_check_for)) {
139 139
             throw new RestException(
140
-                'rest_cannot_create_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
140
+                'rest_cannot_create_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
141 141
                 sprintf(
142 142
                     esc_html__(
143 143
                         // @codingStandardsIgnoreStart
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
                 array('status' => 403)
151 151
             );
152 152
         }
153
-        $submitted_json_data = array_merge((array)$request->get_body_params(), (array)$request->get_json_params());
153
+        $submitted_json_data = array_merge((array) $request->get_body_params(), (array) $request->get_json_params());
154 154
         $model_data = ModelDataTranslator::prepareConditionsQueryParamsForModels(
155 155
             $submitted_json_data,
156 156
             $model,
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
         );
166 166
         $model_obj->save();
167 167
         $new_id = $model_obj->ID();
168
-        if (! $new_id) {
168
+        if ( ! $new_id) {
169 169
             throw new RestException(
170 170
                 'rest_insertion_failed',
171 171
                 sprintf(__('Could not insert new %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -188,9 +188,9 @@  discard block
 block discarded – undo
188 188
     {
189 189
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_edit, 'edit');
190 190
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
191
-        if (! current_user_can($default_cap_to_check_for)) {
191
+        if ( ! current_user_can($default_cap_to_check_for)) {
192 192
             throw new RestException(
193
-                'rest_cannot_edit_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
193
+                'rest_cannot_edit_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
194 194
                 sprintf(
195 195
                     esc_html__(
196 196
                         // @codingStandardsIgnoreStart
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
             );
205 205
         }
206 206
         $obj_id = $request->get_param('id');
207
-        if (! $obj_id) {
207
+        if ( ! $obj_id) {
208 208
             throw new RestException(
209 209
                 'rest_edit_failed',
210 210
                 sprintf(__('Could not edit %1$s', 'event_espresso'), $model->get_this_model_name())
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
             true
218 218
         );
219 219
         $model_obj = $model->get_one_by_ID($obj_id);
220
-        if (! $model_obj instanceof EE_Base_Class) {
220
+        if ( ! $model_obj instanceof EE_Base_Class) {
221 221
             $lowercase_model_name = strtolower($model->get_this_model_name());
222 222
             throw new RestException(
223 223
                 sprintf('rest_%s_invalid_id', $lowercase_model_name),
@@ -243,9 +243,9 @@  discard block
 block discarded – undo
243 243
     {
244 244
         Capabilities::verifyAtLeastPartialAccessTo($model, EEM_Base::caps_delete, 'delete');
245 245
         $default_cap_to_check_for = EE_Restriction_Generator_Base::get_default_restrictions_cap();
246
-        if (! current_user_can($default_cap_to_check_for)) {
246
+        if ( ! current_user_can($default_cap_to_check_for)) {
247 247
             throw new RestException(
248
-                'rest_cannot_delete_' . EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
248
+                'rest_cannot_delete_'.EEH_Inflector::pluralize_and_lower(($model->get_this_model_name())),
249 249
                 sprintf(
250 250
                     esc_html__(
251 251
                         // @codingStandardsIgnoreStart
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
         $obj_id = $request->get_param('id');
262 262
         //this is where we would apply more fine-grained caps
263 263
         $model_obj = $model->get_one_by_ID($obj_id);
264
-        if (! $model_obj instanceof EE_Base_Class) {
264
+        if ( ! $model_obj instanceof EE_Base_Class) {
265 265
             $lowercase_model_name = strtolower($model->get_this_model_name());
266 266
             throw new RestException(
267 267
                 sprintf('rest_%s_invalid_id', $lowercase_model_name),
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
         $requested_allow_blocking = filter_var($request->get_param('allow_blocking'), FILTER_VALIDATE_BOOLEAN);
274 274
         if ($requested_permanent_delete) {
275 275
             $previous = $this->returnModelObjAsJsonResponse($model_obj, $request);
276
-            $deleted = (bool)$model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
276
+            $deleted = (bool) $model->delete_permanently_by_ID($obj_id, $requested_allow_blocking);
277 277
             return array(
278 278
                 'deleted'  => $deleted,
279 279
                 'previous' => $previous,
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
         foreach ($model->field_settings(true) as $field_name => $field_obj) {
314 314
             //we need to reconstruct the normal wpdb results, including the db-only fields
315 315
             //like a secondary table's primary key. The models expect those (but don't care what value they have)
316
-            if( $field_obj instanceof EE_DB_Only_Field_Base){
316
+            if ($field_obj instanceof EE_DB_Only_Field_Base) {
317 317
                 $raw_value = true;
318 318
             } elseif ($field_obj instanceof EE_Datetime_Field) {
319 319
                 $raw_value = $model_obj->get_DateTime_object($field_name);
Please login to merge, or discard this patch.
core/db_models/EEM_Change_Log.model.php 2 patches
Indentation   +227 added lines, -227 removed lines patch added patch discarded remove patch
@@ -13,93 +13,93 @@  discard block
 block discarded – undo
13 13
 class EEM_Change_Log extends EEM_Base
14 14
 {
15 15
 
16
-    /**
17
-     * the related object was created log type
18
-     */
19
-    const type_create = 'create';
20
-    /**
21
-     * the related object was updated (changed, or soft-deleted)
22
-     */
23
-    const type_update = 'update';
24
-    /**
25
-     * the related object was deleted permanently
26
-     */
27
-    const type_delete = 'delete';
28
-    /**
29
-     * the related item had something worth noting happen on it, but
30
-     * only for the purposes of debugging problems
31
-     */
32
-    const type_debug = 'debug';
33
-    /**
34
-     * the related item had an error occur on it
35
-     */
36
-    const type_error = 'error';
37
-    /**
38
-     * the related item is regarding some gateway interaction, like an IPN
39
-     * or request to process a payment
40
-     */
41
-    const type_gateway = 'gateway';
16
+	/**
17
+	 * the related object was created log type
18
+	 */
19
+	const type_create = 'create';
20
+	/**
21
+	 * the related object was updated (changed, or soft-deleted)
22
+	 */
23
+	const type_update = 'update';
24
+	/**
25
+	 * the related object was deleted permanently
26
+	 */
27
+	const type_delete = 'delete';
28
+	/**
29
+	 * the related item had something worth noting happen on it, but
30
+	 * only for the purposes of debugging problems
31
+	 */
32
+	const type_debug = 'debug';
33
+	/**
34
+	 * the related item had an error occur on it
35
+	 */
36
+	const type_error = 'error';
37
+	/**
38
+	 * the related item is regarding some gateway interaction, like an IPN
39
+	 * or request to process a payment
40
+	 */
41
+	const type_gateway = 'gateway';
42 42
 
43
-    /**
44
-     * private instance of the EEM_Change_Log object
45
-     *
46
-     * @access private
47
-     * @var EEM_Change_Log $_instance
48
-     */
49
-    protected static $_instance = null;
43
+	/**
44
+	 * private instance of the EEM_Change_Log object
45
+	 *
46
+	 * @access private
47
+	 * @var EEM_Change_Log $_instance
48
+	 */
49
+	protected static $_instance = null;
50 50
 
51 51
 
52
-    /**
53
-     * constructor
54
-     *
55
-     * @access protected
56
-     * @param null $timezone
57
-     * @throws EE_Error
58
-     */
59
-    protected function __construct($timezone = null)
60
-    {
61
-        global $current_user;
62
-        $this->singular_item       = esc_html__('Log', 'event_espresso');
63
-        $this->plural_item         = esc_html__('Logs', 'event_espresso');
64
-        $this->_tables             = array(
65
-            'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
-        );
67
-        $models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
-        $this->_fields             = array(
69
-            'Log' => array(
70
-                'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
-                'LOG_time'    => new EE_Datetime_Field(
72
-                    'LOG_time',
73
-                    esc_html__("Log Time", 'event_espresso'),
74
-                    false,
75
-                    EE_Datetime_Field::now
76
-                ),
77
-                'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
-                    'OBJ_ID',
79
-                    esc_html__("Object ID (int or string)", 'event_espresso'),
80
-                    true,
81
-                    null,
82
-                    $models_this_can_attach_to
83
-                ),
84
-                'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
-                    'OBJ_type',
86
-                    esc_html__("Object Type", 'event_espresso'),
87
-                    true,
88
-                    null,
89
-                    $models_this_can_attach_to
90
-                ),
91
-                'LOG_type'    => new EE_Plain_Text_Field(
92
-                    'LOG_type',
93
-                    esc_html__("Type of log entry", "event_espresso"),
94
-                    false,
95
-                    self::type_debug
96
-                ),
97
-                'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
-                    'LOG_message',
99
-                    esc_html__("Log Message (body)", 'event_espresso'),
100
-                    true
101
-                ),
102
-                /*
52
+	/**
53
+	 * constructor
54
+	 *
55
+	 * @access protected
56
+	 * @param null $timezone
57
+	 * @throws EE_Error
58
+	 */
59
+	protected function __construct($timezone = null)
60
+	{
61
+		global $current_user;
62
+		$this->singular_item       = esc_html__('Log', 'event_espresso');
63
+		$this->plural_item         = esc_html__('Logs', 'event_espresso');
64
+		$this->_tables             = array(
65
+			'Log' => new EE_Primary_Table('esp_log', 'LOG_ID'),
66
+		);
67
+		$models_this_can_attach_to = array_keys(EE_Registry::instance()->non_abstract_db_models);
68
+		$this->_fields             = array(
69
+			'Log' => array(
70
+				'LOG_ID'      => new EE_Primary_Key_Int_Field('LOG_ID', esc_html__('Log ID', 'event_espresso')),
71
+				'LOG_time'    => new EE_Datetime_Field(
72
+					'LOG_time',
73
+					esc_html__("Log Time", 'event_espresso'),
74
+					false,
75
+					EE_Datetime_Field::now
76
+				),
77
+				'OBJ_ID'      => new EE_Foreign_Key_String_Field(
78
+					'OBJ_ID',
79
+					esc_html__("Object ID (int or string)", 'event_espresso'),
80
+					true,
81
+					null,
82
+					$models_this_can_attach_to
83
+				),
84
+				'OBJ_type'    => new EE_Any_Foreign_Model_Name_Field(
85
+					'OBJ_type',
86
+					esc_html__("Object Type", 'event_espresso'),
87
+					true,
88
+					null,
89
+					$models_this_can_attach_to
90
+				),
91
+				'LOG_type'    => new EE_Plain_Text_Field(
92
+					'LOG_type',
93
+					esc_html__("Type of log entry", "event_espresso"),
94
+					false,
95
+					self::type_debug
96
+				),
97
+				'LOG_message' => new EE_Maybe_Serialized_Text_Field(
98
+					'LOG_message',
99
+					esc_html__("Log Message (body)", 'event_espresso'),
100
+					true
101
+				),
102
+				/*
103 103
                  * Note: when querying for a change log's user, the OBJ_ID and OBJ_type fields are used,
104 104
                  * not the LOG_wp_user field. E.g.,
105 105
                  * `EEM_Change_Log::instance()->get_all(array(array('WP_User.ID'=>1)))` will actually return
@@ -108,158 +108,158 @@  discard block
 block discarded – undo
108 108
                  *  If you want the latter, you can't use the model's magic joining. E.g, you would need to do
109 109
                  * `EEM_Change_Log::instance()->get_all(array(array('LOG_wp_user' => 1)))`.
110 110
                  */
111
-                'LOG_wp_user' => new EE_WP_User_Field(
112
-                    'LOG_wp_user',
113
-                    esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
-                    true
115
-                ),
116
-            ),
117
-        );
118
-        $this->_model_relations    = array();
119
-        foreach ($models_this_can_attach_to as $model) {
120
-            if ($model != 'Change_Log') {
121
-                $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
122
-            }
123
-        }
124
-        //use completely custom caps for this
125
-        $this->_cap_restriction_generators = false;
126
-        //caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
-        foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
-            $this->_cap_restrictions[$cap_context][EE_Restriction_Generator_Base::get_default_restrictions_cap()]
129
-                = new EE_Return_None_Where_Conditions();
130
-        }
131
-        parent::__construct($timezone);
132
-    }
111
+				'LOG_wp_user' => new EE_WP_User_Field(
112
+					'LOG_wp_user',
113
+					esc_html__("User who was logged in while this occurred", 'event_espresso'),
114
+					true
115
+				),
116
+			),
117
+		);
118
+		$this->_model_relations    = array();
119
+		foreach ($models_this_can_attach_to as $model) {
120
+			if ($model != 'Change_Log') {
121
+				$this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
122
+			}
123
+		}
124
+		//use completely custom caps for this
125
+		$this->_cap_restriction_generators = false;
126
+		//caps-wise this is all-or-nothing: if you have the default role you can access anything, otherwise nothing
127
+		foreach ($this->_cap_contexts_to_cap_action_map as $cap_context => $action) {
128
+			$this->_cap_restrictions[$cap_context][EE_Restriction_Generator_Base::get_default_restrictions_cap()]
129
+				= new EE_Return_None_Where_Conditions();
130
+		}
131
+		parent::__construct($timezone);
132
+	}
133 133
 
134
-    /**
135
-     * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
136
-     * @param mixed         $message  array|string of the message you want to record
137
-     * @param EE_Base_Class $related_model_obj
138
-     * @return EE_Change_Log
139
-     * @throws EE_Error
140
-     */
141
-    public function log($log_type, $message, $related_model_obj)
142
-    {
143
-        if ($related_model_obj instanceof EE_Base_Class) {
144
-            $obj_id   = $related_model_obj->ID();
145
-            $obj_type = $related_model_obj->get_model()->get_this_model_name();
146
-        } else {
147
-            $obj_id   = null;
148
-            $obj_type = null;
149
-        }
150
-        /** @var EE_Change_Log $log */
151
-        $log = EE_Change_Log::new_instance(array(
152
-            'LOG_type'    => $log_type,
153
-            'LOG_message' => $message,
154
-            'OBJ_ID'      => $obj_id,
155
-            'OBJ_type'    => $obj_type,
156
-        ));
157
-        $log->save();
158
-        return $log;
159
-    }
134
+	/**
135
+	 * @param string        $log_type !see the acceptable values of LOG_type in EEM__Change_Log::__construct
136
+	 * @param mixed         $message  array|string of the message you want to record
137
+	 * @param EE_Base_Class $related_model_obj
138
+	 * @return EE_Change_Log
139
+	 * @throws EE_Error
140
+	 */
141
+	public function log($log_type, $message, $related_model_obj)
142
+	{
143
+		if ($related_model_obj instanceof EE_Base_Class) {
144
+			$obj_id   = $related_model_obj->ID();
145
+			$obj_type = $related_model_obj->get_model()->get_this_model_name();
146
+		} else {
147
+			$obj_id   = null;
148
+			$obj_type = null;
149
+		}
150
+		/** @var EE_Change_Log $log */
151
+		$log = EE_Change_Log::new_instance(array(
152
+			'LOG_type'    => $log_type,
153
+			'LOG_message' => $message,
154
+			'OBJ_ID'      => $obj_id,
155
+			'OBJ_type'    => $obj_type,
156
+		));
157
+		$log->save();
158
+		return $log;
159
+	}
160 160
 
161 161
 
162
-    /**
163
-     * Adds a gateway log for the specified object, given its ID and type
164
-     *
165
-     * @param string $message
166
-     * @param mixed  $related_obj_id
167
-     * @param string $related_obj_type
168
-     * @throws EE_Error
169
-     * @return EE_Change_Log
170
-     */
171
-    public function gateway_log($message, $related_obj_id, $related_obj_type)
172
-    {
173
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
174
-            throw new EE_Error(
175
-                sprintf(
176
-                    esc_html__(
177
-                        "'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
178
-                        "event_espresso"
179
-                    ),
180
-                    $related_obj_type
181
-                )
182
-            );
183
-        }
184
-        /** @var EE_Change_Log $log */
185
-        $log = EE_Change_Log::new_instance(array(
186
-            'LOG_type'    => EEM_Change_Log::type_gateway,
187
-            'LOG_message' => $message,
188
-            'OBJ_ID'      => $related_obj_id,
189
-            'OBJ_type'    => $related_obj_type,
190
-        ));
191
-        $log->save();
192
-        return $log;
193
-    }
162
+	/**
163
+	 * Adds a gateway log for the specified object, given its ID and type
164
+	 *
165
+	 * @param string $message
166
+	 * @param mixed  $related_obj_id
167
+	 * @param string $related_obj_type
168
+	 * @throws EE_Error
169
+	 * @return EE_Change_Log
170
+	 */
171
+	public function gateway_log($message, $related_obj_id, $related_obj_type)
172
+	{
173
+		if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
174
+			throw new EE_Error(
175
+				sprintf(
176
+					esc_html__(
177
+						"'%s' is not a model name. A model name must be provided when making a gateway log. Eg, 'Payment', 'Payment_Method', etc",
178
+						"event_espresso"
179
+					),
180
+					$related_obj_type
181
+				)
182
+			);
183
+		}
184
+		/** @var EE_Change_Log $log */
185
+		$log = EE_Change_Log::new_instance(array(
186
+			'LOG_type'    => EEM_Change_Log::type_gateway,
187
+			'LOG_message' => $message,
188
+			'OBJ_ID'      => $related_obj_id,
189
+			'OBJ_type'    => $related_obj_type,
190
+		));
191
+		$log->save();
192
+		return $log;
193
+	}
194 194
 
195 195
 
196
-    /**
197
-     * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
198
-     *
199
-     * @param array $query_params @see EEM_Base::get_all
200
-     * @return array of arrays
201
-     * @throws EE_Error
202
-     */
203
-    public function get_all_efficiently($query_params)
204
-    {
205
-        return $this->_get_all_wpdb_results($query_params);
206
-    }
196
+	/**
197
+	 * Just gets the bare-bones wpdb results as an array in cases where efficiency is essential
198
+	 *
199
+	 * @param array $query_params @see EEM_Base::get_all
200
+	 * @return array of arrays
201
+	 * @throws EE_Error
202
+	 */
203
+	public function get_all_efficiently($query_params)
204
+	{
205
+		return $this->_get_all_wpdb_results($query_params);
206
+	}
207 207
 
208 208
 
209
-    /**
210
-     * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
211
-     * models after this, they may be out-of-sync with the database
212
-     *
213
-     * @param DateTime $datetime
214
-     * @return false|int
215
-     * @throws EE_Error
216
-     */
217
-    public function delete_gateway_logs_older_than(DateTime $datetime)
218
-    {
219
-        global $wpdb;
220
-        return $wpdb->query(
221
-            $wpdb->prepare(
222
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
223
-                EEM_Change_Log::type_gateway,
224
-                $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
225
-            )
226
-        );
227
-    }
209
+	/**
210
+	 * Executes a database query to delete gateway logs. Does not affect model objects, so if you attempt to use
211
+	 * models after this, they may be out-of-sync with the database
212
+	 *
213
+	 * @param DateTime $datetime
214
+	 * @return false|int
215
+	 * @throws EE_Error
216
+	 */
217
+	public function delete_gateway_logs_older_than(DateTime $datetime)
218
+	{
219
+		global $wpdb;
220
+		return $wpdb->query(
221
+			$wpdb->prepare(
222
+				'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
223
+				EEM_Change_Log::type_gateway,
224
+				$datetime->format(EE_Datetime_Field::mysql_timestamp_format)
225
+			)
226
+		);
227
+	}
228 228
 
229 229
 
230
-    /**
231
-     * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
232
-     * map vai the given filter.
233
-     *
234
-     * @return array
235
-     */
236
-    public static function get_pretty_label_map_for_registered_types()
237
-    {
238
-        return apply_filters(
239
-            'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
240
-            array(
241
-                self::type_create=>  esc_html__("Create", "event_espresso"),
242
-                self::type_update=>  esc_html__("Update", "event_espresso"),
243
-                self::type_delete => esc_html__("Delete", "event_espresso"),
244
-                self::type_debug=>  esc_html__("Debug", "event_espresso"),
245
-                self::type_error=>  esc_html__("Error", "event_espresso"),
246
-                self::type_gateway=> esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
247
-            )
248
-        );
249
-    }
230
+	/**
231
+	 * Returns the map of type to pretty label for identifiers used for `LOG_type`.  Client code can register their own
232
+	 * map vai the given filter.
233
+	 *
234
+	 * @return array
235
+	 */
236
+	public static function get_pretty_label_map_for_registered_types()
237
+	{
238
+		return apply_filters(
239
+			'FHEE__EEM_Change_Log__get_pretty_label_map_for_registered_types',
240
+			array(
241
+				self::type_create=>  esc_html__("Create", "event_espresso"),
242
+				self::type_update=>  esc_html__("Update", "event_espresso"),
243
+				self::type_delete => esc_html__("Delete", "event_espresso"),
244
+				self::type_debug=>  esc_html__("Debug", "event_espresso"),
245
+				self::type_error=>  esc_html__("Error", "event_espresso"),
246
+				self::type_gateway=> esc_html__("Gateway Interaction (IPN or Direct Payment)", 'event_espresso')
247
+			)
248
+		);
249
+	}
250 250
 
251 251
 
252
-    /**
253
-     * Return the pretty (localized) label for the given log type identifier.
254
-     * @param string $type_identifier
255
-     * @return string
256
-     */
257
-    public static function get_pretty_label_for_type($type_identifier)
258
-    {
259
-        $type_identifier_map = self::get_pretty_label_map_for_registered_types();
260
-        //we fallback to the incoming type identifier if there is no localized label for it.
261
-        return isset($type_identifier_map[$type_identifier])
262
-            ? $type_identifier_map[$type_identifier]
263
-            : $type_identifier;
264
-    }
252
+	/**
253
+	 * Return the pretty (localized) label for the given log type identifier.
254
+	 * @param string $type_identifier
255
+	 * @return string
256
+	 */
257
+	public static function get_pretty_label_for_type($type_identifier)
258
+	{
259
+		$type_identifier_map = self::get_pretty_label_map_for_registered_types();
260
+		//we fallback to the incoming type identifier if there is no localized label for it.
261
+		return isset($type_identifier_map[$type_identifier])
262
+			? $type_identifier_map[$type_identifier]
263
+			: $type_identifier;
264
+	}
265 265
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
                 ),
116 116
             ),
117 117
         );
118
-        $this->_model_relations    = array();
118
+        $this->_model_relations = array();
119 119
         foreach ($models_this_can_attach_to as $model) {
120 120
             if ($model != 'Change_Log') {
121 121
                 $this->_model_relations[$model] = new EE_Belongs_To_Any_Relation();
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
      */
171 171
     public function gateway_log($message, $related_obj_id, $related_obj_type)
172 172
     {
173
-        if (! EE_Registry::instance()->is_model_name($related_obj_type)) {
173
+        if ( ! EE_Registry::instance()->is_model_name($related_obj_type)) {
174 174
             throw new EE_Error(
175 175
                 sprintf(
176 176
                     esc_html__(
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
         global $wpdb;
220 220
         return $wpdb->query(
221 221
             $wpdb->prepare(
222
-                'DELETE FROM ' . $this->table() . ' WHERE LOG_type = %s AND LOG_time < %s',
222
+                'DELETE FROM '.$this->table().' WHERE LOG_type = %s AND LOG_time < %s',
223 223
                 EEM_Change_Log::type_gateway,
224 224
                 $datetime->format(EE_Datetime_Field::mysql_timestamp_format)
225 225
             )
Please login to merge, or discard this patch.
core/EE_Registry.core.php 2 patches
Indentation   +1513 added lines, -1513 removed lines patch added patch discarded remove patch
@@ -22,1519 +22,1519 @@
 block discarded – undo
22 22
 class EE_Registry implements ResettableInterface
23 23
 {
24 24
 
25
-    /**
26
-     * @var EE_Registry $_instance
27
-     */
28
-    private static $_instance;
29
-
30
-    /**
31
-     * @var EE_Dependency_Map $_dependency_map
32
-     */
33
-    protected $_dependency_map;
34
-
35
-    /**
36
-     * @var array $_class_abbreviations
37
-     */
38
-    protected $_class_abbreviations = array();
39
-
40
-    /**
41
-     * @var CommandBusInterface $BUS
42
-     */
43
-    public $BUS;
44
-
45
-    /**
46
-     * @var EE_Cart $CART
47
-     */
48
-    public $CART;
49
-
50
-    /**
51
-     * @var EE_Config $CFG
52
-     */
53
-    public $CFG;
54
-
55
-    /**
56
-     * @var EE_Network_Config $NET_CFG
57
-     */
58
-    public $NET_CFG;
59
-
60
-    /**
61
-     * StdClass object for storing library classes in
62
-     *
63
-     * @var StdClass $LIB
64
-     */
65
-    public $LIB;
66
-
67
-    /**
68
-     * @var EE_Request_Handler $REQ
69
-     */
70
-    public $REQ;
71
-
72
-    /**
73
-     * @var EE_Session $SSN
74
-     */
75
-    public $SSN;
76
-
77
-    /**
78
-     * @since 4.5.0
79
-     * @var EE_Capabilities $CAP
80
-     */
81
-    public $CAP;
82
-
83
-    /**
84
-     * @since 4.9.0
85
-     * @var EE_Message_Resource_Manager $MRM
86
-     */
87
-    public $MRM;
88
-
89
-
90
-    /**
91
-     * @var Registry $AssetsRegistry
92
-     */
93
-    public $AssetsRegistry;
94
-
95
-    /**
96
-     * StdClass object for holding addons which have registered themselves to work with EE core
97
-     *
98
-     * @var EE_Addon[] $addons
99
-     */
100
-    public $addons;
101
-
102
-    /**
103
-     * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
-     *
105
-     * @var EEM_Base[] $models
106
-     */
107
-    public $models = array();
108
-
109
-    /**
110
-     * @var EED_Module[] $modules
111
-     */
112
-    public $modules;
113
-
114
-    /**
115
-     * @var EES_Shortcode[] $shortcodes
116
-     */
117
-    public $shortcodes;
118
-
119
-    /**
120
-     * @var WP_Widget[] $widgets
121
-     */
122
-    public $widgets;
123
-
124
-    /**
125
-     * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
-     * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
-     * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
-     * classnames (eg "EEM_Event")
129
-     *
130
-     * @var array $non_abstract_db_models
131
-     */
132
-    public $non_abstract_db_models = array();
133
-
134
-
135
-    /**
136
-     * internationalization for JS strings
137
-     *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
-     *    in js file:  var translatedString = eei18n.string_key;
139
-     *
140
-     * @var array $i18n_js_strings
141
-     */
142
-    public static $i18n_js_strings = array();
143
-
144
-
145
-    /**
146
-     * $main_file - path to espresso.php
147
-     *
148
-     * @var array $main_file
149
-     */
150
-    public $main_file;
151
-
152
-    /**
153
-     * array of ReflectionClass objects where the key is the class name
154
-     *
155
-     * @var ReflectionClass[] $_reflectors
156
-     */
157
-    public $_reflectors;
158
-
159
-    /**
160
-     * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
-     *
162
-     * @var boolean $_cache_on
163
-     */
164
-    protected $_cache_on = true;
165
-
166
-
167
-
168
-    /**
169
-     * @singleton method used to instantiate class object
170
-     * @param  EE_Dependency_Map $dependency_map
171
-     * @return EE_Registry instance
172
-     * @throws InvalidArgumentException
173
-     * @throws InvalidInterfaceException
174
-     * @throws InvalidDataTypeException
175
-     */
176
-    public static function instance(EE_Dependency_Map $dependency_map = null)
177
-    {
178
-        // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
180
-            self::$_instance = new self($dependency_map);
181
-        }
182
-        return self::$_instance;
183
-    }
184
-
185
-
186
-
187
-    /**
188
-     * protected constructor to prevent direct creation
189
-     *
190
-     * @Constructor
191
-     * @param  EE_Dependency_Map $dependency_map
192
-     * @throws InvalidDataTypeException
193
-     * @throws InvalidInterfaceException
194
-     * @throws InvalidArgumentException
195
-     */
196
-    protected function __construct(EE_Dependency_Map $dependency_map)
197
-    {
198
-        $this->_dependency_map = $dependency_map;
199
-        $this->LIB = new stdClass();
200
-        $this->addons = new stdClass();
201
-        $this->modules = new stdClass();
202
-        $this->shortcodes = new stdClass();
203
-        $this->widgets = new stdClass();
204
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
-    }
206
-
207
-
208
-
209
-    /**
210
-     * initialize
211
-     *
212
-     * @throws EE_Error
213
-     * @throws ReflectionException
214
-     */
215
-    public function initialize()
216
-    {
217
-        $this->_class_abbreviations = apply_filters(
218
-            'FHEE__EE_Registry____construct___class_abbreviations',
219
-            array(
220
-                'EE_Config'                                       => 'CFG',
221
-                'EE_Session'                                      => 'SSN',
222
-                'EE_Capabilities'                                 => 'CAP',
223
-                'EE_Cart'                                         => 'CART',
224
-                'EE_Network_Config'                               => 'NET_CFG',
225
-                'EE_Request_Handler'                              => 'REQ',
226
-                'EE_Message_Resource_Manager'                     => 'MRM',
227
-                'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
-                'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
-            )
230
-        );
231
-        $this->load_core('Base', array(), true);
232
-        // add our request and response objects to the cache
233
-        $request_loader = $this->_dependency_map->class_loader('EE_Request');
234
-        $this->_set_cached_class(
235
-            $request_loader(),
236
-            'EE_Request'
237
-        );
238
-        $response_loader = $this->_dependency_map->class_loader('EE_Response');
239
-        $this->_set_cached_class(
240
-            $response_loader(),
241
-            'EE_Response'
242
-        );
243
-        add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
-    }
245
-
246
-
247
-
248
-    /**
249
-     * @return void
250
-     */
251
-    public function init()
252
-    {
253
-        // Get current page protocol
254
-        $protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
-        // Output admin-ajax.php URL with same protocol as current page
256
-        self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
-        self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
-    }
259
-
260
-
261
-
262
-    /**
263
-     * localize_i18n_js_strings
264
-     *
265
-     * @return string
266
-     */
267
-    public static function localize_i18n_js_strings()
268
-    {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
270
-        foreach ($i18n_js_strings as $key => $value) {
271
-            if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
-            }
274
-        }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
-    }
277
-
278
-
279
-
280
-    /**
281
-     * @param mixed string | EED_Module $module
282
-     * @throws EE_Error
283
-     * @throws ReflectionException
284
-     */
285
-    public function add_module($module)
286
-    {
287
-        if ($module instanceof EED_Module) {
288
-            $module_class = get_class($module);
289
-            $this->modules->{$module_class} = $module;
290
-        } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
292
-                $this->load_core('Module_Request_Router');
293
-            }
294
-            EE_Module_Request_Router::module_factory($module);
295
-        }
296
-    }
297
-
298
-
299
-
300
-    /**
301
-     * @param string $module_name
302
-     * @return mixed EED_Module | NULL
303
-     */
304
-    public function get_module($module_name = '')
305
-    {
306
-        return isset($this->modules->{$module_name})
307
-            ? $this->modules->{$module_name}
308
-            : null;
309
-    }
310
-
311
-
312
-
313
-    /**
314
-     * loads core classes - must be singletons
315
-     *
316
-     * @param string $class_name - simple class name ie: session
317
-     * @param mixed  $arguments
318
-     * @param bool   $load_only
319
-     * @return mixed
320
-     * @throws EE_Error
321
-     * @throws ReflectionException
322
-     */
323
-    public function load_core($class_name, $arguments = array(), $load_only = false)
324
-    {
325
-        $core_paths = apply_filters(
326
-            'FHEE__EE_Registry__load_core__core_paths',
327
-            array(
328
-                EE_CORE,
329
-                EE_ADMIN,
330
-                EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
335
-            )
336
-        );
337
-        // retrieve instantiated class
338
-        return $this->_load(
339
-            $core_paths,
340
-            'EE_',
341
-            $class_name,
342
-            'core',
343
-            $arguments,
344
-            false,
345
-            true,
346
-            $load_only
347
-        );
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * loads service classes
354
-     *
355
-     * @param string $class_name - simple class name ie: session
356
-     * @param mixed  $arguments
357
-     * @param bool   $load_only
358
-     * @return mixed
359
-     * @throws EE_Error
360
-     * @throws ReflectionException
361
-     */
362
-    public function load_service($class_name, $arguments = array(), $load_only = false)
363
-    {
364
-        $service_paths = apply_filters(
365
-            'FHEE__EE_Registry__load_service__service_paths',
366
-            array(
367
-                EE_CORE . 'services' . DS,
368
-            )
369
-        );
370
-        // retrieve instantiated class
371
-        return $this->_load(
372
-            $service_paths,
373
-            'EE_',
374
-            $class_name,
375
-            'class',
376
-            $arguments,
377
-            false,
378
-            true,
379
-            $load_only
380
-        );
381
-    }
382
-
383
-
384
-
385
-    /**
386
-     * loads data_migration_scripts
387
-     *
388
-     * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
389
-     * @param mixed  $arguments
390
-     * @return EE_Data_Migration_Script_Base|mixed
391
-     * @throws EE_Error
392
-     * @throws ReflectionException
393
-     */
394
-    public function load_dms($class_name, $arguments = array())
395
-    {
396
-        // retrieve instantiated class
397
-        return $this->_load(
398
-            EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
399
-            'EE_DMS_',
400
-            $class_name,
401
-            'dms',
402
-            $arguments,
403
-            false,
404
-            false
405
-        );
406
-    }
407
-
408
-
409
-
410
-    /**
411
-     * loads object creating classes - must be singletons
412
-     *
413
-     * @param string $class_name - simple class name ie: attendee
414
-     * @param mixed  $arguments  - an array of arguments to pass to the class
415
-     * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
416
-     *                           instantiate
417
-     * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
418
-     *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
419
-     * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
420
-     *                           (default)
421
-     * @return EE_Base_Class | bool
422
-     * @throws EE_Error
423
-     * @throws ReflectionException
424
-     */
425
-    public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
426
-    {
427
-        $paths = apply_filters(
428
-            'FHEE__EE_Registry__load_class__paths', array(
429
-            EE_CORE,
430
-            EE_CLASSES,
431
-            EE_BUSINESS,
432
-        )
433
-        );
434
-        // retrieve instantiated class
435
-        return $this->_load(
436
-            $paths,
437
-            'EE_',
438
-            $class_name,
439
-            'class',
440
-            $arguments,
441
-            $from_db,
442
-            $cache,
443
-            $load_only
444
-        );
445
-    }
446
-
447
-
448
-
449
-    /**
450
-     * loads helper classes - must be singletons
451
-     *
452
-     * @param string $class_name - simple class name ie: price
453
-     * @param mixed  $arguments
454
-     * @param bool   $load_only
455
-     * @return EEH_Base | bool
456
-     * @throws EE_Error
457
-     * @throws ReflectionException
458
-     */
459
-    public function load_helper($class_name, $arguments = array(), $load_only = true)
460
-    {
461
-        // todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
462
-        $helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
463
-        // retrieve instantiated class
464
-        return $this->_load(
465
-            $helper_paths,
466
-            'EEH_',
467
-            $class_name,
468
-            'helper',
469
-            $arguments,
470
-            false,
471
-            true,
472
-            $load_only
473
-        );
474
-    }
475
-
476
-
477
-
478
-    /**
479
-     * loads core classes - must be singletons
480
-     *
481
-     * @param string $class_name - simple class name ie: session
482
-     * @param mixed  $arguments
483
-     * @param bool   $load_only
484
-     * @param bool   $cache      whether to cache the object or not.
485
-     * @return mixed
486
-     * @throws EE_Error
487
-     * @throws ReflectionException
488
-     */
489
-    public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
490
-    {
491
-        $paths = array(
492
-            EE_LIBRARIES,
493
-            EE_LIBRARIES . 'messages' . DS,
494
-            EE_LIBRARIES . 'shortcodes' . DS,
495
-            EE_LIBRARIES . 'qtips' . DS,
496
-            EE_LIBRARIES . 'payment_methods' . DS,
497
-        );
498
-        // retrieve instantiated class
499
-        return $this->_load(
500
-            $paths,
501
-            'EE_',
502
-            $class_name,
503
-            'lib',
504
-            $arguments,
505
-            false,
506
-            $cache,
507
-            $load_only
508
-        );
509
-    }
510
-
511
-
512
-
513
-    /**
514
-     * loads model classes - must be singletons
515
-     *
516
-     * @param string $class_name - simple class name ie: price
517
-     * @param mixed  $arguments
518
-     * @param bool   $load_only
519
-     * @return EEM_Base | bool
520
-     * @throws EE_Error
521
-     * @throws ReflectionException
522
-     */
523
-    public function load_model($class_name, $arguments = array(), $load_only = false)
524
-    {
525
-        $paths = apply_filters(
526
-            'FHEE__EE_Registry__load_model__paths', array(
527
-            EE_MODELS,
528
-            EE_CORE,
529
-        )
530
-        );
531
-        // retrieve instantiated class
532
-        return $this->_load(
533
-            $paths,
534
-            'EEM_',
535
-            $class_name,
536
-            'model',
537
-            $arguments,
538
-            false,
539
-            true,
540
-            $load_only
541
-        );
542
-    }
543
-
544
-
545
-
546
-    /**
547
-     * loads model classes - must be singletons
548
-     *
549
-     * @param string $class_name - simple class name ie: price
550
-     * @param mixed  $arguments
551
-     * @param bool   $load_only
552
-     * @return mixed | bool
553
-     * @throws EE_Error
554
-     * @throws ReflectionException
555
-     */
556
-    public function load_model_class($class_name, $arguments = array(), $load_only = true)
557
-    {
558
-        $paths = array(
559
-            EE_MODELS . 'fields' . DS,
560
-            EE_MODELS . 'helpers' . DS,
561
-            EE_MODELS . 'relations' . DS,
562
-            EE_MODELS . 'strategies' . DS,
563
-        );
564
-        // retrieve instantiated class
565
-        return $this->_load(
566
-            $paths,
567
-            'EE_',
568
-            $class_name,
569
-            '',
570
-            $arguments,
571
-            false,
572
-            true,
573
-            $load_only
574
-        );
575
-    }
576
-
577
-
578
-
579
-    /**
580
-     * Determines if $model_name is the name of an actual EE model.
581
-     *
582
-     * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
583
-     * @return boolean
584
-     */
585
-    public function is_model_name($model_name)
586
-    {
587
-        return isset($this->models[$model_name]);
588
-    }
589
-
590
-
591
-
592
-    /**
593
-     * generic class loader
594
-     *
595
-     * @param string $path_to_file - directory path to file location, not including filename
596
-     * @param string $file_name    - file name  ie:  my_file.php, including extension
597
-     * @param string $type         - file type - core? class? helper? model?
598
-     * @param mixed  $arguments
599
-     * @param bool   $load_only
600
-     * @return mixed
601
-     * @throws EE_Error
602
-     * @throws ReflectionException
603
-     */
604
-    public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
605
-    {
606
-        // retrieve instantiated class
607
-        return $this->_load(
608
-            $path_to_file,
609
-            '',
610
-            $file_name,
611
-            $type,
612
-            $arguments,
613
-            false,
614
-            true,
615
-            $load_only
616
-        );
617
-    }
618
-
619
-
620
-
621
-    /**
622
-     * @param string $path_to_file - directory path to file location, not including filename
623
-     * @param string $class_name   - full class name  ie:  My_Class
624
-     * @param string $type         - file type - core? class? helper? model?
625
-     * @param mixed  $arguments
626
-     * @param bool   $load_only
627
-     * @return bool|EE_Addon|object
628
-     * @throws EE_Error
629
-     * @throws ReflectionException
630
-     */
631
-    public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
632
-    {
633
-        // retrieve instantiated class
634
-        return $this->_load(
635
-            $path_to_file,
636
-            'addon',
637
-            $class_name,
638
-            $type,
639
-            $arguments,
640
-            false,
641
-            true,
642
-            $load_only
643
-        );
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * instantiates, caches, and automatically resolves dependencies
650
-     * for classes that use a Fully Qualified Class Name.
651
-     * if the class is not capable of being loaded using PSR-4 autoloading,
652
-     * then you need to use one of the existing load_*() methods
653
-     * which can resolve the classname and filepath from the passed arguments
654
-     *
655
-     * @param bool|string $class_name   Fully Qualified Class Name
656
-     * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
657
-     * @param bool        $cache        whether to cache the instantiated object for reuse
658
-     * @param bool        $from_db      some classes are instantiated from the db
659
-     *                                  and thus call a different method to instantiate
660
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
661
-     * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
662
-     * @return bool|null|mixed          null = failure to load or instantiate class object.
663
-     *                                  object = class loaded and instantiated successfully.
664
-     *                                  bool = fail or success when $load_only is true
665
-     * @throws EE_Error
666
-     * @throws ReflectionException
667
-     */
668
-    public function create(
669
-        $class_name = false,
670
-        $arguments = array(),
671
-        $cache = false,
672
-        $from_db = false,
673
-        $load_only = false,
674
-        $addon = false
675
-    ) {
676
-        $class_name = ltrim($class_name, '\\');
677
-        $class_name = $this->_dependency_map->get_alias($class_name);
678
-        $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679
-        // if a non-FQCN was passed, then verifyClassExists() might return an object
680
-        // or it could return null if the class just could not be found anywhere
681
-        if ($class_exists instanceof $class_name || $class_exists === null){
682
-            // either way, return the results
683
-            return $class_exists;
684
-        }
685
-        $class_name = $class_exists;
686
-        // if we're only loading the class and it already exists, then let's just return true immediately
687
-        if ($load_only) {
688
-            return true;
689
-        }
690
-        $addon = $addon
691
-            ? 'addon'
692
-            : '';
693
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
694
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
695
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
696
-        if ($this->_cache_on && $cache && ! $load_only) {
697
-            // return object if it's already cached
698
-            $cached_class = $this->_get_cached_class($class_name, $addon);
699
-            if ($cached_class !== null) {
700
-                return $cached_class;
701
-            }
702
-        }
703
-        // obtain the loader method from the dependency map
704
-        $loader = $this->_dependency_map->class_loader($class_name);
705
-        // instantiate the requested object
706
-        if ($loader instanceof Closure) {
707
-            $class_obj = $loader($arguments);
708
-        } else if ($loader && method_exists($this, $loader)) {
709
-            $class_obj = $this->{$loader}($class_name, $arguments);
710
-        } else {
711
-            $class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
712
-        }
713
-        if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
714
-            // save it for later... kinda like gum  { : $
715
-            $this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
716
-        }
717
-        $this->_cache_on = true;
718
-        return $class_obj;
719
-    }
720
-
721
-
722
-
723
-    /**
724
-     * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
725
-     *
726
-     * @param string $class_name
727
-     * @param array  $arguments
728
-     * @param int    $attempt
729
-     * @return mixed
730
-     */
731
-    private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
732
-        if (is_object($class_name) || class_exists($class_name)) {
733
-            return $class_name;
734
-        }
735
-        switch ($attempt) {
736
-            case 1:
737
-                // if it's a FQCN then maybe the class is registered with a preceding \
738
-                $class_name = strpos($class_name, '\\') !== false
739
-                    ? '\\' . ltrim($class_name, '\\')
740
-                    : $class_name;
741
-                break;
742
-            case 2:
743
-                //
744
-                $loader = $this->_dependency_map->class_loader($class_name);
745
-                if ($loader && method_exists($this, $loader)) {
746
-                    return $this->{$loader}($class_name, $arguments);
747
-                }
748
-                break;
749
-            case 3:
750
-            default;
751
-                return null;
752
-        }
753
-        $attempt++;
754
-        return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
755
-    }
756
-
757
-
758
-
759
-    /**
760
-     * instantiates, caches, and injects dependencies for classes
761
-     *
762
-     * @param array       $file_paths   an array of paths to folders to look in
763
-     * @param string      $class_prefix EE  or EEM or... ???
764
-     * @param bool|string $class_name   $class name
765
-     * @param string      $type         file type - core? class? helper? model?
766
-     * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
767
-     * @param bool        $from_db      some classes are instantiated from the db
768
-     *                                  and thus call a different method to instantiate
769
-     * @param bool        $cache        whether to cache the instantiated object for reuse
770
-     * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
771
-     * @return bool|null|object null = failure to load or instantiate class object.
772
-     *                                  object = class loaded and instantiated successfully.
773
-     *                                  bool = fail or success when $load_only is true
774
-     * @throws EE_Error
775
-     * @throws ReflectionException
776
-     */
777
-    protected function _load(
778
-        $file_paths = array(),
779
-        $class_prefix = 'EE_',
780
-        $class_name = false,
781
-        $type = 'class',
782
-        $arguments = array(),
783
-        $from_db = false,
784
-        $cache = true,
785
-        $load_only = false
786
-    ) {
787
-        $class_name = ltrim($class_name, '\\');
788
-        // strip php file extension
789
-        $class_name = str_replace('.php', '', trim($class_name));
790
-        // does the class have a prefix ?
791
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
792
-            // make sure $class_prefix is uppercase
793
-            $class_prefix = strtoupper(trim($class_prefix));
794
-            // add class prefix ONCE!!!
795
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
796
-        }
797
-        $class_name = $this->_dependency_map->get_alias($class_name);
798
-        $class_exists = class_exists($class_name);
799
-        // if we're only loading the class and it already exists, then let's just return true immediately
800
-        if ($load_only && $class_exists) {
801
-            return true;
802
-        }
803
-        // $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
804
-        // $cache is controlled by individual calls to separate Registry loader methods like load_class()
805
-        // $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
806
-        if ($this->_cache_on && $cache && ! $load_only) {
807
-            // return object if it's already cached
808
-            $cached_class = $this->_get_cached_class($class_name, $class_prefix);
809
-            if ($cached_class !== null) {
810
-                return $cached_class;
811
-            }
812
-        }
813
-        // if the class doesn't already exist.. then we need to try and find the file and load it
814
-        if (! $class_exists) {
815
-            // get full path to file
816
-            $path = $this->_resolve_path($class_name, $type, $file_paths);
817
-            // load the file
818
-            $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819
-            // if loading failed, or we are only loading a file but NOT instantiating an object
820
-            if (! $loaded || $load_only) {
821
-                // return boolean if only loading, or null if an object was expected
822
-                return $load_only
823
-                    ? $loaded
824
-                    : null;
825
-            }
826
-        }
827
-        // instantiate the requested object
828
-        $class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
829
-        if ($this->_cache_on && $cache) {
830
-            // save it for later... kinda like gum  { : $
831
-            $this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
832
-        }
833
-        $this->_cache_on = true;
834
-        return $class_obj;
835
-    }
836
-
837
-
838
-
839
-    /**
840
-     * @param string $class_name
841
-     * @param string $default have to specify something, but not anything that will conflict
842
-     * @return mixed|string
843
-     */
844
-    protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
845
-    {
846
-        return isset($this->_class_abbreviations[$class_name])
847
-            ? $this->_class_abbreviations[$class_name]
848
-            : $default;
849
-    }
850
-
851
-    /**
852
-     * attempts to find a cached version of the requested class
853
-     * by looking in the following places:
854
-     *        $this->{$class_abbreviation}            ie:    $this->CART
855
-     *        $this->{$class_name}                        ie:    $this->Some_Class
856
-     *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
857
-     *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
858
-     *
859
-     * @param string $class_name
860
-     * @param string $class_prefix
861
-     * @return mixed
862
-     */
863
-    protected function _get_cached_class($class_name, $class_prefix = '')
864
-    {
865
-        if ($class_name === 'EE_Registry') {
866
-            return $this;
867
-        }
868
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
869
-        $class_name = str_replace('\\', '_', $class_name);
870
-        // check if class has already been loaded, and return it if it has been
871
-        if (isset($this->{$class_abbreviation})) {
872
-            return $this->{$class_abbreviation};
873
-        }
874
-        if (isset ($this->{$class_name})) {
875
-            return $this->{$class_name};
876
-        }
877
-        if (isset ($this->LIB->{$class_name})) {
878
-            return $this->LIB->{$class_name};
879
-        }
880
-        if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
881
-            return $this->addons->{$class_name};
882
-        }
883
-        return null;
884
-    }
885
-
886
-
887
-
888
-    /**
889
-     * removes a cached version of the requested class
890
-     *
891
-     * @param string  $class_name
892
-     * @param boolean $addon
893
-     * @return boolean
894
-     */
895
-    public function clear_cached_class($class_name, $addon = false)
896
-    {
897
-        $class_abbreviation = $this->get_class_abbreviation($class_name);
898
-        $class_name = str_replace('\\', '_', $class_name);
899
-        // check if class has already been loaded, and return it if it has been
900
-        if (isset($this->{$class_abbreviation})) {
901
-            $this->{$class_abbreviation} = null;
902
-            return true;
903
-        }
904
-        if (isset($this->{$class_name})) {
905
-            $this->{$class_name} = null;
906
-            return true;
907
-        }
908
-        if (isset($this->LIB->{$class_name})) {
909
-            unset($this->LIB->{$class_name});
910
-            return true;
911
-        }
912
-        if ($addon && isset($this->addons->{$class_name})) {
913
-            unset($this->addons->{$class_name});
914
-            return true;
915
-        }
916
-        return false;
917
-    }
918
-
919
-
920
-
921
-    /**
922
-     * attempts to find a full valid filepath for the requested class.
923
-     * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
924
-     * then returns that path if the target file has been found and is readable
925
-     *
926
-     * @param string $class_name
927
-     * @param string $type
928
-     * @param array  $file_paths
929
-     * @return string | bool
930
-     */
931
-    protected function _resolve_path($class_name, $type = '', $file_paths = array())
932
-    {
933
-        // make sure $file_paths is an array
934
-        $file_paths = is_array($file_paths)
935
-            ? $file_paths
936
-            : array($file_paths);
937
-        // cycle thru paths
938
-        foreach ($file_paths as $key => $file_path) {
939
-            // convert all separators to proper DS, if no filepath, then use EE_CLASSES
940
-            $file_path = $file_path
941
-                ? str_replace(array('/', '\\'), DS, $file_path)
942
-                : EE_CLASSES;
943
-            // prep file type
944
-            $type = ! empty($type)
945
-                ? trim($type, '.') . '.'
946
-                : '';
947
-            // build full file path
948
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
949
-            //does the file exist and can be read ?
950
-            if (is_readable($file_paths[$key])) {
951
-                return $file_paths[$key];
952
-            }
953
-        }
954
-        return false;
955
-    }
956
-
957
-
958
-
959
-    /**
960
-     * basically just performs a require_once()
961
-     * but with some error handling
962
-     *
963
-     * @param  string $path
964
-     * @param  string $class_name
965
-     * @param  string $type
966
-     * @param  array  $file_paths
967
-     * @return bool
968
-     * @throws EE_Error
969
-     * @throws ReflectionException
970
-     */
971
-    protected function _require_file($path, $class_name, $type = '', $file_paths = array())
972
-    {
973
-        // don't give up! you gotta...
974
-        try {
975
-            //does the file exist and can it be read ?
976
-            if (! $path) {
977
-                // so sorry, can't find the file
978
-                throw new EE_Error (
979
-                    sprintf(
980
-                        esc_html__(
981
-                            'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
982
-                            'event_espresso'
983
-                        ),
984
-                        trim($type, '.'),
985
-                        $class_name,
986
-                        '<br />' . implode(',<br />', $file_paths)
987
-                    )
988
-                );
989
-            }
990
-            // get the file
991
-            require_once($path);
992
-            // if the class isn't already declared somewhere
993
-            if (class_exists($class_name, false) === false) {
994
-                // so sorry, not a class
995
-                throw new EE_Error(
996
-                    sprintf(
997
-                        esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
998
-                        $type,
999
-                        $path,
1000
-                        $class_name
1001
-                    )
1002
-                );
1003
-            }
1004
-        } catch (EE_Error $e) {
1005
-            $e->get_error();
1006
-            return false;
1007
-        }
1008
-        return true;
1009
-    }
1010
-
1011
-
1012
-
1013
-    /**
1014
-     * _create_object
1015
-     * Attempts to instantiate the requested class via any of the
1016
-     * commonly used instantiation methods employed throughout EE.
1017
-     * The priority for instantiation is as follows:
1018
-     *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1019
-     *        - model objects via their 'new_instance_from_db' method
1020
-     *        - model objects via their 'new_instance' method
1021
-     *        - "singleton" classes" via their 'instance' method
1022
-     *    - standard instantiable classes via their __constructor
1023
-     * Prior to instantiation, if the classname exists in the dependency_map,
1024
-     * then the constructor for the requested class will be examined to determine
1025
-     * if any dependencies exist, and if they can be injected.
1026
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1027
-     *
1028
-     * @param string $class_name
1029
-     * @param array  $arguments
1030
-     * @param string $type
1031
-     * @param bool   $from_db
1032
-     * @return null|object
1033
-     * @throws EE_Error
1034
-     * @throws ReflectionException
1035
-     */
1036
-    protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1037
-    {
1038
-        // create reflection
1039
-        $reflector = $this->get_ReflectionClass($class_name);
1040
-        // make sure arguments are an array
1041
-        $arguments = is_array($arguments)
1042
-            ? $arguments
1043
-            : array($arguments);
1044
-        // and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1045
-        // else wrap it in an additional array so that it doesn't get split into multiple parameters
1046
-        $arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1047
-            ? $arguments
1048
-            : array($arguments);
1049
-        // attempt to inject dependencies ?
1050
-        if ($this->_dependency_map->has($class_name)) {
1051
-            $arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1052
-        }
1053
-        // instantiate the class if possible
1054
-        if ($reflector->isAbstract()) {
1055
-            // nothing to instantiate, loading file was enough
1056
-            // does not throw an exception so $instantiation_mode is unused
1057
-            // $instantiation_mode = "1) no constructor abstract class";
1058
-            return true;
1059
-        }
1060
-        if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1061
-            // no constructor = static methods only... nothing to instantiate, loading file was enough
1062
-            // $instantiation_mode = "2) no constructor but instantiable";
1063
-            return $reflector->newInstance();
1064
-        }
1065
-        if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1066
-            // $instantiation_mode = "3) new_instance_from_db()";
1067
-            return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1068
-        }
1069
-        if (method_exists($class_name, 'new_instance')) {
1070
-            // $instantiation_mode = "4) new_instance()";
1071
-            return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1072
-        }
1073
-        if (method_exists($class_name, 'instance')) {
1074
-            // $instantiation_mode = "5) instance()";
1075
-            return call_user_func_array(array($class_name, 'instance'), $arguments);
1076
-        }
1077
-        if ($reflector->isInstantiable()) {
1078
-            // $instantiation_mode = "6) constructor";
1079
-            return $reflector->newInstanceArgs($arguments);
1080
-        }
1081
-        // heh ? something's not right !
1082
-        throw new EE_Error(
1083
-            sprintf(
1084
-                __('The %s file %s could not be instantiated.', 'event_espresso'),
1085
-                $type,
1086
-                $class_name
1087
-            )
1088
-        );
1089
-    }
1090
-
1091
-
1092
-
1093
-    /**
1094
-     * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1095
-     * @param array $array
1096
-     * @return bool
1097
-     */
1098
-    protected function _array_is_numerically_and_sequentially_indexed(array $array)
1099
-    {
1100
-        return ! empty($array)
1101
-            ? array_keys($array) === range(0, count($array) - 1)
1102
-            : true;
1103
-    }
1104
-
1105
-
1106
-
1107
-    /**
1108
-     * getReflectionClass
1109
-     * checks if a ReflectionClass object has already been generated for a class
1110
-     * and returns that instead of creating a new one
1111
-     *
1112
-     * @param string $class_name
1113
-     * @return ReflectionClass
1114
-     * @throws ReflectionException
1115
-     */
1116
-    public function get_ReflectionClass($class_name)
1117
-    {
1118
-        if (
1119
-            ! isset($this->_reflectors[$class_name])
1120
-            || ! $this->_reflectors[$class_name] instanceof ReflectionClass
1121
-        ) {
1122
-            $this->_reflectors[$class_name] = new ReflectionClass($class_name);
1123
-        }
1124
-        return $this->_reflectors[$class_name];
1125
-    }
1126
-
1127
-
1128
-
1129
-    /**
1130
-     * _resolve_dependencies
1131
-     * examines the constructor for the requested class to determine
1132
-     * if any dependencies exist, and if they can be injected.
1133
-     * If so, then those classes will be added to the array of arguments passed to the constructor
1134
-     * PLZ NOTE: this is achieved by type hinting the constructor params
1135
-     * For example:
1136
-     *        if attempting to load a class "Foo" with the following constructor:
1137
-     *        __construct( Bar $bar_class, Fighter $grohl_class )
1138
-     *        then $bar_class and $grohl_class will be added to the $arguments array,
1139
-     *        but only IF they are NOT already present in the incoming arguments array,
1140
-     *        and the correct classes can be loaded
1141
-     *
1142
-     * @param ReflectionClass $reflector
1143
-     * @param string          $class_name
1144
-     * @param array           $arguments
1145
-     * @return array
1146
-     * @throws EE_Error
1147
-     * @throws ReflectionException
1148
-     */
1149
-    protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1150
-    {
1151
-        // let's examine the constructor
1152
-        $constructor = $reflector->getConstructor();
1153
-        // whu? huh? nothing?
1154
-        if (! $constructor) {
1155
-            return $arguments;
1156
-        }
1157
-        // get constructor parameters
1158
-        $params = $constructor->getParameters();
1159
-        // and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1160
-        $argument_keys = array_keys($arguments);
1161
-        // now loop thru all of the constructors expected parameters
1162
-        foreach ($params as $index => $param) {
1163
-            // is this a dependency for a specific class ?
1164
-            $param_class = $param->getClass()
1165
-                ? $param->getClass()->name
1166
-                : null;
1167
-            // BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1168
-            $param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1169
-                ? $this->_dependency_map->get_alias($param_class, $class_name)
1170
-                : $param_class;
1171
-            if (
1172
-                // param is not even a class
1173
-                $param_class === null
1174
-                // and something already exists in the incoming arguments for this param
1175
-                && array_key_exists($index, $argument_keys)
1176
-                && array_key_exists($argument_keys[$index], $arguments)
1177
-            ) {
1178
-                // so let's skip this argument and move on to the next
1179
-                continue;
1180
-            }
1181
-            if (
1182
-                // parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1183
-                $param_class !== null
1184
-                && isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1185
-                && $arguments[$argument_keys[$index]] instanceof $param_class
1186
-            ) {
1187
-                // skip this argument and move on to the next
1188
-                continue;
1189
-            }
1190
-            if (
1191
-                // parameter is type hinted as a class, and should be injected
1192
-                $param_class !== null
1193
-                && $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1194
-            ) {
1195
-                $arguments = $this->_resolve_dependency(
1196
-                    $class_name,
1197
-                    $param_class,
1198
-                    $arguments,
1199
-                    $index,
1200
-                    $argument_keys
1201
-                );
1202
-            } else {
1203
-                try {
1204
-                    $arguments[$index] = $param->isDefaultValueAvailable()
1205
-                        ? $param->getDefaultValue()
1206
-                        : null;
1207
-                } catch (ReflectionException $e) {
1208
-                    throw new ReflectionException(
1209
-                        sprintf(
1210
-                            esc_html__('%1$s for parameter "$%2$s on classname "%3$s"', 'event_espresso'),
1211
-                            $e->getMessage(),
1212
-                            $param->getName(),
1213
-                            $class_name
1214
-                        )
1215
-                    );
1216
-                }
1217
-            }
1218
-        }
1219
-        return $arguments;
1220
-    }
1221
-
1222
-
1223
-
1224
-    /**
1225
-     * @param string $class_name
1226
-     * @param string $param_class
1227
-     * @param array  $arguments
1228
-     * @param mixed  $index
1229
-     * @param array  $argument_keys
1230
-     * @return array
1231
-     * @throws EE_Error
1232
-     * @throws ReflectionException
1233
-     * @throws InvalidArgumentException
1234
-     * @throws InvalidInterfaceException
1235
-     * @throws InvalidDataTypeException
1236
-     */
1237
-    protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1238
-    {
1239
-        $dependency = null;
1240
-        // should dependency be loaded from cache ?
1241
-        $cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1242
-            $class_name,
1243
-            $param_class
1244
-        );
1245
-        $cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1246
-        // we might have a dependency...
1247
-        // let's MAYBE try and find it in our cache if that's what's been requested
1248
-        $cached_class = $cache_on
1249
-            ? $this->_get_cached_class($param_class)
1250
-            : null;
1251
-        // and grab it if it exists
1252
-        if ($cached_class instanceof $param_class) {
1253
-            $dependency = $cached_class;
1254
-        } else if ($param_class !== $class_name) {
1255
-            // obtain the loader method from the dependency map
1256
-            $loader = $this->_dependency_map->class_loader($param_class);
1257
-            // is loader a custom closure ?
1258
-            if ($loader instanceof Closure) {
1259
-                $dependency = $loader($arguments);
1260
-            } else {
1261
-                // set the cache on property for the recursive loading call
1262
-                $this->_cache_on = $cache_on;
1263
-                // if not, then let's try and load it via the registry
1264
-                if ($loader && method_exists($this, $loader)) {
1265
-                    $dependency = $this->{$loader}($param_class);
1266
-                } else {
1267
-                    $dependency = LoaderFactory::getLoader()->load(
1268
-                        $param_class,
1269
-                        array(),
1270
-                        $cache_on
1271
-                    );
1272
-                }
1273
-            }
1274
-        }
1275
-        // did we successfully find the correct dependency ?
1276
-        if ($dependency instanceof $param_class) {
1277
-            // then let's inject it into the incoming array of arguments at the correct location
1278
-            $arguments[$index] = $dependency;
1279
-        }
1280
-        return $arguments;
1281
-    }
1282
-
1283
-
1284
-
1285
-    /**
1286
-     * _set_cached_class
1287
-     * attempts to cache the instantiated class locally
1288
-     * in one of the following places, in the following order:
1289
-     *        $this->{class_abbreviation}   ie:    $this->CART
1290
-     *        $this->{$class_name}          ie:    $this->Some_Class
1291
-     *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1292
-     *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1293
-     *
1294
-     * @param object $class_obj
1295
-     * @param string $class_name
1296
-     * @param string $class_prefix
1297
-     * @param bool   $from_db
1298
-     * @return void
1299
-     */
1300
-    protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1301
-    {
1302
-        if ($class_name === 'EE_Registry' || empty($class_obj)) {
1303
-            return;
1304
-        }
1305
-        // return newly instantiated class
1306
-        $class_abbreviation = $this->get_class_abbreviation($class_name, '');
1307
-        if ($class_abbreviation) {
1308
-            $this->{$class_abbreviation} = $class_obj;
1309
-            return;
1310
-        }
1311
-        $class_name = str_replace('\\', '_', $class_name);
1312
-        if (property_exists($this, $class_name)) {
1313
-            $this->{$class_name} = $class_obj;
1314
-            return;
1315
-        }
1316
-        if ($class_prefix === 'addon') {
1317
-            $this->addons->{$class_name} = $class_obj;
1318
-            return;
1319
-        }
1320
-        if (! $from_db) {
1321
-            $this->LIB->{$class_name} = $class_obj;
1322
-        }
1323
-    }
1324
-
1325
-
1326
-
1327
-    /**
1328
-     * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1329
-     *
1330
-     * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1331
-     *                          in the EE_Dependency_Map::$_class_loaders array,
1332
-     *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1333
-     * @param array  $arguments
1334
-     * @return object
1335
-     */
1336
-    public static function factory($classname, $arguments = array())
1337
-    {
1338
-        $loader = self::instance()->_dependency_map->class_loader($classname);
1339
-        if ($loader instanceof Closure) {
1340
-            return $loader($arguments);
1341
-        }
1342
-        if (method_exists(self::instance(), $loader)) {
1343
-            return self::instance()->{$loader}($classname, $arguments);
1344
-        }
1345
-        return null;
1346
-    }
1347
-
1348
-
1349
-
1350
-    /**
1351
-     * Gets the addon by its name/slug (not classname. For that, just
1352
-     * use the classname as the property name on EE_Config::instance()->addons)
1353
-     *
1354
-     * @param string $name
1355
-     * @return EE_Addon
1356
-     */
1357
-    public function get_addon_by_name($name)
1358
-    {
1359
-        foreach ($this->addons as $addon) {
1360
-            if ($addon->name() === $name) {
1361
-                return $addon;
1362
-            }
1363
-        }
1364
-        return null;
1365
-    }
1366
-
1367
-
1368
-
1369
-    /**
1370
-     * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1371
-     * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1372
-     * name is the addon's classname. So if you just want to get the addon by classname, use
1373
-     * EE_Config::instance()->addons->{classname}
1374
-     *
1375
-     * @return EE_Addon[] where the KEYS are the addon's name()
1376
-     */
1377
-    public function get_addons_by_name()
1378
-    {
1379
-        $addons = array();
1380
-        foreach ($this->addons as $addon) {
1381
-            $addons[$addon->name()] = $addon;
1382
-        }
1383
-        return $addons;
1384
-    }
1385
-
1386
-
1387
-
1388
-    /**
1389
-     * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1390
-     * a stale copy of it around
1391
-     *
1392
-     * @param string $model_name
1393
-     * @return \EEM_Base
1394
-     * @throws \EE_Error
1395
-     */
1396
-    public function reset_model($model_name)
1397
-    {
1398
-        $model_class_name = strpos($model_name, 'EEM_') !== 0
1399
-            ? "EEM_{$model_name}"
1400
-            : $model_name;
1401
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1402
-            return null;
1403
-        }
1404
-        //get that model reset it and make sure we nuke the old reference to it
1405
-        if ($this->LIB->{$model_class_name} instanceof $model_class_name
1406
-            && is_callable(
1407
-                array($model_class_name, 'reset')
1408
-            )) {
1409
-            $this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1410
-        } else {
1411
-            throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1412
-        }
1413
-        return $this->LIB->{$model_class_name};
1414
-    }
1415
-
1416
-
1417
-
1418
-    /**
1419
-     * Resets the registry.
1420
-     * The criteria for what gets reset is based on what can be shared between sites on the same request when
1421
-     * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1422
-     * - $_dependency_map
1423
-     * - $_class_abbreviations
1424
-     * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1425
-     * - $REQ:  Still on the same request so no need to change.
1426
-     * - $CAP: There is no site specific state in the EE_Capability class.
1427
-     * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1428
-     * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1429
-     * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1430
-     *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1431
-     *             switch or on the restore.
1432
-     * - $modules
1433
-     * - $shortcodes
1434
-     * - $widgets
1435
-     *
1436
-     * @param boolean $hard             [deprecated]
1437
-     * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1438
-     *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1439
-     *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1440
-     * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1441
-     *                                  client
1442
-     *                                  code instead can just change the model context to a different blog id if
1443
-     *                                  necessary
1444
-     * @return EE_Registry
1445
-     * @throws EE_Error
1446
-     * @throws ReflectionException
1447
-     */
1448
-    public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1449
-    {
1450
-        $instance = self::instance();
1451
-        $instance->_cache_on = true;
1452
-        // reset some "special" classes
1453
-        EEH_Activation::reset();
1454
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1455
-        $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1456
-        $instance->CART = null;
1457
-        $instance->MRM = null;
1458
-        $instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1459
-        //messages reset
1460
-        EED_Messages::reset();
1461
-        //handle of objects cached on LIB
1462
-        foreach (array('LIB', 'modules') as $cache) {
1463
-            foreach ($instance->{$cache} as $class_name => $class) {
1464
-                if (self::_reset_and_unset_object($class, $reset_models)) {
1465
-                    unset($instance->{$cache}->{$class_name});
1466
-                }
1467
-            }
1468
-        }
1469
-        return $instance;
1470
-    }
1471
-
1472
-
1473
-
1474
-    /**
1475
-     * if passed object implements ResettableInterface, then call it's reset() method
1476
-     * if passed object implements InterminableInterface, then return false,
1477
-     * to indicate that it should NOT be cleared from the Registry cache
1478
-     *
1479
-     * @param      $object
1480
-     * @param bool $reset_models
1481
-     * @return bool returns true if cached object should be unset
1482
-     */
1483
-    private static function _reset_and_unset_object($object, $reset_models)
1484
-    {
1485
-        if (! is_object($object)) {
1486
-            // don't unset anything that's not an object
1487
-            return false;
1488
-        }
1489
-        if ($object instanceof EED_Module) {
1490
-            $object::reset();
1491
-            // don't unset modules
1492
-            return false;
1493
-        }
1494
-        if ($object instanceof ResettableInterface) {
1495
-            if ($object instanceof EEM_Base) {
1496
-                if ($reset_models) {
1497
-                    $object->reset();
1498
-                    return true;
1499
-                }
1500
-                return false;
1501
-            }
1502
-            $object->reset();
1503
-            return true;
1504
-        }
1505
-        if (! $object instanceof InterminableInterface) {
1506
-            return true;
1507
-        }
1508
-        return false;
1509
-    }
1510
-
1511
-
1512
-
1513
-    /**
1514
-     * Gets all the custom post type models defined
1515
-     *
1516
-     * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1517
-     */
1518
-    public function cpt_models()
1519
-    {
1520
-        $cpt_models = array();
1521
-        foreach ($this->non_abstract_db_models as $short_name => $classname) {
1522
-            if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1523
-                $cpt_models[$short_name] = $classname;
1524
-            }
1525
-        }
1526
-        return $cpt_models;
1527
-    }
1528
-
1529
-
1530
-
1531
-    /**
1532
-     * @return \EE_Config
1533
-     */
1534
-    public static function CFG()
1535
-    {
1536
-        return self::instance()->CFG;
1537
-    }
25
+	/**
26
+	 * @var EE_Registry $_instance
27
+	 */
28
+	private static $_instance;
29
+
30
+	/**
31
+	 * @var EE_Dependency_Map $_dependency_map
32
+	 */
33
+	protected $_dependency_map;
34
+
35
+	/**
36
+	 * @var array $_class_abbreviations
37
+	 */
38
+	protected $_class_abbreviations = array();
39
+
40
+	/**
41
+	 * @var CommandBusInterface $BUS
42
+	 */
43
+	public $BUS;
44
+
45
+	/**
46
+	 * @var EE_Cart $CART
47
+	 */
48
+	public $CART;
49
+
50
+	/**
51
+	 * @var EE_Config $CFG
52
+	 */
53
+	public $CFG;
54
+
55
+	/**
56
+	 * @var EE_Network_Config $NET_CFG
57
+	 */
58
+	public $NET_CFG;
59
+
60
+	/**
61
+	 * StdClass object for storing library classes in
62
+	 *
63
+	 * @var StdClass $LIB
64
+	 */
65
+	public $LIB;
66
+
67
+	/**
68
+	 * @var EE_Request_Handler $REQ
69
+	 */
70
+	public $REQ;
71
+
72
+	/**
73
+	 * @var EE_Session $SSN
74
+	 */
75
+	public $SSN;
76
+
77
+	/**
78
+	 * @since 4.5.0
79
+	 * @var EE_Capabilities $CAP
80
+	 */
81
+	public $CAP;
82
+
83
+	/**
84
+	 * @since 4.9.0
85
+	 * @var EE_Message_Resource_Manager $MRM
86
+	 */
87
+	public $MRM;
88
+
89
+
90
+	/**
91
+	 * @var Registry $AssetsRegistry
92
+	 */
93
+	public $AssetsRegistry;
94
+
95
+	/**
96
+	 * StdClass object for holding addons which have registered themselves to work with EE core
97
+	 *
98
+	 * @var EE_Addon[] $addons
99
+	 */
100
+	public $addons;
101
+
102
+	/**
103
+	 * keys are 'short names' (eg Event), values are class names (eg 'EEM_Event')
104
+	 *
105
+	 * @var EEM_Base[] $models
106
+	 */
107
+	public $models = array();
108
+
109
+	/**
110
+	 * @var EED_Module[] $modules
111
+	 */
112
+	public $modules;
113
+
114
+	/**
115
+	 * @var EES_Shortcode[] $shortcodes
116
+	 */
117
+	public $shortcodes;
118
+
119
+	/**
120
+	 * @var WP_Widget[] $widgets
121
+	 */
122
+	public $widgets;
123
+
124
+	/**
125
+	 * this is an array of all implemented model names (i.e. not the parent abstract models, or models
126
+	 * which don't actually fetch items from the DB in the normal way (ie, are not children of EEM_Base)).
127
+	 * Keys are model "short names" (eg "Event") as used in model relations, and values are
128
+	 * classnames (eg "EEM_Event")
129
+	 *
130
+	 * @var array $non_abstract_db_models
131
+	 */
132
+	public $non_abstract_db_models = array();
133
+
134
+
135
+	/**
136
+	 * internationalization for JS strings
137
+	 *    usage:   EE_Registry::i18n_js_strings['string_key'] = esc_html__( 'string to translate.', 'event_espresso' );
138
+	 *    in js file:  var translatedString = eei18n.string_key;
139
+	 *
140
+	 * @var array $i18n_js_strings
141
+	 */
142
+	public static $i18n_js_strings = array();
143
+
144
+
145
+	/**
146
+	 * $main_file - path to espresso.php
147
+	 *
148
+	 * @var array $main_file
149
+	 */
150
+	public $main_file;
151
+
152
+	/**
153
+	 * array of ReflectionClass objects where the key is the class name
154
+	 *
155
+	 * @var ReflectionClass[] $_reflectors
156
+	 */
157
+	public $_reflectors;
158
+
159
+	/**
160
+	 * boolean flag to indicate whether or not to load/save dependencies from/to the cache
161
+	 *
162
+	 * @var boolean $_cache_on
163
+	 */
164
+	protected $_cache_on = true;
165
+
166
+
167
+
168
+	/**
169
+	 * @singleton method used to instantiate class object
170
+	 * @param  EE_Dependency_Map $dependency_map
171
+	 * @return EE_Registry instance
172
+	 * @throws InvalidArgumentException
173
+	 * @throws InvalidInterfaceException
174
+	 * @throws InvalidDataTypeException
175
+	 */
176
+	public static function instance(EE_Dependency_Map $dependency_map = null)
177
+	{
178
+		// check if class object is instantiated
179
+		if (! self::$_instance instanceof EE_Registry) {
180
+			self::$_instance = new self($dependency_map);
181
+		}
182
+		return self::$_instance;
183
+	}
184
+
185
+
186
+
187
+	/**
188
+	 * protected constructor to prevent direct creation
189
+	 *
190
+	 * @Constructor
191
+	 * @param  EE_Dependency_Map $dependency_map
192
+	 * @throws InvalidDataTypeException
193
+	 * @throws InvalidInterfaceException
194
+	 * @throws InvalidArgumentException
195
+	 */
196
+	protected function __construct(EE_Dependency_Map $dependency_map)
197
+	{
198
+		$this->_dependency_map = $dependency_map;
199
+		$this->LIB = new stdClass();
200
+		$this->addons = new stdClass();
201
+		$this->modules = new stdClass();
202
+		$this->shortcodes = new stdClass();
203
+		$this->widgets = new stdClass();
204
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
205
+	}
206
+
207
+
208
+
209
+	/**
210
+	 * initialize
211
+	 *
212
+	 * @throws EE_Error
213
+	 * @throws ReflectionException
214
+	 */
215
+	public function initialize()
216
+	{
217
+		$this->_class_abbreviations = apply_filters(
218
+			'FHEE__EE_Registry____construct___class_abbreviations',
219
+			array(
220
+				'EE_Config'                                       => 'CFG',
221
+				'EE_Session'                                      => 'SSN',
222
+				'EE_Capabilities'                                 => 'CAP',
223
+				'EE_Cart'                                         => 'CART',
224
+				'EE_Network_Config'                               => 'NET_CFG',
225
+				'EE_Request_Handler'                              => 'REQ',
226
+				'EE_Message_Resource_Manager'                     => 'MRM',
227
+				'EventEspresso\core\services\commands\CommandBus' => 'BUS',
228
+				'EventEspresso\core\services\assets\Registry'     => 'AssetsRegistry',
229
+			)
230
+		);
231
+		$this->load_core('Base', array(), true);
232
+		// add our request and response objects to the cache
233
+		$request_loader = $this->_dependency_map->class_loader('EE_Request');
234
+		$this->_set_cached_class(
235
+			$request_loader(),
236
+			'EE_Request'
237
+		);
238
+		$response_loader = $this->_dependency_map->class_loader('EE_Response');
239
+		$this->_set_cached_class(
240
+			$response_loader(),
241
+			'EE_Response'
242
+		);
243
+		add_action('AHEE__EE_System__set_hooks_for_core', array($this, 'init'));
244
+	}
245
+
246
+
247
+
248
+	/**
249
+	 * @return void
250
+	 */
251
+	public function init()
252
+	{
253
+		// Get current page protocol
254
+		$protocol = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
255
+		// Output admin-ajax.php URL with same protocol as current page
256
+		self::$i18n_js_strings['ajax_url'] = admin_url('admin-ajax.php', $protocol);
257
+		self::$i18n_js_strings['wp_debug'] = defined('WP_DEBUG') ? WP_DEBUG : false;
258
+	}
259
+
260
+
261
+
262
+	/**
263
+	 * localize_i18n_js_strings
264
+	 *
265
+	 * @return string
266
+	 */
267
+	public static function localize_i18n_js_strings()
268
+	{
269
+		$i18n_js_strings = (array)self::$i18n_js_strings;
270
+		foreach ($i18n_js_strings as $key => $value) {
271
+			if (is_scalar($value)) {
272
+				$i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
273
+			}
274
+		}
275
+		return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
276
+	}
277
+
278
+
279
+
280
+	/**
281
+	 * @param mixed string | EED_Module $module
282
+	 * @throws EE_Error
283
+	 * @throws ReflectionException
284
+	 */
285
+	public function add_module($module)
286
+	{
287
+		if ($module instanceof EED_Module) {
288
+			$module_class = get_class($module);
289
+			$this->modules->{$module_class} = $module;
290
+		} else {
291
+			if (! class_exists('EE_Module_Request_Router')) {
292
+				$this->load_core('Module_Request_Router');
293
+			}
294
+			EE_Module_Request_Router::module_factory($module);
295
+		}
296
+	}
297
+
298
+
299
+
300
+	/**
301
+	 * @param string $module_name
302
+	 * @return mixed EED_Module | NULL
303
+	 */
304
+	public function get_module($module_name = '')
305
+	{
306
+		return isset($this->modules->{$module_name})
307
+			? $this->modules->{$module_name}
308
+			: null;
309
+	}
310
+
311
+
312
+
313
+	/**
314
+	 * loads core classes - must be singletons
315
+	 *
316
+	 * @param string $class_name - simple class name ie: session
317
+	 * @param mixed  $arguments
318
+	 * @param bool   $load_only
319
+	 * @return mixed
320
+	 * @throws EE_Error
321
+	 * @throws ReflectionException
322
+	 */
323
+	public function load_core($class_name, $arguments = array(), $load_only = false)
324
+	{
325
+		$core_paths = apply_filters(
326
+			'FHEE__EE_Registry__load_core__core_paths',
327
+			array(
328
+				EE_CORE,
329
+				EE_ADMIN,
330
+				EE_CPTS,
331
+				EE_CORE . 'data_migration_scripts' . DS,
332
+				EE_CORE . 'capabilities' . DS,
333
+				EE_CORE . 'request_stack' . DS,
334
+				EE_CORE . 'middleware' . DS,
335
+			)
336
+		);
337
+		// retrieve instantiated class
338
+		return $this->_load(
339
+			$core_paths,
340
+			'EE_',
341
+			$class_name,
342
+			'core',
343
+			$arguments,
344
+			false,
345
+			true,
346
+			$load_only
347
+		);
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * loads service classes
354
+	 *
355
+	 * @param string $class_name - simple class name ie: session
356
+	 * @param mixed  $arguments
357
+	 * @param bool   $load_only
358
+	 * @return mixed
359
+	 * @throws EE_Error
360
+	 * @throws ReflectionException
361
+	 */
362
+	public function load_service($class_name, $arguments = array(), $load_only = false)
363
+	{
364
+		$service_paths = apply_filters(
365
+			'FHEE__EE_Registry__load_service__service_paths',
366
+			array(
367
+				EE_CORE . 'services' . DS,
368
+			)
369
+		);
370
+		// retrieve instantiated class
371
+		return $this->_load(
372
+			$service_paths,
373
+			'EE_',
374
+			$class_name,
375
+			'class',
376
+			$arguments,
377
+			false,
378
+			true,
379
+			$load_only
380
+		);
381
+	}
382
+
383
+
384
+
385
+	/**
386
+	 * loads data_migration_scripts
387
+	 *
388
+	 * @param string $class_name - class name for the DMS ie: EE_DMS_Core_4_2_0
389
+	 * @param mixed  $arguments
390
+	 * @return EE_Data_Migration_Script_Base|mixed
391
+	 * @throws EE_Error
392
+	 * @throws ReflectionException
393
+	 */
394
+	public function load_dms($class_name, $arguments = array())
395
+	{
396
+		// retrieve instantiated class
397
+		return $this->_load(
398
+			EE_Data_Migration_Manager::instance()->get_data_migration_script_folders(),
399
+			'EE_DMS_',
400
+			$class_name,
401
+			'dms',
402
+			$arguments,
403
+			false,
404
+			false
405
+		);
406
+	}
407
+
408
+
409
+
410
+	/**
411
+	 * loads object creating classes - must be singletons
412
+	 *
413
+	 * @param string $class_name - simple class name ie: attendee
414
+	 * @param mixed  $arguments  - an array of arguments to pass to the class
415
+	 * @param bool   $from_db    - some classes are instantiated from the db and thus call a different method to
416
+	 *                           instantiate
417
+	 * @param bool   $cache      if you don't want the class to be stored in the internal cache (non-persistent) then
418
+	 *                           set this to FALSE (ie. when instantiating model objects from client in a loop)
419
+	 * @param bool   $load_only  whether or not to just load the file and NOT instantiate, or load AND instantiate
420
+	 *                           (default)
421
+	 * @return EE_Base_Class | bool
422
+	 * @throws EE_Error
423
+	 * @throws ReflectionException
424
+	 */
425
+	public function load_class($class_name, $arguments = array(), $from_db = false, $cache = true, $load_only = false)
426
+	{
427
+		$paths = apply_filters(
428
+			'FHEE__EE_Registry__load_class__paths', array(
429
+			EE_CORE,
430
+			EE_CLASSES,
431
+			EE_BUSINESS,
432
+		)
433
+		);
434
+		// retrieve instantiated class
435
+		return $this->_load(
436
+			$paths,
437
+			'EE_',
438
+			$class_name,
439
+			'class',
440
+			$arguments,
441
+			$from_db,
442
+			$cache,
443
+			$load_only
444
+		);
445
+	}
446
+
447
+
448
+
449
+	/**
450
+	 * loads helper classes - must be singletons
451
+	 *
452
+	 * @param string $class_name - simple class name ie: price
453
+	 * @param mixed  $arguments
454
+	 * @param bool   $load_only
455
+	 * @return EEH_Base | bool
456
+	 * @throws EE_Error
457
+	 * @throws ReflectionException
458
+	 */
459
+	public function load_helper($class_name, $arguments = array(), $load_only = true)
460
+	{
461
+		// todo: add doing_it_wrong() in a few versions after all addons have had calls to this method removed
462
+		$helper_paths = apply_filters('FHEE__EE_Registry__load_helper__helper_paths', array(EE_HELPERS));
463
+		// retrieve instantiated class
464
+		return $this->_load(
465
+			$helper_paths,
466
+			'EEH_',
467
+			$class_name,
468
+			'helper',
469
+			$arguments,
470
+			false,
471
+			true,
472
+			$load_only
473
+		);
474
+	}
475
+
476
+
477
+
478
+	/**
479
+	 * loads core classes - must be singletons
480
+	 *
481
+	 * @param string $class_name - simple class name ie: session
482
+	 * @param mixed  $arguments
483
+	 * @param bool   $load_only
484
+	 * @param bool   $cache      whether to cache the object or not.
485
+	 * @return mixed
486
+	 * @throws EE_Error
487
+	 * @throws ReflectionException
488
+	 */
489
+	public function load_lib($class_name, $arguments = array(), $load_only = false, $cache = true)
490
+	{
491
+		$paths = array(
492
+			EE_LIBRARIES,
493
+			EE_LIBRARIES . 'messages' . DS,
494
+			EE_LIBRARIES . 'shortcodes' . DS,
495
+			EE_LIBRARIES . 'qtips' . DS,
496
+			EE_LIBRARIES . 'payment_methods' . DS,
497
+		);
498
+		// retrieve instantiated class
499
+		return $this->_load(
500
+			$paths,
501
+			'EE_',
502
+			$class_name,
503
+			'lib',
504
+			$arguments,
505
+			false,
506
+			$cache,
507
+			$load_only
508
+		);
509
+	}
510
+
511
+
512
+
513
+	/**
514
+	 * loads model classes - must be singletons
515
+	 *
516
+	 * @param string $class_name - simple class name ie: price
517
+	 * @param mixed  $arguments
518
+	 * @param bool   $load_only
519
+	 * @return EEM_Base | bool
520
+	 * @throws EE_Error
521
+	 * @throws ReflectionException
522
+	 */
523
+	public function load_model($class_name, $arguments = array(), $load_only = false)
524
+	{
525
+		$paths = apply_filters(
526
+			'FHEE__EE_Registry__load_model__paths', array(
527
+			EE_MODELS,
528
+			EE_CORE,
529
+		)
530
+		);
531
+		// retrieve instantiated class
532
+		return $this->_load(
533
+			$paths,
534
+			'EEM_',
535
+			$class_name,
536
+			'model',
537
+			$arguments,
538
+			false,
539
+			true,
540
+			$load_only
541
+		);
542
+	}
543
+
544
+
545
+
546
+	/**
547
+	 * loads model classes - must be singletons
548
+	 *
549
+	 * @param string $class_name - simple class name ie: price
550
+	 * @param mixed  $arguments
551
+	 * @param bool   $load_only
552
+	 * @return mixed | bool
553
+	 * @throws EE_Error
554
+	 * @throws ReflectionException
555
+	 */
556
+	public function load_model_class($class_name, $arguments = array(), $load_only = true)
557
+	{
558
+		$paths = array(
559
+			EE_MODELS . 'fields' . DS,
560
+			EE_MODELS . 'helpers' . DS,
561
+			EE_MODELS . 'relations' . DS,
562
+			EE_MODELS . 'strategies' . DS,
563
+		);
564
+		// retrieve instantiated class
565
+		return $this->_load(
566
+			$paths,
567
+			'EE_',
568
+			$class_name,
569
+			'',
570
+			$arguments,
571
+			false,
572
+			true,
573
+			$load_only
574
+		);
575
+	}
576
+
577
+
578
+
579
+	/**
580
+	 * Determines if $model_name is the name of an actual EE model.
581
+	 *
582
+	 * @param string $model_name like Event, Attendee, Question_Group_Question, etc.
583
+	 * @return boolean
584
+	 */
585
+	public function is_model_name($model_name)
586
+	{
587
+		return isset($this->models[$model_name]);
588
+	}
589
+
590
+
591
+
592
+	/**
593
+	 * generic class loader
594
+	 *
595
+	 * @param string $path_to_file - directory path to file location, not including filename
596
+	 * @param string $file_name    - file name  ie:  my_file.php, including extension
597
+	 * @param string $type         - file type - core? class? helper? model?
598
+	 * @param mixed  $arguments
599
+	 * @param bool   $load_only
600
+	 * @return mixed
601
+	 * @throws EE_Error
602
+	 * @throws ReflectionException
603
+	 */
604
+	public function load_file($path_to_file, $file_name, $type = '', $arguments = array(), $load_only = true)
605
+	{
606
+		// retrieve instantiated class
607
+		return $this->_load(
608
+			$path_to_file,
609
+			'',
610
+			$file_name,
611
+			$type,
612
+			$arguments,
613
+			false,
614
+			true,
615
+			$load_only
616
+		);
617
+	}
618
+
619
+
620
+
621
+	/**
622
+	 * @param string $path_to_file - directory path to file location, not including filename
623
+	 * @param string $class_name   - full class name  ie:  My_Class
624
+	 * @param string $type         - file type - core? class? helper? model?
625
+	 * @param mixed  $arguments
626
+	 * @param bool   $load_only
627
+	 * @return bool|EE_Addon|object
628
+	 * @throws EE_Error
629
+	 * @throws ReflectionException
630
+	 */
631
+	public function load_addon($path_to_file, $class_name, $type = 'class', $arguments = array(), $load_only = false)
632
+	{
633
+		// retrieve instantiated class
634
+		return $this->_load(
635
+			$path_to_file,
636
+			'addon',
637
+			$class_name,
638
+			$type,
639
+			$arguments,
640
+			false,
641
+			true,
642
+			$load_only
643
+		);
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * instantiates, caches, and automatically resolves dependencies
650
+	 * for classes that use a Fully Qualified Class Name.
651
+	 * if the class is not capable of being loaded using PSR-4 autoloading,
652
+	 * then you need to use one of the existing load_*() methods
653
+	 * which can resolve the classname and filepath from the passed arguments
654
+	 *
655
+	 * @param bool|string $class_name   Fully Qualified Class Name
656
+	 * @param array       $arguments    an argument, or array of arguments to pass to the class upon instantiation
657
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
658
+	 * @param bool        $from_db      some classes are instantiated from the db
659
+	 *                                  and thus call a different method to instantiate
660
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
661
+	 * @param bool|string $addon        if true, will cache the object in the EE_Registry->$addons array
662
+	 * @return bool|null|mixed          null = failure to load or instantiate class object.
663
+	 *                                  object = class loaded and instantiated successfully.
664
+	 *                                  bool = fail or success when $load_only is true
665
+	 * @throws EE_Error
666
+	 * @throws ReflectionException
667
+	 */
668
+	public function create(
669
+		$class_name = false,
670
+		$arguments = array(),
671
+		$cache = false,
672
+		$from_db = false,
673
+		$load_only = false,
674
+		$addon = false
675
+	) {
676
+		$class_name = ltrim($class_name, '\\');
677
+		$class_name = $this->_dependency_map->get_alias($class_name);
678
+		$class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679
+		// if a non-FQCN was passed, then verifyClassExists() might return an object
680
+		// or it could return null if the class just could not be found anywhere
681
+		if ($class_exists instanceof $class_name || $class_exists === null){
682
+			// either way, return the results
683
+			return $class_exists;
684
+		}
685
+		$class_name = $class_exists;
686
+		// if we're only loading the class and it already exists, then let's just return true immediately
687
+		if ($load_only) {
688
+			return true;
689
+		}
690
+		$addon = $addon
691
+			? 'addon'
692
+			: '';
693
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
694
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
695
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
696
+		if ($this->_cache_on && $cache && ! $load_only) {
697
+			// return object if it's already cached
698
+			$cached_class = $this->_get_cached_class($class_name, $addon);
699
+			if ($cached_class !== null) {
700
+				return $cached_class;
701
+			}
702
+		}
703
+		// obtain the loader method from the dependency map
704
+		$loader = $this->_dependency_map->class_loader($class_name);
705
+		// instantiate the requested object
706
+		if ($loader instanceof Closure) {
707
+			$class_obj = $loader($arguments);
708
+		} else if ($loader && method_exists($this, $loader)) {
709
+			$class_obj = $this->{$loader}($class_name, $arguments);
710
+		} else {
711
+			$class_obj = $this->_create_object($class_name, $arguments, $addon, $from_db);
712
+		}
713
+		if (($this->_cache_on && $cache) || $this->get_class_abbreviation($class_name, '')) {
714
+			// save it for later... kinda like gum  { : $
715
+			$this->_set_cached_class($class_obj, $class_name, $addon, $from_db);
716
+		}
717
+		$this->_cache_on = true;
718
+		return $class_obj;
719
+	}
720
+
721
+
722
+
723
+	/**
724
+	 * Recursively checks that a class exists and potentially attempts to load classes with non-FQCNs
725
+	 *
726
+	 * @param string $class_name
727
+	 * @param array  $arguments
728
+	 * @param int    $attempt
729
+	 * @return mixed
730
+	 */
731
+	private function loadOrVerifyClassExists($class_name, array $arguments, $attempt = 1) {
732
+		if (is_object($class_name) || class_exists($class_name)) {
733
+			return $class_name;
734
+		}
735
+		switch ($attempt) {
736
+			case 1:
737
+				// if it's a FQCN then maybe the class is registered with a preceding \
738
+				$class_name = strpos($class_name, '\\') !== false
739
+					? '\\' . ltrim($class_name, '\\')
740
+					: $class_name;
741
+				break;
742
+			case 2:
743
+				//
744
+				$loader = $this->_dependency_map->class_loader($class_name);
745
+				if ($loader && method_exists($this, $loader)) {
746
+					return $this->{$loader}($class_name, $arguments);
747
+				}
748
+				break;
749
+			case 3:
750
+			default;
751
+				return null;
752
+		}
753
+		$attempt++;
754
+		return $this->loadOrVerifyClassExists($class_name, $arguments, $attempt);
755
+	}
756
+
757
+
758
+
759
+	/**
760
+	 * instantiates, caches, and injects dependencies for classes
761
+	 *
762
+	 * @param array       $file_paths   an array of paths to folders to look in
763
+	 * @param string      $class_prefix EE  or EEM or... ???
764
+	 * @param bool|string $class_name   $class name
765
+	 * @param string      $type         file type - core? class? helper? model?
766
+	 * @param mixed       $arguments    an argument or array of arguments to pass to the class upon instantiation
767
+	 * @param bool        $from_db      some classes are instantiated from the db
768
+	 *                                  and thus call a different method to instantiate
769
+	 * @param bool        $cache        whether to cache the instantiated object for reuse
770
+	 * @param bool        $load_only    if true, will only load the file, but will NOT instantiate an object
771
+	 * @return bool|null|object null = failure to load or instantiate class object.
772
+	 *                                  object = class loaded and instantiated successfully.
773
+	 *                                  bool = fail or success when $load_only is true
774
+	 * @throws EE_Error
775
+	 * @throws ReflectionException
776
+	 */
777
+	protected function _load(
778
+		$file_paths = array(),
779
+		$class_prefix = 'EE_',
780
+		$class_name = false,
781
+		$type = 'class',
782
+		$arguments = array(),
783
+		$from_db = false,
784
+		$cache = true,
785
+		$load_only = false
786
+	) {
787
+		$class_name = ltrim($class_name, '\\');
788
+		// strip php file extension
789
+		$class_name = str_replace('.php', '', trim($class_name));
790
+		// does the class have a prefix ?
791
+		if (! empty($class_prefix) && $class_prefix !== 'addon') {
792
+			// make sure $class_prefix is uppercase
793
+			$class_prefix = strtoupper(trim($class_prefix));
794
+			// add class prefix ONCE!!!
795
+			$class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
796
+		}
797
+		$class_name = $this->_dependency_map->get_alias($class_name);
798
+		$class_exists = class_exists($class_name);
799
+		// if we're only loading the class and it already exists, then let's just return true immediately
800
+		if ($load_only && $class_exists) {
801
+			return true;
802
+		}
803
+		// $this->_cache_on is toggled during the recursive loading that can occur with dependency injection
804
+		// $cache is controlled by individual calls to separate Registry loader methods like load_class()
805
+		// $load_only is also controlled by individual calls to separate Registry loader methods like load_file()
806
+		if ($this->_cache_on && $cache && ! $load_only) {
807
+			// return object if it's already cached
808
+			$cached_class = $this->_get_cached_class($class_name, $class_prefix);
809
+			if ($cached_class !== null) {
810
+				return $cached_class;
811
+			}
812
+		}
813
+		// if the class doesn't already exist.. then we need to try and find the file and load it
814
+		if (! $class_exists) {
815
+			// get full path to file
816
+			$path = $this->_resolve_path($class_name, $type, $file_paths);
817
+			// load the file
818
+			$loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819
+			// if loading failed, or we are only loading a file but NOT instantiating an object
820
+			if (! $loaded || $load_only) {
821
+				// return boolean if only loading, or null if an object was expected
822
+				return $load_only
823
+					? $loaded
824
+					: null;
825
+			}
826
+		}
827
+		// instantiate the requested object
828
+		$class_obj = $this->_create_object($class_name, $arguments, $type, $from_db);
829
+		if ($this->_cache_on && $cache) {
830
+			// save it for later... kinda like gum  { : $
831
+			$this->_set_cached_class($class_obj, $class_name, $class_prefix, $from_db);
832
+		}
833
+		$this->_cache_on = true;
834
+		return $class_obj;
835
+	}
836
+
837
+
838
+
839
+	/**
840
+	 * @param string $class_name
841
+	 * @param string $default have to specify something, but not anything that will conflict
842
+	 * @return mixed|string
843
+	 */
844
+	protected function get_class_abbreviation($class_name, $default = 'FANCY_BATMAN_PANTS')
845
+	{
846
+		return isset($this->_class_abbreviations[$class_name])
847
+			? $this->_class_abbreviations[$class_name]
848
+			: $default;
849
+	}
850
+
851
+	/**
852
+	 * attempts to find a cached version of the requested class
853
+	 * by looking in the following places:
854
+	 *        $this->{$class_abbreviation}            ie:    $this->CART
855
+	 *        $this->{$class_name}                        ie:    $this->Some_Class
856
+	 *        $this->LIB->{$class_name}                ie:    $this->LIB->Some_Class
857
+	 *        $this->addon->{$class_name}    ie:    $this->addon->Some_Addon_Class
858
+	 *
859
+	 * @param string $class_name
860
+	 * @param string $class_prefix
861
+	 * @return mixed
862
+	 */
863
+	protected function _get_cached_class($class_name, $class_prefix = '')
864
+	{
865
+		if ($class_name === 'EE_Registry') {
866
+			return $this;
867
+		}
868
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
869
+		$class_name = str_replace('\\', '_', $class_name);
870
+		// check if class has already been loaded, and return it if it has been
871
+		if (isset($this->{$class_abbreviation})) {
872
+			return $this->{$class_abbreviation};
873
+		}
874
+		if (isset ($this->{$class_name})) {
875
+			return $this->{$class_name};
876
+		}
877
+		if (isset ($this->LIB->{$class_name})) {
878
+			return $this->LIB->{$class_name};
879
+		}
880
+		if ($class_prefix === 'addon' && isset ($this->addons->{$class_name})) {
881
+			return $this->addons->{$class_name};
882
+		}
883
+		return null;
884
+	}
885
+
886
+
887
+
888
+	/**
889
+	 * removes a cached version of the requested class
890
+	 *
891
+	 * @param string  $class_name
892
+	 * @param boolean $addon
893
+	 * @return boolean
894
+	 */
895
+	public function clear_cached_class($class_name, $addon = false)
896
+	{
897
+		$class_abbreviation = $this->get_class_abbreviation($class_name);
898
+		$class_name = str_replace('\\', '_', $class_name);
899
+		// check if class has already been loaded, and return it if it has been
900
+		if (isset($this->{$class_abbreviation})) {
901
+			$this->{$class_abbreviation} = null;
902
+			return true;
903
+		}
904
+		if (isset($this->{$class_name})) {
905
+			$this->{$class_name} = null;
906
+			return true;
907
+		}
908
+		if (isset($this->LIB->{$class_name})) {
909
+			unset($this->LIB->{$class_name});
910
+			return true;
911
+		}
912
+		if ($addon && isset($this->addons->{$class_name})) {
913
+			unset($this->addons->{$class_name});
914
+			return true;
915
+		}
916
+		return false;
917
+	}
918
+
919
+
920
+
921
+	/**
922
+	 * attempts to find a full valid filepath for the requested class.
923
+	 * loops thru each of the base paths in the $file_paths array and appends : "{classname} . {file type} . php"
924
+	 * then returns that path if the target file has been found and is readable
925
+	 *
926
+	 * @param string $class_name
927
+	 * @param string $type
928
+	 * @param array  $file_paths
929
+	 * @return string | bool
930
+	 */
931
+	protected function _resolve_path($class_name, $type = '', $file_paths = array())
932
+	{
933
+		// make sure $file_paths is an array
934
+		$file_paths = is_array($file_paths)
935
+			? $file_paths
936
+			: array($file_paths);
937
+		// cycle thru paths
938
+		foreach ($file_paths as $key => $file_path) {
939
+			// convert all separators to proper DS, if no filepath, then use EE_CLASSES
940
+			$file_path = $file_path
941
+				? str_replace(array('/', '\\'), DS, $file_path)
942
+				: EE_CLASSES;
943
+			// prep file type
944
+			$type = ! empty($type)
945
+				? trim($type, '.') . '.'
946
+				: '';
947
+			// build full file path
948
+			$file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
949
+			//does the file exist and can be read ?
950
+			if (is_readable($file_paths[$key])) {
951
+				return $file_paths[$key];
952
+			}
953
+		}
954
+		return false;
955
+	}
956
+
957
+
958
+
959
+	/**
960
+	 * basically just performs a require_once()
961
+	 * but with some error handling
962
+	 *
963
+	 * @param  string $path
964
+	 * @param  string $class_name
965
+	 * @param  string $type
966
+	 * @param  array  $file_paths
967
+	 * @return bool
968
+	 * @throws EE_Error
969
+	 * @throws ReflectionException
970
+	 */
971
+	protected function _require_file($path, $class_name, $type = '', $file_paths = array())
972
+	{
973
+		// don't give up! you gotta...
974
+		try {
975
+			//does the file exist and can it be read ?
976
+			if (! $path) {
977
+				// so sorry, can't find the file
978
+				throw new EE_Error (
979
+					sprintf(
980
+						esc_html__(
981
+							'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
982
+							'event_espresso'
983
+						),
984
+						trim($type, '.'),
985
+						$class_name,
986
+						'<br />' . implode(',<br />', $file_paths)
987
+					)
988
+				);
989
+			}
990
+			// get the file
991
+			require_once($path);
992
+			// if the class isn't already declared somewhere
993
+			if (class_exists($class_name, false) === false) {
994
+				// so sorry, not a class
995
+				throw new EE_Error(
996
+					sprintf(
997
+						esc_html__('The %s file %s does not appear to contain the %s Class.', 'event_espresso'),
998
+						$type,
999
+						$path,
1000
+						$class_name
1001
+					)
1002
+				);
1003
+			}
1004
+		} catch (EE_Error $e) {
1005
+			$e->get_error();
1006
+			return false;
1007
+		}
1008
+		return true;
1009
+	}
1010
+
1011
+
1012
+
1013
+	/**
1014
+	 * _create_object
1015
+	 * Attempts to instantiate the requested class via any of the
1016
+	 * commonly used instantiation methods employed throughout EE.
1017
+	 * The priority for instantiation is as follows:
1018
+	 *        - abstract classes or any class flagged as "load only" (no instantiation occurs)
1019
+	 *        - model objects via their 'new_instance_from_db' method
1020
+	 *        - model objects via their 'new_instance' method
1021
+	 *        - "singleton" classes" via their 'instance' method
1022
+	 *    - standard instantiable classes via their __constructor
1023
+	 * Prior to instantiation, if the classname exists in the dependency_map,
1024
+	 * then the constructor for the requested class will be examined to determine
1025
+	 * if any dependencies exist, and if they can be injected.
1026
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1027
+	 *
1028
+	 * @param string $class_name
1029
+	 * @param array  $arguments
1030
+	 * @param string $type
1031
+	 * @param bool   $from_db
1032
+	 * @return null|object
1033
+	 * @throws EE_Error
1034
+	 * @throws ReflectionException
1035
+	 */
1036
+	protected function _create_object($class_name, $arguments = array(), $type = '', $from_db = false)
1037
+	{
1038
+		// create reflection
1039
+		$reflector = $this->get_ReflectionClass($class_name);
1040
+		// make sure arguments are an array
1041
+		$arguments = is_array($arguments)
1042
+			? $arguments
1043
+			: array($arguments);
1044
+		// and if arguments array is numerically and sequentially indexed, then we want it to remain as is,
1045
+		// else wrap it in an additional array so that it doesn't get split into multiple parameters
1046
+		$arguments = $this->_array_is_numerically_and_sequentially_indexed($arguments)
1047
+			? $arguments
1048
+			: array($arguments);
1049
+		// attempt to inject dependencies ?
1050
+		if ($this->_dependency_map->has($class_name)) {
1051
+			$arguments = $this->_resolve_dependencies($reflector, $class_name, $arguments);
1052
+		}
1053
+		// instantiate the class if possible
1054
+		if ($reflector->isAbstract()) {
1055
+			// nothing to instantiate, loading file was enough
1056
+			// does not throw an exception so $instantiation_mode is unused
1057
+			// $instantiation_mode = "1) no constructor abstract class";
1058
+			return true;
1059
+		}
1060
+		if (empty($arguments) && $reflector->getConstructor() === null && $reflector->isInstantiable()) {
1061
+			// no constructor = static methods only... nothing to instantiate, loading file was enough
1062
+			// $instantiation_mode = "2) no constructor but instantiable";
1063
+			return $reflector->newInstance();
1064
+		}
1065
+		if ($from_db && method_exists($class_name, 'new_instance_from_db')) {
1066
+			// $instantiation_mode = "3) new_instance_from_db()";
1067
+			return call_user_func_array(array($class_name, 'new_instance_from_db'), $arguments);
1068
+		}
1069
+		if (method_exists($class_name, 'new_instance')) {
1070
+			// $instantiation_mode = "4) new_instance()";
1071
+			return call_user_func_array(array($class_name, 'new_instance'), $arguments);
1072
+		}
1073
+		if (method_exists($class_name, 'instance')) {
1074
+			// $instantiation_mode = "5) instance()";
1075
+			return call_user_func_array(array($class_name, 'instance'), $arguments);
1076
+		}
1077
+		if ($reflector->isInstantiable()) {
1078
+			// $instantiation_mode = "6) constructor";
1079
+			return $reflector->newInstanceArgs($arguments);
1080
+		}
1081
+		// heh ? something's not right !
1082
+		throw new EE_Error(
1083
+			sprintf(
1084
+				__('The %s file %s could not be instantiated.', 'event_espresso'),
1085
+				$type,
1086
+				$class_name
1087
+			)
1088
+		);
1089
+	}
1090
+
1091
+
1092
+
1093
+	/**
1094
+	 * @see http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
1095
+	 * @param array $array
1096
+	 * @return bool
1097
+	 */
1098
+	protected function _array_is_numerically_and_sequentially_indexed(array $array)
1099
+	{
1100
+		return ! empty($array)
1101
+			? array_keys($array) === range(0, count($array) - 1)
1102
+			: true;
1103
+	}
1104
+
1105
+
1106
+
1107
+	/**
1108
+	 * getReflectionClass
1109
+	 * checks if a ReflectionClass object has already been generated for a class
1110
+	 * and returns that instead of creating a new one
1111
+	 *
1112
+	 * @param string $class_name
1113
+	 * @return ReflectionClass
1114
+	 * @throws ReflectionException
1115
+	 */
1116
+	public function get_ReflectionClass($class_name)
1117
+	{
1118
+		if (
1119
+			! isset($this->_reflectors[$class_name])
1120
+			|| ! $this->_reflectors[$class_name] instanceof ReflectionClass
1121
+		) {
1122
+			$this->_reflectors[$class_name] = new ReflectionClass($class_name);
1123
+		}
1124
+		return $this->_reflectors[$class_name];
1125
+	}
1126
+
1127
+
1128
+
1129
+	/**
1130
+	 * _resolve_dependencies
1131
+	 * examines the constructor for the requested class to determine
1132
+	 * if any dependencies exist, and if they can be injected.
1133
+	 * If so, then those classes will be added to the array of arguments passed to the constructor
1134
+	 * PLZ NOTE: this is achieved by type hinting the constructor params
1135
+	 * For example:
1136
+	 *        if attempting to load a class "Foo" with the following constructor:
1137
+	 *        __construct( Bar $bar_class, Fighter $grohl_class )
1138
+	 *        then $bar_class and $grohl_class will be added to the $arguments array,
1139
+	 *        but only IF they are NOT already present in the incoming arguments array,
1140
+	 *        and the correct classes can be loaded
1141
+	 *
1142
+	 * @param ReflectionClass $reflector
1143
+	 * @param string          $class_name
1144
+	 * @param array           $arguments
1145
+	 * @return array
1146
+	 * @throws EE_Error
1147
+	 * @throws ReflectionException
1148
+	 */
1149
+	protected function _resolve_dependencies(ReflectionClass $reflector, $class_name, $arguments = array())
1150
+	{
1151
+		// let's examine the constructor
1152
+		$constructor = $reflector->getConstructor();
1153
+		// whu? huh? nothing?
1154
+		if (! $constructor) {
1155
+			return $arguments;
1156
+		}
1157
+		// get constructor parameters
1158
+		$params = $constructor->getParameters();
1159
+		// and the keys for the incoming arguments array so that we can compare existing arguments with what is expected
1160
+		$argument_keys = array_keys($arguments);
1161
+		// now loop thru all of the constructors expected parameters
1162
+		foreach ($params as $index => $param) {
1163
+			// is this a dependency for a specific class ?
1164
+			$param_class = $param->getClass()
1165
+				? $param->getClass()->name
1166
+				: null;
1167
+			// BUT WAIT !!! This class may be an alias for something else (or getting replaced at runtime)
1168
+			$param_class = $this->_dependency_map->has_alias($param_class, $class_name)
1169
+				? $this->_dependency_map->get_alias($param_class, $class_name)
1170
+				: $param_class;
1171
+			if (
1172
+				// param is not even a class
1173
+				$param_class === null
1174
+				// and something already exists in the incoming arguments for this param
1175
+				&& array_key_exists($index, $argument_keys)
1176
+				&& array_key_exists($argument_keys[$index], $arguments)
1177
+			) {
1178
+				// so let's skip this argument and move on to the next
1179
+				continue;
1180
+			}
1181
+			if (
1182
+				// parameter is type hinted as a class, exists as an incoming argument, AND it's the correct class
1183
+				$param_class !== null
1184
+				&& isset($argument_keys[$index], $arguments[$argument_keys[$index]])
1185
+				&& $arguments[$argument_keys[$index]] instanceof $param_class
1186
+			) {
1187
+				// skip this argument and move on to the next
1188
+				continue;
1189
+			}
1190
+			if (
1191
+				// parameter is type hinted as a class, and should be injected
1192
+				$param_class !== null
1193
+				&& $this->_dependency_map->has_dependency_for_class($class_name, $param_class)
1194
+			) {
1195
+				$arguments = $this->_resolve_dependency(
1196
+					$class_name,
1197
+					$param_class,
1198
+					$arguments,
1199
+					$index,
1200
+					$argument_keys
1201
+				);
1202
+			} else {
1203
+				try {
1204
+					$arguments[$index] = $param->isDefaultValueAvailable()
1205
+						? $param->getDefaultValue()
1206
+						: null;
1207
+				} catch (ReflectionException $e) {
1208
+					throw new ReflectionException(
1209
+						sprintf(
1210
+							esc_html__('%1$s for parameter "$%2$s on classname "%3$s"', 'event_espresso'),
1211
+							$e->getMessage(),
1212
+							$param->getName(),
1213
+							$class_name
1214
+						)
1215
+					);
1216
+				}
1217
+			}
1218
+		}
1219
+		return $arguments;
1220
+	}
1221
+
1222
+
1223
+
1224
+	/**
1225
+	 * @param string $class_name
1226
+	 * @param string $param_class
1227
+	 * @param array  $arguments
1228
+	 * @param mixed  $index
1229
+	 * @param array  $argument_keys
1230
+	 * @return array
1231
+	 * @throws EE_Error
1232
+	 * @throws ReflectionException
1233
+	 * @throws InvalidArgumentException
1234
+	 * @throws InvalidInterfaceException
1235
+	 * @throws InvalidDataTypeException
1236
+	 */
1237
+	protected function _resolve_dependency($class_name, $param_class, $arguments, $index, array $argument_keys)
1238
+	{
1239
+		$dependency = null;
1240
+		// should dependency be loaded from cache ?
1241
+		$cache_on = $this->_dependency_map->loading_strategy_for_class_dependency(
1242
+			$class_name,
1243
+			$param_class
1244
+		);
1245
+		$cache_on = $cache_on !== EE_Dependency_Map::load_new_object;
1246
+		// we might have a dependency...
1247
+		// let's MAYBE try and find it in our cache if that's what's been requested
1248
+		$cached_class = $cache_on
1249
+			? $this->_get_cached_class($param_class)
1250
+			: null;
1251
+		// and grab it if it exists
1252
+		if ($cached_class instanceof $param_class) {
1253
+			$dependency = $cached_class;
1254
+		} else if ($param_class !== $class_name) {
1255
+			// obtain the loader method from the dependency map
1256
+			$loader = $this->_dependency_map->class_loader($param_class);
1257
+			// is loader a custom closure ?
1258
+			if ($loader instanceof Closure) {
1259
+				$dependency = $loader($arguments);
1260
+			} else {
1261
+				// set the cache on property for the recursive loading call
1262
+				$this->_cache_on = $cache_on;
1263
+				// if not, then let's try and load it via the registry
1264
+				if ($loader && method_exists($this, $loader)) {
1265
+					$dependency = $this->{$loader}($param_class);
1266
+				} else {
1267
+					$dependency = LoaderFactory::getLoader()->load(
1268
+						$param_class,
1269
+						array(),
1270
+						$cache_on
1271
+					);
1272
+				}
1273
+			}
1274
+		}
1275
+		// did we successfully find the correct dependency ?
1276
+		if ($dependency instanceof $param_class) {
1277
+			// then let's inject it into the incoming array of arguments at the correct location
1278
+			$arguments[$index] = $dependency;
1279
+		}
1280
+		return $arguments;
1281
+	}
1282
+
1283
+
1284
+
1285
+	/**
1286
+	 * _set_cached_class
1287
+	 * attempts to cache the instantiated class locally
1288
+	 * in one of the following places, in the following order:
1289
+	 *        $this->{class_abbreviation}   ie:    $this->CART
1290
+	 *        $this->{$class_name}          ie:    $this->Some_Class
1291
+	 *        $this->addon->{$$class_name}    ie:    $this->addon->Some_Addon_Class
1292
+	 *        $this->LIB->{$class_name}     ie:    $this->LIB->Some_Class
1293
+	 *
1294
+	 * @param object $class_obj
1295
+	 * @param string $class_name
1296
+	 * @param string $class_prefix
1297
+	 * @param bool   $from_db
1298
+	 * @return void
1299
+	 */
1300
+	protected function _set_cached_class($class_obj, $class_name, $class_prefix = '', $from_db = false)
1301
+	{
1302
+		if ($class_name === 'EE_Registry' || empty($class_obj)) {
1303
+			return;
1304
+		}
1305
+		// return newly instantiated class
1306
+		$class_abbreviation = $this->get_class_abbreviation($class_name, '');
1307
+		if ($class_abbreviation) {
1308
+			$this->{$class_abbreviation} = $class_obj;
1309
+			return;
1310
+		}
1311
+		$class_name = str_replace('\\', '_', $class_name);
1312
+		if (property_exists($this, $class_name)) {
1313
+			$this->{$class_name} = $class_obj;
1314
+			return;
1315
+		}
1316
+		if ($class_prefix === 'addon') {
1317
+			$this->addons->{$class_name} = $class_obj;
1318
+			return;
1319
+		}
1320
+		if (! $from_db) {
1321
+			$this->LIB->{$class_name} = $class_obj;
1322
+		}
1323
+	}
1324
+
1325
+
1326
+
1327
+	/**
1328
+	 * call any loader that's been registered in the EE_Dependency_Map::$_class_loaders array
1329
+	 *
1330
+	 * @param string $classname PLEASE NOTE: the class name needs to match what's registered
1331
+	 *                          in the EE_Dependency_Map::$_class_loaders array,
1332
+	 *                          including the class prefix, ie: "EE_", "EEM_", "EEH_", etc
1333
+	 * @param array  $arguments
1334
+	 * @return object
1335
+	 */
1336
+	public static function factory($classname, $arguments = array())
1337
+	{
1338
+		$loader = self::instance()->_dependency_map->class_loader($classname);
1339
+		if ($loader instanceof Closure) {
1340
+			return $loader($arguments);
1341
+		}
1342
+		if (method_exists(self::instance(), $loader)) {
1343
+			return self::instance()->{$loader}($classname, $arguments);
1344
+		}
1345
+		return null;
1346
+	}
1347
+
1348
+
1349
+
1350
+	/**
1351
+	 * Gets the addon by its name/slug (not classname. For that, just
1352
+	 * use the classname as the property name on EE_Config::instance()->addons)
1353
+	 *
1354
+	 * @param string $name
1355
+	 * @return EE_Addon
1356
+	 */
1357
+	public function get_addon_by_name($name)
1358
+	{
1359
+		foreach ($this->addons as $addon) {
1360
+			if ($addon->name() === $name) {
1361
+				return $addon;
1362
+			}
1363
+		}
1364
+		return null;
1365
+	}
1366
+
1367
+
1368
+
1369
+	/**
1370
+	 * Gets an array of all the registered addons, where the keys are their names. (ie, what each returns for their
1371
+	 * name() function) They're already available on EE_Config::instance()->addons as properties, where each property's
1372
+	 * name is the addon's classname. So if you just want to get the addon by classname, use
1373
+	 * EE_Config::instance()->addons->{classname}
1374
+	 *
1375
+	 * @return EE_Addon[] where the KEYS are the addon's name()
1376
+	 */
1377
+	public function get_addons_by_name()
1378
+	{
1379
+		$addons = array();
1380
+		foreach ($this->addons as $addon) {
1381
+			$addons[$addon->name()] = $addon;
1382
+		}
1383
+		return $addons;
1384
+	}
1385
+
1386
+
1387
+
1388
+	/**
1389
+	 * Resets the specified model's instance AND makes sure EE_Registry doesn't keep
1390
+	 * a stale copy of it around
1391
+	 *
1392
+	 * @param string $model_name
1393
+	 * @return \EEM_Base
1394
+	 * @throws \EE_Error
1395
+	 */
1396
+	public function reset_model($model_name)
1397
+	{
1398
+		$model_class_name = strpos($model_name, 'EEM_') !== 0
1399
+			? "EEM_{$model_name}"
1400
+			: $model_name;
1401
+		if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1402
+			return null;
1403
+		}
1404
+		//get that model reset it and make sure we nuke the old reference to it
1405
+		if ($this->LIB->{$model_class_name} instanceof $model_class_name
1406
+			&& is_callable(
1407
+				array($model_class_name, 'reset')
1408
+			)) {
1409
+			$this->LIB->{$model_class_name} = $this->LIB->{$model_class_name}->reset();
1410
+		} else {
1411
+			throw new EE_Error(sprintf(esc_html__('Model %s does not have a method "reset"', 'event_espresso'), $model_name));
1412
+		}
1413
+		return $this->LIB->{$model_class_name};
1414
+	}
1415
+
1416
+
1417
+
1418
+	/**
1419
+	 * Resets the registry.
1420
+	 * The criteria for what gets reset is based on what can be shared between sites on the same request when
1421
+	 * switch_to_blog is used in a multisite install.  Here is a list of things that are NOT reset.
1422
+	 * - $_dependency_map
1423
+	 * - $_class_abbreviations
1424
+	 * - $NET_CFG (EE_Network_Config): The config is shared network wide so no need to reset.
1425
+	 * - $REQ:  Still on the same request so no need to change.
1426
+	 * - $CAP: There is no site specific state in the EE_Capability class.
1427
+	 * - $SSN: Although ideally, the session should not be shared between site switches, we can't reset it because only
1428
+	 * one Session can be active in a single request.  Resetting could resolve in "headers already sent" errors.
1429
+	 * - $addons:  In multisite, the state of the addons is something controlled via hooks etc in a normal request.  So
1430
+	 *             for now, we won't reset the addons because it could break calls to an add-ons class/methods in the
1431
+	 *             switch or on the restore.
1432
+	 * - $modules
1433
+	 * - $shortcodes
1434
+	 * - $widgets
1435
+	 *
1436
+	 * @param boolean $hard             [deprecated]
1437
+	 * @param boolean $reinstantiate    whether to create new instances of EE_Registry's singletons too,
1438
+	 *                                  or just reset without re-instantiating (handy to set to FALSE if you're not
1439
+	 *                                  sure if you CAN currently reinstantiate the singletons at the moment)
1440
+	 * @param   bool  $reset_models     Defaults to true.  When false, then the models are not reset.  This is so
1441
+	 *                                  client
1442
+	 *                                  code instead can just change the model context to a different blog id if
1443
+	 *                                  necessary
1444
+	 * @return EE_Registry
1445
+	 * @throws EE_Error
1446
+	 * @throws ReflectionException
1447
+	 */
1448
+	public static function reset($hard = false, $reinstantiate = true, $reset_models = true)
1449
+	{
1450
+		$instance = self::instance();
1451
+		$instance->_cache_on = true;
1452
+		// reset some "special" classes
1453
+		EEH_Activation::reset();
1454
+		$hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1455
+		$instance->CFG = EE_Config::reset($hard, $reinstantiate);
1456
+		$instance->CART = null;
1457
+		$instance->MRM = null;
1458
+		$instance->AssetsRegistry = $instance->create('EventEspresso\core\services\assets\Registry');
1459
+		//messages reset
1460
+		EED_Messages::reset();
1461
+		//handle of objects cached on LIB
1462
+		foreach (array('LIB', 'modules') as $cache) {
1463
+			foreach ($instance->{$cache} as $class_name => $class) {
1464
+				if (self::_reset_and_unset_object($class, $reset_models)) {
1465
+					unset($instance->{$cache}->{$class_name});
1466
+				}
1467
+			}
1468
+		}
1469
+		return $instance;
1470
+	}
1471
+
1472
+
1473
+
1474
+	/**
1475
+	 * if passed object implements ResettableInterface, then call it's reset() method
1476
+	 * if passed object implements InterminableInterface, then return false,
1477
+	 * to indicate that it should NOT be cleared from the Registry cache
1478
+	 *
1479
+	 * @param      $object
1480
+	 * @param bool $reset_models
1481
+	 * @return bool returns true if cached object should be unset
1482
+	 */
1483
+	private static function _reset_and_unset_object($object, $reset_models)
1484
+	{
1485
+		if (! is_object($object)) {
1486
+			// don't unset anything that's not an object
1487
+			return false;
1488
+		}
1489
+		if ($object instanceof EED_Module) {
1490
+			$object::reset();
1491
+			// don't unset modules
1492
+			return false;
1493
+		}
1494
+		if ($object instanceof ResettableInterface) {
1495
+			if ($object instanceof EEM_Base) {
1496
+				if ($reset_models) {
1497
+					$object->reset();
1498
+					return true;
1499
+				}
1500
+				return false;
1501
+			}
1502
+			$object->reset();
1503
+			return true;
1504
+		}
1505
+		if (! $object instanceof InterminableInterface) {
1506
+			return true;
1507
+		}
1508
+		return false;
1509
+	}
1510
+
1511
+
1512
+
1513
+	/**
1514
+	 * Gets all the custom post type models defined
1515
+	 *
1516
+	 * @return array keys are model "short names" (Eg "Event") and keys are classnames (eg "EEM_Event")
1517
+	 */
1518
+	public function cpt_models()
1519
+	{
1520
+		$cpt_models = array();
1521
+		foreach ($this->non_abstract_db_models as $short_name => $classname) {
1522
+			if (is_subclass_of($classname, 'EEM_CPT_Base')) {
1523
+				$cpt_models[$short_name] = $classname;
1524
+			}
1525
+		}
1526
+		return $cpt_models;
1527
+	}
1528
+
1529
+
1530
+
1531
+	/**
1532
+	 * @return \EE_Config
1533
+	 */
1534
+	public static function CFG()
1535
+	{
1536
+		return self::instance()->CFG;
1537
+	}
1538 1538
 
1539 1539
 
1540 1540
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
     public static function instance(EE_Dependency_Map $dependency_map = null)
177 177
     {
178 178
         // check if class object is instantiated
179
-        if (! self::$_instance instanceof EE_Registry) {
179
+        if ( ! self::$_instance instanceof EE_Registry) {
180 180
             self::$_instance = new self($dependency_map);
181 181
         }
182 182
         return self::$_instance;
@@ -266,13 +266,13 @@  discard block
 block discarded – undo
266 266
      */
267 267
     public static function localize_i18n_js_strings()
268 268
     {
269
-        $i18n_js_strings = (array)self::$i18n_js_strings;
269
+        $i18n_js_strings = (array) self::$i18n_js_strings;
270 270
         foreach ($i18n_js_strings as $key => $value) {
271 271
             if (is_scalar($value)) {
272
-                $i18n_js_strings[$key] = html_entity_decode((string)$value, ENT_QUOTES, 'UTF-8');
272
+                $i18n_js_strings[$key] = html_entity_decode((string) $value, ENT_QUOTES, 'UTF-8');
273 273
             }
274 274
         }
275
-        return '/* <![CDATA[ */ var eei18n = ' . wp_json_encode($i18n_js_strings) . '; /* ]]> */';
275
+        return '/* <![CDATA[ */ var eei18n = '.wp_json_encode($i18n_js_strings).'; /* ]]> */';
276 276
     }
277 277
 
278 278
 
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
             $module_class = get_class($module);
289 289
             $this->modules->{$module_class} = $module;
290 290
         } else {
291
-            if (! class_exists('EE_Module_Request_Router')) {
291
+            if ( ! class_exists('EE_Module_Request_Router')) {
292 292
                 $this->load_core('Module_Request_Router');
293 293
             }
294 294
             EE_Module_Request_Router::module_factory($module);
@@ -328,10 +328,10 @@  discard block
 block discarded – undo
328 328
                 EE_CORE,
329 329
                 EE_ADMIN,
330 330
                 EE_CPTS,
331
-                EE_CORE . 'data_migration_scripts' . DS,
332
-                EE_CORE . 'capabilities' . DS,
333
-                EE_CORE . 'request_stack' . DS,
334
-                EE_CORE . 'middleware' . DS,
331
+                EE_CORE.'data_migration_scripts'.DS,
332
+                EE_CORE.'capabilities'.DS,
333
+                EE_CORE.'request_stack'.DS,
334
+                EE_CORE.'middleware'.DS,
335 335
             )
336 336
         );
337 337
         // retrieve instantiated class
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
         $service_paths = apply_filters(
365 365
             'FHEE__EE_Registry__load_service__service_paths',
366 366
             array(
367
-                EE_CORE . 'services' . DS,
367
+                EE_CORE.'services'.DS,
368 368
             )
369 369
         );
370 370
         // retrieve instantiated class
@@ -490,10 +490,10 @@  discard block
 block discarded – undo
490 490
     {
491 491
         $paths = array(
492 492
             EE_LIBRARIES,
493
-            EE_LIBRARIES . 'messages' . DS,
494
-            EE_LIBRARIES . 'shortcodes' . DS,
495
-            EE_LIBRARIES . 'qtips' . DS,
496
-            EE_LIBRARIES . 'payment_methods' . DS,
493
+            EE_LIBRARIES.'messages'.DS,
494
+            EE_LIBRARIES.'shortcodes'.DS,
495
+            EE_LIBRARIES.'qtips'.DS,
496
+            EE_LIBRARIES.'payment_methods'.DS,
497 497
         );
498 498
         // retrieve instantiated class
499 499
         return $this->_load(
@@ -556,10 +556,10 @@  discard block
 block discarded – undo
556 556
     public function load_model_class($class_name, $arguments = array(), $load_only = true)
557 557
     {
558 558
         $paths = array(
559
-            EE_MODELS . 'fields' . DS,
560
-            EE_MODELS . 'helpers' . DS,
561
-            EE_MODELS . 'relations' . DS,
562
-            EE_MODELS . 'strategies' . DS,
559
+            EE_MODELS.'fields'.DS,
560
+            EE_MODELS.'helpers'.DS,
561
+            EE_MODELS.'relations'.DS,
562
+            EE_MODELS.'strategies'.DS,
563 563
         );
564 564
         // retrieve instantiated class
565 565
         return $this->_load(
@@ -678,7 +678,7 @@  discard block
 block discarded – undo
678 678
         $class_exists = $this->loadOrVerifyClassExists($class_name, $arguments);
679 679
         // if a non-FQCN was passed, then verifyClassExists() might return an object
680 680
         // or it could return null if the class just could not be found anywhere
681
-        if ($class_exists instanceof $class_name || $class_exists === null){
681
+        if ($class_exists instanceof $class_name || $class_exists === null) {
682 682
             // either way, return the results
683 683
             return $class_exists;
684 684
         }
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
             case 1:
737 737
                 // if it's a FQCN then maybe the class is registered with a preceding \
738 738
                 $class_name = strpos($class_name, '\\') !== false
739
-                    ? '\\' . ltrim($class_name, '\\')
739
+                    ? '\\'.ltrim($class_name, '\\')
740 740
                     : $class_name;
741 741
                 break;
742 742
             case 2:
@@ -788,11 +788,11 @@  discard block
 block discarded – undo
788 788
         // strip php file extension
789 789
         $class_name = str_replace('.php', '', trim($class_name));
790 790
         // does the class have a prefix ?
791
-        if (! empty($class_prefix) && $class_prefix !== 'addon') {
791
+        if ( ! empty($class_prefix) && $class_prefix !== 'addon') {
792 792
             // make sure $class_prefix is uppercase
793 793
             $class_prefix = strtoupper(trim($class_prefix));
794 794
             // add class prefix ONCE!!!
795
-            $class_name = $class_prefix . str_replace($class_prefix, '', $class_name);
795
+            $class_name = $class_prefix.str_replace($class_prefix, '', $class_name);
796 796
         }
797 797
         $class_name = $this->_dependency_map->get_alias($class_name);
798 798
         $class_exists = class_exists($class_name);
@@ -811,13 +811,13 @@  discard block
 block discarded – undo
811 811
             }
812 812
         }
813 813
         // if the class doesn't already exist.. then we need to try and find the file and load it
814
-        if (! $class_exists) {
814
+        if ( ! $class_exists) {
815 815
             // get full path to file
816 816
             $path = $this->_resolve_path($class_name, $type, $file_paths);
817 817
             // load the file
818 818
             $loaded = $this->_require_file($path, $class_name, $type, $file_paths);
819 819
             // if loading failed, or we are only loading a file but NOT instantiating an object
820
-            if (! $loaded || $load_only) {
820
+            if ( ! $loaded || $load_only) {
821 821
                 // return boolean if only loading, or null if an object was expected
822 822
                 return $load_only
823 823
                     ? $loaded
@@ -942,10 +942,10 @@  discard block
 block discarded – undo
942 942
                 : EE_CLASSES;
943 943
             // prep file type
944 944
             $type = ! empty($type)
945
-                ? trim($type, '.') . '.'
945
+                ? trim($type, '.').'.'
946 946
                 : '';
947 947
             // build full file path
948
-            $file_paths[$key] = rtrim($file_path, DS) . DS . $class_name . '.' . $type . 'php';
948
+            $file_paths[$key] = rtrim($file_path, DS).DS.$class_name.'.'.$type.'php';
949 949
             //does the file exist and can be read ?
950 950
             if (is_readable($file_paths[$key])) {
951 951
                 return $file_paths[$key];
@@ -973,9 +973,9 @@  discard block
 block discarded – undo
973 973
         // don't give up! you gotta...
974 974
         try {
975 975
             //does the file exist and can it be read ?
976
-            if (! $path) {
976
+            if ( ! $path) {
977 977
                 // so sorry, can't find the file
978
-                throw new EE_Error (
978
+                throw new EE_Error(
979 979
                     sprintf(
980 980
                         esc_html__(
981 981
                             'The %1$s file %2$s could not be located or is not readable due to file permissions. Please ensure that the following filepath(s) are correct: %3$s',
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
                         ),
984 984
                         trim($type, '.'),
985 985
                         $class_name,
986
-                        '<br />' . implode(',<br />', $file_paths)
986
+                        '<br />'.implode(',<br />', $file_paths)
987 987
                     )
988 988
                 );
989 989
             }
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
         // let's examine the constructor
1152 1152
         $constructor = $reflector->getConstructor();
1153 1153
         // whu? huh? nothing?
1154
-        if (! $constructor) {
1154
+        if ( ! $constructor) {
1155 1155
             return $arguments;
1156 1156
         }
1157 1157
         // get constructor parameters
@@ -1317,7 +1317,7 @@  discard block
 block discarded – undo
1317 1317
             $this->addons->{$class_name} = $class_obj;
1318 1318
             return;
1319 1319
         }
1320
-        if (! $from_db) {
1320
+        if ( ! $from_db) {
1321 1321
             $this->LIB->{$class_name} = $class_obj;
1322 1322
         }
1323 1323
     }
@@ -1398,7 +1398,7 @@  discard block
 block discarded – undo
1398 1398
         $model_class_name = strpos($model_name, 'EEM_') !== 0
1399 1399
             ? "EEM_{$model_name}"
1400 1400
             : $model_name;
1401
-        if (! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1401
+        if ( ! isset($this->LIB->{$model_class_name}) || ! $this->LIB->{$model_class_name} instanceof EEM_Base) {
1402 1402
             return null;
1403 1403
         }
1404 1404
         //get that model reset it and make sure we nuke the old reference to it
@@ -1451,7 +1451,7 @@  discard block
 block discarded – undo
1451 1451
         $instance->_cache_on = true;
1452 1452
         // reset some "special" classes
1453 1453
         EEH_Activation::reset();
1454
-        $hard = apply_filters( 'FHEE__EE_Registry__reset__hard', $hard);
1454
+        $hard = apply_filters('FHEE__EE_Registry__reset__hard', $hard);
1455 1455
         $instance->CFG = EE_Config::reset($hard, $reinstantiate);
1456 1456
         $instance->CART = null;
1457 1457
         $instance->MRM = null;
@@ -1482,7 +1482,7 @@  discard block
 block discarded – undo
1482 1482
      */
1483 1483
     private static function _reset_and_unset_object($object, $reset_models)
1484 1484
     {
1485
-        if (! is_object($object)) {
1485
+        if ( ! is_object($object)) {
1486 1486
             // don't unset anything that's not an object
1487 1487
             return false;
1488 1488
         }
@@ -1502,7 +1502,7 @@  discard block
 block discarded – undo
1502 1502
             $object->reset();
1503 1503
             return true;
1504 1504
         }
1505
-        if (! $object instanceof InterminableInterface) {
1505
+        if ( ! $object instanceof InterminableInterface) {
1506 1506
             return true;
1507 1507
         }
1508 1508
         return false;
Please login to merge, or discard this patch.
core/helpers/EEH_Line_Item.helper.php 1 patch
Spacing   +346 added lines, -346 removed lines patch added patch discarded remove patch
@@ -1,4 +1,4 @@  discard block
 block discarded – undo
1
-<?php if (!defined('EVENT_ESPRESSO_VERSION')) { exit('No direct script access allowed'); }
1
+<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) { exit('No direct script access allowed'); }
2 2
 /**
3 3
  *
4 4
  * EEH_Line_Item
@@ -45,8 +45,8 @@  discard block
 block discarded – undo
45 45
 	 * @return boolean success
46 46
 	 * @throws \EE_Error
47 47
 	 */
48
-	public static function add_unrelated_item( EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL  ){
49
-		$items_subtotal = self::get_pre_tax_subtotal( $parent_line_item );
48
+	public static function add_unrelated_item(EE_Line_Item $parent_line_item, $name, $unit_price, $description = '', $quantity = 1, $taxable = FALSE, $code = NULL) {
49
+		$items_subtotal = self::get_pre_tax_subtotal($parent_line_item);
50 50
 		$line_item = EE_Line_Item::new_instance(array(
51 51
 			'LIN_name' => $name,
52 52
 			'LIN_desc' => $description,
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 			'LIN_quantity' => $quantity,
55 55
 			'LIN_percent' => null,
56 56
 			'LIN_is_taxable' => $taxable,
57
-			'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count( $items_subtotal->children() ) : 0,
57
+			'LIN_order' => $items_subtotal instanceof EE_Line_Item ? count($items_subtotal->children()) : 0,
58 58
 			'LIN_total' => (float) $unit_price * (int) $quantity,
59 59
 			'LIN_type'=>  EEM_Line_Item::type_line_item,
60 60
 			'LIN_code' => $code,
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
 			$line_item,
65 65
 			$parent_line_item
66 66
 		);
67
-		return self::add_item( $parent_line_item, $line_item );
67
+		return self::add_item($parent_line_item, $line_item);
68 68
 	}
69 69
 
70 70
 
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 	 * @return boolean success
87 87
 	 * @throws \EE_Error
88 88
 	 */
89
-	public static function add_percentage_based_item( EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE ){
89
+	public static function add_percentage_based_item(EE_Line_Item $parent_line_item, $name, $percentage_amount, $description = '', $taxable = FALSE) {
90 90
 		$line_item = EE_Line_Item::new_instance(array(
91 91
 			'LIN_name' => $name,
92 92
 			'LIN_desc' => $description,
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 			'LIN_percent' => $percentage_amount,
95 95
 			'LIN_quantity' => NULL,
96 96
 			'LIN_is_taxable' => $taxable,
97
-			'LIN_total' => (float) ( $percentage_amount * ( $parent_line_item->total() / 100 ) ),
97
+			'LIN_total' => (float) ($percentage_amount * ($parent_line_item->total() / 100)),
98 98
 			'LIN_type'=>  EEM_Line_Item::type_line_item,
99 99
 			'LIN_parent' => $parent_line_item->ID()
100 100
 		));
@@ -123,15 +123,15 @@  discard block
 block discarded – undo
123 123
 	 * @return \EE_Line_Item
124 124
 	 * @throws \EE_Error
125 125
 	 */
126
-	public static function add_ticket_purchase( EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1 ){
127
-		if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total() ) {
128
-			throw new EE_Error( sprintf( __( 'A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso' ), $ticket->ID(), $total_line_item->ID() ) );
126
+	public static function add_ticket_purchase(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1) {
127
+		if ( ! $total_line_item instanceof EE_Line_Item || ! $total_line_item->is_total()) {
128
+			throw new EE_Error(sprintf(__('A valid line item total is required in order to add tickets. A line item of type "%s" was passed.', 'event_espresso'), $ticket->ID(), $total_line_item->ID()));
129 129
 		}
130 130
 		// either increment the qty for an existing ticket
131
-		$line_item = self::increment_ticket_qty_if_already_in_cart( $total_line_item, $ticket, $qty );
131
+		$line_item = self::increment_ticket_qty_if_already_in_cart($total_line_item, $ticket, $qty);
132 132
 		// or add a new one
133
-		if ( ! $line_item instanceof EE_Line_Item ) {
134
-			$line_item = self::create_ticket_line_item( $total_line_item, $ticket, $qty );
133
+		if ( ! $line_item instanceof EE_Line_Item) {
134
+			$line_item = self::create_ticket_line_item($total_line_item, $ticket, $qty);
135 135
 		}
136 136
 		$total_line_item->recalculate_total_including_taxes();
137 137
 		return $line_item;
@@ -147,11 +147,11 @@  discard block
 block discarded – undo
147 147
 	 * @return \EE_Line_Item
148 148
 	 * @throws \EE_Error
149 149
 	 */
150
-	public static function increment_ticket_qty_if_already_in_cart( EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1 ) {
150
+	public static function increment_ticket_qty_if_already_in_cart(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1) {
151 151
 		$line_item = null;
152
-		if ( $total_line_item instanceof EE_Line_Item && $total_line_item->is_total() ) {
153
-			$ticket_line_items = EEH_Line_Item::get_ticket_line_items( $total_line_item );
154
-			foreach ( (array)$ticket_line_items as $ticket_line_item ) {
152
+		if ($total_line_item instanceof EE_Line_Item && $total_line_item->is_total()) {
153
+			$ticket_line_items = EEH_Line_Item::get_ticket_line_items($total_line_item);
154
+			foreach ((array) $ticket_line_items as $ticket_line_item) {
155 155
 				if (
156 156
 					$ticket_line_item instanceof EE_Line_Item
157 157
 					&& (int) $ticket_line_item->OBJ_ID() === (int) $ticket->ID()
@@ -161,8 +161,8 @@  discard block
 block discarded – undo
161 161
 				}
162 162
 			}
163 163
 		}
164
-		if ( $line_item instanceof EE_Line_Item ) {
165
-			EEH_Line_Item::increment_quantity( $line_item, $qty );
164
+		if ($line_item instanceof EE_Line_Item) {
165
+			EEH_Line_Item::increment_quantity($line_item, $qty);
166 166
 			return $line_item;
167 167
 		}
168 168
 		return null;
@@ -179,16 +179,16 @@  discard block
 block discarded – undo
179 179
 	 * @return void
180 180
 	 * @throws \EE_Error
181 181
 	 */
182
-	public static function increment_quantity( EE_Line_Item $line_item, $qty = 1 ) {
183
-		if( ! $line_item->is_percent() ) {
182
+	public static function increment_quantity(EE_Line_Item $line_item, $qty = 1) {
183
+		if ( ! $line_item->is_percent()) {
184 184
 			$qty += $line_item->quantity();
185
-			$line_item->set_quantity( $qty );
186
-			$line_item->set_total( $line_item->unit_price() * $qty );
185
+			$line_item->set_quantity($qty);
186
+			$line_item->set_total($line_item->unit_price() * $qty);
187 187
 			$line_item->save();
188 188
 		}
189
-		foreach( $line_item->children() as $child ) {
190
-			if( $child->is_sub_line_item() ) {
191
-				EEH_Line_Item::update_quantity( $child, $qty );
189
+		foreach ($line_item->children() as $child) {
190
+			if ($child->is_sub_line_item()) {
191
+				EEH_Line_Item::update_quantity($child, $qty);
192 192
 			}
193 193
 		}
194 194
 	}
@@ -204,17 +204,17 @@  discard block
 block discarded – undo
204 204
 	 * @return void
205 205
 	 * @throws \EE_Error
206 206
 	 */
207
-	public static function decrement_quantity( EE_Line_Item $line_item, $qty = 1 ) {
208
-		if( ! $line_item->is_percent() ) {
207
+	public static function decrement_quantity(EE_Line_Item $line_item, $qty = 1) {
208
+		if ( ! $line_item->is_percent()) {
209 209
 			$qty = $line_item->quantity() - $qty;
210
-			$qty = max( $qty, 0 );
211
-			$line_item->set_quantity( $qty );
212
-			$line_item->set_total( $line_item->unit_price() * $qty );
210
+			$qty = max($qty, 0);
211
+			$line_item->set_quantity($qty);
212
+			$line_item->set_total($line_item->unit_price() * $qty);
213 213
 			$line_item->save();
214 214
 		}
215
-		foreach( $line_item->children() as $child ) {
216
-			if( $child->is_sub_line_item() ) {
217
-				EEH_Line_Item::update_quantity( $child, $qty );
215
+		foreach ($line_item->children() as $child) {
216
+			if ($child->is_sub_line_item()) {
217
+				EEH_Line_Item::update_quantity($child, $qty);
218 218
 			}
219 219
 		}
220 220
 	}
@@ -229,15 +229,15 @@  discard block
 block discarded – undo
229 229
 	 * @param int          $new_quantity
230 230
 	 * @throws \EE_Error
231 231
 	 */
232
-	public static function update_quantity( EE_Line_Item $line_item, $new_quantity ) {
233
-		if( ! $line_item->is_percent() ) {
234
-			$line_item->set_quantity( $new_quantity );
235
-			$line_item->set_total( $line_item->unit_price() * $new_quantity );
232
+	public static function update_quantity(EE_Line_Item $line_item, $new_quantity) {
233
+		if ( ! $line_item->is_percent()) {
234
+			$line_item->set_quantity($new_quantity);
235
+			$line_item->set_total($line_item->unit_price() * $new_quantity);
236 236
 			$line_item->save();
237 237
 		}
238
-		foreach( $line_item->children() as $child ) {
239
-			if( $child->is_sub_line_item() ) {
240
-				EEH_Line_Item::update_quantity( $child, $new_quantity );
238
+		foreach ($line_item->children() as $child) {
239
+			if ($child->is_sub_line_item()) {
240
+				EEH_Line_Item::update_quantity($child, $new_quantity);
241 241
 			}
242 242
 		}
243 243
 	}
@@ -252,43 +252,43 @@  discard block
 block discarded – undo
252 252
 	 * @return \EE_Line_Item
253 253
 	 * @throws \EE_Error
254 254
 	 */
255
-	public static function create_ticket_line_item( EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1 ) {
255
+	public static function create_ticket_line_item(EE_Line_Item $total_line_item, EE_Ticket $ticket, $qty = 1) {
256 256
 		$datetimes = $ticket->datetimes();
257
-		$first_datetime = reset( $datetimes );
258
-		if( $first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event ) {
257
+		$first_datetime = reset($datetimes);
258
+		if ($first_datetime instanceof EE_Datetime && $first_datetime->event() instanceof EE_Event) {
259 259
 			$first_datetime_name = $first_datetime->event()->name();
260 260
 		} else {
261
-			$first_datetime_name = __( 'Event', 'event_espresso' );
261
+			$first_datetime_name = __('Event', 'event_espresso');
262 262
 		}
263
-		$event = sprintf( _x( '(For %1$s)', '(For Event Name)', 'event_espresso' ), $first_datetime_name );
263
+		$event = sprintf(_x('(For %1$s)', '(For Event Name)', 'event_espresso'), $first_datetime_name);
264 264
 		// get event subtotal line
265
-		$events_sub_total = self::get_event_line_item_for_ticket( $total_line_item, $ticket );
265
+		$events_sub_total = self::get_event_line_item_for_ticket($total_line_item, $ticket);
266 266
 		// add $ticket to cart
267
-		$line_item = EE_Line_Item::new_instance( array(
267
+		$line_item = EE_Line_Item::new_instance(array(
268 268
 			'LIN_name'       	=> $ticket->name(),
269
-			'LIN_desc'       		=> $ticket->description() !== '' ? $ticket->description() . ' ' . $event : $event,
269
+			'LIN_desc'       		=> $ticket->description() !== '' ? $ticket->description().' '.$event : $event,
270 270
 			'LIN_unit_price' 	=> $ticket->price(),
271 271
 			'LIN_quantity'   	=> $qty,
272 272
 			'LIN_is_taxable' 	=> $ticket->taxable(),
273
-			'LIN_order'      	=> count( $events_sub_total->children() ),
273
+			'LIN_order'      	=> count($events_sub_total->children()),
274 274
 			'LIN_total'      		=> $ticket->price() * $qty,
275 275
 			'LIN_type'       		=> EEM_Line_Item::type_line_item,
276 276
 			'OBJ_ID'         		=> $ticket->ID(),
277 277
 			'OBJ_type'       	=> 'Ticket'
278
-		) );
278
+		));
279 279
 		$line_item = apply_filters(
280 280
 			'FHEE__EEH_Line_Item__create_ticket_line_item__line_item',
281 281
 			$line_item
282 282
 		);
283
-		$events_sub_total->add_child_line_item( $line_item );
283
+		$events_sub_total->add_child_line_item($line_item);
284 284
 		//now add the sub-line items
285 285
 		$running_total_for_ticket = 0;
286
-		foreach ( $ticket->prices( array( 'order_by' => array( 'PRC_order' => 'ASC' ) ) ) as $price ) {
286
+		foreach ($ticket->prices(array('order_by' => array('PRC_order' => 'ASC'))) as $price) {
287 287
 			$sign = $price->is_discount() ? -1 : 1;
288 288
 			$price_total = $price->is_percent()
289 289
 				? $running_total_for_ticket * $price->amount() / 100
290 290
 				: $price->amount() * $qty;
291
-			$sub_line_item = EE_Line_Item::new_instance( array(
291
+			$sub_line_item = EE_Line_Item::new_instance(array(
292 292
 				'LIN_name'       	=> $price->name(),
293 293
 				'LIN_desc'       		=> $price->desc(),
294 294
 				'LIN_quantity'   	=> $price->is_percent() ? null : $qty,
@@ -298,18 +298,18 @@  discard block
 block discarded – undo
298 298
 				'LIN_type'       		=> EEM_Line_Item::type_sub_line_item,
299 299
 				'OBJ_ID'         		=> $price->ID(),
300 300
 				'OBJ_type'       	=> 'Price'
301
-			) );
301
+			));
302 302
 			$sub_line_item = apply_filters(
303 303
 				'FHEE__EEH_Line_Item__create_ticket_line_item__sub_line_item',
304 304
 				$sub_line_item
305 305
 			);
306
-			if ( $price->is_percent() ) {
307
-				$sub_line_item->set_percent( $sign * $price->amount() );
306
+			if ($price->is_percent()) {
307
+				$sub_line_item->set_percent($sign * $price->amount());
308 308
 			} else {
309
-				$sub_line_item->set_unit_price( $sign * $price->amount() );
309
+				$sub_line_item->set_unit_price($sign * $price->amount());
310 310
 			}
311 311
 			$running_total_for_ticket += $price_total;
312
-			$line_item->add_child_line_item( $sub_line_item );
312
+			$line_item->add_child_line_item($sub_line_item);
313 313
 		}
314 314
 		return $line_item;
315 315
 	}
@@ -329,11 +329,11 @@  discard block
 block discarded – undo
329 329
 	 * @return boolean
330 330
 	 * @throws \EE_Error
331 331
 	 */
332
-	public static function add_item( EE_Line_Item $total_line_item, EE_Line_Item $item ){
333
-		$pre_tax_subtotal = self::get_pre_tax_subtotal( $total_line_item );
334
-		if ( $pre_tax_subtotal instanceof EE_Line_Item ){
332
+	public static function add_item(EE_Line_Item $total_line_item, EE_Line_Item $item) {
333
+		$pre_tax_subtotal = self::get_pre_tax_subtotal($total_line_item);
334
+		if ($pre_tax_subtotal instanceof EE_Line_Item) {
335 335
 			$success = $pre_tax_subtotal->add_child_line_item($item);
336
-		}else{
336
+		} else {
337 337
 			return FALSE;
338 338
 		}
339 339
 		$total_line_item->recalculate_total_including_taxes();
@@ -352,34 +352,34 @@  discard block
 block discarded – undo
352 352
 	 * @return bool success
353 353
 	 * @throws \EE_Error
354 354
 	 */
355
-	public static function cancel_ticket_line_item( EE_Line_Item $ticket_line_item, $qty = 1 ) {
355
+	public static function cancel_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1) {
356 356
 		// validate incoming line_item
357
-		if ( $ticket_line_item->OBJ_type() !== 'Ticket' ) {
357
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
358 358
 			throw new EE_Error(
359 359
 				sprintf(
360
-					__( 'The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso' ),
360
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
361 361
 					$ticket_line_item->type()
362 362
 				)
363 363
 			);
364 364
 		}
365
-		if ( $ticket_line_item->quantity() < $qty ) {
365
+		if ($ticket_line_item->quantity() < $qty) {
366 366
 			throw new EE_Error(
367 367
 				sprintf(
368
-					__( 'Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso' ),
368
+					__('Can not cancel %1$d ticket(s) because the supplied line item has a quantity of %2$d.', 'event_espresso'),
369 369
 					$qty,
370 370
 					$ticket_line_item->quantity()
371 371
 				)
372 372
 			);
373 373
 		}
374 374
 		// decrement ticket quantity; don't rely on auto-fixing when recalculating totals to do this
375
-		$ticket_line_item->set_quantity( $ticket_line_item->quantity() - $qty );
376
-		foreach( $ticket_line_item->children() as $child_line_item ) {
377
-			if(
375
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() - $qty);
376
+		foreach ($ticket_line_item->children() as $child_line_item) {
377
+			if (
378 378
 				$child_line_item->is_sub_line_item()
379 379
 				&& ! $child_line_item->is_percent()
380 380
 				&& ! $child_line_item->is_cancellation()
381 381
 			) {
382
-				$child_line_item->set_quantity( $child_line_item->quantity() - $qty );
382
+				$child_line_item->set_quantity($child_line_item->quantity() - $qty);
383 383
 			}
384 384
 		}
385 385
 		// get cancellation sub line item
@@ -387,37 +387,37 @@  discard block
 block discarded – undo
387 387
 			$ticket_line_item,
388 388
 			EEM_Line_Item::type_cancellation
389 389
 		);
390
-		$cancellation_line_item = reset( $cancellation_line_item );
390
+		$cancellation_line_item = reset($cancellation_line_item);
391 391
 		// verify that this ticket was indeed previously cancelled
392
-		if ( $cancellation_line_item instanceof EE_Line_Item ) {
392
+		if ($cancellation_line_item instanceof EE_Line_Item) {
393 393
 			// increment cancelled quantity
394
-			$cancellation_line_item->set_quantity( $cancellation_line_item->quantity() + $qty );
394
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() + $qty);
395 395
 		} else {
396 396
 			// create cancellation sub line item
397
-			$cancellation_line_item = EE_Line_Item::new_instance( array(
398
-				'LIN_name'       => __( 'Cancellation', 'event_espresso' ),
397
+			$cancellation_line_item = EE_Line_Item::new_instance(array(
398
+				'LIN_name'       => __('Cancellation', 'event_espresso'),
399 399
 				'LIN_desc'       => sprintf(
400
-					_x( 'Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso' ),
400
+					_x('Cancelled %1$s : %2$s', 'Cancelled Ticket Name : 2015-01-01 11:11', 'event_espresso'),
401 401
 					$ticket_line_item->name(),
402
-					current_time( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) )
402
+					current_time(get_option('date_format').' '.get_option('time_format'))
403 403
 				),
404 404
 				'LIN_unit_price' => 0, // $ticket_line_item->unit_price()
405 405
 				'LIN_quantity'   => $qty,
406 406
 				'LIN_is_taxable' => $ticket_line_item->is_taxable(),
407
-				'LIN_order'      => count( $ticket_line_item->children() ),
407
+				'LIN_order'      => count($ticket_line_item->children()),
408 408
 				'LIN_total'      => 0, // $ticket_line_item->unit_price()
409 409
 				'LIN_type'       => EEM_Line_Item::type_cancellation,
410
-			) );
411
-			$ticket_line_item->add_child_line_item( $cancellation_line_item );
410
+			));
411
+			$ticket_line_item->add_child_line_item($cancellation_line_item);
412 412
 		}
413
-		if ( $ticket_line_item->save_this_and_descendants() > 0 ) {
413
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
414 414
 			// decrement parent line item quantity
415 415
 			$event_line_item = $ticket_line_item->parent();
416
-			if ( $event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event' ) {
417
-				$event_line_item->set_quantity( $event_line_item->quantity() - $qty );
416
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
417
+				$event_line_item->set_quantity($event_line_item->quantity() - $qty);
418 418
 				$event_line_item->save();
419 419
 			}
420
-			EEH_Line_Item::get_grand_total_and_recalculate_everything( $ticket_line_item );
420
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
421 421
 			return true;
422 422
 		}
423 423
 		return false;
@@ -435,12 +435,12 @@  discard block
 block discarded – undo
435 435
 	 * @return bool success
436 436
 	 * @throws \EE_Error
437 437
 	 */
438
-	public static function reinstate_canceled_ticket_line_item( EE_Line_Item $ticket_line_item, $qty = 1 ) {
438
+	public static function reinstate_canceled_ticket_line_item(EE_Line_Item $ticket_line_item, $qty = 1) {
439 439
 		// validate incoming line_item
440
-		if ( $ticket_line_item->OBJ_type() !== 'Ticket' ) {
440
+		if ($ticket_line_item->OBJ_type() !== 'Ticket') {
441 441
 			throw new EE_Error(
442 442
 				sprintf(
443
-					__( 'The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso' ),
443
+					__('The supplied line item must have an Object Type of "Ticket", not %1$s.', 'event_espresso'),
444 444
 					$ticket_line_item->type()
445 445
 				)
446 446
 			);
@@ -450,42 +450,42 @@  discard block
 block discarded – undo
450 450
 			$ticket_line_item,
451 451
 			EEM_Line_Item::type_cancellation
452 452
 		);
453
-		$cancellation_line_item = reset( $cancellation_line_item );
453
+		$cancellation_line_item = reset($cancellation_line_item);
454 454
 		// verify that this ticket was indeed previously cancelled
455
-		if ( ! $cancellation_line_item instanceof EE_Line_Item ) {
455
+		if ( ! $cancellation_line_item instanceof EE_Line_Item) {
456 456
 			return false;
457 457
 		}
458
-		if ( $cancellation_line_item->quantity() > $qty ) {
458
+		if ($cancellation_line_item->quantity() > $qty) {
459 459
 			// decrement cancelled quantity
460
-			$cancellation_line_item->set_quantity( $cancellation_line_item->quantity() - $qty );
461
-		} else if ( $cancellation_line_item->quantity() == $qty ) {
460
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
461
+		} else if ($cancellation_line_item->quantity() == $qty) {
462 462
 			// decrement cancelled quantity in case anyone still has the object kicking around
463
-			$cancellation_line_item->set_quantity( $cancellation_line_item->quantity() - $qty );
463
+			$cancellation_line_item->set_quantity($cancellation_line_item->quantity() - $qty);
464 464
 			// delete because quantity will end up as 0
465 465
 			$cancellation_line_item->delete();
466 466
 			// and attempt to destroy the object,
467 467
 			// even though PHP won't actually destroy it until it needs the memory
468
-			unset( $cancellation_line_item );
468
+			unset($cancellation_line_item);
469 469
 		} else {
470 470
 			// what ?!?! negative quantity ?!?!
471 471
 			throw new EE_Error(
472 472
 				sprintf(
473
-					__( 'Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
474
-						'event_espresso' ),
473
+					__('Can not reinstate %1$d cancelled ticket(s) because the cancelled ticket quantity is only %2$d.',
474
+						'event_espresso'),
475 475
 					$qty,
476 476
 					$cancellation_line_item->quantity()
477 477
 				)
478 478
 			);
479 479
 		}
480 480
 		// increment ticket quantity
481
-		$ticket_line_item->set_quantity( $ticket_line_item->quantity() + $qty );
482
-		if ( $ticket_line_item->save_this_and_descendants() > 0 ) {
481
+		$ticket_line_item->set_quantity($ticket_line_item->quantity() + $qty);
482
+		if ($ticket_line_item->save_this_and_descendants() > 0) {
483 483
 			// increment parent line item quantity
484 484
 			$event_line_item = $ticket_line_item->parent();
485
-			if ( $event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event' ) {
486
-				$event_line_item->set_quantity( $event_line_item->quantity() + $qty );
485
+			if ($event_line_item instanceof EE_Line_Item && $event_line_item->OBJ_type() === 'Event') {
486
+				$event_line_item->set_quantity($event_line_item->quantity() + $qty);
487 487
 			}
488
-			EEH_Line_Item::get_grand_total_and_recalculate_everything( $ticket_line_item );
488
+			EEH_Line_Item::get_grand_total_and_recalculate_everything($ticket_line_item);
489 489
 			return true;
490 490
 		}
491 491
 		return false;
@@ -500,8 +500,8 @@  discard block
 block discarded – undo
500 500
 	 * @param EE_Line_Item $line_item
501 501
 	 * @return \EE_Line_Item
502 502
 	 */
503
-	public static function get_grand_total_and_recalculate_everything( EE_Line_Item $line_item ){
504
-		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item( $line_item );
503
+	public static function get_grand_total_and_recalculate_everything(EE_Line_Item $line_item) {
504
+		$grand_total_line_item = EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item);
505 505
 		return $grand_total_line_item->recalculate_total_including_taxes();
506 506
 	}
507 507
 
@@ -514,11 +514,11 @@  discard block
 block discarded – undo
514 514
 	 * @return \EE_Line_Item
515 515
 	 * @throws \EE_Error
516 516
 	 */
517
-	public static function get_pre_tax_subtotal( EE_Line_Item $total_line_item ){
518
-		$pre_tax_subtotal = $total_line_item->get_child_line_item( 'pre-tax-subtotal' );
517
+	public static function get_pre_tax_subtotal(EE_Line_Item $total_line_item) {
518
+		$pre_tax_subtotal = $total_line_item->get_child_line_item('pre-tax-subtotal');
519 519
 		return $pre_tax_subtotal instanceof EE_Line_Item
520 520
 			? $pre_tax_subtotal
521
-			: self::create_pre_tax_subtotal( $total_line_item );
521
+			: self::create_pre_tax_subtotal($total_line_item);
522 522
 	}
523 523
 
524 524
 
@@ -530,9 +530,9 @@  discard block
 block discarded – undo
530 530
 	 * @return \EE_Line_Item
531 531
 	 * @throws \EE_Error
532 532
 	 */
533
-	public static function get_taxes_subtotal( EE_Line_Item $total_line_item ){
534
-		$taxes = $total_line_item->get_child_line_item( 'taxes' );
535
-		return $taxes ? $taxes : self::create_taxes_subtotal( $total_line_item );
533
+	public static function get_taxes_subtotal(EE_Line_Item $total_line_item) {
534
+		$taxes = $total_line_item->get_child_line_item('taxes');
535
+		return $taxes ? $taxes : self::create_taxes_subtotal($total_line_item);
536 536
 	}
537 537
 
538 538
 
@@ -545,12 +545,12 @@  discard block
 block discarded – undo
545 545
 	 * @return void
546 546
 	 * @throws \EE_Error
547 547
 	 */
548
-	public static function set_TXN_ID( EE_Line_Item $line_item, $transaction = NULL ){
549
-		if( $transaction ){
548
+	public static function set_TXN_ID(EE_Line_Item $line_item, $transaction = NULL) {
549
+		if ($transaction) {
550 550
 			/** @type EEM_Transaction $EEM_Transaction */
551
-			$EEM_Transaction = EE_Registry::instance()->load_model( 'Transaction' );
552
-			$TXN_ID = $EEM_Transaction->ensure_is_ID( $transaction );
553
-			$line_item->set_TXN_ID( $TXN_ID );
551
+			$EEM_Transaction = EE_Registry::instance()->load_model('Transaction');
552
+			$TXN_ID = $EEM_Transaction->ensure_is_ID($transaction);
553
+			$line_item->set_TXN_ID($TXN_ID);
554 554
 		}
555 555
 	}
556 556
 
@@ -565,8 +565,8 @@  discard block
 block discarded – undo
565 565
 	 * @return \EE_Line_Item of type total
566 566
 	 * @throws \EE_Error
567 567
 	 */
568
-	public static function create_total_line_item( $transaction = NULL ){
569
-		$total_line_item = EE_Line_Item::new_instance( array(
568
+	public static function create_total_line_item($transaction = NULL) {
569
+		$total_line_item = EE_Line_Item::new_instance(array(
570 570
 			'LIN_code'	=> 'total',
571 571
 			'LIN_name'	=> __('Grand Total', 'event_espresso'),
572 572
 			'LIN_type'	=> EEM_Line_Item::type_total,
@@ -576,9 +576,9 @@  discard block
 block discarded – undo
576 576
 			'FHEE__EEH_Line_Item__create_total_line_item__total_line_item',
577 577
 			$total_line_item
578 578
 		);
579
-		self::set_TXN_ID( $total_line_item, $transaction );
580
-		self::create_pre_tax_subtotal( $total_line_item, $transaction );
581
-		self::create_taxes_subtotal( $total_line_item, $transaction );
579
+		self::set_TXN_ID($total_line_item, $transaction);
580
+		self::create_pre_tax_subtotal($total_line_item, $transaction);
581
+		self::create_taxes_subtotal($total_line_item, $transaction);
582 582
 		return $total_line_item;
583 583
 	}
584 584
 
@@ -592,19 +592,19 @@  discard block
 block discarded – undo
592 592
 	 * @return EE_Line_Item
593 593
 	 * @throws \EE_Error
594 594
 	 */
595
-	protected static function create_pre_tax_subtotal( EE_Line_Item $total_line_item, $transaction = NULL ){
596
-		$pre_tax_line_item = EE_Line_Item::new_instance( array(
595
+	protected static function create_pre_tax_subtotal(EE_Line_Item $total_line_item, $transaction = NULL) {
596
+		$pre_tax_line_item = EE_Line_Item::new_instance(array(
597 597
 			'LIN_code' 	=> 'pre-tax-subtotal',
598
-			'LIN_name' 	=> __( 'Pre-Tax Subtotal', 'event_espresso' ),
598
+			'LIN_name' 	=> __('Pre-Tax Subtotal', 'event_espresso'),
599 599
 			'LIN_type' 	=> EEM_Line_Item::type_sub_total
600
-		) );
600
+		));
601 601
 		$pre_tax_line_item = apply_filters(
602 602
 			'FHEE__EEH_Line_Item__create_pre_tax_subtotal__pre_tax_line_item',
603 603
 			$pre_tax_line_item
604 604
 		);
605
-		self::set_TXN_ID( $pre_tax_line_item, $transaction );
606
-		$total_line_item->add_child_line_item( $pre_tax_line_item );
607
-		self::create_event_subtotal( $pre_tax_line_item, $transaction );
605
+		self::set_TXN_ID($pre_tax_line_item, $transaction);
606
+		$total_line_item->add_child_line_item($pre_tax_line_item);
607
+		self::create_event_subtotal($pre_tax_line_item, $transaction);
608 608
 		return $pre_tax_line_item;
609 609
 	}
610 610
 
@@ -619,21 +619,21 @@  discard block
 block discarded – undo
619 619
 	 * @return EE_Line_Item
620 620
 	 * @throws \EE_Error
621 621
 	 */
622
-	protected static function create_taxes_subtotal( EE_Line_Item $total_line_item, $transaction = NULL ){
622
+	protected static function create_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL) {
623 623
 		$tax_line_item = EE_Line_Item::new_instance(array(
624 624
 			'LIN_code'	=> 'taxes',
625 625
 			'LIN_name' 	=> __('Taxes', 'event_espresso'),
626 626
 			'LIN_type'	=> EEM_Line_Item::type_tax_sub_total,
627
-			'LIN_order' => 1000,//this should always come last
627
+			'LIN_order' => 1000, //this should always come last
628 628
 		));
629 629
 		$tax_line_item = apply_filters(
630 630
 			'FHEE__EEH_Line_Item__create_taxes_subtotal__tax_line_item',
631 631
 			$tax_line_item
632 632
 		);
633
-		self::set_TXN_ID( $tax_line_item, $transaction );
634
-		$total_line_item->add_child_line_item( $tax_line_item );
633
+		self::set_TXN_ID($tax_line_item, $transaction);
634
+		$total_line_item->add_child_line_item($tax_line_item);
635 635
 		//and lastly, add the actual taxes
636
-		self::apply_taxes( $total_line_item );
636
+		self::apply_taxes($total_line_item);
637 637
 		return $tax_line_item;
638 638
 	}
639 639
 
@@ -648,11 +648,11 @@  discard block
 block discarded – undo
648 648
 	 * @return EE_Line_Item
649 649
 	 * @throws \EE_Error
650 650
 	 */
651
-	public static function create_event_subtotal( EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL ){
651
+	public static function create_event_subtotal(EE_Line_Item $pre_tax_line_item, $transaction = NULL, $event = NULL) {
652 652
 		$event_line_item = EE_Line_Item::new_instance(array(
653
-			'LIN_code'	=> self::get_event_code( $event ),
654
-			'LIN_name' 	=> self::get_event_name( $event ),
655
-			'LIN_desc' 	=> self::get_event_desc( $event ),
653
+			'LIN_code'	=> self::get_event_code($event),
654
+			'LIN_name' 	=> self::get_event_name($event),
655
+			'LIN_desc' 	=> self::get_event_desc($event),
656 656
 			'LIN_type'	=> EEM_Line_Item::type_sub_total,
657 657
 			'OBJ_type' 	=> 'Event',
658 658
 			'OBJ_ID' 		=>  $event instanceof EE_Event ? $event->ID() : 0
@@ -661,8 +661,8 @@  discard block
 block discarded – undo
661 661
 			'FHEE__EEH_Line_Item__create_event_subtotal__event_line_item',
662 662
 			$event_line_item
663 663
 		);
664
-		self::set_TXN_ID( $event_line_item, $transaction );
665
-		$pre_tax_line_item->add_child_line_item( $event_line_item );
664
+		self::set_TXN_ID($event_line_item, $transaction);
665
+		$pre_tax_line_item->add_child_line_item($event_line_item);
666 666
 		return $event_line_item;
667 667
 	}
668 668
 
@@ -675,8 +675,8 @@  discard block
 block discarded – undo
675 675
 	 * @return string
676 676
 	 * @throws \EE_Error
677 677
 	 */
678
-	public static function get_event_code( $event ) {
679
-		return 'event-' . ( $event instanceof EE_Event ? $event->ID() : '0' );
678
+	public static function get_event_code($event) {
679
+		return 'event-'.($event instanceof EE_Event ? $event->ID() : '0');
680 680
 	}
681 681
 
682 682
 	/**
@@ -684,8 +684,8 @@  discard block
 block discarded – undo
684 684
 	 * @param EE_Event $event
685 685
 	 * @return string
686 686
 	 */
687
-	public static function get_event_name( $event ) {
688
-		return $event instanceof EE_Event ? $event->name() : __( 'Event', 'event_espresso' );
687
+	public static function get_event_name($event) {
688
+		return $event instanceof EE_Event ? $event->name() : __('Event', 'event_espresso');
689 689
 	}
690 690
 
691 691
 	/**
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 	 * @param EE_Event $event
694 694
 	 * @return string
695 695
 	 */
696
-	public static function get_event_desc( $event ) {
696
+	public static function get_event_desc($event) {
697 697
 		return $event instanceof EE_Event ? $event->short_description() : '';
698 698
 	}
699 699
 
@@ -707,27 +707,27 @@  discard block
 block discarded – undo
707 707
 	  * @throws \EE_Error
708 708
 	  * @return EE_Line_Item
709 709
 	  */
710
-	public static function get_event_line_item_for_ticket( EE_Line_Item $grand_total, EE_Ticket $ticket ) {
710
+	public static function get_event_line_item_for_ticket(EE_Line_Item $grand_total, EE_Ticket $ticket) {
711 711
 		$first_datetime = $ticket->first_datetime();
712
-		if ( ! $first_datetime instanceof EE_Datetime ) {
712
+		if ( ! $first_datetime instanceof EE_Datetime) {
713 713
 			throw new EE_Error(
714
-				sprintf( __( 'The supplied ticket (ID %d) has no datetimes', 'event_espresso' ), $ticket->ID() )
714
+				sprintf(__('The supplied ticket (ID %d) has no datetimes', 'event_espresso'), $ticket->ID())
715 715
 			);
716 716
 		}
717 717
 		$event = $first_datetime->event();
718
-		if ( ! $event instanceof EE_Event ) {
718
+		if ( ! $event instanceof EE_Event) {
719 719
 			throw new EE_Error(
720 720
 				sprintf(
721
-					__( 'The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso' ),
721
+					__('The supplied ticket (ID %d) has no event data associated with it.', 'event_espresso'),
722 722
 					$ticket->ID()
723 723
 				)
724 724
 			);
725 725
 		}
726
-		$events_sub_total = EEH_Line_Item::get_event_line_item( $grand_total, $event );
727
-		if ( ! $events_sub_total instanceof EE_Line_Item ) {
726
+		$events_sub_total = EEH_Line_Item::get_event_line_item($grand_total, $event);
727
+		if ( ! $events_sub_total instanceof EE_Line_Item) {
728 728
 			throw new EE_Error(
729 729
 				sprintf(
730
-					__( 'There is no events sub-total for ticket %s on total line item %d', 'event_espresso' ),
730
+					__('There is no events sub-total for ticket %s on total line item %d', 'event_espresso'),
731 731
 					$ticket->ID(),
732 732
 					$grand_total->ID()
733 733
 				)
@@ -746,31 +746,31 @@  discard block
 block discarded – undo
746 746
 	 * @return EE_Line_Item for the event subtotal which is a child of $grand_total
747 747
 	 * @throws \EE_Error
748 748
 	 */
749
-	public static function get_event_line_item( EE_Line_Item $grand_total, $event ) {
749
+	public static function get_event_line_item(EE_Line_Item $grand_total, $event) {
750 750
 		/** @type EE_Event $event */
751
-		$event = EEM_Event::instance()->ensure_is_obj( $event, true );
751
+		$event = EEM_Event::instance()->ensure_is_obj($event, true);
752 752
 		$event_line_item = NULL;
753 753
 		$found = false;
754
-		foreach ( EEH_Line_Item::get_event_subtotals( $grand_total ) as $event_line_item ) {
754
+		foreach (EEH_Line_Item::get_event_subtotals($grand_total) as $event_line_item) {
755 755
 			// default event subtotal, we should only ever find this the first time this method is called
756
-			if ( ! $event_line_item->OBJ_ID() ) {
756
+			if ( ! $event_line_item->OBJ_ID()) {
757 757
 				// let's use this! but first... set the event details
758
-				EEH_Line_Item::set_event_subtotal_details( $event_line_item, $event );
758
+				EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
759 759
 				$found = true;
760 760
 				break;
761
-			} else if ( $event_line_item->OBJ_ID() === $event->ID() ) {
761
+			} else if ($event_line_item->OBJ_ID() === $event->ID()) {
762 762
 				// found existing line item for this event in the cart, so break out of loop and use this one
763 763
 				$found = true;
764 764
 				break;
765 765
 			}
766 766
 		}
767
-		if ( ! $found ) {
767
+		if ( ! $found) {
768 768
 			//there is no event sub-total yet, so add it
769
-			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal( $grand_total );
769
+			$pre_tax_subtotal = EEH_Line_Item::get_pre_tax_subtotal($grand_total);
770 770
 			// create a new "event" subtotal below that
771
-			$event_line_item = EEH_Line_Item::create_event_subtotal( $pre_tax_subtotal, null, $event );
771
+			$event_line_item = EEH_Line_Item::create_event_subtotal($pre_tax_subtotal, null, $event);
772 772
 			// and set the event details
773
-			EEH_Line_Item::set_event_subtotal_details( $event_line_item, $event );
773
+			EEH_Line_Item::set_event_subtotal_details($event_line_item, $event);
774 774
 		}
775 775
 		return $event_line_item;
776 776
 	}
@@ -791,13 +791,13 @@  discard block
 block discarded – undo
791 791
 		EE_Event $event,
792 792
 		$transaction = null
793 793
 	) {
794
-		if ( $event instanceof EE_Event ) {
795
-			$event_line_item->set_code( self::get_event_code( $event ) );
796
-			$event_line_item->set_name( self::get_event_name( $event ) );
797
-			$event_line_item->set_desc( self::get_event_desc( $event ) );
798
-			$event_line_item->set_OBJ_ID( $event->ID() );
794
+		if ($event instanceof EE_Event) {
795
+			$event_line_item->set_code(self::get_event_code($event));
796
+			$event_line_item->set_name(self::get_event_name($event));
797
+			$event_line_item->set_desc(self::get_event_desc($event));
798
+			$event_line_item->set_OBJ_ID($event->ID());
799 799
 		}
800
-		self::set_TXN_ID( $event_line_item, $transaction );
800
+		self::set_TXN_ID($event_line_item, $transaction);
801 801
 	}
802 802
 
803 803
 
@@ -810,19 +810,19 @@  discard block
 block discarded – undo
810 810
 	 * @param EE_Line_Item $total_line_item of type EEM_Line_Item::type_total
811 811
 	 * @throws \EE_Error
812 812
 	 */
813
-	public static function apply_taxes( EE_Line_Item $total_line_item ){
813
+	public static function apply_taxes(EE_Line_Item $total_line_item) {
814 814
 		/** @type EEM_Price $EEM_Price */
815
-		$EEM_Price = EE_Registry::instance()->load_model( 'Price' );
815
+		$EEM_Price = EE_Registry::instance()->load_model('Price');
816 816
 		// get array of taxes via Price Model
817 817
 		$ordered_taxes = $EEM_Price->get_all_prices_that_are_taxes();
818
-		ksort( $ordered_taxes );
819
-		$taxes_line_item = self::get_taxes_subtotal( $total_line_item );
818
+		ksort($ordered_taxes);
819
+		$taxes_line_item = self::get_taxes_subtotal($total_line_item);
820 820
 		//just to be safe, remove its old tax line items
821 821
 		$taxes_line_item->delete_children_line_items();
822 822
 		//loop thru taxes
823
-		foreach ( $ordered_taxes as $order => $taxes ) {
824
-			foreach ( $taxes as $tax ) {
825
-				if ( $tax instanceof EE_Price ) {
823
+		foreach ($ordered_taxes as $order => $taxes) {
824
+			foreach ($taxes as $tax) {
825
+				if ($tax instanceof EE_Price) {
826 826
 					$tax_line_item = EE_Line_Item::new_instance(
827 827
 						array(
828 828
 							'LIN_name'       => $tax->name(),
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
 						'FHEE__EEH_Line_Item__apply_taxes__tax_line_item',
841 841
 						$tax_line_item
842 842
 					);
843
-					$taxes_line_item->add_child_line_item( $tax_line_item );
843
+					$taxes_line_item->add_child_line_item($tax_line_item);
844 844
 				}
845 845
 			}
846 846
 		}
@@ -857,10 +857,10 @@  discard block
 block discarded – undo
857 857
 	 * @return float
858 858
 	 * @throws \EE_Error
859 859
 	 */
860
-	public static function ensure_taxes_applied( $total_line_item ){
861
-		$taxes_subtotal = self::get_taxes_subtotal( $total_line_item );
862
-		if( ! $taxes_subtotal->children()){
863
-			self::apply_taxes( $total_line_item );
860
+	public static function ensure_taxes_applied($total_line_item) {
861
+		$taxes_subtotal = self::get_taxes_subtotal($total_line_item);
862
+		if ( ! $taxes_subtotal->children()) {
863
+			self::apply_taxes($total_line_item);
864 864
 		}
865 865
 		return $taxes_subtotal->total();
866 866
 	}
@@ -874,16 +874,16 @@  discard block
 block discarded – undo
874 874
 	 * @return bool
875 875
 	 * @throws \EE_Error
876 876
 	 */
877
-	public static function delete_all_child_items( EE_Line_Item $parent_line_item ) {
877
+	public static function delete_all_child_items(EE_Line_Item $parent_line_item) {
878 878
 		$deleted = 0;
879
-		foreach ( $parent_line_item->children() as $child_line_item ) {
880
-			if ( $child_line_item instanceof EE_Line_Item ) {
881
-				$deleted += EEH_Line_Item::delete_all_child_items( $child_line_item );
882
-				if ( $child_line_item->ID() ) {
879
+		foreach ($parent_line_item->children() as $child_line_item) {
880
+			if ($child_line_item instanceof EE_Line_Item) {
881
+				$deleted += EEH_Line_Item::delete_all_child_items($child_line_item);
882
+				if ($child_line_item->ID()) {
883 883
 					$child_line_item->delete();
884
-					unset( $child_line_item );
884
+					unset($child_line_item);
885 885
 				} else {
886
-					$parent_line_item->delete_child_line_item( $child_line_item->code() );
886
+					$parent_line_item->delete_child_line_item($child_line_item->code());
887 887
 				}
888 888
 				$deleted++;
889 889
 			}
@@ -905,9 +905,9 @@  discard block
 block discarded – undo
905 905
 	 * @param array|bool|string $line_item_codes
906 906
 	 * @return int number of items successfully removed
907 907
 	 */
908
-	public static function delete_items( EE_Line_Item $total_line_item, $line_item_codes = FALSE ) {
908
+	public static function delete_items(EE_Line_Item $total_line_item, $line_item_codes = FALSE) {
909 909
 
910
-		if( $total_line_item->type() !== EEM_Line_Item::type_total ){
910
+		if ($total_line_item->type() !== EEM_Line_Item::type_total) {
911 911
 			EE_Error::doing_it_wrong(
912 912
 				'EEH_Line_Item::delete_items',
913 913
 				__(
@@ -917,20 +917,20 @@  discard block
 block discarded – undo
917 917
 				'4.6.18'
918 918
 			);
919 919
 		}
920
-		do_action( 'AHEE_log', __FILE__, __FUNCTION__, '' );
920
+		do_action('AHEE_log', __FILE__, __FUNCTION__, '');
921 921
 
922 922
 		// check if only a single line_item_id was passed
923
-		if ( ! empty( $line_item_codes ) && ! is_array( $line_item_codes )) {
923
+		if ( ! empty($line_item_codes) && ! is_array($line_item_codes)) {
924 924
 			// place single line_item_id in an array to appear as multiple line_item_ids
925
-			$line_item_codes = array ( $line_item_codes );
925
+			$line_item_codes = array($line_item_codes);
926 926
 		}
927 927
 		$removals = 0;
928 928
 		// cycle thru line_item_ids
929
-		foreach ( $line_item_codes as $line_item_id ) {
929
+		foreach ($line_item_codes as $line_item_id) {
930 930
 			$removals += $total_line_item->delete_child_line_item($line_item_id);
931 931
 		}
932 932
 
933
-		if ( $removals > 0 ) {
933
+		if ($removals > 0) {
934 934
 			$total_line_item->recalculate_taxes_and_tax_total();
935 935
 			return $removals;
936 936
 		} else {
@@ -963,33 +963,33 @@  discard block
 block discarded – undo
963 963
 		$code = null,
964 964
 		$add_to_existing_line_item = false
965 965
 	) {
966
-		$tax_subtotal = self::get_taxes_subtotal( $total_line_item );
966
+		$tax_subtotal = self::get_taxes_subtotal($total_line_item);
967 967
             $taxable_total = $total_line_item->taxable_total();
968 968
 
969
-            if( $add_to_existing_line_item ) {
970
-                $new_tax = $tax_subtotal->get_child_line_item( $code );
969
+            if ($add_to_existing_line_item) {
970
+                $new_tax = $tax_subtotal->get_child_line_item($code);
971 971
 	            EEM_Line_Item::instance()->delete(
972
-		            array( array( 'LIN_code' => array( '!=', $code ), 'LIN_parent' => $tax_subtotal->ID() ) )
972
+		            array(array('LIN_code' => array('!=', $code), 'LIN_parent' => $tax_subtotal->ID()))
973 973
 	            );
974 974
             } else {
975 975
                 $new_tax = null;
976 976
                 $tax_subtotal->delete_children_line_items();
977 977
             }
978
-            if( $new_tax ) {
979
-                $new_tax->set_total( $new_tax->total() + $amount );
980
-                $new_tax->set_percent( $taxable_total ? $new_tax->total() / $taxable_total * 100 : 0 );
978
+            if ($new_tax) {
979
+                $new_tax->set_total($new_tax->total() + $amount);
980
+                $new_tax->set_percent($taxable_total ? $new_tax->total() / $taxable_total * 100 : 0);
981 981
             } else {
982 982
                 //no existing tax item. Create it
983
-				$new_tax = EE_Line_Item::new_instance( array(
983
+				$new_tax = EE_Line_Item::new_instance(array(
984 984
 					'TXN_ID'      => $total_line_item->TXN_ID(),
985
-					'LIN_name'    => $name ? $name : __( 'Tax', 'event_espresso' ),
985
+					'LIN_name'    => $name ? $name : __('Tax', 'event_espresso'),
986 986
 					'LIN_desc'    => $description ? $description : '',
987
-					'LIN_percent' => $taxable_total ? ( $amount / $taxable_total * 100 ) : 0,
987
+					'LIN_percent' => $taxable_total ? ($amount / $taxable_total * 100) : 0,
988 988
 					'LIN_total'   => $amount,
989 989
 					'LIN_parent'  => $tax_subtotal->ID(),
990 990
 					'LIN_type'    => EEM_Line_Item::type_tax,
991 991
 					'LIN_code'    => $code
992
-				) );
992
+				));
993 993
 			}
994 994
 
995 995
             $new_tax = apply_filters(
@@ -998,7 +998,7 @@  discard block
 block discarded – undo
998 998
 				$total_line_item
999 999
             );
1000 1000
             $new_tax->save();
1001
-            $tax_subtotal->set_total( $new_tax->total() );
1001
+            $tax_subtotal->set_total($new_tax->total());
1002 1002
             $tax_subtotal->save();
1003 1003
             $total_line_item->recalculate_total_including_taxes();
1004 1004
             return $new_tax;
@@ -1020,14 +1020,14 @@  discard block
 block discarded – undo
1020 1020
 		$code_substring_for_whitelist = null
1021 1021
 	) {
1022 1022
 		$whitelisted = false;
1023
-		if( $code_substring_for_whitelist !== null ) {
1024
-			$whitelisted = strpos( $line_item->code(), $code_substring_for_whitelist ) !== false ? true : false;
1023
+		if ($code_substring_for_whitelist !== null) {
1024
+			$whitelisted = strpos($line_item->code(), $code_substring_for_whitelist) !== false ? true : false;
1025 1025
 		}
1026
-		if( ! $whitelisted && $line_item->is_line_item() ) {
1027
-			$line_item->set_is_taxable( $taxable );
1026
+		if ( ! $whitelisted && $line_item->is_line_item()) {
1027
+			$line_item->set_is_taxable($taxable);
1028 1028
 		}
1029
-		foreach( $line_item->children() as $child_line_item ) {
1030
-			EEH_Line_Item::set_line_items_taxable( $child_line_item, $taxable, $code_substring_for_whitelist );
1029
+		foreach ($line_item->children() as $child_line_item) {
1030
+			EEH_Line_Item::set_line_items_taxable($child_line_item, $taxable, $code_substring_for_whitelist);
1031 1031
 		}
1032 1032
 	}
1033 1033
 
@@ -1040,8 +1040,8 @@  discard block
 block discarded – undo
1040 1040
 	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1041 1041
 	 * @return EE_Line_Item[]
1042 1042
 	 */
1043
-	public static function get_event_subtotals( EE_Line_Item $parent_line_item ) {
1044
-		return self::get_subtotals_of_object_type( $parent_line_item, 'Event' );
1043
+	public static function get_event_subtotals(EE_Line_Item $parent_line_item) {
1044
+		return self::get_subtotals_of_object_type($parent_line_item, 'Event');
1045 1045
 	}
1046 1046
 
1047 1047
 
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
 	 * @param string $obj_type
1055 1055
 	 * @return EE_Line_Item[]
1056 1056
 	 */
1057
-	public static function get_subtotals_of_object_type( EE_Line_Item $parent_line_item, $obj_type = '' ) {
1057
+	public static function get_subtotals_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '') {
1058 1058
 		return self::_get_descendants_by_type_and_object_type(
1059 1059
 			$parent_line_item,
1060 1060
 			EEM_Line_Item::type_sub_total,
@@ -1071,8 +1071,8 @@  discard block
 block discarded – undo
1071 1071
 	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1072 1072
 	 * @return EE_Line_Item[]
1073 1073
 	 */
1074
-	public static function get_ticket_line_items( EE_Line_Item $parent_line_item ) {
1075
-		return self::get_line_items_of_object_type( $parent_line_item, 'Ticket' );
1074
+	public static function get_ticket_line_items(EE_Line_Item $parent_line_item) {
1075
+		return self::get_line_items_of_object_type($parent_line_item, 'Ticket');
1076 1076
 	}
1077 1077
 
1078 1078
 
@@ -1085,8 +1085,8 @@  discard block
 block discarded – undo
1085 1085
 	 * @param string $obj_type
1086 1086
 	 * @return EE_Line_Item[]
1087 1087
 	 */
1088
-	public static function get_line_items_of_object_type( EE_Line_Item $parent_line_item, $obj_type = '' ) {
1089
-		return self::_get_descendants_by_type_and_object_type( $parent_line_item, EEM_Line_Item::type_line_item, $obj_type );
1088
+	public static function get_line_items_of_object_type(EE_Line_Item $parent_line_item, $obj_type = '') {
1089
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, EEM_Line_Item::type_line_item, $obj_type);
1090 1090
 	}
1091 1091
 
1092 1092
 
@@ -1097,8 +1097,8 @@  discard block
 block discarded – undo
1097 1097
 	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1098 1098
 	 * @return EE_Line_Item[]
1099 1099
 	 */
1100
-	public static function get_tax_descendants( EE_Line_Item $parent_line_item ) {
1101
-		return EEH_Line_Item::get_descendants_of_type( $parent_line_item, EEM_Line_Item::type_tax );
1100
+	public static function get_tax_descendants(EE_Line_Item $parent_line_item) {
1101
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_tax);
1102 1102
 	}
1103 1103
 
1104 1104
 
@@ -1109,8 +1109,8 @@  discard block
 block discarded – undo
1109 1109
 	 * @param \EE_Line_Item $parent_line_item - the line item to find descendants of
1110 1110
 	 * @return EE_Line_Item[]
1111 1111
 	 */
1112
-	public static function get_line_item_descendants( EE_Line_Item $parent_line_item ) {
1113
-		return EEH_Line_Item::get_descendants_of_type( $parent_line_item, EEM_Line_Item::type_line_item );
1112
+	public static function get_line_item_descendants(EE_Line_Item $parent_line_item) {
1113
+		return EEH_Line_Item::get_descendants_of_type($parent_line_item, EEM_Line_Item::type_line_item);
1114 1114
 	}
1115 1115
 
1116 1116
 
@@ -1123,8 +1123,8 @@  discard block
 block discarded – undo
1123 1123
 	 * @param string $line_item_type one of the EEM_Line_Item constants
1124 1124
 	 * @return EE_Line_Item[]
1125 1125
 	 */
1126
-	public static function get_descendants_of_type( EE_Line_Item $parent_line_item, $line_item_type ) {
1127
-		return self::_get_descendants_by_type_and_object_type( $parent_line_item, $line_item_type, NULL );
1126
+	public static function get_descendants_of_type(EE_Line_Item $parent_line_item, $line_item_type) {
1127
+		return self::_get_descendants_by_type_and_object_type($parent_line_item, $line_item_type, NULL);
1128 1128
 	}
1129 1129
 
1130 1130
 
@@ -1143,8 +1143,8 @@  discard block
 block discarded – undo
1143 1143
 		$obj_type = null
1144 1144
 	) {
1145 1145
 		$objects = array();
1146
-		foreach ( $parent_line_item->children() as $child_line_item ) {
1147
-			if ( $child_line_item instanceof EE_Line_Item ) {
1146
+		foreach ($parent_line_item->children() as $child_line_item) {
1147
+			if ($child_line_item instanceof EE_Line_Item) {
1148 1148
 				if (
1149 1149
 					$child_line_item->type() === $line_item_type
1150 1150
 				    && (
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
 		$OBJ_type = '',
1185 1185
 		$OBJ_IDs = array()
1186 1186
 	) {
1187
-		return self::_get_descendants_by_object_type_and_object_ID( $parent_line_item, $OBJ_type, $OBJ_IDs );
1187
+		return self::_get_descendants_by_object_type_and_object_ID($parent_line_item, $OBJ_type, $OBJ_IDs);
1188 1188
 	}
1189 1189
 
1190 1190
 
@@ -1203,12 +1203,12 @@  discard block
 block discarded – undo
1203 1203
 		$OBJ_IDs
1204 1204
 	) {
1205 1205
 		$objects = array();
1206
-		foreach ( $parent_line_item->children() as $child_line_item ) {
1207
-			if ( $child_line_item instanceof EE_Line_Item ) {
1206
+		foreach ($parent_line_item->children() as $child_line_item) {
1207
+			if ($child_line_item instanceof EE_Line_Item) {
1208 1208
 				if (
1209 1209
 					$child_line_item->OBJ_type() === $OBJ_type
1210
-					&& is_array( $OBJ_IDs )
1211
-					&& in_array( $child_line_item->OBJ_ID(), $OBJ_IDs )
1210
+					&& is_array($OBJ_IDs)
1211
+					&& in_array($child_line_item->OBJ_ID(), $OBJ_IDs)
1212 1212
 				) {
1213 1213
 					$objects[] = $child_line_item;
1214 1214
 				} else {
@@ -1238,8 +1238,8 @@  discard block
 block discarded – undo
1238 1238
 	 * @param string $type like one of the EEM_Line_Item::type_*
1239 1239
 	 * @return EE_Line_Item
1240 1240
 	 */
1241
-	public static function get_nearest_descendant_of_type( EE_Line_Item $parent_line_item, $type ) {
1242
-		return self::_get_nearest_descendant( $parent_line_item, 'LIN_type' , $type );
1241
+	public static function get_nearest_descendant_of_type(EE_Line_Item $parent_line_item, $type) {
1242
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_type', $type);
1243 1243
 	}
1244 1244
 
1245 1245
 
@@ -1253,8 +1253,8 @@  discard block
 block discarded – undo
1253 1253
 	 * @param string $code any value used for LIN_code
1254 1254
 	 * @return EE_Line_Item
1255 1255
 	 */
1256
-	public static function get_nearest_descendant_having_code( EE_Line_Item $parent_line_item, $code ) {
1257
-		return self::_get_nearest_descendant( $parent_line_item, 'LIN_code' , $code );
1256
+	public static function get_nearest_descendant_having_code(EE_Line_Item $parent_line_item, $code) {
1257
+		return self::_get_nearest_descendant($parent_line_item, 'LIN_code', $code);
1258 1258
 	}
1259 1259
 
1260 1260
 
@@ -1268,15 +1268,15 @@  discard block
 block discarded – undo
1268 1268
 	 * @param string $value any value stored in $search_field
1269 1269
 	 * @return EE_Line_Item
1270 1270
 	 */
1271
-	protected static function _get_nearest_descendant( EE_Line_Item $parent_line_item, $search_field, $value ) {
1272
-		foreach( $parent_line_item->children() as $child ){
1273
-			if ( $child->get( $search_field ) == $value ){
1271
+	protected static function _get_nearest_descendant(EE_Line_Item $parent_line_item, $search_field, $value) {
1272
+		foreach ($parent_line_item->children() as $child) {
1273
+			if ($child->get($search_field) == $value) {
1274 1274
 				return $child;
1275 1275
 			}
1276 1276
 		}
1277
-		foreach( $parent_line_item->children() as $child ){
1278
-			$descendant_found = self::_get_nearest_descendant( $child, $search_field, $value );
1279
-			if ( $descendant_found ){
1277
+		foreach ($parent_line_item->children() as $child) {
1278
+			$descendant_found = self::_get_nearest_descendant($child, $search_field, $value);
1279
+			if ($descendant_found) {
1280 1280
 				return $descendant_found;
1281 1281
 			}
1282 1282
 		}
@@ -1293,24 +1293,24 @@  discard block
 block discarded – undo
1293 1293
 	 * @return \EE_Line_Item
1294 1294
 	 * @throws \EE_Error
1295 1295
 	 */
1296
-	public static function find_transaction_grand_total_for_line_item( EE_Line_Item $line_item ){
1297
-		if ( $line_item->TXN_ID() ) {
1298
-			$total_line_item = $line_item->transaction()->total_line_item( false );
1299
-			if ( $total_line_item instanceof EE_Line_Item ) {
1296
+	public static function find_transaction_grand_total_for_line_item(EE_Line_Item $line_item) {
1297
+		if ($line_item->TXN_ID()) {
1298
+			$total_line_item = $line_item->transaction()->total_line_item(false);
1299
+			if ($total_line_item instanceof EE_Line_Item) {
1300 1300
 				return $total_line_item;
1301 1301
 			}
1302 1302
 		} else {
1303 1303
 			$line_item_parent = $line_item->parent();
1304
-			if ( $line_item_parent instanceof EE_Line_Item ) {
1305
-				if ( $line_item_parent->is_total() ) {
1304
+			if ($line_item_parent instanceof EE_Line_Item) {
1305
+				if ($line_item_parent->is_total()) {
1306 1306
 					return $line_item_parent;
1307 1307
 				}
1308
-				return EEH_Line_Item::find_transaction_grand_total_for_line_item( $line_item_parent );
1308
+				return EEH_Line_Item::find_transaction_grand_total_for_line_item($line_item_parent);
1309 1309
 			}
1310 1310
 		}
1311 1311
 		throw new EE_Error(
1312 1312
 			sprintf(
1313
-				__( 'A valid grand total for line item %1$d was not found.', 'event_espresso' ),
1313
+				__('A valid grand total for line item %1$d was not found.', 'event_espresso'),
1314 1314
 				$line_item->ID()
1315 1315
 			)
1316 1316
 		);
@@ -1327,31 +1327,31 @@  discard block
 block discarded – undo
1327 1327
 	 * @return void
1328 1328
 	 * @throws \EE_Error
1329 1329
 	 */
1330
-	public static function visualize( EE_Line_Item $line_item, $indentation = 0 ){
1330
+	public static function visualize(EE_Line_Item $line_item, $indentation = 0) {
1331 1331
 		echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1332
-		if ( ! $indentation ) {
1333
-			echo defined( 'EE_TESTS_DIR' ) ? "\n" : '<br />';
1332
+		if ( ! $indentation) {
1333
+			echo defined('EE_TESTS_DIR') ? "\n" : '<br />';
1334 1334
 		}
1335
-		for( $i = 0; $i < $indentation; $i++ ){
1335
+		for ($i = 0; $i < $indentation; $i++) {
1336 1336
 			echo ". ";
1337 1337
 		}
1338 1338
 		$breakdown = '';
1339
-		if ( $line_item->is_line_item()){
1340
-			if ( $line_item->is_percent() ) {
1339
+		if ($line_item->is_line_item()) {
1340
+			if ($line_item->is_percent()) {
1341 1341
 				$breakdown = "{$line_item->percent()}%";
1342 1342
 			} else {
1343
-				$breakdown = '$' . "{$line_item->unit_price()} x {$line_item->quantity()}";
1343
+				$breakdown = '$'."{$line_item->unit_price()} x {$line_item->quantity()}";
1344 1344
 			}
1345 1345
 		}
1346
-		echo $line_item->name() . " [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : " . '$' . "{$line_item->total()}";
1347
-		if ( $breakdown ) {
1346
+		echo $line_item->name()." [ ID:{$line_item->ID()} | qty:{$line_item->quantity()} ] {$line_item->type()} : ".'$'."{$line_item->total()}";
1347
+		if ($breakdown) {
1348 1348
 			echo " ( {$breakdown} )";
1349 1349
 		}
1350
-		if( $line_item->is_taxable() ){
1350
+		if ($line_item->is_taxable()) {
1351 1351
 			echo "  * taxable";
1352 1352
 		}
1353
-		if( $line_item->children() ){
1354
-			foreach($line_item->children() as $child){
1353
+		if ($line_item->children()) {
1354
+			foreach ($line_item->children() as $child) {
1355 1355
 				self::visualize($child, $indentation + 1);
1356 1356
 			}
1357 1357
 		}
@@ -1392,97 +1392,97 @@  discard block
 block discarded – undo
1392 1392
 	 *                                          is theirs, which can be done with
1393 1393
 	 *                                          `EEM_Line_Item::instance()->get_line_item_for_registration( $registration );`
1394 1394
 	 */
1395
-	public static function calculate_reg_final_prices_per_line_item( EE_Line_Item $line_item, $billable_ticket_quantities = array() ) {
1395
+	public static function calculate_reg_final_prices_per_line_item(EE_Line_Item $line_item, $billable_ticket_quantities = array()) {
1396 1396
 		//init running grand total if not already
1397
-		if ( ! isset( $running_totals[ 'total' ] ) ) {
1398
-			$running_totals[ 'total' ] = 0;
1397
+		if ( ! isset($running_totals['total'])) {
1398
+			$running_totals['total'] = 0;
1399 1399
 		}
1400
-		if( ! isset( $running_totals[ 'taxable' ] ) ) {
1401
-			$running_totals[ 'taxable' ] = array( 'total' => 0 );
1400
+		if ( ! isset($running_totals['taxable'])) {
1401
+			$running_totals['taxable'] = array('total' => 0);
1402 1402
 		}
1403
-		foreach ( $line_item->children() as $child_line_item ) {
1404
-			switch ( $child_line_item->type() ) {
1403
+		foreach ($line_item->children() as $child_line_item) {
1404
+			switch ($child_line_item->type()) {
1405 1405
 
1406 1406
 				case EEM_Line_Item::type_sub_total :
1407
-					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item( $child_line_item, $billable_ticket_quantities );
1407
+					$running_totals_from_subtotal = EEH_Line_Item::calculate_reg_final_prices_per_line_item($child_line_item, $billable_ticket_quantities);
1408 1408
 					//combine arrays but preserve numeric keys
1409
-					$running_totals = array_replace_recursive( $running_totals_from_subtotal, $running_totals );
1410
-					$running_totals[ 'total' ] += $running_totals_from_subtotal[ 'total' ];
1411
-					$running_totals[ 'taxable'][ 'total' ] += $running_totals_from_subtotal[ 'taxable' ][ 'total' ];
1409
+					$running_totals = array_replace_recursive($running_totals_from_subtotal, $running_totals);
1410
+					$running_totals['total'] += $running_totals_from_subtotal['total'];
1411
+					$running_totals['taxable']['total'] += $running_totals_from_subtotal['taxable']['total'];
1412 1412
 					break;
1413 1413
 
1414 1414
 				case EEM_Line_Item::type_tax_sub_total :
1415 1415
 
1416 1416
 					//find how much the taxes percentage is
1417
-					if ( $child_line_item->percent() !== 0 ) {
1417
+					if ($child_line_item->percent() !== 0) {
1418 1418
 						$tax_percent_decimal = $child_line_item->percent() / 100;
1419 1419
 					} else {
1420 1420
 						$tax_percent_decimal = EE_Taxes::get_total_taxes_percentage() / 100;
1421 1421
 					}
1422 1422
 					//and apply to all the taxable totals, and add to the pretax totals
1423
-					foreach ( $running_totals as $line_item_id => $this_running_total ) {
1423
+					foreach ($running_totals as $line_item_id => $this_running_total) {
1424 1424
 						//"total" and "taxable" array key is an exception
1425
-						if ( $line_item_id === 'taxable' ) {
1425
+						if ($line_item_id === 'taxable') {
1426 1426
 							continue;
1427 1427
 						}
1428
-						$taxable_total = $running_totals[ 'taxable' ][ $line_item_id ];
1429
-						$running_totals[ $line_item_id ] += ( $taxable_total * $tax_percent_decimal );
1428
+						$taxable_total = $running_totals['taxable'][$line_item_id];
1429
+						$running_totals[$line_item_id] += ($taxable_total * $tax_percent_decimal);
1430 1430
 					}
1431 1431
 					break;
1432 1432
 
1433 1433
 				case EEM_Line_Item::type_line_item :
1434 1434
 
1435 1435
 					// ticket line items or ????
1436
-					if ( $child_line_item->OBJ_type() === 'Ticket' ) {
1436
+					if ($child_line_item->OBJ_type() === 'Ticket') {
1437 1437
 						// kk it's a ticket
1438
-						if ( isset( $running_totals[ $child_line_item->ID() ] ) ) {
1438
+						if (isset($running_totals[$child_line_item->ID()])) {
1439 1439
 							//huh? that shouldn't happen.
1440
-							$running_totals[ 'total' ] += $child_line_item->total();
1440
+							$running_totals['total'] += $child_line_item->total();
1441 1441
 						} else {
1442 1442
 							//its not in our running totals yet. great.
1443
-							if ( $child_line_item->is_taxable() ) {
1443
+							if ($child_line_item->is_taxable()) {
1444 1444
 								$taxable_amount = $child_line_item->unit_price();
1445 1445
 							} else {
1446 1446
 								$taxable_amount = 0;
1447 1447
 							}
1448 1448
 							// are we only calculating totals for some tickets?
1449
-							if ( isset( $billable_ticket_quantities[ $child_line_item->OBJ_ID() ] ) ) {
1450
-								$quantity = $billable_ticket_quantities[ $child_line_item->OBJ_ID() ];
1451
-								$running_totals[ $child_line_item->ID() ] = $quantity
1449
+							if (isset($billable_ticket_quantities[$child_line_item->OBJ_ID()])) {
1450
+								$quantity = $billable_ticket_quantities[$child_line_item->OBJ_ID()];
1451
+								$running_totals[$child_line_item->ID()] = $quantity
1452 1452
 									? $child_line_item->unit_price()
1453 1453
 									: 0;
1454
-								$running_totals[ 'taxable' ][ $child_line_item->ID() ] = $quantity
1454
+								$running_totals['taxable'][$child_line_item->ID()] = $quantity
1455 1455
 									? $taxable_amount
1456 1456
 									: 0;
1457 1457
 							} else {
1458 1458
 								$quantity = $child_line_item->quantity();
1459
-								$running_totals[ $child_line_item->ID() ] = $child_line_item->unit_price();
1460
-								$running_totals[ 'taxable' ][ $child_line_item->ID() ] = $taxable_amount;
1459
+								$running_totals[$child_line_item->ID()] = $child_line_item->unit_price();
1460
+								$running_totals['taxable'][$child_line_item->ID()] = $taxable_amount;
1461 1461
 							}
1462
-							$running_totals[ 'taxable' ][ 'total' ] += $taxable_amount * $quantity;
1463
-							$running_totals[ 'total' ] += $child_line_item->unit_price() * $quantity;
1462
+							$running_totals['taxable']['total'] += $taxable_amount * $quantity;
1463
+							$running_totals['total'] += $child_line_item->unit_price() * $quantity;
1464 1464
 						}
1465 1465
 					} else {
1466 1466
 						// it's some other type of item added to the cart
1467 1467
 						// it should affect the running totals
1468 1468
 						// basically we want to convert it into a PERCENT modifier. Because
1469 1469
 						// more clearly affect all registration's final price equally
1470
-						$line_items_percent_of_running_total = $running_totals[ 'total' ] > 0
1471
-							? ( $child_line_item->total() / $running_totals[ 'total' ] ) + 1
1470
+						$line_items_percent_of_running_total = $running_totals['total'] > 0
1471
+							? ($child_line_item->total() / $running_totals['total']) + 1
1472 1472
 							: 1;
1473
-						foreach ( $running_totals as $line_item_id => $this_running_total ) {
1473
+						foreach ($running_totals as $line_item_id => $this_running_total) {
1474 1474
 							//the "taxable" array key is an exception
1475
-							if ( $line_item_id === 'taxable' ) {
1475
+							if ($line_item_id === 'taxable') {
1476 1476
 								continue;
1477 1477
 							}
1478 1478
 							// update the running totals
1479 1479
 							// yes this actually even works for the running grand total!
1480
-							$running_totals[ $line_item_id ] =
1480
+							$running_totals[$line_item_id] =
1481 1481
 								$line_items_percent_of_running_total * $this_running_total;
1482 1482
 
1483
-							if ( $child_line_item->is_taxable() ) {
1484
-								$running_totals[ 'taxable' ][ $line_item_id ] =
1485
-									$line_items_percent_of_running_total * $running_totals[ 'taxable' ][ $line_item_id ];
1483
+							if ($child_line_item->is_taxable()) {
1484
+								$running_totals['taxable'][$line_item_id] =
1485
+									$line_items_percent_of_running_total * $running_totals['taxable'][$line_item_id];
1486 1486
 							}
1487 1487
 						}
1488 1488
 					}
@@ -1500,16 +1500,16 @@  discard block
 block discarded – undo
1500 1500
 	 * @return float | null
1501 1501
 	 * @throws \OutOfRangeException
1502 1502
 	 */
1503
-	public static function calculate_final_price_for_ticket_line_item( \EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item ) {
1503
+	public static function calculate_final_price_for_ticket_line_item(\EE_Line_Item $total_line_item, \EE_Line_Item $ticket_line_item) {
1504 1504
 		static $final_prices_per_ticket_line_item = array();
1505
-		if ( empty( $final_prices_per_ticket_line_item ) ) {
1505
+		if (empty($final_prices_per_ticket_line_item)) {
1506 1506
 			$final_prices_per_ticket_line_item = \EEH_Line_Item::calculate_reg_final_prices_per_line_item(
1507 1507
 				$total_line_item
1508 1508
 			);
1509 1509
 		}
1510 1510
 		//ok now find this new registration's final price
1511
-		if ( isset( $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ] ) ) {
1512
-			return $final_prices_per_ticket_line_item[ $ticket_line_item->ID() ];
1511
+		if (isset($final_prices_per_ticket_line_item[$ticket_line_item->ID()])) {
1512
+			return $final_prices_per_ticket_line_item[$ticket_line_item->ID()];
1513 1513
 		}
1514 1514
 		$message = sprintf(
1515 1515
 			__(
@@ -1518,11 +1518,11 @@  discard block
 block discarded – undo
1518 1518
 			),
1519 1519
 			$ticket_line_item->ID()
1520 1520
 		);
1521
-		if ( WP_DEBUG ) {
1522
-			$message .= '<br>' . print_r( $final_prices_per_ticket_line_item, true );
1523
-			throw new \OutOfRangeException( $message );
1521
+		if (WP_DEBUG) {
1522
+			$message .= '<br>'.print_r($final_prices_per_ticket_line_item, true);
1523
+			throw new \OutOfRangeException($message);
1524 1524
 		} else {
1525
-			EE_Log::instance()->log( __CLASS__, __FUNCTION__, $message );
1525
+			EE_Log::instance()->log(__CLASS__, __FUNCTION__, $message);
1526 1526
 		}
1527 1527
 		return null;
1528 1528
 	}
@@ -1538,15 +1538,15 @@  discard block
 block discarded – undo
1538 1538
 	 * @return \EE_Line_Item
1539 1539
 	 * @throws \EE_Error
1540 1540
 	 */
1541
-	public static function billable_line_item_tree( EE_Line_Item $line_item, $registrations ) {
1542
-		$copy_li = EEH_Line_Item::billable_line_item( $line_item, $registrations );
1543
-		foreach ( $line_item->children() as $child_li ) {
1544
-			$copy_li->add_child_line_item( EEH_Line_Item::billable_line_item_tree( $child_li, $registrations ) );
1541
+	public static function billable_line_item_tree(EE_Line_Item $line_item, $registrations) {
1542
+		$copy_li = EEH_Line_Item::billable_line_item($line_item, $registrations);
1543
+		foreach ($line_item->children() as $child_li) {
1544
+			$copy_li->add_child_line_item(EEH_Line_Item::billable_line_item_tree($child_li, $registrations));
1545 1545
 		}
1546 1546
 		//if this is the grand total line item, make sure the totals all add up
1547 1547
 		//(we could have duplicated this logic AS we copied the line items, but
1548 1548
 		//it seems DRYer this way)
1549
-		if ( $copy_li->type() === EEM_Line_Item::type_total ) {
1549
+		if ($copy_li->type() === EEM_Line_Item::type_total) {
1550 1550
 			$copy_li->recalculate_total_including_taxes();
1551 1551
 		}
1552 1552
 		return $copy_li;
@@ -1563,24 +1563,24 @@  discard block
 block discarded – undo
1563 1563
 	 * @throws \EE_Error
1564 1564
 	 * @param EE_Registration[] $registrations
1565 1565
 	 */
1566
-	public static function billable_line_item( EE_Line_Item $line_item, $registrations ) {
1566
+	public static function billable_line_item(EE_Line_Item $line_item, $registrations) {
1567 1567
 		$new_li_fields = $line_item->model_field_array();
1568
-		if ( $line_item->type() === EEM_Line_Item::type_line_item &&
1568
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1569 1569
 			$line_item->OBJ_type() === 'Ticket'
1570 1570
 		) {
1571 1571
 			$count = 0;
1572
-			foreach ( $registrations as $registration ) {
1573
-				if ( $line_item->OBJ_ID() === $registration->ticket_ID() &&
1574
-					in_array( $registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment() )
1572
+			foreach ($registrations as $registration) {
1573
+				if ($line_item->OBJ_ID() === $registration->ticket_ID() &&
1574
+					in_array($registration->status_ID(), EEM_Registration::reg_statuses_that_allow_payment())
1575 1575
 				) {
1576 1576
 					$count++;
1577 1577
 				}
1578 1578
 			}
1579
-			$new_li_fields[ 'LIN_quantity' ] = $count;
1579
+			$new_li_fields['LIN_quantity'] = $count;
1580 1580
 		}
1581 1581
 		//don't set the total. We'll leave that up to the code that calculates it
1582
-		unset( $new_li_fields[ 'LIN_ID' ], $new_li_fields[ 'LIN_parent' ], $new_li_fields[ 'LIN_total' ] );
1583
-		return EE_Line_Item::new_instance( $new_li_fields );
1582
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent'], $new_li_fields['LIN_total']);
1583
+		return EE_Line_Item::new_instance($new_li_fields);
1584 1584
 	}
1585 1585
 
1586 1586
 
@@ -1593,19 +1593,19 @@  discard block
 block discarded – undo
1593 1593
 	 * @return \EE_Line_Item|null
1594 1594
 	 * @throws \EE_Error
1595 1595
 	 */
1596
-	public static function non_empty_line_items( EE_Line_Item $line_item ) {
1597
-		$copied_li = EEH_Line_Item::non_empty_line_item( $line_item );
1598
-		if ( $copied_li === null ) {
1596
+	public static function non_empty_line_items(EE_Line_Item $line_item) {
1597
+		$copied_li = EEH_Line_Item::non_empty_line_item($line_item);
1598
+		if ($copied_li === null) {
1599 1599
 			return null;
1600 1600
 		}
1601 1601
 		//if this is an event subtotal, we want to only include it if it
1602 1602
 		//has a non-zero total and at least one ticket line item child
1603 1603
 		$ticket_children = 0;
1604
-		foreach ( $line_item->children() as $child_li ) {
1605
-			$child_li_copy = EEH_Line_Item::non_empty_line_items( $child_li );
1606
-			if ( $child_li_copy !== null ) {
1607
-				$copied_li->add_child_line_item( $child_li_copy );
1608
-				if ( $child_li_copy->type() === EEM_Line_Item::type_line_item &&
1604
+		foreach ($line_item->children() as $child_li) {
1605
+			$child_li_copy = EEH_Line_Item::non_empty_line_items($child_li);
1606
+			if ($child_li_copy !== null) {
1607
+				$copied_li->add_child_line_item($child_li_copy);
1608
+				if ($child_li_copy->type() === EEM_Line_Item::type_line_item &&
1609 1609
 					$child_li_copy->OBJ_type() === 'Ticket'
1610 1610
 				) {
1611 1611
 					$ticket_children++;
@@ -1635,8 +1635,8 @@  discard block
 block discarded – undo
1635 1635
 	 * @return EE_Line_Item
1636 1636
 	 * @throws \EE_Error
1637 1637
 	 */
1638
-	public static function non_empty_line_item( EE_Line_Item $line_item ) {
1639
-		if ( $line_item->type() === EEM_Line_Item::type_line_item &&
1638
+	public static function non_empty_line_item(EE_Line_Item $line_item) {
1639
+		if ($line_item->type() === EEM_Line_Item::type_line_item &&
1640 1640
 			$line_item->OBJ_type() === 'Ticket' &&
1641 1641
 			$line_item->quantity() === 0
1642 1642
 		) {
@@ -1644,8 +1644,8 @@  discard block
 block discarded – undo
1644 1644
 		}
1645 1645
 		$new_li_fields = $line_item->model_field_array();
1646 1646
 		//don't set the total. We'll leave that up to the code that calculates it
1647
-		unset( $new_li_fields[ 'LIN_ID' ], $new_li_fields[ 'LIN_parent' ] );
1648
-		return EE_Line_Item::new_instance( $new_li_fields );
1647
+		unset($new_li_fields['LIN_ID'], $new_li_fields['LIN_parent']);
1648
+		return EE_Line_Item::new_instance($new_li_fields);
1649 1649
 	}
1650 1650
 
1651 1651
 
@@ -1657,9 +1657,9 @@  discard block
 block discarded – undo
1657 1657
 	 * @return \EE_Line_Item
1658 1658
 	 * @throws \EE_Error
1659 1659
 	 */
1660
-	public static function get_items_subtotal( EE_Line_Item $total_line_item ){
1661
-		EE_Error::doing_it_wrong( 'EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0' );
1662
-		return self::get_pre_tax_subtotal( $total_line_item );
1660
+	public static function get_items_subtotal(EE_Line_Item $total_line_item) {
1661
+		EE_Error::doing_it_wrong('EEH_Line_Item::get_items_subtotal()', __('Method replaced with EEH_Line_Item::get_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1662
+		return self::get_pre_tax_subtotal($total_line_item);
1663 1663
 	}
1664 1664
 
1665 1665
 
@@ -1670,9 +1670,9 @@  discard block
 block discarded – undo
1670 1670
 	 * @return \EE_Line_Item
1671 1671
 	 * @throws \EE_Error
1672 1672
 	 */
1673
-	public static function create_default_total_line_item( $transaction = NULL) {
1674
-		EE_Error::doing_it_wrong( 'EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0' );
1675
-		return self::create_total_line_item( $transaction );
1673
+	public static function create_default_total_line_item($transaction = NULL) {
1674
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_total_line_item()', __('Method replaced with EEH_Line_Item::create_total_line_item()', 'event_espresso'), '4.6.0');
1675
+		return self::create_total_line_item($transaction);
1676 1676
 	}
1677 1677
 
1678 1678
 
@@ -1684,9 +1684,9 @@  discard block
 block discarded – undo
1684 1684
 	 * @return \EE_Line_Item
1685 1685
 	 * @throws \EE_Error
1686 1686
 	 */
1687
-	public static function create_default_tickets_subtotal( EE_Line_Item $total_line_item, $transaction = NULL) {
1688
-		EE_Error::doing_it_wrong( 'EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0' );
1689
-		return self::create_pre_tax_subtotal( $total_line_item, $transaction );
1687
+	public static function create_default_tickets_subtotal(EE_Line_Item $total_line_item, $transaction = NULL) {
1688
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_tickets_subtotal()', __('Method replaced with EEH_Line_Item::create_pre_tax_subtotal()', 'event_espresso'), '4.6.0');
1689
+		return self::create_pre_tax_subtotal($total_line_item, $transaction);
1690 1690
 	}
1691 1691
 
1692 1692
 
@@ -1698,9 +1698,9 @@  discard block
 block discarded – undo
1698 1698
 	 * @return \EE_Line_Item
1699 1699
 	 * @throws \EE_Error
1700 1700
 	 */
1701
-	public static function create_default_taxes_subtotal( EE_Line_Item $total_line_item, $transaction = NULL) {
1702
-		EE_Error::doing_it_wrong( 'EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0' );
1703
-		return self::create_taxes_subtotal( $total_line_item, $transaction );
1701
+	public static function create_default_taxes_subtotal(EE_Line_Item $total_line_item, $transaction = NULL) {
1702
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_taxes_subtotal()', __('Method replaced with EEH_Line_Item::create_taxes_subtotal()', 'event_espresso'), '4.6.0');
1703
+		return self::create_taxes_subtotal($total_line_item, $transaction);
1704 1704
 	}
1705 1705
 
1706 1706
 
@@ -1712,9 +1712,9 @@  discard block
 block discarded – undo
1712 1712
 	 * @return \EE_Line_Item
1713 1713
 	 * @throws \EE_Error
1714 1714
 	 */
1715
-	public static function create_default_event_subtotal( EE_Line_Item $total_line_item, $transaction = NULL) {
1716
-		EE_Error::doing_it_wrong( 'EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0' );
1717
-		return self::create_event_subtotal( $total_line_item, $transaction );
1715
+	public static function create_default_event_subtotal(EE_Line_Item $total_line_item, $transaction = NULL) {
1716
+		EE_Error::doing_it_wrong('EEH_Line_Item::create_default_event_subtotal()', __('Method replaced with EEH_Line_Item::create_event_subtotal()', 'event_espresso'), '4.6.0');
1717
+		return self::create_event_subtotal($total_line_item, $transaction);
1718 1718
 	}
1719 1719
 
1720 1720
 
Please login to merge, or discard this patch.
core/EE_Dependency_Map.core.php 2 patches
Indentation   +789 added lines, -789 removed lines patch added patch discarded remove patch
@@ -5,7 +5,7 @@  discard block
 block discarded – undo
5 5
 use EventEspresso\core\services\loaders\LoaderInterface;
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
 
@@ -22,794 +22,794 @@  discard block
 block discarded – undo
22 22
 class EE_Dependency_Map
23 23
 {
24 24
 
25
-    /**
26
-     * This means that the requested class dependency is not present in the dependency map
27
-     */
28
-    const not_registered = 0;
29
-
30
-    /**
31
-     * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
-     */
33
-    const load_new_object = 1;
34
-
35
-    /**
36
-     * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
-     * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
-     */
39
-    const load_from_cache = 2;
40
-
41
-    /**
42
-     * When registering a dependency,
43
-     * this indicates to keep any existing dependencies that already exist,
44
-     * and simply discard any new dependencies declared in the incoming data
45
-     */
46
-    const KEEP_EXISTING_DEPENDENCIES = 0;
47
-
48
-    /**
49
-     * When registering a dependency,
50
-     * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
-     */
52
-    const OVERWRITE_DEPENDENCIES = 1;
53
-
54
-
55
-
56
-    /**
57
-     * @type EE_Dependency_Map $_instance
58
-     */
59
-    protected static $_instance;
60
-
61
-    /**
62
-     * @type EE_Request $request
63
-     */
64
-    protected $_request;
65
-
66
-    /**
67
-     * @type EE_Response $response
68
-     */
69
-    protected $_response;
70
-
71
-    /**
72
-     * @type LoaderInterface $loader
73
-     */
74
-    protected $loader;
75
-
76
-    /**
77
-     * @type array $_dependency_map
78
-     */
79
-    protected $_dependency_map = array();
80
-
81
-    /**
82
-     * @type array $_class_loaders
83
-     */
84
-    protected $_class_loaders = array();
85
-
86
-    /**
87
-     * @type array $_aliases
88
-     */
89
-    protected $_aliases = array();
90
-
91
-
92
-
93
-    /**
94
-     * EE_Dependency_Map constructor.
95
-     *
96
-     * @param EE_Request  $request
97
-     * @param EE_Response $response
98
-     */
99
-    protected function __construct(EE_Request $request, EE_Response $response)
100
-    {
101
-        $this->_request = $request;
102
-        $this->_response = $response;
103
-        add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
-        do_action('EE_Dependency_Map____construct');
105
-    }
106
-
107
-
108
-
109
-    /**
110
-     * @throws InvalidDataTypeException
111
-     * @throws InvalidInterfaceException
112
-     * @throws InvalidArgumentException
113
-     */
114
-    public function initialize()
115
-    {
116
-        $this->_register_core_dependencies();
117
-        $this->_register_core_class_loaders();
118
-        $this->_register_core_aliases();
119
-    }
120
-
121
-
122
-
123
-    /**
124
-     * @singleton method used to instantiate class object
125
-     * @access    public
126
-     * @param EE_Request  $request
127
-     * @param EE_Response $response
128
-     * @return EE_Dependency_Map
129
-     */
130
-    public static function instance(EE_Request $request = null, EE_Response $response = null)
131
-    {
132
-        // check if class object is instantiated, and instantiated properly
133
-        if (! self::$_instance instanceof EE_Dependency_Map) {
134
-            self::$_instance = new EE_Dependency_Map($request, $response);
135
-        }
136
-        return self::$_instance;
137
-    }
138
-
139
-
140
-
141
-    /**
142
-     * @param LoaderInterface $loader
143
-     */
144
-    public function setLoader(LoaderInterface $loader)
145
-    {
146
-        $this->loader = $loader;
147
-    }
148
-
149
-
150
-
151
-    /**
152
-     * @param string $class
153
-     * @param array  $dependencies
154
-     * @param int    $overwrite
155
-     * @return bool
156
-     */
157
-    public static function register_dependencies(
158
-        $class,
159
-        array $dependencies,
160
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
-    ) {
162
-        return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
-    }
164
-
165
-
166
-
167
-    /**
168
-     * Assigns an array of class names and corresponding load sources (new or cached)
169
-     * to the class specified by the first parameter.
170
-     * IMPORTANT !!!
171
-     * The order of elements in the incoming $dependencies array MUST match
172
-     * the order of the constructor parameters for the class in question.
173
-     * This is especially important when overriding any existing dependencies that are registered.
174
-     * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
-     *
176
-     * @param string $class
177
-     * @param array  $dependencies
178
-     * @param int    $overwrite
179
-     * @return bool
180
-     */
181
-    public function registerDependencies(
182
-        $class,
183
-        array $dependencies,
184
-        $overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
-    ) {
186
-        $class = trim($class, '\\');
187
-        $registered = false;
188
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
189
-            self::$_instance->_dependency_map[ $class ] = array();
190
-        }
191
-        // we need to make sure that any aliases used when registering a dependency
192
-        // get resolved to the correct class name
193
-        foreach ((array)$dependencies as $dependency => $load_source) {
194
-            $alias = self::$_instance->get_alias($dependency);
195
-            if (
196
-                $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
-            ) {
199
-                unset($dependencies[$dependency]);
200
-                $dependencies[$alias] = $load_source;
201
-                $registered = true;
202
-            }
203
-        }
204
-        // now add our two lists of dependencies together.
205
-        // using Union (+=) favours the arrays in precedence from left to right,
206
-        // so $dependencies is NOT overwritten because it is listed first
207
-        // ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
-        // Union is way faster than array_merge() but should be used with caution...
209
-        // especially with numerically indexed arrays
210
-        $dependencies += self::$_instance->_dependency_map[ $class ];
211
-        // now we need to ensure that the resulting dependencies
212
-        // array only has the entries that are required for the class
213
-        // so first count how many dependencies were originally registered for the class
214
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
-        // if that count is non-zero (meaning dependencies were already registered)
216
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
217
-            // then truncate the  final array to match that count
218
-            ? array_slice($dependencies, 0, $dependency_count)
219
-            // otherwise just take the incoming array because nothing previously existed
220
-            : $dependencies;
221
-        return $registered;
222
-    }
223
-
224
-
225
-
226
-    /**
227
-     * @param string $class_name
228
-     * @param string $loader
229
-     * @return bool
230
-     * @throws DomainException
231
-     */
232
-    public static function register_class_loader($class_name, $loader = 'load_core')
233
-    {
234
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
-            throw new DomainException(
236
-                esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
-            );
238
-        }
239
-        // check that loader is callable or method starts with "load_" and exists in EE_Registry
240
-        if (
241
-            ! is_callable($loader)
242
-            && (
243
-                strpos($loader, 'load_') !== 0
244
-                || ! method_exists('EE_Registry', $loader)
245
-            )
246
-        ) {
247
-            throw new DomainException(
248
-                sprintf(
249
-                    esc_html__(
250
-                        '"%1$s" is not a valid loader method on EE_Registry.',
251
-                        'event_espresso'
252
-                    ),
253
-                    $loader
254
-                )
255
-            );
256
-        }
257
-        $class_name = self::$_instance->get_alias($class_name);
258
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
-            self::$_instance->_class_loaders[$class_name] = $loader;
260
-            return true;
261
-        }
262
-        return false;
263
-    }
264
-
265
-
266
-
267
-    /**
268
-     * @return array
269
-     */
270
-    public function dependency_map()
271
-    {
272
-        return $this->_dependency_map;
273
-    }
274
-
275
-
276
-
277
-    /**
278
-     * returns TRUE if dependency map contains a listing for the provided class name
279
-     *
280
-     * @param string $class_name
281
-     * @return boolean
282
-     */
283
-    public function has($class_name = '')
284
-    {
285
-        // all legacy models have the same dependencies
286
-        if (strpos($class_name, 'EEM_') === 0) {
287
-            $class_name = 'LEGACY_MODELS';
288
-        }
289
-        return isset($this->_dependency_map[$class_name]) ? true : false;
290
-    }
291
-
292
-
293
-
294
-    /**
295
-     * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
-     *
297
-     * @param string $class_name
298
-     * @param string $dependency
299
-     * @return bool
300
-     */
301
-    public function has_dependency_for_class($class_name = '', $dependency = '')
302
-    {
303
-        // all legacy models have the same dependencies
304
-        if (strpos($class_name, 'EEM_') === 0) {
305
-            $class_name = 'LEGACY_MODELS';
306
-        }
307
-        $dependency = $this->get_alias($dependency);
308
-        return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
-            ? true
310
-            : false;
311
-    }
312
-
313
-
314
-
315
-    /**
316
-     * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
-     *
318
-     * @param string $class_name
319
-     * @param string $dependency
320
-     * @return int
321
-     */
322
-    public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
-    {
324
-        // all legacy models have the same dependencies
325
-        if (strpos($class_name, 'EEM_') === 0) {
326
-            $class_name = 'LEGACY_MODELS';
327
-        }
328
-        $dependency = $this->get_alias($dependency);
329
-        return $this->has_dependency_for_class($class_name, $dependency)
330
-            ? $this->_dependency_map[$class_name][$dependency]
331
-            : EE_Dependency_Map::not_registered;
332
-    }
333
-
334
-
335
-
336
-    /**
337
-     * @param string $class_name
338
-     * @return string | Closure
339
-     */
340
-    public function class_loader($class_name)
341
-    {
342
-        // all legacy models use load_model()
343
-        if(strpos($class_name, 'EEM_') === 0){
344
-            return 'load_model';
345
-        }
346
-        $class_name = $this->get_alias($class_name);
347
-        return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
-    }
349
-
350
-
351
-
352
-    /**
353
-     * @return array
354
-     */
355
-    public function class_loaders()
356
-    {
357
-        return $this->_class_loaders;
358
-    }
359
-
360
-
361
-
362
-    /**
363
-     * adds an alias for a classname
364
-     *
365
-     * @param string $class_name the class name that should be used (concrete class to replace interface)
366
-     * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
-     * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
-     */
369
-    public function add_alias($class_name, $alias, $for_class = '')
370
-    {
371
-        if ($for_class !== '') {
372
-            if (! isset($this->_aliases[$for_class])) {
373
-                $this->_aliases[$for_class] = array();
374
-            }
375
-            $this->_aliases[$for_class][$class_name] = $alias;
376
-        }
377
-        $this->_aliases[$class_name] = $alias;
378
-    }
379
-
380
-
381
-
382
-    /**
383
-     * returns TRUE if the provided class name has an alias
384
-     *
385
-     * @param string $class_name
386
-     * @param string $for_class
387
-     * @return bool
388
-     */
389
-    public function has_alias($class_name = '', $for_class = '')
390
-    {
391
-        return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
-               || (
393
-                   isset($this->_aliases[$class_name])
394
-                   && ! is_array($this->_aliases[$class_name])
395
-               );
396
-    }
397
-
398
-
399
-
400
-    /**
401
-     * returns alias for class name if one exists, otherwise returns the original classname
402
-     * functions recursively, so that multiple aliases can be used to drill down to a classname
403
-     *  for example:
404
-     *      if the following two entries were added to the _aliases array:
405
-     *          array(
406
-     *              'interface_alias'           => 'some\namespace\interface'
407
-     *              'some\namespace\interface'  => 'some\namespace\classname'
408
-     *          )
409
-     *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
-     *      to load an instance of 'some\namespace\classname'
411
-     *
412
-     * @param string $class_name
413
-     * @param string $for_class
414
-     * @return string
415
-     */
416
-    public function get_alias($class_name = '', $for_class = '')
417
-    {
418
-        if (! $this->has_alias($class_name, $for_class)) {
419
-            return $class_name;
420
-        }
421
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
-            return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
-        }
424
-        return $this->get_alias($this->_aliases[$class_name]);
425
-    }
426
-
427
-
428
-
429
-    /**
430
-     * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
-     * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
-     * This is done by using the following class constants:
433
-     *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
-     *        EE_Dependency_Map::load_new_object - generates a new object every time
435
-     */
436
-    protected function _register_core_dependencies()
437
-    {
438
-        $this->_dependency_map = array(
439
-            'EE_Request_Handler'                                                                                          => array(
440
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
441
-            ),
442
-            'EE_System'                                                                                                   => array(
443
-                'EE_Registry'                                => EE_Dependency_Map::load_from_cache,
444
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
445
-                'EE_Capabilities'                            => EE_Dependency_Map::load_from_cache,
446
-                'EE_Request'                                 => EE_Dependency_Map::load_from_cache,
447
-                'EE_Maintenance_Mode'                        => EE_Dependency_Map::load_from_cache,
448
-            ),
449
-            'EE_Session'                                                                                                  => array(
450
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
451
-                'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
452
-            ),
453
-            'EE_Cart'                                                                                                     => array(
454
-                'EE_Session' => EE_Dependency_Map::load_from_cache,
455
-            ),
456
-            'EE_Front_Controller'                                                                                         => array(
457
-                'EE_Registry'              => EE_Dependency_Map::load_from_cache,
458
-                'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
459
-                'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
460
-            ),
461
-            'EE_Messenger_Collection_Loader'                                                                              => array(
462
-                'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
463
-            ),
464
-            'EE_Message_Type_Collection_Loader'                                                                           => array(
465
-                'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
466
-            ),
467
-            'EE_Message_Resource_Manager'                                                                                 => array(
468
-                'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
469
-                'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
470
-                'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
471
-            ),
472
-            'EE_Message_Factory'                                                                                          => array(
473
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
474
-            ),
475
-            'EE_messages'                                                                                                 => array(
476
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
477
-            ),
478
-            'EE_Messages_Generator'                                                                                       => array(
479
-                'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
480
-                'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
481
-                'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
482
-                'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
483
-            ),
484
-            'EE_Messages_Processor'                                                                                       => array(
485
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
486
-            ),
487
-            'EE_Messages_Queue'                                                                                           => array(
488
-                'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
489
-            ),
490
-            'EE_Messages_Template_Defaults'                                                                               => array(
491
-                'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
492
-                'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
493
-            ),
494
-            'EE_Message_To_Generate_From_Request'                                                                         => array(
495
-                'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
-                'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
497
-            ),
498
-            'EventEspresso\core\services\commands\CommandBus'                                                             => array(
499
-                'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
500
-            ),
501
-            'EventEspresso\services\commands\CommandHandler'                                                              => array(
502
-                'EE_Registry'         => EE_Dependency_Map::load_from_cache,
503
-                'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
504
-            ),
505
-            'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
506
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
507
-            ),
508
-            'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
509
-                'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
510
-                'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
511
-            ),
512
-            'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
513
-                'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
514
-            ),
515
-            'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
516
-                'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
517
-            ),
518
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
519
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
520
-            ),
521
-            'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
522
-                'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
523
-            ),
524
-            'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
525
-                'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
526
-            ),
527
-            'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
528
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
529
-            ),
530
-            'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
531
-                'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
532
-            ),
533
-            'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
534
-                'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
535
-            ),
536
-            'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
537
-                'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
538
-            ),
539
-            'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
540
-                'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
541
-            ),
542
-            'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
543
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
544
-            ),
545
-            'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
546
-                'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
547
-            ),
548
-            'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
549
-                'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
550
-            ),
551
-            'EventEspresso\core\services\database\TableManager'                                                           => array(
552
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
553
-            ),
554
-            'EE_Data_Migration_Class_Base'                                                                                => array(
555
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
-            ),
558
-            'EE_DMS_Core_4_1_0'                                                                                           => array(
559
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
-            ),
562
-            'EE_DMS_Core_4_2_0'                                                                                           => array(
563
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
-            ),
566
-            'EE_DMS_Core_4_3_0'                                                                                           => array(
567
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
-            ),
570
-            'EE_DMS_Core_4_4_0'                                                                                           => array(
571
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
-            ),
574
-            'EE_DMS_Core_4_5_0'                                                                                           => array(
575
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
-            ),
578
-            'EE_DMS_Core_4_6_0'                                                                                           => array(
579
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
-            ),
582
-            'EE_DMS_Core_4_7_0'                                                                                           => array(
583
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
-            ),
586
-            'EE_DMS_Core_4_8_0'                                                                                           => array(
587
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
-            ),
590
-            'EE_DMS_Core_4_9_0'                                                                                           => array(
591
-                'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
-                'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
-            ),
594
-            'EventEspresso\core\services\assets\Registry'                                                                 => array(
595
-                'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
596
-                'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
597
-            ),
598
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
599
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
600
-            ),
601
-            'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
602
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
603
-            ),
604
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
605
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
606
-            ),
607
-            'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
608
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
609
-            ),
610
-            'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
611
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
612
-            ),
613
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
614
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
615
-            ),
616
-            'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
617
-                'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
618
-            ),
619
-            'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
620
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
621
-            ),
622
-            'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
623
-                'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
624
-            ),
625
-            'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
626
-                'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
627
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
628
-            ),
629
-            'EventEspresso\core\domain\values\EmailAddress'                              => array(
630
-                null,
631
-                'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
632
-            ),
633
-            'EventEspresso\core\services\orm\ModelFieldFactory' => array(
634
-                'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
635
-            ),
636
-            'LEGACY_MODELS'                                                   => array(
637
-                null,
638
-                'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
639
-            ),
640
-            'EE_Module_Request_Router' => array(
641
-                'EE_Request' => EE_Dependency_Map::load_from_cache,
642
-            ),
643
-        );
644
-    }
645
-
646
-
647
-
648
-    /**
649
-     * Registers how core classes are loaded.
650
-     * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
651
-     *        'EE_Request_Handler' => 'load_core'
652
-     *        'EE_Messages_Queue'  => 'load_lib'
653
-     *        'EEH_Debug_Tools'    => 'load_helper'
654
-     * or, if greater control is required, by providing a custom closure. For example:
655
-     *        'Some_Class' => function () {
656
-     *            return new Some_Class();
657
-     *        },
658
-     * This is required for instantiating dependencies
659
-     * where an interface has been type hinted in a class constructor. For example:
660
-     *        'Required_Interface' => function () {
661
-     *            return new A_Class_That_Implements_Required_Interface();
662
-     *        },
663
-     *
664
-     * @throws InvalidInterfaceException
665
-     * @throws InvalidDataTypeException
666
-     * @throws InvalidArgumentException
667
-     */
668
-    protected function _register_core_class_loaders()
669
-    {
670
-        //for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
671
-        //be used in a closure.
672
-        $request = &$this->_request;
673
-        $response = &$this->_response;
674
-        // $loader = &$this->loader;
675
-        $this->_class_loaders = array(
676
-            //load_core
677
-            'EE_Capabilities'                      => 'load_core',
678
-            'EE_Encryption'                        => 'load_core',
679
-            'EE_Front_Controller'                  => 'load_core',
680
-            'EE_Module_Request_Router'             => 'load_core',
681
-            'EE_Registry'                          => 'load_core',
682
-            'EE_Request'                           => function () use (&$request) {
683
-                return $request;
684
-            },
685
-            'EE_Response'                          => function () use (&$response) {
686
-                return $response;
687
-            },
688
-            'EE_Request_Handler'                   => 'load_core',
689
-            'EE_Session'                           => 'load_core',
690
-            'EE_Cron_Tasks'                        => 'load_core',
691
-            'EE_System'                            => 'load_core',
692
-            'EE_Maintenance_Mode'                  => 'load_core',
693
-            'EE_Register_CPTs'                     => 'load_core',
694
-            'EE_Admin'                             => 'load_core',
695
-            //load_lib
696
-            'EE_Message_Resource_Manager'          => 'load_lib',
697
-            'EE_Message_Type_Collection'           => 'load_lib',
698
-            'EE_Message_Type_Collection_Loader'    => 'load_lib',
699
-            'EE_Messenger_Collection'              => 'load_lib',
700
-            'EE_Messenger_Collection_Loader'       => 'load_lib',
701
-            'EE_Messages_Processor'                => 'load_lib',
702
-            'EE_Message_Repository'                => 'load_lib',
703
-            'EE_Messages_Queue'                    => 'load_lib',
704
-            'EE_Messages_Data_Handler_Collection'  => 'load_lib',
705
-            'EE_Message_Template_Group_Collection' => 'load_lib',
706
-            'EE_Payment_Method_Manager'            => 'load_lib',
707
-            'EE_Messages_Generator'                => function () {
708
-                return EE_Registry::instance()->load_lib(
709
-                    'Messages_Generator',
710
-                    array(),
711
-                    false,
712
-                    false
713
-                );
714
-            },
715
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
716
-                return EE_Registry::instance()->load_lib(
717
-                    'Messages_Template_Defaults',
718
-                    $arguments,
719
-                    false,
720
-                    false
721
-                );
722
-            },
723
-            //load_model
724
-            // 'EEM_Attendee'                         => 'load_model',
725
-            // 'EEM_Message_Template_Group'           => 'load_model',
726
-            // 'EEM_Message_Template'                 => 'load_model',
727
-            //load_helper
728
-            'EEH_Parse_Shortcodes'                 => function () {
729
-                if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
730
-                    return new EEH_Parse_Shortcodes();
731
-                }
732
-                return null;
733
-            },
734
-            'EE_Template_Config'                   => function () {
735
-                return EE_Config::instance()->template_settings;
736
-            },
737
-            'EE_Currency_Config'                   => function () {
738
-                return EE_Config::instance()->currency;
739
-            },
740
-            'EE_Registration_Config'                   => function () {
741
-                return EE_Config::instance()->registration;
742
-            },
743
-            'EventEspresso\core\services\loaders\Loader' => function () {
744
-                return LoaderFactory::getLoader();
745
-            },
746
-        );
747
-    }
748
-
749
-
750
-
751
-    /**
752
-     * can be used for supplying alternate names for classes,
753
-     * or for connecting interface names to instantiable classes
754
-     */
755
-    protected function _register_core_aliases()
756
-    {
757
-        $this->_aliases = array(
758
-            'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
759
-            'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
760
-            'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
761
-            'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
762
-            'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
763
-            'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
764
-            'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
765
-            'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
766
-            'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
767
-            'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
768
-            'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
769
-            'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
770
-            'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
771
-            'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
772
-            'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
773
-            'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
774
-            'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
775
-            'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
776
-            'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
777
-            'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
778
-            'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
779
-            'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
780
-            'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
781
-            'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
782
-            'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
783
-            'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
784
-            'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
785
-            'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
786
-            'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
787
-            'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
788
-            'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
789
-            'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
790
-            'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
791
-            'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
792
-            'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
793
-            'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
794
-            'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
795
-        );
796
-    }
797
-
798
-
799
-
800
-    /**
801
-     * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
802
-     * request Primarily used by unit tests.
803
-     *
804
-     * @throws InvalidDataTypeException
805
-     * @throws InvalidInterfaceException
806
-     * @throws InvalidArgumentException
807
-     */
808
-    public function reset()
809
-    {
810
-        $this->_register_core_class_loaders();
811
-        $this->_register_core_dependencies();
812
-    }
25
+	/**
26
+	 * This means that the requested class dependency is not present in the dependency map
27
+	 */
28
+	const not_registered = 0;
29
+
30
+	/**
31
+	 * This instructs class loaders to ALWAYS return a newly instantiated object for the requested class.
32
+	 */
33
+	const load_new_object = 1;
34
+
35
+	/**
36
+	 * This instructs class loaders to return a previously instantiated and cached object for the requested class.
37
+	 * IF a previously instantiated object does not exist, a new one will be created and added to the cache.
38
+	 */
39
+	const load_from_cache = 2;
40
+
41
+	/**
42
+	 * When registering a dependency,
43
+	 * this indicates to keep any existing dependencies that already exist,
44
+	 * and simply discard any new dependencies declared in the incoming data
45
+	 */
46
+	const KEEP_EXISTING_DEPENDENCIES = 0;
47
+
48
+	/**
49
+	 * When registering a dependency,
50
+	 * this indicates to overwrite any existing dependencies that already exist using the incoming data
51
+	 */
52
+	const OVERWRITE_DEPENDENCIES = 1;
53
+
54
+
55
+
56
+	/**
57
+	 * @type EE_Dependency_Map $_instance
58
+	 */
59
+	protected static $_instance;
60
+
61
+	/**
62
+	 * @type EE_Request $request
63
+	 */
64
+	protected $_request;
65
+
66
+	/**
67
+	 * @type EE_Response $response
68
+	 */
69
+	protected $_response;
70
+
71
+	/**
72
+	 * @type LoaderInterface $loader
73
+	 */
74
+	protected $loader;
75
+
76
+	/**
77
+	 * @type array $_dependency_map
78
+	 */
79
+	protected $_dependency_map = array();
80
+
81
+	/**
82
+	 * @type array $_class_loaders
83
+	 */
84
+	protected $_class_loaders = array();
85
+
86
+	/**
87
+	 * @type array $_aliases
88
+	 */
89
+	protected $_aliases = array();
90
+
91
+
92
+
93
+	/**
94
+	 * EE_Dependency_Map constructor.
95
+	 *
96
+	 * @param EE_Request  $request
97
+	 * @param EE_Response $response
98
+	 */
99
+	protected function __construct(EE_Request $request, EE_Response $response)
100
+	{
101
+		$this->_request = $request;
102
+		$this->_response = $response;
103
+		add_action('EE_Load_Espresso_Core__handle_request__initialize_core_loading', array($this, 'initialize'));
104
+		do_action('EE_Dependency_Map____construct');
105
+	}
106
+
107
+
108
+
109
+	/**
110
+	 * @throws InvalidDataTypeException
111
+	 * @throws InvalidInterfaceException
112
+	 * @throws InvalidArgumentException
113
+	 */
114
+	public function initialize()
115
+	{
116
+		$this->_register_core_dependencies();
117
+		$this->_register_core_class_loaders();
118
+		$this->_register_core_aliases();
119
+	}
120
+
121
+
122
+
123
+	/**
124
+	 * @singleton method used to instantiate class object
125
+	 * @access    public
126
+	 * @param EE_Request  $request
127
+	 * @param EE_Response $response
128
+	 * @return EE_Dependency_Map
129
+	 */
130
+	public static function instance(EE_Request $request = null, EE_Response $response = null)
131
+	{
132
+		// check if class object is instantiated, and instantiated properly
133
+		if (! self::$_instance instanceof EE_Dependency_Map) {
134
+			self::$_instance = new EE_Dependency_Map($request, $response);
135
+		}
136
+		return self::$_instance;
137
+	}
138
+
139
+
140
+
141
+	/**
142
+	 * @param LoaderInterface $loader
143
+	 */
144
+	public function setLoader(LoaderInterface $loader)
145
+	{
146
+		$this->loader = $loader;
147
+	}
148
+
149
+
150
+
151
+	/**
152
+	 * @param string $class
153
+	 * @param array  $dependencies
154
+	 * @param int    $overwrite
155
+	 * @return bool
156
+	 */
157
+	public static function register_dependencies(
158
+		$class,
159
+		array $dependencies,
160
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
161
+	) {
162
+		return self::$_instance->registerDependencies($class, $dependencies, $overwrite);
163
+	}
164
+
165
+
166
+
167
+	/**
168
+	 * Assigns an array of class names and corresponding load sources (new or cached)
169
+	 * to the class specified by the first parameter.
170
+	 * IMPORTANT !!!
171
+	 * The order of elements in the incoming $dependencies array MUST match
172
+	 * the order of the constructor parameters for the class in question.
173
+	 * This is especially important when overriding any existing dependencies that are registered.
174
+	 * the third parameter controls whether any duplicate dependencies are overwritten or not.
175
+	 *
176
+	 * @param string $class
177
+	 * @param array  $dependencies
178
+	 * @param int    $overwrite
179
+	 * @return bool
180
+	 */
181
+	public function registerDependencies(
182
+		$class,
183
+		array $dependencies,
184
+		$overwrite = EE_Dependency_Map::KEEP_EXISTING_DEPENDENCIES
185
+	) {
186
+		$class = trim($class, '\\');
187
+		$registered = false;
188
+		if (empty(self::$_instance->_dependency_map[ $class ])) {
189
+			self::$_instance->_dependency_map[ $class ] = array();
190
+		}
191
+		// we need to make sure that any aliases used when registering a dependency
192
+		// get resolved to the correct class name
193
+		foreach ((array)$dependencies as $dependency => $load_source) {
194
+			$alias = self::$_instance->get_alias($dependency);
195
+			if (
196
+				$overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
+				|| ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
198
+			) {
199
+				unset($dependencies[$dependency]);
200
+				$dependencies[$alias] = $load_source;
201
+				$registered = true;
202
+			}
203
+		}
204
+		// now add our two lists of dependencies together.
205
+		// using Union (+=) favours the arrays in precedence from left to right,
206
+		// so $dependencies is NOT overwritten because it is listed first
207
+		// ie: with A = B + C, entries in B take precedence over duplicate entries in C
208
+		// Union is way faster than array_merge() but should be used with caution...
209
+		// especially with numerically indexed arrays
210
+		$dependencies += self::$_instance->_dependency_map[ $class ];
211
+		// now we need to ensure that the resulting dependencies
212
+		// array only has the entries that are required for the class
213
+		// so first count how many dependencies were originally registered for the class
214
+		$dependency_count = count(self::$_instance->_dependency_map[ $class ]);
215
+		// if that count is non-zero (meaning dependencies were already registered)
216
+		self::$_instance->_dependency_map[ $class ] = $dependency_count
217
+			// then truncate the  final array to match that count
218
+			? array_slice($dependencies, 0, $dependency_count)
219
+			// otherwise just take the incoming array because nothing previously existed
220
+			: $dependencies;
221
+		return $registered;
222
+	}
223
+
224
+
225
+
226
+	/**
227
+	 * @param string $class_name
228
+	 * @param string $loader
229
+	 * @return bool
230
+	 * @throws DomainException
231
+	 */
232
+	public static function register_class_loader($class_name, $loader = 'load_core')
233
+	{
234
+		if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235
+			throw new DomainException(
236
+				esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237
+			);
238
+		}
239
+		// check that loader is callable or method starts with "load_" and exists in EE_Registry
240
+		if (
241
+			! is_callable($loader)
242
+			&& (
243
+				strpos($loader, 'load_') !== 0
244
+				|| ! method_exists('EE_Registry', $loader)
245
+			)
246
+		) {
247
+			throw new DomainException(
248
+				sprintf(
249
+					esc_html__(
250
+						'"%1$s" is not a valid loader method on EE_Registry.',
251
+						'event_espresso'
252
+					),
253
+					$loader
254
+				)
255
+			);
256
+		}
257
+		$class_name = self::$_instance->get_alias($class_name);
258
+		if (! isset(self::$_instance->_class_loaders[$class_name])) {
259
+			self::$_instance->_class_loaders[$class_name] = $loader;
260
+			return true;
261
+		}
262
+		return false;
263
+	}
264
+
265
+
266
+
267
+	/**
268
+	 * @return array
269
+	 */
270
+	public function dependency_map()
271
+	{
272
+		return $this->_dependency_map;
273
+	}
274
+
275
+
276
+
277
+	/**
278
+	 * returns TRUE if dependency map contains a listing for the provided class name
279
+	 *
280
+	 * @param string $class_name
281
+	 * @return boolean
282
+	 */
283
+	public function has($class_name = '')
284
+	{
285
+		// all legacy models have the same dependencies
286
+		if (strpos($class_name, 'EEM_') === 0) {
287
+			$class_name = 'LEGACY_MODELS';
288
+		}
289
+		return isset($this->_dependency_map[$class_name]) ? true : false;
290
+	}
291
+
292
+
293
+
294
+	/**
295
+	 * returns TRUE if dependency map contains a listing for the provided class name AND dependency
296
+	 *
297
+	 * @param string $class_name
298
+	 * @param string $dependency
299
+	 * @return bool
300
+	 */
301
+	public function has_dependency_for_class($class_name = '', $dependency = '')
302
+	{
303
+		// all legacy models have the same dependencies
304
+		if (strpos($class_name, 'EEM_') === 0) {
305
+			$class_name = 'LEGACY_MODELS';
306
+		}
307
+		$dependency = $this->get_alias($dependency);
308
+		return isset($this->_dependency_map[$class_name], $this->_dependency_map[$class_name][$dependency])
309
+			? true
310
+			: false;
311
+	}
312
+
313
+
314
+
315
+	/**
316
+	 * returns loading strategy for whether a previously cached dependency should be loaded or a new instance returned
317
+	 *
318
+	 * @param string $class_name
319
+	 * @param string $dependency
320
+	 * @return int
321
+	 */
322
+	public function loading_strategy_for_class_dependency($class_name = '', $dependency = '')
323
+	{
324
+		// all legacy models have the same dependencies
325
+		if (strpos($class_name, 'EEM_') === 0) {
326
+			$class_name = 'LEGACY_MODELS';
327
+		}
328
+		$dependency = $this->get_alias($dependency);
329
+		return $this->has_dependency_for_class($class_name, $dependency)
330
+			? $this->_dependency_map[$class_name][$dependency]
331
+			: EE_Dependency_Map::not_registered;
332
+	}
333
+
334
+
335
+
336
+	/**
337
+	 * @param string $class_name
338
+	 * @return string | Closure
339
+	 */
340
+	public function class_loader($class_name)
341
+	{
342
+		// all legacy models use load_model()
343
+		if(strpos($class_name, 'EEM_') === 0){
344
+			return 'load_model';
345
+		}
346
+		$class_name = $this->get_alias($class_name);
347
+		return isset($this->_class_loaders[$class_name]) ? $this->_class_loaders[$class_name] : '';
348
+	}
349
+
350
+
351
+
352
+	/**
353
+	 * @return array
354
+	 */
355
+	public function class_loaders()
356
+	{
357
+		return $this->_class_loaders;
358
+	}
359
+
360
+
361
+
362
+	/**
363
+	 * adds an alias for a classname
364
+	 *
365
+	 * @param string $class_name the class name that should be used (concrete class to replace interface)
366
+	 * @param string $alias      the class name that would be type hinted for (abstract parent or interface)
367
+	 * @param string $for_class  the class that has the dependency (is type hinting for the interface)
368
+	 */
369
+	public function add_alias($class_name, $alias, $for_class = '')
370
+	{
371
+		if ($for_class !== '') {
372
+			if (! isset($this->_aliases[$for_class])) {
373
+				$this->_aliases[$for_class] = array();
374
+			}
375
+			$this->_aliases[$for_class][$class_name] = $alias;
376
+		}
377
+		$this->_aliases[$class_name] = $alias;
378
+	}
379
+
380
+
381
+
382
+	/**
383
+	 * returns TRUE if the provided class name has an alias
384
+	 *
385
+	 * @param string $class_name
386
+	 * @param string $for_class
387
+	 * @return bool
388
+	 */
389
+	public function has_alias($class_name = '', $for_class = '')
390
+	{
391
+		return isset($this->_aliases[$for_class], $this->_aliases[$for_class][$class_name])
392
+			   || (
393
+				   isset($this->_aliases[$class_name])
394
+				   && ! is_array($this->_aliases[$class_name])
395
+			   );
396
+	}
397
+
398
+
399
+
400
+	/**
401
+	 * returns alias for class name if one exists, otherwise returns the original classname
402
+	 * functions recursively, so that multiple aliases can be used to drill down to a classname
403
+	 *  for example:
404
+	 *      if the following two entries were added to the _aliases array:
405
+	 *          array(
406
+	 *              'interface_alias'           => 'some\namespace\interface'
407
+	 *              'some\namespace\interface'  => 'some\namespace\classname'
408
+	 *          )
409
+	 *      then one could use EE_Registry::instance()->create( 'interface_alias' )
410
+	 *      to load an instance of 'some\namespace\classname'
411
+	 *
412
+	 * @param string $class_name
413
+	 * @param string $for_class
414
+	 * @return string
415
+	 */
416
+	public function get_alias($class_name = '', $for_class = '')
417
+	{
418
+		if (! $this->has_alias($class_name, $for_class)) {
419
+			return $class_name;
420
+		}
421
+		if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
422
+			return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423
+		}
424
+		return $this->get_alias($this->_aliases[$class_name]);
425
+	}
426
+
427
+
428
+
429
+	/**
430
+	 * Registers the core dependencies and whether a previously instantiated object should be loaded from the cache,
431
+	 * if one exists, or whether a new object should be generated every time the requested class is loaded.
432
+	 * This is done by using the following class constants:
433
+	 *        EE_Dependency_Map::load_from_cache - loads previously instantiated object
434
+	 *        EE_Dependency_Map::load_new_object - generates a new object every time
435
+	 */
436
+	protected function _register_core_dependencies()
437
+	{
438
+		$this->_dependency_map = array(
439
+			'EE_Request_Handler'                                                                                          => array(
440
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
441
+			),
442
+			'EE_System'                                                                                                   => array(
443
+				'EE_Registry'                                => EE_Dependency_Map::load_from_cache,
444
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
445
+				'EE_Capabilities'                            => EE_Dependency_Map::load_from_cache,
446
+				'EE_Request'                                 => EE_Dependency_Map::load_from_cache,
447
+				'EE_Maintenance_Mode'                        => EE_Dependency_Map::load_from_cache,
448
+			),
449
+			'EE_Session'                                                                                                  => array(
450
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
451
+				'EE_Encryption'                                           => EE_Dependency_Map::load_from_cache,
452
+			),
453
+			'EE_Cart'                                                                                                     => array(
454
+				'EE_Session' => EE_Dependency_Map::load_from_cache,
455
+			),
456
+			'EE_Front_Controller'                                                                                         => array(
457
+				'EE_Registry'              => EE_Dependency_Map::load_from_cache,
458
+				'EE_Request_Handler'       => EE_Dependency_Map::load_from_cache,
459
+				'EE_Module_Request_Router' => EE_Dependency_Map::load_from_cache,
460
+			),
461
+			'EE_Messenger_Collection_Loader'                                                                              => array(
462
+				'EE_Messenger_Collection' => EE_Dependency_Map::load_new_object,
463
+			),
464
+			'EE_Message_Type_Collection_Loader'                                                                           => array(
465
+				'EE_Message_Type_Collection' => EE_Dependency_Map::load_new_object,
466
+			),
467
+			'EE_Message_Resource_Manager'                                                                                 => array(
468
+				'EE_Messenger_Collection_Loader'    => EE_Dependency_Map::load_new_object,
469
+				'EE_Message_Type_Collection_Loader' => EE_Dependency_Map::load_new_object,
470
+				'EEM_Message_Template_Group'        => EE_Dependency_Map::load_from_cache,
471
+			),
472
+			'EE_Message_Factory'                                                                                          => array(
473
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
474
+			),
475
+			'EE_messages'                                                                                                 => array(
476
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
477
+			),
478
+			'EE_Messages_Generator'                                                                                       => array(
479
+				'EE_Messages_Queue'                    => EE_Dependency_Map::load_new_object,
480
+				'EE_Messages_Data_Handler_Collection'  => EE_Dependency_Map::load_new_object,
481
+				'EE_Message_Template_Group_Collection' => EE_Dependency_Map::load_new_object,
482
+				'EEH_Parse_Shortcodes'                 => EE_Dependency_Map::load_from_cache,
483
+			),
484
+			'EE_Messages_Processor'                                                                                       => array(
485
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
486
+			),
487
+			'EE_Messages_Queue'                                                                                           => array(
488
+				'EE_Message_Repository' => EE_Dependency_Map::load_new_object,
489
+			),
490
+			'EE_Messages_Template_Defaults'                                                                               => array(
491
+				'EEM_Message_Template_Group' => EE_Dependency_Map::load_from_cache,
492
+				'EEM_Message_Template'       => EE_Dependency_Map::load_from_cache,
493
+			),
494
+			'EE_Message_To_Generate_From_Request'                                                                         => array(
495
+				'EE_Message_Resource_Manager' => EE_Dependency_Map::load_from_cache,
496
+				'EE_Request_Handler'          => EE_Dependency_Map::load_from_cache,
497
+			),
498
+			'EventEspresso\core\services\commands\CommandBus'                                                             => array(
499
+				'EventEspresso\core\services\commands\CommandHandlerManager' => EE_Dependency_Map::load_from_cache,
500
+			),
501
+			'EventEspresso\services\commands\CommandHandler'                                                              => array(
502
+				'EE_Registry'         => EE_Dependency_Map::load_from_cache,
503
+				'CommandBusInterface' => EE_Dependency_Map::load_from_cache,
504
+			),
505
+			'EventEspresso\core\services\commands\CommandHandlerManager'                                                  => array(
506
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
507
+			),
508
+			'EventEspresso\core\services\commands\CompositeCommandHandler'                                                => array(
509
+				'EventEspresso\core\services\commands\CommandBus'     => EE_Dependency_Map::load_from_cache,
510
+				'EventEspresso\core\services\commands\CommandFactory' => EE_Dependency_Map::load_from_cache,
511
+			),
512
+			'EventEspresso\core\services\commands\CommandFactory'                                                         => array(
513
+				'EventEspresso\core\services\loaders\Loader' => EE_Dependency_Map::load_from_cache,
514
+			),
515
+			'EventEspresso\core\services\commands\middleware\CapChecker'                                                  => array(
516
+				'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker' => EE_Dependency_Map::load_from_cache,
517
+			),
518
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker'                                         => array(
519
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
520
+			),
521
+			'EventEspresso\core\domain\services\capabilities\RegistrationsCapChecker'                                     => array(
522
+				'EE_Capabilities' => EE_Dependency_Map::load_from_cache,
523
+			),
524
+			'EventEspresso\core\services\commands\registration\CreateRegistrationCommandHandler'                          => array(
525
+				'EventEspresso\core\domain\services\registration\CreateRegistrationService' => EE_Dependency_Map::load_from_cache,
526
+			),
527
+			'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommandHandler'                     => array(
528
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
529
+			),
530
+			'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommandHandler'                    => array(
531
+				'EventEspresso\core\domain\services\registration\CopyRegistrationService' => EE_Dependency_Map::load_from_cache,
532
+			),
533
+			'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler'         => array(
534
+				'EventEspresso\core\domain\services\registration\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
535
+			),
536
+			'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler' => array(
537
+				'EventEspresso\core\domain\services\registration\UpdateRegistrationService' => EE_Dependency_Map::load_from_cache,
538
+			),
539
+			'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommandHandler'                              => array(
540
+				'EventEspresso\core\domain\services\ticket\CreateTicketLineItemService' => EE_Dependency_Map::load_from_cache,
541
+			),
542
+			'EventEspresso\core\services\commands\ticket\CancelTicketLineItemCommandHandler'                              => array(
543
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
544
+			),
545
+			'EventEspresso\core\domain\services\registration\CancelRegistrationService'                                   => array(
546
+				'EventEspresso\core\domain\services\ticket\CancelTicketLineItemService' => EE_Dependency_Map::load_from_cache,
547
+			),
548
+			'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler'                                  => array(
549
+				'EEM_Attendee' => EE_Dependency_Map::load_from_cache,
550
+			),
551
+			'EventEspresso\core\services\database\TableManager'                                                           => array(
552
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
553
+			),
554
+			'EE_Data_Migration_Class_Base'                                                                                => array(
555
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
556
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
557
+			),
558
+			'EE_DMS_Core_4_1_0'                                                                                           => array(
559
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
560
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
561
+			),
562
+			'EE_DMS_Core_4_2_0'                                                                                           => array(
563
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
564
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
565
+			),
566
+			'EE_DMS_Core_4_3_0'                                                                                           => array(
567
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
568
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
569
+			),
570
+			'EE_DMS_Core_4_4_0'                                                                                           => array(
571
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
572
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
573
+			),
574
+			'EE_DMS_Core_4_5_0'                                                                                           => array(
575
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
576
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
577
+			),
578
+			'EE_DMS_Core_4_6_0'                                                                                           => array(
579
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
580
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
581
+			),
582
+			'EE_DMS_Core_4_7_0'                                                                                           => array(
583
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
584
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
585
+			),
586
+			'EE_DMS_Core_4_8_0'                                                                                           => array(
587
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
588
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
589
+			),
590
+			'EE_DMS_Core_4_9_0'                                                                                           => array(
591
+				'EventEspresso\core\services\database\TableAnalysis' => EE_Dependency_Map::load_from_cache,
592
+				'EventEspresso\core\services\database\TableManager'  => EE_Dependency_Map::load_from_cache,
593
+			),
594
+			'EventEspresso\core\services\assets\Registry'                                                                 => array(
595
+				'EE_Template_Config' => EE_Dependency_Map::load_from_cache,
596
+				'EE_Currency_Config' => EE_Dependency_Map::load_from_cache,
597
+			),
598
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCancelled'                                             => array(
599
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
600
+			),
601
+			'EventEspresso\core\domain\entities\shortcodes\EspressoCheckout'                                              => array(
602
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
603
+			),
604
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEventAttendees'                                        => array(
605
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
606
+			),
607
+			'EventEspresso\core\domain\entities\shortcodes\EspressoEvents'                                                => array(
608
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
609
+			),
610
+			'EventEspresso\core\domain\entities\shortcodes\EspressoThankYou'                                              => array(
611
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
612
+			),
613
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTicketSelector'                                        => array(
614
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
615
+			),
616
+			'EventEspresso\core\domain\entities\shortcodes\EspressoTxnPage'                                               => array(
617
+				'EventEspresso\core\services\cache\PostRelatedCacheManager' => EE_Dependency_Map::load_from_cache,
618
+			),
619
+			'EventEspresso\core\services\cache\BasicCacheManager'                        => array(
620
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
621
+			),
622
+			'EventEspresso\core\services\cache\PostRelatedCacheManager'                  => array(
623
+				'EventEspresso\core\services\cache\TransientCacheStorage' => EE_Dependency_Map::load_from_cache,
624
+			),
625
+			'EventEspresso\core\domain\services\validation\email\EmailValidationService' => array(
626
+				'EE_Registration_Config'                                  => EE_Dependency_Map::load_from_cache,
627
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
628
+			),
629
+			'EventEspresso\core\domain\values\EmailAddress'                              => array(
630
+				null,
631
+				'EventEspresso\core\domain\services\validation\email\EmailValidationService' => EE_Dependency_Map::load_from_cache,
632
+			),
633
+			'EventEspresso\core\services\orm\ModelFieldFactory' => array(
634
+				'EventEspresso\core\services\loaders\Loader'              => EE_Dependency_Map::load_from_cache,
635
+			),
636
+			'LEGACY_MODELS'                                                   => array(
637
+				null,
638
+				'EventEspresso\core\services\database\ModelFieldFactory' => EE_Dependency_Map::load_from_cache,
639
+			),
640
+			'EE_Module_Request_Router' => array(
641
+				'EE_Request' => EE_Dependency_Map::load_from_cache,
642
+			),
643
+		);
644
+	}
645
+
646
+
647
+
648
+	/**
649
+	 * Registers how core classes are loaded.
650
+	 * This can either be done by simply providing the name of one of the EE_Registry loader methods such as:
651
+	 *        'EE_Request_Handler' => 'load_core'
652
+	 *        'EE_Messages_Queue'  => 'load_lib'
653
+	 *        'EEH_Debug_Tools'    => 'load_helper'
654
+	 * or, if greater control is required, by providing a custom closure. For example:
655
+	 *        'Some_Class' => function () {
656
+	 *            return new Some_Class();
657
+	 *        },
658
+	 * This is required for instantiating dependencies
659
+	 * where an interface has been type hinted in a class constructor. For example:
660
+	 *        'Required_Interface' => function () {
661
+	 *            return new A_Class_That_Implements_Required_Interface();
662
+	 *        },
663
+	 *
664
+	 * @throws InvalidInterfaceException
665
+	 * @throws InvalidDataTypeException
666
+	 * @throws InvalidArgumentException
667
+	 */
668
+	protected function _register_core_class_loaders()
669
+	{
670
+		//for PHP5.3 compat, we need to register any properties called here in a variable because `$this` cannot
671
+		//be used in a closure.
672
+		$request = &$this->_request;
673
+		$response = &$this->_response;
674
+		// $loader = &$this->loader;
675
+		$this->_class_loaders = array(
676
+			//load_core
677
+			'EE_Capabilities'                      => 'load_core',
678
+			'EE_Encryption'                        => 'load_core',
679
+			'EE_Front_Controller'                  => 'load_core',
680
+			'EE_Module_Request_Router'             => 'load_core',
681
+			'EE_Registry'                          => 'load_core',
682
+			'EE_Request'                           => function () use (&$request) {
683
+				return $request;
684
+			},
685
+			'EE_Response'                          => function () use (&$response) {
686
+				return $response;
687
+			},
688
+			'EE_Request_Handler'                   => 'load_core',
689
+			'EE_Session'                           => 'load_core',
690
+			'EE_Cron_Tasks'                        => 'load_core',
691
+			'EE_System'                            => 'load_core',
692
+			'EE_Maintenance_Mode'                  => 'load_core',
693
+			'EE_Register_CPTs'                     => 'load_core',
694
+			'EE_Admin'                             => 'load_core',
695
+			//load_lib
696
+			'EE_Message_Resource_Manager'          => 'load_lib',
697
+			'EE_Message_Type_Collection'           => 'load_lib',
698
+			'EE_Message_Type_Collection_Loader'    => 'load_lib',
699
+			'EE_Messenger_Collection'              => 'load_lib',
700
+			'EE_Messenger_Collection_Loader'       => 'load_lib',
701
+			'EE_Messages_Processor'                => 'load_lib',
702
+			'EE_Message_Repository'                => 'load_lib',
703
+			'EE_Messages_Queue'                    => 'load_lib',
704
+			'EE_Messages_Data_Handler_Collection'  => 'load_lib',
705
+			'EE_Message_Template_Group_Collection' => 'load_lib',
706
+			'EE_Payment_Method_Manager'            => 'load_lib',
707
+			'EE_Messages_Generator'                => function () {
708
+				return EE_Registry::instance()->load_lib(
709
+					'Messages_Generator',
710
+					array(),
711
+					false,
712
+					false
713
+				);
714
+			},
715
+			'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
716
+				return EE_Registry::instance()->load_lib(
717
+					'Messages_Template_Defaults',
718
+					$arguments,
719
+					false,
720
+					false
721
+				);
722
+			},
723
+			//load_model
724
+			// 'EEM_Attendee'                         => 'load_model',
725
+			// 'EEM_Message_Template_Group'           => 'load_model',
726
+			// 'EEM_Message_Template'                 => 'load_model',
727
+			//load_helper
728
+			'EEH_Parse_Shortcodes'                 => function () {
729
+				if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
730
+					return new EEH_Parse_Shortcodes();
731
+				}
732
+				return null;
733
+			},
734
+			'EE_Template_Config'                   => function () {
735
+				return EE_Config::instance()->template_settings;
736
+			},
737
+			'EE_Currency_Config'                   => function () {
738
+				return EE_Config::instance()->currency;
739
+			},
740
+			'EE_Registration_Config'                   => function () {
741
+				return EE_Config::instance()->registration;
742
+			},
743
+			'EventEspresso\core\services\loaders\Loader' => function () {
744
+				return LoaderFactory::getLoader();
745
+			},
746
+		);
747
+	}
748
+
749
+
750
+
751
+	/**
752
+	 * can be used for supplying alternate names for classes,
753
+	 * or for connecting interface names to instantiable classes
754
+	 */
755
+	protected function _register_core_aliases()
756
+	{
757
+		$this->_aliases = array(
758
+			'CommandBusInterface'                                                          => 'EventEspresso\core\services\commands\CommandBusInterface',
759
+			'EventEspresso\core\services\commands\CommandBusInterface'                     => 'EventEspresso\core\services\commands\CommandBus',
760
+			'CommandHandlerManagerInterface'                                               => 'EventEspresso\core\services\commands\CommandHandlerManagerInterface',
761
+			'EventEspresso\core\services\commands\CommandHandlerManagerInterface'          => 'EventEspresso\core\services\commands\CommandHandlerManager',
762
+			'CapChecker'                                                                   => 'EventEspresso\core\services\commands\middleware\CapChecker',
763
+			'AddActionHook'                                                                => 'EventEspresso\core\services\commands\middleware\AddActionHook',
764
+			'CapabilitiesChecker'                                                          => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
765
+			'CapabilitiesCheckerInterface'                                                 => 'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface',
766
+			'EventEspresso\core\domain\services\capabilities\CapabilitiesCheckerInterface' => 'EventEspresso\core\domain\services\capabilities\CapabilitiesChecker',
767
+			'CreateRegistrationService'                                                    => 'EventEspresso\core\domain\services\registration\CreateRegistrationService',
768
+			'CreateRegCodeCommandHandler'                                                  => 'EventEspresso\core\services\commands\registration\CreateRegCodeCommand',
769
+			'CreateRegUrlLinkCommandHandler'                                               => 'EventEspresso\core\services\commands\registration\CreateRegUrlLinkCommand',
770
+			'CreateRegistrationCommandHandler'                                             => 'EventEspresso\core\services\commands\registration\CreateRegistrationCommand',
771
+			'CopyRegistrationDetailsCommandHandler'                                        => 'EventEspresso\core\services\commands\registration\CopyRegistrationDetailsCommand',
772
+			'CopyRegistrationPaymentsCommandHandler'                                       => 'EventEspresso\core\services\commands\registration\CopyRegistrationPaymentsCommand',
773
+			'CancelRegistrationAndTicketLineItemCommandHandler'                            => 'EventEspresso\core\services\commands\registration\CancelRegistrationAndTicketLineItemCommandHandler',
774
+			'UpdateRegistrationAndTransactionAfterChangeCommandHandler'                    => 'EventEspresso\core\services\commands\registration\UpdateRegistrationAndTransactionAfterChangeCommandHandler',
775
+			'CreateTicketLineItemCommandHandler'                                           => 'EventEspresso\core\services\commands\ticket\CreateTicketLineItemCommand',
776
+			'CreateTransactionCommandHandler'                                     => 'EventEspresso\core\services\commands\transaction\CreateTransactionCommandHandler',
777
+			'CreateAttendeeCommandHandler'                                        => 'EventEspresso\core\services\commands\attendee\CreateAttendeeCommandHandler',
778
+			'TableManager'                                                                 => 'EventEspresso\core\services\database\TableManager',
779
+			'TableAnalysis'                                                                => 'EventEspresso\core\services\database\TableAnalysis',
780
+			'EspressoShortcode'                                                            => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
781
+			'ShortcodeInterface'                                                           => 'EventEspresso\core\services\shortcodes\ShortcodeInterface',
782
+			'EventEspresso\core\services\shortcodes\ShortcodeInterface'                    => 'EventEspresso\core\services\shortcodes\EspressoShortcode',
783
+			'EventEspresso\core\services\cache\CacheStorageInterface'                      => 'EventEspresso\core\services\cache\TransientCacheStorage',
784
+			'LoaderInterface'                                                              => 'EventEspresso\core\services\loaders\LoaderInterface',
785
+			'EventEspresso\core\services\loaders\LoaderInterface'                          => 'EventEspresso\core\services\loaders\Loader',
786
+			'CommandFactoryInterface'                                                     => 'EventEspresso\core\services\commands\CommandFactoryInterface',
787
+			'EventEspresso\core\services\commands\CommandFactoryInterface'                => 'EventEspresso\core\services\commands\CommandFactory',
788
+			'EventEspresso\core\domain\services\session\SessionIdentifierInterface'       => 'EE_Session',
789
+			'EmailValidatorInterface'                                                     => 'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface',
790
+			'EventEspresso\core\domain\services\validation\email\EmailValidatorInterface' => 'EventEspresso\core\domain\services\validation\email\EmailValidationService',
791
+			'NoticeConverterInterface'                                            => 'EventEspresso\core\services\notices\NoticeConverterInterface',
792
+			'EventEspresso\core\services\notices\NoticeConverterInterface'        => 'EventEspresso\core\services\notices\ConvertNoticesToEeErrors',
793
+			'NoticesContainerInterface'                                            => 'EventEspresso\core\services\notices\NoticesContainerInterface',
794
+			'EventEspresso\core\services\notices\NoticesContainerInterface'        => 'EventEspresso\core\services\notices\NoticesContainer',
795
+		);
796
+	}
797
+
798
+
799
+
800
+	/**
801
+	 * This is used to reset the internal map and class_loaders to their original default state at the beginning of the
802
+	 * request Primarily used by unit tests.
803
+	 *
804
+	 * @throws InvalidDataTypeException
805
+	 * @throws InvalidInterfaceException
806
+	 * @throws InvalidArgumentException
807
+	 */
808
+	public function reset()
809
+	{
810
+		$this->_register_core_class_loaders();
811
+		$this->_register_core_dependencies();
812
+	}
813 813
 
814 814
 
815 815
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -4,7 +4,7 @@  discard block
 block discarded – undo
4 4
 use EventEspresso\core\services\loaders\LoaderFactory;
5 5
 use EventEspresso\core\services\loaders\LoaderInterface;
6 6
 
7
-if (! defined('EVENT_ESPRESSO_VERSION')) {
7
+if ( ! defined('EVENT_ESPRESSO_VERSION')) {
8 8
     exit('No direct script access allowed');
9 9
 }
10 10
 
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
     public static function instance(EE_Request $request = null, EE_Response $response = null)
131 131
     {
132 132
         // check if class object is instantiated, and instantiated properly
133
-        if (! self::$_instance instanceof EE_Dependency_Map) {
133
+        if ( ! self::$_instance instanceof EE_Dependency_Map) {
134 134
             self::$_instance = new EE_Dependency_Map($request, $response);
135 135
         }
136 136
         return self::$_instance;
@@ -185,16 +185,16 @@  discard block
 block discarded – undo
185 185
     ) {
186 186
         $class = trim($class, '\\');
187 187
         $registered = false;
188
-        if (empty(self::$_instance->_dependency_map[ $class ])) {
189
-            self::$_instance->_dependency_map[ $class ] = array();
188
+        if (empty(self::$_instance->_dependency_map[$class])) {
189
+            self::$_instance->_dependency_map[$class] = array();
190 190
         }
191 191
         // we need to make sure that any aliases used when registering a dependency
192 192
         // get resolved to the correct class name
193
-        foreach ((array)$dependencies as $dependency => $load_source) {
193
+        foreach ((array) $dependencies as $dependency => $load_source) {
194 194
             $alias = self::$_instance->get_alias($dependency);
195 195
             if (
196 196
                 $overwrite === EE_Dependency_Map::OVERWRITE_DEPENDENCIES
197
-                || ! isset(self::$_instance->_dependency_map[ $class ][ $alias ])
197
+                || ! isset(self::$_instance->_dependency_map[$class][$alias])
198 198
             ) {
199 199
                 unset($dependencies[$dependency]);
200 200
                 $dependencies[$alias] = $load_source;
@@ -207,13 +207,13 @@  discard block
 block discarded – undo
207 207
         // ie: with A = B + C, entries in B take precedence over duplicate entries in C
208 208
         // Union is way faster than array_merge() but should be used with caution...
209 209
         // especially with numerically indexed arrays
210
-        $dependencies += self::$_instance->_dependency_map[ $class ];
210
+        $dependencies += self::$_instance->_dependency_map[$class];
211 211
         // now we need to ensure that the resulting dependencies
212 212
         // array only has the entries that are required for the class
213 213
         // so first count how many dependencies were originally registered for the class
214
-        $dependency_count = count(self::$_instance->_dependency_map[ $class ]);
214
+        $dependency_count = count(self::$_instance->_dependency_map[$class]);
215 215
         // if that count is non-zero (meaning dependencies were already registered)
216
-        self::$_instance->_dependency_map[ $class ] = $dependency_count
216
+        self::$_instance->_dependency_map[$class] = $dependency_count
217 217
             // then truncate the  final array to match that count
218 218
             ? array_slice($dependencies, 0, $dependency_count)
219 219
             // otherwise just take the incoming array because nothing previously existed
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
      */
232 232
     public static function register_class_loader($class_name, $loader = 'load_core')
233 233
     {
234
-        if (! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
234
+        if ( ! $loader instanceof Closure && strpos($class_name, '\\') !== false) {
235 235
             throw new DomainException(
236 236
                 esc_html__('Don\'t use class loaders for FQCNs.', 'event_espresso')
237 237
             );
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
             );
256 256
         }
257 257
         $class_name = self::$_instance->get_alias($class_name);
258
-        if (! isset(self::$_instance->_class_loaders[$class_name])) {
258
+        if ( ! isset(self::$_instance->_class_loaders[$class_name])) {
259 259
             self::$_instance->_class_loaders[$class_name] = $loader;
260 260
             return true;
261 261
         }
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
     public function class_loader($class_name)
341 341
     {
342 342
         // all legacy models use load_model()
343
-        if(strpos($class_name, 'EEM_') === 0){
343
+        if (strpos($class_name, 'EEM_') === 0) {
344 344
             return 'load_model';
345 345
         }
346 346
         $class_name = $this->get_alias($class_name);
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
     public function add_alias($class_name, $alias, $for_class = '')
370 370
     {
371 371
         if ($for_class !== '') {
372
-            if (! isset($this->_aliases[$for_class])) {
372
+            if ( ! isset($this->_aliases[$for_class])) {
373 373
                 $this->_aliases[$for_class] = array();
374 374
             }
375 375
             $this->_aliases[$for_class][$class_name] = $alias;
@@ -415,10 +415,10 @@  discard block
 block discarded – undo
415 415
      */
416 416
     public function get_alias($class_name = '', $for_class = '')
417 417
     {
418
-        if (! $this->has_alias($class_name, $for_class)) {
418
+        if ( ! $this->has_alias($class_name, $for_class)) {
419 419
             return $class_name;
420 420
         }
421
-        if ($for_class !== '' && isset($this->_aliases[ $for_class ][ $class_name ])) {
421
+        if ($for_class !== '' && isset($this->_aliases[$for_class][$class_name])) {
422 422
             return $this->get_alias($this->_aliases[$for_class][$class_name], $for_class);
423 423
         }
424 424
         return $this->get_alias($this->_aliases[$class_name]);
@@ -679,10 +679,10 @@  discard block
 block discarded – undo
679 679
             'EE_Front_Controller'                  => 'load_core',
680 680
             'EE_Module_Request_Router'             => 'load_core',
681 681
             'EE_Registry'                          => 'load_core',
682
-            'EE_Request'                           => function () use (&$request) {
682
+            'EE_Request'                           => function() use (&$request) {
683 683
                 return $request;
684 684
             },
685
-            'EE_Response'                          => function () use (&$response) {
685
+            'EE_Response'                          => function() use (&$response) {
686 686
                 return $response;
687 687
             },
688 688
             'EE_Request_Handler'                   => 'load_core',
@@ -704,7 +704,7 @@  discard block
 block discarded – undo
704 704
             'EE_Messages_Data_Handler_Collection'  => 'load_lib',
705 705
             'EE_Message_Template_Group_Collection' => 'load_lib',
706 706
             'EE_Payment_Method_Manager'            => 'load_lib',
707
-            'EE_Messages_Generator'                => function () {
707
+            'EE_Messages_Generator'                => function() {
708 708
                 return EE_Registry::instance()->load_lib(
709 709
                     'Messages_Generator',
710 710
                     array(),
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
                     false
713 713
                 );
714 714
             },
715
-            'EE_Messages_Template_Defaults'        => function ($arguments = array()) {
715
+            'EE_Messages_Template_Defaults'        => function($arguments = array()) {
716 716
                 return EE_Registry::instance()->load_lib(
717 717
                     'Messages_Template_Defaults',
718 718
                     $arguments,
@@ -725,22 +725,22 @@  discard block
 block discarded – undo
725 725
             // 'EEM_Message_Template_Group'           => 'load_model',
726 726
             // 'EEM_Message_Template'                 => 'load_model',
727 727
             //load_helper
728
-            'EEH_Parse_Shortcodes'                 => function () {
728
+            'EEH_Parse_Shortcodes'                 => function() {
729 729
                 if (EE_Registry::instance()->load_helper('Parse_Shortcodes')) {
730 730
                     return new EEH_Parse_Shortcodes();
731 731
                 }
732 732
                 return null;
733 733
             },
734
-            'EE_Template_Config'                   => function () {
734
+            'EE_Template_Config'                   => function() {
735 735
                 return EE_Config::instance()->template_settings;
736 736
             },
737
-            'EE_Currency_Config'                   => function () {
737
+            'EE_Currency_Config'                   => function() {
738 738
                 return EE_Config::instance()->currency;
739 739
             },
740
-            'EE_Registration_Config'                   => function () {
740
+            'EE_Registration_Config'                   => function() {
741 741
                 return EE_Config::instance()->registration;
742 742
             },
743
-            'EventEspresso\core\services\loaders\Loader' => function () {
743
+            'EventEspresso\core\services\loaders\Loader' => function() {
744 744
                 return LoaderFactory::getLoader();
745 745
             },
746 746
         );
Please login to merge, or discard this patch.
core/libraries/plugin_api/EE_Register_Payment_Method.lib.php 1 patch
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -22,163 +22,163 @@
 block discarded – undo
22 22
 class EE_Register_Payment_Method implements EEI_Plugin_API
23 23
 {
24 24
 
25
-    /**
26
-     * Holds values for registered payment methods
27
-     *
28
-     * @var array
29
-     */
30
-    protected static $_settings = array();
31
-
32
-
33
-
34
-    /**
35
-     * Method for registering new EE_PMT_Base children
36
-     *
37
-     * @since    4.5.0
38
-     * @param string  $payment_method_id    a unique identifier for this set of modules Required.
39
-     * @param  array  $setup_args           an array of arguments provided for registering modules Required.{
40
-     * @type string[] $payment_method_paths each element is the folder containing the EE_PMT_Base child class
41
-     *                                      (eg, 'public_html/wp-content/plugins/my_plugin/Payomatic/' which contains
42
-     *                                      the files EE_PMT_Payomatic.pm.php)
43
-     *                                      }
44
-     * @throws EE_Error
45
-     * @type array payment_method_paths    an array of full server paths to folders containing any EE_PMT_Base
46
-     *                                      children, or to the EED_Module files themselves
47
-     * @return void
48
-     * @throws InvalidDataTypeException
49
-     * @throws DomainException
50
-     * @throws InvalidArgumentException
51
-     * @throws InvalidInterfaceException
52
-     * @throws InvalidDataTypeException
53
-     */
54
-    public static function register($payment_method_id = null, $setup_args = array())
55
-    {
56
-        //required fields MUST be present, so let's make sure they are.
57
-        if (empty($payment_method_id) || ! is_array($setup_args) || empty($setup_args['payment_method_paths'])) {
58
-            throw new EE_Error(
59
-                esc_html__(
60
-                    'In order to register Payment Methods with EE_Register_Payment_Method::register(), you must include a "payment_method_id" (a unique identifier for this set of modules), and an array containing the following keys: "payment_method_paths" (an array of full server paths to folders that contain modules, or to the module files themselves)',
61
-                    'event_espresso'
62
-                )
63
-            );
64
-        }
65
-        //make sure we don't register twice
66
-        if (isset(self::$_settings[$payment_method_id])) {
67
-            return;
68
-        }
69
-        //make sure this was called in the right place!
70
-        if (
71
-            ! did_action('AHEE__EE_System__load_espresso_addons')
72
-            || did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')
73
-        ) {
74
-            EE_Error::doing_it_wrong(
75
-                __METHOD__,
76
-                esc_html__(
77
-                    'An attempt to register modules has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register modules.',
78
-                    'event_espresso'
79
-                ),
80
-                '4.3.0'
81
-            );
82
-        }
83
-        //setup $_settings array from incoming values.
84
-        self::$_settings[$payment_method_id] = array(
85
-            // array of full server paths to any EE_PMT_Base children used
86
-            'payment_method_paths' => isset($setup_args['payment_method_paths'])
87
-                ? (array)$setup_args['payment_method_paths']
88
-                : array(),
89
-        );
90
-        // add to list of modules to be registered
91
-        add_filter(
92
-            'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
93
-            array('EE_Register_Payment_Method', 'add_payment_methods')
94
-        );
95
-        // If EE_Payment_Method_Manager::register_payment_methods has already been called,
96
-        // then we need to add our caps for this payment method manually
97
-        if (did_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods')) {
98
-            $payment_method_manager = LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
99
-            // register payment methods directly
100
-            foreach (self::$_settings[$payment_method_id]['payment_method_paths'] as $payment_method_path) {
101
-                $payment_method_manager->register_payment_method($payment_method_path);
102
-            }
103
-            $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
104
-            $capabilities->addCaps(
105
-                self::getPaymentMethodCapabilities(self::$_settings[$payment_method_id])
106
-            );
107
-        }
108
-    }
109
-
110
-
111
-
112
-    /**
113
-     * Filters the list of payment methods to add ours.
114
-     * and they're just full filepaths to FOLDERS containing a payment method class file. Eg.
115
-     *
116
-     * @param array $payment_method_folders array of paths to all payment methods that require registering
117
-     * @return array
118
-     */
119
-    public static function add_payment_methods($payment_method_folders)
120
-    {
121
-        foreach (self::$_settings as $settings) {
122
-            foreach ($settings['payment_method_paths'] as $payment_method_path) {
123
-                $payment_method_folders[] = $payment_method_path;
124
-            }
125
-        }
126
-        return $payment_method_folders;
127
-    }
128
-
129
-
130
-
131
-    /**
132
-     * This deregisters a module that was previously registered with a specific $module_id.
133
-     *
134
-     * @since    4.3.0
135
-     *
136
-     * @param string $module_id the name for the module that was previously registered
137
-     * @return void
138
-     * @throws DomainException
139
-     * @throws EE_Error
140
-     * @throws InvalidArgumentException
141
-     * @throws InvalidInterfaceException
142
-     * @throws InvalidDataTypeException
143
-     */
144
-    public static function deregister($module_id = null)
145
-    {
146
-        if (isset(self::$_settings[$module_id])) {
147
-            $capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
148
-            $capabilities->removeCaps(
149
-                self::getPaymentMethodCapabilities(self::$_settings[$module_id])
150
-            );
151
-            unset(self::$_settings[$module_id]);
152
-        }
153
-    }
154
-
155
-
156
-
157
-    /**
158
-     * returns an array of the caps that get added when a Payment Method is registered
159
-     *
160
-     * @param array $settings
161
-     * @return array
162
-     * @throws DomainException
163
-     * @throws EE_Error
164
-     * @throws InvalidArgumentException
165
-     * @throws InvalidInterfaceException
166
-     * @throws InvalidDataTypeException
167
-     */
168
-    private static function getPaymentMethodCapabilities(array $settings)
169
-    {
170
-        $payment_method_manager = LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
171
-        $payment_method_caps = array('administrator' => array());
172
-        if (isset($settings['payment_method_paths'])) {
173
-            foreach ($settings['payment_method_paths'] as $payment_method_path) {
174
-                $payment_method_caps = $payment_method_manager->addPaymentMethodCap(
175
-                    strtolower(basename($payment_method_path)),
176
-                    $payment_method_caps
177
-                );
178
-            }
179
-        }
180
-        return $payment_method_caps;
181
-    }
25
+	/**
26
+	 * Holds values for registered payment methods
27
+	 *
28
+	 * @var array
29
+	 */
30
+	protected static $_settings = array();
31
+
32
+
33
+
34
+	/**
35
+	 * Method for registering new EE_PMT_Base children
36
+	 *
37
+	 * @since    4.5.0
38
+	 * @param string  $payment_method_id    a unique identifier for this set of modules Required.
39
+	 * @param  array  $setup_args           an array of arguments provided for registering modules Required.{
40
+	 * @type string[] $payment_method_paths each element is the folder containing the EE_PMT_Base child class
41
+	 *                                      (eg, 'public_html/wp-content/plugins/my_plugin/Payomatic/' which contains
42
+	 *                                      the files EE_PMT_Payomatic.pm.php)
43
+	 *                                      }
44
+	 * @throws EE_Error
45
+	 * @type array payment_method_paths    an array of full server paths to folders containing any EE_PMT_Base
46
+	 *                                      children, or to the EED_Module files themselves
47
+	 * @return void
48
+	 * @throws InvalidDataTypeException
49
+	 * @throws DomainException
50
+	 * @throws InvalidArgumentException
51
+	 * @throws InvalidInterfaceException
52
+	 * @throws InvalidDataTypeException
53
+	 */
54
+	public static function register($payment_method_id = null, $setup_args = array())
55
+	{
56
+		//required fields MUST be present, so let's make sure they are.
57
+		if (empty($payment_method_id) || ! is_array($setup_args) || empty($setup_args['payment_method_paths'])) {
58
+			throw new EE_Error(
59
+				esc_html__(
60
+					'In order to register Payment Methods with EE_Register_Payment_Method::register(), you must include a "payment_method_id" (a unique identifier for this set of modules), and an array containing the following keys: "payment_method_paths" (an array of full server paths to folders that contain modules, or to the module files themselves)',
61
+					'event_espresso'
62
+				)
63
+			);
64
+		}
65
+		//make sure we don't register twice
66
+		if (isset(self::$_settings[$payment_method_id])) {
67
+			return;
68
+		}
69
+		//make sure this was called in the right place!
70
+		if (
71
+			! did_action('AHEE__EE_System__load_espresso_addons')
72
+			|| did_action('AHEE__EE_System__register_shortcodes_modules_and_widgets')
73
+		) {
74
+			EE_Error::doing_it_wrong(
75
+				__METHOD__,
76
+				esc_html__(
77
+					'An attempt to register modules has failed because it was not registered at the correct time.  Please use the "AHEE__EE_System__register_shortcodes_modules_and_widgets" hook to register modules.',
78
+					'event_espresso'
79
+				),
80
+				'4.3.0'
81
+			);
82
+		}
83
+		//setup $_settings array from incoming values.
84
+		self::$_settings[$payment_method_id] = array(
85
+			// array of full server paths to any EE_PMT_Base children used
86
+			'payment_method_paths' => isset($setup_args['payment_method_paths'])
87
+				? (array)$setup_args['payment_method_paths']
88
+				: array(),
89
+		);
90
+		// add to list of modules to be registered
91
+		add_filter(
92
+			'FHEE__EE_Payment_Method_Manager__register_payment_methods__payment_methods_to_register',
93
+			array('EE_Register_Payment_Method', 'add_payment_methods')
94
+		);
95
+		// If EE_Payment_Method_Manager::register_payment_methods has already been called,
96
+		// then we need to add our caps for this payment method manually
97
+		if (did_action('FHEE__EE_Payment_Method_Manager__register_payment_methods__registered_payment_methods')) {
98
+			$payment_method_manager = LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
99
+			// register payment methods directly
100
+			foreach (self::$_settings[$payment_method_id]['payment_method_paths'] as $payment_method_path) {
101
+				$payment_method_manager->register_payment_method($payment_method_path);
102
+			}
103
+			$capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
104
+			$capabilities->addCaps(
105
+				self::getPaymentMethodCapabilities(self::$_settings[$payment_method_id])
106
+			);
107
+		}
108
+	}
109
+
110
+
111
+
112
+	/**
113
+	 * Filters the list of payment methods to add ours.
114
+	 * and they're just full filepaths to FOLDERS containing a payment method class file. Eg.
115
+	 *
116
+	 * @param array $payment_method_folders array of paths to all payment methods that require registering
117
+	 * @return array
118
+	 */
119
+	public static function add_payment_methods($payment_method_folders)
120
+	{
121
+		foreach (self::$_settings as $settings) {
122
+			foreach ($settings['payment_method_paths'] as $payment_method_path) {
123
+				$payment_method_folders[] = $payment_method_path;
124
+			}
125
+		}
126
+		return $payment_method_folders;
127
+	}
128
+
129
+
130
+
131
+	/**
132
+	 * This deregisters a module that was previously registered with a specific $module_id.
133
+	 *
134
+	 * @since    4.3.0
135
+	 *
136
+	 * @param string $module_id the name for the module that was previously registered
137
+	 * @return void
138
+	 * @throws DomainException
139
+	 * @throws EE_Error
140
+	 * @throws InvalidArgumentException
141
+	 * @throws InvalidInterfaceException
142
+	 * @throws InvalidDataTypeException
143
+	 */
144
+	public static function deregister($module_id = null)
145
+	{
146
+		if (isset(self::$_settings[$module_id])) {
147
+			$capabilities = LoaderFactory::getLoader()->getShared('EE_Capabilities');
148
+			$capabilities->removeCaps(
149
+				self::getPaymentMethodCapabilities(self::$_settings[$module_id])
150
+			);
151
+			unset(self::$_settings[$module_id]);
152
+		}
153
+	}
154
+
155
+
156
+
157
+	/**
158
+	 * returns an array of the caps that get added when a Payment Method is registered
159
+	 *
160
+	 * @param array $settings
161
+	 * @return array
162
+	 * @throws DomainException
163
+	 * @throws EE_Error
164
+	 * @throws InvalidArgumentException
165
+	 * @throws InvalidInterfaceException
166
+	 * @throws InvalidDataTypeException
167
+	 */
168
+	private static function getPaymentMethodCapabilities(array $settings)
169
+	{
170
+		$payment_method_manager = LoaderFactory::getLoader()->getShared('EE_Payment_Method_Manager');
171
+		$payment_method_caps = array('administrator' => array());
172
+		if (isset($settings['payment_method_paths'])) {
173
+			foreach ($settings['payment_method_paths'] as $payment_method_path) {
174
+				$payment_method_caps = $payment_method_manager->addPaymentMethodCap(
175
+					strtolower(basename($payment_method_path)),
176
+					$payment_method_caps
177
+				);
178
+			}
179
+		}
180
+		return $payment_method_caps;
181
+	}
182 182
 
183 183
 }
184 184
 // End of file EE_Register_Payment_Method.lib.php
Please login to merge, or discard this patch.
core/libraries/messages/EE_Messages_Data_Handler_Collection.lib.php 1 patch
Spacing   +9 added lines, -9 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
 
@@ -26,10 +26,10 @@  discard block
 block discarded – undo
26 26
 	 *                                                   classname to create an alternative index for retrieving data_handlers.
27 27
 	 * @return bool
28 28
 	 */
29
-	public function add( $data_handler, $data = null) {
29
+	public function add($data_handler, $data = null) {
30 30
 		$data = $data === null ? array() : (array) $data;
31
-		$info['key'] = $this->get_key( get_class( $data_handler ), $data );
32
-		return parent::add( $data_handler, $info );
31
+		$info['key'] = $this->get_key(get_class($data_handler), $data);
32
+		return parent::add($data_handler, $info);
33 33
 	}
34 34
 	
35 35
 
@@ -44,8 +44,8 @@  discard block
 block discarded – undo
44 44
 	 *
45 45
 	 * @return  string      md5 hash using provided info.
46 46
 	 */
47
-	public function get_key( $classname, $data ) {
48
-		return md5( $classname . serialize( $data ) );
47
+	public function get_key($classname, $data) {
48
+		return md5($classname.serialize($data));
49 49
 	}
50 50
 
51 51
 
@@ -61,11 +61,11 @@  discard block
 block discarded – undo
61 61
 	 *
62 62
 	 * @return null|EE_Messages_incoming_data
63 63
 	 */
64
-	public function get_by_key( $key ) {
64
+	public function get_by_key($key) {
65 65
 		$this->rewind();
66
-		while( $this->valid() ) {
66
+		while ($this->valid()) {
67 67
 			$data = $this->getInfo();
68
-			if ( isset( $data['key'] ) && $data['key'] === $key ) {
68
+			if (isset($data['key']) && $data['key'] === $key) {
69 69
 				$handler = $this->current();
70 70
 				$this->rewind();
71 71
 				return $handler;
Please login to merge, or discard this patch.